How can I mock os.environ using unittest.mock.patch?

Viewed 20

I have some code like:

@metric_scope
def get_room_by_computer_number(metrics, computer: str) -> typing.Optional[str]:
    logger.info(f"Searching room by device: {computer}")

    if not os.environ.get('STAGE') != 'phi':
        return None

    # more code here

which I am trying to test like so:

@patch("requests.post")
def test_if_room_exist(self, mock_requests):
    mock_response = MagicMock()
    mock_response.status_code = 200
    mock_response.json.return_value = {
        "data": {
            "platform_devices_management_device_assignments": [
                {"asset_id": "PL00", "room": "room 1", "serial_number": "255CXP3"}
            ]
        }
    }

    mock_requests.post.return_value = mock_response
    self.assertEqual(get_room_by_computer_number(computer="PL00"), "room 1")

The code will return None if a specific value is not set in os.environ. I want to test what happens assuming the value is set.

How can I mock the data in os.environ to pass the test ?

1 Answers
>>> from unittest.mock import patch
>>> with patch("os.environ",{"poop":"smells"}):
...    import os
...    print(os.environ)
...
{'poop': 'smells'}
>>> @patch('os.environ',{'foo':'bar'})
... def a_func(x,*a,**kw):
...     import os
...     print(os.environ)
...
>>> a_func(55)
{'foo': 'bar'}
>>>

seems pretty straightforward to me ...

if you just want to override some small bit

>>> import os
>>> @patch('os.environ',{**os.environ,**{'foo':'bar'}})
... def a_func(x,*a,**kw):
...     print(os.environ)
...
>>> a_func(55)
{'SHELL': '/bin/bash', 'NVM_INC': '/home/s
Related