【问题标题】:how to pass magic mocked references to main method in python如何将魔术模拟引用传递给python中的主要方法
【发布时间】:2017-12-07 21:55:34
【问题描述】:

我尝试将在 main 函数中构造的类存根,以便我可以针对 main 进行测试并断言类是用特定数据初始化的。但是 main 函数仍然没有拾取模拟实例。如何将模拟实例传递给 main。

from unittest.mock import patch
from contextlib import contextmanager

@contextmanager
def use_mocked(method, cls, ret_value):

class MockedClass(cls):
    pass

def func(cls):
    return ret_value

def fullname(o):
    return o.__module__ + "." + o.__name__

setattr(MockedClass, method, classmethod(func))

with patch(fullname(cls), MockedClass):
    yield

这是一个补丁实用程序,用于确保 main 传递了模拟引用。我可能对我对其运作方式的理解感到困惑。

def test_main():
    magic_b = MagicMock(spec_set=Benchmark, wraps=Benchmark)
    with use_mocked("__new__", DataStream, magic_b):
        main.main()
        magic_b.assert_called_once_with() # fails

在主模块中,我有一个主方法定义为...

import benchmark.Benchmark
def main():
    b = benchmark.Benchmark() # <- this is not the mocked instance
    ...

【问题讨论】:

    标签: python unit-testing mocking


    【解决方案1】:

    我依赖于 unittest.mock 中的相同补丁实用程序,但只是在我的测试周围以装饰器的形式使用它。 patch() 现在在主要导入的 Benchmark 类中传递(重要的是在 main 中打补丁,而不是在它自己的基准模块中即不打补丁 benchmark.Benchmark)。主模块保持不变,测试现在通过。

    import main
    
    @patch("main.Benchmark")
    # b here is a ref to MagicMock class mocking Benchmark;
    # it is substituted into the execution of main module,
    # patch provides it as a param so you can assert against it.
    def test_main(b): 
        main.main()
        b.assert_called_once_with()
    

    【讨论】:

      猜你喜欢
      • 2019-03-04
      • 2014-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-02
      • 1970-01-01
      • 1970-01-01
      • 2015-03-05
      相关资源
      最近更新 更多