如何覆盖单元测试的其他文件的导入

2024-06-01 06:19:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为我的主.py的main()函数

这是我的简化版主.py公司名称:

from Configuration import Configuration # Configuration.py is a file in the same dir

def main():
  try:
    Configuration('settings.ini')
  except:
    sys.exit(1) # Test path1
  sys.exit(0) # Test path2

if __name__ == '__main__':
    main()

在我的Unit Tests\MainUnitTests.py中,我想导入..\Main.py并伪造{}类,这样我就可以点击Test path1和{}

我发现我可以用以下内容断言sys.exit()

^{pr2}$

但是我无法覆盖from Configuration import Configuration

有什么想法?在

到目前为止,我在Unit Tests\MainUnitTests.py中尝试了以下操作:

class FakeFactory(object):
  def __init__(self, *a):
    pass

sys.modules['Configuration'] = __import__('FakeFactory')

class Configuration(FakeFactory):
  pass

另一个演示示例:

在食品公司名称:

from bar import a,b

x = a()

class a(object):
  def __init__(self):
    self.q = 2

y = a()

print x.q, y.q # prints '1 2' as intended

b() # I want this to print 2 without modifying bar.py

在棒.py公司名称:

class a(object):
  def __init__(self):
    self.q = 1

def b():
  t = a()
  print t.q

Tags: frompytestimportself名称objectmain
1条回答
网友
1楼 · 发布于 2024-06-01 06:19:09

使用导入时

from bar import a

它直接将名称导入模块中,因此monkeypatching bar没有帮助,您需要直接在主文件中重写{}:

^{pr2}$

要知道unittest在the ^{} subpackage中有帮助函数,我相信您可以做一些类似的事情:

from unittest.mock import patch

...
with patch("main.a", fake_a) as mock_obj: #there are additional things you can do with the mock_obj
    do_stuff()

这在第一个使用configuration的示例中是有效的,因为需要修补的类没有在全局作用域中使用,尽管foo在加载后立即使用bar.a,因此您需要在加载foo之前对其进行修补:

from unittest.mock import patch

...
with patch("bar.a", fake_a) as mock_obj: #there are additional things you can do with the mock_obj
    import foo #now when it loads it will be loaded with the patched name

但是在这种情况下,foo.a不会在with块的末尾恢复,因为它不能被unittest捕获。。。我真的希望你的实际用例不要使用模块级别的补丁。在

相关问题 更多 >