Reputation: 575
I need to mock os.environ in unit tests written using the pytest framework.
Here is a dummy version of the code I want to test, located in getters.py
:
import os
username = os.environ['MY_USER']
password = os.environ['MY_PASS']
def get_data(...):
access_token = request_access_token(username, password)
...
return data
and here is an example of a unit test in test_getters.py
:
import pytest
import src.getters
class TestGetData(object):
def test_something(self):
data = src.getters.get_data(...)
assert ...
Test collection fails with the following error:
=========================== short test summary info ============================
ERROR tests/test_getters.py - KeyError: 'MY_USER'
!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
=============================== 1 error in 0.68s ===============================
I would like to be able to mock once for the whole test class if possible.
Is there some kind of a decorator I can use? Or some other recommended way of mocking os.environ?
Upvotes: 3
Views: 10445
Reputation: 6298
Use monkeypatch.setenv()
of Monkeypatching:
Docs:
Modifying environment variables for a test e.g. to test program behavior if an environment variable is missing, or to set multiple values to a known variable. monkeypatch.setenv() and monkeypatch.delenv() can be used for these patches.
Code:
import pytest
import src.getters
class TestGetData(object):
def test_something(self):
monkeypatch.setenv('MY_USER', 'Nanna')
monkeypatch.setenv('MY_PASS', 'P@ssw0rd')
data = src.getters.get_data(...)
assert ...
Upvotes: 7