[Tutor] Patching os.environ
Albert-Jan Roskam
sjeik_appie at hotmail.com
Tue Mar 19 07:16:45 EDT 2024
Hi,
What is the correct way of patching a dict in a test fixture? Below,
MyTest1 fails, while MyTest2 succeeds. I thought the two tests were
equivalent!
Thanks!
Albert-Jan
import os
import unittest
from unittest.mock import patch
class MyTest1(unittest.TestCase):
def setUp(self):
patcher = patch.dict(os.environ, {"FOO": "bar"}, clear=True)
self.addCleanup(patcher.stop)
def test_bla1(self):
# why does this test fail?
self.assertEqual(os.environ.get("FOO"), "bar")
class MyTest2(unittest.TestCase):
@patch.dict(os.environ, {"FOO": "bar"}, clear=True)
def test_bla2(self):
self.assertEqual(os.environ.get("FOO"), "bar")
if __name__ == "__main__":
unittest.main()
More information about the Tutor
mailing list