I have created a file with 2 functions under test. The file with this functions is called env_function.py
and is in the same folder of the test file (test_os_environment.py
).
Below there is the code of env_function.py
:
import os
def tested_function():
return os.environ
def tested_function_2():
if os.environ['LANGUAGE'] == 'en_US':
return 0
return 1
The tested_function_2()
use the value of the key LANGUAGE
in os.environ
(the key LANGUAGE
is really present in my system) as you say in the question:
Every test with a test function that uses the dictionary os.environ['key'], fails
The test file test_os_environment.py
contains 2 tests function (I have modified your test function):
import unittest
from unittest import mock
import os
from env_function import tested_function, tested_function_2
class MyTestCase(unittest.TestCase):
def test_env_var(self):
with mock.patch.dict("os.environ", {"env_var": "value_for_env_var"}):
self.assertTrue("env_var" in tested_function())
os.environ.pop("env_var")
self.assertTrue("env_var" not in tested_function())
self.assertTrue("env_var" not in os.environ)
def test_func2(self):
self.assertEqual(0, tested_function_2())
self.assertTrue("LANGUAGE" in os.environ)
if __name__ == '__main__':
unittest.main()
After the context manager with mock.patch.dict()
, the dictionary os.environ
doesn't contain the env_var
key. This is proofed by the assertion:
self.assertTrue("env_var" not in os.environ)
The tests contained in the function test_func2()
pass (tested_function_2()
return 0 as expected).
This is the output of the test execution with pytest in parallel:
$ pytest -n 2
========================= test session starts =========================
platform linux -- Python 3.6.9, pytest-7.0.1, pluggy-1.0.0
rootdir: /home/frank/tests
plugins: mock-3.6.1, xdist-3.0.2
gw0 [4] / gw1 [4]
.... [100%]
========================== 4 passed in 0.40s ==========================
To find your problem I suggest you to compare my context with yours.
This other post could be useful.