python-3.x - python3模拟成员变量多次获取

标签 python-3.x pytest python-unittest

我有一个用例,我需要模拟一个成员变量,但我希望它每次访问时都返回不同的值。

例子;

def run_test():
    myClass = MyDumbClass()
    for i in range(2):
        print(myClass.response)

class MyDumbClass():
    def __init__(self):
        self.response = None

 @pytest.mark.parametrize("responses", [[200,201]])
 @patch("blah.MyDumbClass")
 def test_stuff(mockMyDumbClass, responses)
     run_test()
     assert stuff

我在这里希望的是在 run_test 方法中,第一次迭代将打印 200 然后下一次将打印 201。这可能吗,一直在查看 unittest 和 pytest 文档,但找不到任何关于以这种方式模拟成员变量的信息。
刚开始用python3学习pytest和unittest,所以如果风格不是最好的,请原谅我。

最佳答案

如果你包装 myDumbClass.response 在 get 函数中 - 说 get_response() 那么你可以使用副作用模拟类的参数。

  • 副作用将模拟方法的 return_value 设置为每次调用模拟方法时返回不同值的迭代器。

  • 例如你可以做
    def run_test():
        myClass = MyDumbClass()
        for i in range(2):
            print(myClass.get_response())
    
    class MyDumbClass():
        def __init__(self):
            self.response = None
    
        def get_response(self):
            return self.response
    
    @pytest.mark.parametrize("responses", [([200,201])])
    def test_stuff( responses):
        with mock.patch('blah.MyDumbClass.get_response', side_effect=responses):
            run_test()
        assert False
    

    结果
    ----------------------------------- Captured stdout call ------------------------------------------------------------
    200
    201
    

    编辑
  • 无需通过上下文管理器进行修补,例如 与 mock.patch .您可以通过装饰器以几乎相同的方式修补。例如这工作正常
    @patch('blah.MyDumbClass.get_response',side_effect=[200,100])
    def test_stuff(mockMyDumbClass):
        run_test()
        assert False
    ----------------------------------- Captured stdout call ------------------------------------------------------------
    200
    201
    
  • 关于python-3.x - python3模拟成员变量多次获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54545348/

    相关文章:

    Python 3 代码未按预期执行,给出了错误的数字

    python unittest : mocking a dict-like object

    regex - 在大写字母前插入空格但不在缩写之间插入空格的 pythonic 方法

    python - 使用 Tweepy 访问 twitter API 时出错

    python - 尽可能高效地在 Python 中叠加混合模式(Numpy、OpenCV)

    python - 如何使用 xunit 风格的 setup_function

    python - 如何测试使用 exec_() 调用的自定义对话框窗口?

    python - pytest fixture 中的 pytest-mock mock 者

    Python 测试如何运行参数化测试用例并将参数传递给 setupClass

    python - PyUnit 中是否弃用了测试套件?