I have the following dataclass:
import os
import dataclasses
@dataclasses.dataclass
class Example:
host: str = os.environ.get('SERVICE_HOST', 'localhost')
port: str = os.environ.get('SERVICE_PORT', 30650)
How do I write a test for this? I tried the following which looks like it should work:
from stackoverflow import Example
import os
def test_example(monkeypatch):
# GIVEN environment variables are set for host and port
monkeypatch.setenv('SERVICE_HOST', 'server.example.com')
monkeypatch.setenv('SERVICE_PORT', '12345')
# AND a class instance is initialized without specifying a host or port
example = Example()
# THEN the instance should reflect the host and port specified in the environment variables
assert example.host == 'server.example.com'
assert example.port == '12345'
but this fails with:
====================================================================== test session starts ======================================================================
platform linux -- Python 3.8.12, pytest-7.1.2, pluggy-1.0.0
rootdir: /home/biogeek/tmp
collected 1 item
test_example.py F [100%]
=========================================================================== FAILURES ============================================================================
_________________________________________________________________________ test_example __________________________________________________________________________
monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x7f39de559220>
def test_example(monkeypatch):
# GIVEN environment variables are set for host and port
monkeypatch.setenv('SERVICE_HOST', 'server.example.com')
monkeypatch.setenv('SERVICE_PORT', '12345')
# AND a class instance is initialized without specifying a host or port
example = Example()
# THEN the instance should reflect the host and port specified in the environment variables
> assert example.host == 'server.example.com'
E AssertionError: assert 'localhost' == 'server.example.com'
E - server.example.com
E + localhost
test_example.py:12: AssertionError
==================================================================== short test summary info ====================================================================
FAILED test_example.py::test_example - AssertionError: assert 'localhost' == 'server.example.com'
======================================================================= 1 failed in 0.05s =======================================================================