Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 类上的Mock属性方法_Python_Unit Testing - Fatal编程技术网

Python 类上的Mock属性方法

Python 类上的Mock属性方法,python,unit-testing,Python,Unit Testing,我有以下数据类: from dataclasses import dataclass @dataclass class Foo: bar: str baz: str @property def qux(self) -> str: return self.bar 我想在测试期间更改qux的行为。我了解PropertyMock,可以编写如下内容: with mock.patch("__main__.Foo.qux", new_callabl

我有以下数据类:

from dataclasses import dataclass

@dataclass
class Foo:
    bar: str
    baz: str

    @property
    def qux(self) -> str:
        return self.bar
我想在测试期间更改
qux
的行为。我了解
PropertyMock
,可以编写如下内容:

with mock.patch("__main__.Foo.qux", new_callable=mock.PropertyMock(return_value="test")):
    foo = Foo(bar="a", baz="b")
    print(foo.qux)
def _unbound(self) -> str:
    return self.baz

with mock.patch("__main__.Foo.qux", new_callable=mock.PropertyMock(new=_unbound)):
    foo = Foo(bar="a", baz="b")
    print(foo.qux)
相反,我想替换属性方法(未修饰),类似于:

with mock.patch("__main__.Foo.qux", new_callable=mock.PropertyMock(return_value="test")):
    foo = Foo(bar="a", baz="b")
    print(foo.qux)
def _unbound(self) -> str:
    return self.baz

with mock.patch("__main__.Foo.qux", new_callable=mock.PropertyMock(new=_unbound)):
    foo = Foo(bar="a", baz="b")
    print(foo.qux)
在创建
补丁
对象时,我尝试了
new\u callable
new
等多种组合,但我看到:

TypeError: _unbound() missing 1 required positional argument: 'self'

是否有一种方法可以使用包含对dataclass引用的绑定方法模拟属性?

您可以编写自己的属性模拟,这符合您在
\uuuu get\uuuu
中的要求:

class MyMock(mock.PropertyMock):
    def __get__(self, obj, obj_type=None):
        return _unbound(obj)


def test_unbound():
    with mock.patch("__main__.Foo.qux", new=MyMock()):
        foo = Foo(bar="a", baz="b")
        assert foo.qux == "b"
问题是如何将正确的对象释放到
\u unbound

必须有一个更干净的方法来实现这一点,尽管我看不到