简体   繁体   English

Mock构造函数中的Python PropertyMock

[英]Python PropertyMock in Mock constructor

I'm using Michael Foord's mock library and have a question about it. 我正在使用Michael Foord的模拟库,并对此有疑问。

I want to mock a property, so I do this: 我想模拟一个属性,所以我这样做:

eggs = mock.PropertyMock(return_value='eggs')
spam = mock.Mock()
type(spam).eggs = eggs
assert spam.eggs == 'eggs'

This works brilliantly. 这非常出色。 However I find the type() part ugly and would love to do something like this: 但是我发现type()部分很难看,并且喜欢这样做:

eggs = mock.PropertyMock(return_value='eggs')
spam = mock.Mock(eggs = eggs)
assert spam.eggs == 'eggs'

The last example doesn't work as expected, spam.eggs becomes a method instead of a property. 最后一个例子没有按预期工作, spam.eggs成为一个方法而不是一个属性。


I know I can use mock.Mock(eggs = 'eggs') so eggs is not a method, but I want to be able to assert the property. 我知道我可以使用mock.Mock(eggs = 'eggs')所以eggs不是一种方法,但我希望能够断言该属性。 :-) :-)


I am using Python 2.7, but I assume unittest.Mock works too. 我使用的是Python 2.7,但我认为unittest.Mock适用。

The patch can help you to a degree, the code is taken from official Mock document 该补丁可以在一定程度上帮助您,代码取自官方Mock文档

>>> class Foo(object):
...     @property
...     def foo(self):
...         return 'something'
...     @foo.setter
...     def foo(self, value):
...         pass
...
>>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:
...     mock_foo.return_value = 'mockity-mock'
...     this_foo = Foo()
...     print this_foo.foo
...     this_foo.foo = 6
...
mockity-mock
>>> mock_foo.mock_calls
[call(), call(6)]

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

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