如何修补 os.environ 的模块级访问?
我正在为从另一个模块 legacy.py
导入的模块 module.py
编写测试用例。 legacy.py
在模块级别读取 os.environ["some_var"]
。当我尝试运行 module.py
的测试用例时,它们因 os.environsome_var
的 KeyError
失败代码>.
代码如下所示:
module.py
from legacy import db
def fun():
pass
legacy.py
import os
env = os.environ["some_var"]
class db:
def __init__(self):
pass
当运行 module.py
的测试用例时,我收到 KeyError :'some_var'
。
我尝试修补 os
(在模块级别也将其放在从测试文件中的 module.py
导入之前),但导入语句在修补之前就已运行。我尝试在 StackOverflow 上寻找类似的问题,但没有找到我在这里面临的确切问题。
我该如何嘲笑它?或者任何其他能够运行测试用例的建议。假设我无法修改 legacy.py
文件。
I am writing test cases for a module module.py
that imports from another module legacy.py
. The legacy.py
reads os.environ["some_var"]
at module level. When I am trying to run test cases for module.py
, they are failing with KeyError
for some_var
in os.environ
.
This is how code looks like:
module.py
from legacy import db
def fun():
pass
legacy.py
import os
env = os.environ["some_var"]
class db:
def __init__(self):
pass
When running test cases for module.py
, I am getting KeyError: 'some_var'
.
I tried patching os
(at module level also putting it before importing from module.py
in test file) but the import statement is run before it could be patched. I tried looking for similar question on StackOverflow but didn't find the exact problem I am facing here.
How can I mock it? Or any other suggestion to be able to run the test cases. Assume that I cannot modify the legacy.py
file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

您可以使用
mock.patch .dict
。官方文档中有一个例子。这是一个基于您的问题的功能齐全的示例。
module.py
test_module.py
无论环境变量是在类/方法范围之外还是内部加载都没有关系,因为您将为所有测试范围进行模拟。
You could use the
mock.patch.dict
. There is an example in official doc.Here is a fully functional example based in your question.
module.py
test_module.py
Doesn't matter if the environment var is loaded in outside or inside the class/method scope, because you will mock for all test scope.