英文:
mock.patch-ing the .append method of the Python list
问题
我正在单元测试一个包含在if语句中的一行代码,如果一个变量具有特定的值,我会将一个项目附加到列表中。
foo = []
if bar == 'a':
foo.append(bar)
我想要断言已经调用了这样一个附加操作。我以前曾对来自各种来源的方法进行了修补,但还没有修补过属于基本Python数据类型的方法。对于mock.patch装饰器,我应该指定哪个类作为路径?
@mock.patch('append')
def test_appends_bar_to_foo(mock_append):
assert mock_append.called
使用上述代码,我得到了TypeError: Need a valid target to patch. You supplied: 'append' 的错误消息。
英文:
I am unit testing a single line of code within an if statement where I append an item onto a list if a variable has a specific value.
foo = []
if bar == 'a':
foo.append(bar)
I would like to assert that such an append has been called. I have patched methods from a variety of sources before, but not methods belonging to basic Python data types. What class would I specify as the path for the mock.patch decorator?
@mock.patch('append')
def test_appends_bar_to_foo(mock_append):
assert mock_append.called
With the above code, I get TypeError: Need a valid target to patch. You supplied: 'append'
答案1
得分: 1
你可以对foo
进行修补,并断言其append
方法已被调用:
foo = []
with mock.patch('__main__.foo') as mock_foo:
foo.append(1)
mock_foo.append.assert_called() # 断言成功
英文:
You can patch foo
instead and assert that its append
method has been called:
foo = []
with mock.patch('__main__.foo') as mock_foo:
foo.append(1)
mock_foo.append.assert_called() # assertion success
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论