翻译结果:mock.patch-ing Python 列表的 .append 方法

huangapple go评论78阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年5月30日 11:13:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76361397.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定