如何模拟导入模块中引用的环境变量?
我创建了一个包含环境变量的文件,并且正在为此文件编写测试。文件(“ 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于
os.getenv()
在导入时间运行UnitSest无法模拟对象。在导入my_variables
: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 theos
module before importingmy_variables
:我使用了这样的东西(仍然我还没有找到如何在
test_env_var
中求解import
语句)。I used something like this (still i haven't figured out how to solve the
import
statement insidetest_env_var
).