简体   繁体   English

Python:使用 side_effect 模拟实例变量

[英]Python: Mock a instance variable with a side_effect

we currently try to mock an instance variable of a class object with a side_effect.我们目前尝试使用 side_effect 模拟类对象的实例变量。 The first time we access the attribute we want to get a different value as the second time.第一次访问属性时,我们希望获得与第二次不同的值。 We test an async method and the value can change during the two accesses.我们测试了一个异步方法,并且在两次访问期间该值可能会发生变化。

Here is a simple example:这是一个简单的例子:

from unittest import TestCase
from unittest.mock import PropertyMock, patch


class MyObject:

    def __init__(self):
        self.variable = None

    def my_func(self):
        print(self.variable)
        print(self.variable)


class TestObject(TestCase):

    def test_my_func(self):
        object = MyObject()
        with patch.object(object, "variable", new_callable=PropertyMock(side_effect=["test", "test2"])):
            object.my_func()

We would expect that this print at first test and then test2.我们希望在第一个 test 和 test2 时打印。 But the output is:但输出是:

test
test
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

Maybe you could simplify your use-case with something like this:-也许你可以用这样的东西来简化你的用例:-

class MyClass():
    def __init__(self):
        self.__var = 0

    @property
    def var(self):
        rv = self.__var
        self.__var += 1
        return rv


MC = MyClass()
print(MC.var)
print(MC.var)

Every time MC.var is acquired using this technique it will be incremented by 1. Obviously a variation on your theme but may give you some ideas每次使用这种技术获取 MC.var 时,它都会加 1。显然是您主题的变体,但可能会给您一些想法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM