如何模拟导入模块中引用的环境变量?

发布于 2025-01-23 03:28:59 字数 1018 浏览 1 评论 0原文

我创建了一个包含环境变量的文件,并且正在为此文件编写测试。文件(“ my_variables.py”)看起来像:

import os

if os.getenv("VCAP_APPLICATION"):
    foo = os.getenv("foo")
else:
    foo = "bar"

在我的测试中,我嘲笑“ vcap_application”的定义” env var。然后,我断言my_variables.foo等于“ foo”。情况并非如此,因为它等于“ bar”

我认为导入模块时,我模拟的变量未正确模拟。这就是为什么我试图在嘲笑变量后试图导入模块的原因。我的测试看起来像这样:

import unittest
import os
from unittest.mock import patch

class MyTestCase(unittest.TestCase):

    @patch.dict(
        os.environ,
        { 
            "VCAP_APPLICATION": "True",
            "foo": "foo"
        }
    )
    def test_env_var(self):
        print(os.getenv("VCAP_APPLICATION")) # Returns True, so env var is mocked!
        import my_variables
        self.assertEqual(my_variables.foo, "foo") # Results in AssertionError

断言平等导致断言:

AssertionError: 'Bar' =! 'Foo'

我首先在文件的顶部进口。嘲笑后,我现在将其放置。我如何模拟env var,以便我导入的模块使用该模块?

I have created a file containing environment variables and I am writing a test for this file. The file ("my_variables.py") looks like:

import os

if os.getenv("VCAP_APPLICATION"):
    foo = os.getenv("foo")
else:
    foo = "bar"

In my test I am mocking the definition of the the "VCAP_APPLICATION" env var. I then assert if my_variables.foo is equal to "foo". This is not the case, as it is equal to "bar".

I think my mocked variable is not properly mocked when importing the module. This is why I tried to import the module after mocking my variables. My test looks like this:

import unittest
import os
from unittest.mock import patch

class MyTestCase(unittest.TestCase):

    @patch.dict(
        os.environ,
        { 
            "VCAP_APPLICATION": "True",
            "foo": "foo"
        }
    )
    def test_env_var(self):
        print(os.getenv("VCAP_APPLICATION")) # Returns True, so env var is mocked!
        import my_variables
        self.assertEqual(my_variables.foo, "foo") # Results in AssertionError

Asserting equality results in an AssertionError:

AssertionError: 'Bar' =! 'Foo'

I first had the import at the top of the file. I now placed it after mocking. How can I mock the env var so that my imported module uses that one?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不喜欢何必死缠烂打 2025-01-30 03:28:59

由于os.getenv()在导入时间运行UnitSest无法模拟对象。在导入my_variables

import unittest
import os

class MyTestCase(unittest.TestCase):
    def test_env_var(self):
        os.environ["VCAP_APPLICATION"] = "True"
        os.environ["foo"] = "foo"
        import my_variables
        self.assertEqual(my_variables.foo, "foo")

since the os.getenv() runs at import time unittest cant mock the object. You're going to have to get hacky by setting the environment variables in the os module before importing my_variables:

import unittest
import os

class MyTestCase(unittest.TestCase):
    def test_env_var(self):
        os.environ["VCAP_APPLICATION"] = "True"
        os.environ["foo"] = "foo"
        import my_variables
        self.assertEqual(my_variables.foo, "foo")
暗藏城府 2025-01-30 03:28:59

我使用了这样的东西(仍然我还没有找到如何在test_env_var中求解import语句)。

import os
import unittest
from unittest.mock import patch


class MyTestCase(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        """
        For future use
        """
        super().setUpClass()

        your_envs = {
            "VCAP_APPLICATION": "True",
            "foo": "foo"
        }

        cls.env = patch.dict(in_dict=os.environ, values=your_envs, clear=True)
        cls.env.start()

    @classmethod
    def tearDownClass(cls):
        """
        For future use
        """
        super().tearDownClass()
        cls.env.stop()

    def test_env_var(self):
        print(os.getenv("VCAP_APPLICATION"))  # Returns True, so env var is mocked!
        import my_variables
        self.assertEqual(my_variables.foo, "foo")  # Results in AssertionError


if __name__ == '__main__':
    unittest.main()

I used something like this (still i haven't figured out how to solve the import statement inside test_env_var).

import os
import unittest
from unittest.mock import patch


class MyTestCase(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        """
        For future use
        """
        super().setUpClass()

        your_envs = {
            "VCAP_APPLICATION": "True",
            "foo": "foo"
        }

        cls.env = patch.dict(in_dict=os.environ, values=your_envs, clear=True)
        cls.env.start()

    @classmethod
    def tearDownClass(cls):
        """
        For future use
        """
        super().tearDownClass()
        cls.env.stop()

    def test_env_var(self):
        print(os.getenv("VCAP_APPLICATION"))  # Returns True, so env var is mocked!
        import my_variables
        self.assertEqual(my_variables.foo, "foo")  # Results in AssertionError


if __name__ == '__main__':
    unittest.main()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文