[Tutor] Patching os.environ

Albert-Jan Roskam sjeik_appie at hotmail.com
Tue Mar 19 07:41:31 EDT 2024


   Aaah.. got it already: I have use "patcher.start()" after I've defined
   it.
   On Mar 19, 2024 12:16, Albert-Jan Roskam <sjeik_appie at hotmail.com> wrote:

        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()
     _______________________________________________
     Tutor maillist  -  Tutor at python.org
     To unsubscribe or change subscription options:
     https://mail.python.org/mailman/listinfo/tutor


More information about the Tutor mailing list