有没有一种方法可以测试使用Pytest包将特定对象类型作为参数传递给函数?

时间:2019-05-09 19:35:12

标签: python

我正在使用Pytest来测试一个类,并且我想验证(最好通过.assert_drawn_with()),我期望传递给要检查的函数的参数之一是特定的对象类型。我遇到的问题是.assert_drawn_with()似乎只能验证基本类型的参数(字符串,整数等)。对于那些熟悉.NET Mocking库,MOQ的人,我想做这样的事情:

mockedSomething.Verify(x => x.mockedSomethingsFunction(It.IsAny());

这是针对我正在使用TDD进行设计的Python Web应用程序。使用Python版本3.7.1的pytest和pytest-mock软件包。

我正在测试的课程:

class Foo():
def __init__(self, proxy, htmlBuilder):
        self._htmlBuilder = htmlBuilder
        self._proxy = proxy

def default(self):
    userData = self._proxy.get_the_data_object()
    return self._htmlBuilder.build_html(userData, True)  

测试功能:

import pytest

def test_this_is_the_test(mocker):
#assemble
user = User()
mocker.patch.object(Proxy, 'get_the_data_object')
Proxy.get_the_data_object.return_value = user
mocker.spy(HtmlBuilder, 'build_html')

#act
Foo.default()

#assert
assert HtmlBuilder.build_html.assert_called_with(user, True)

我希望我在补丁程序(用户)中返回的对象是发送到.build_html(User arg1,Bool arg2)函数中的对象,并且我的断言会通过。但是测试失败了,这就是当我像在代码示例(用户,True)中所做的那样断言时,pytest写出的输出:

E       AssertionError: assert None
E        +  where None = <bound method wrap_assert_called_with of <MagicMock name='build_html' id='140017474442688'>>(<Foo.Models.Foo.User object at 0x7f585bd39b00>, True)
E        +    where <bound method wrap_assert_called_with of <MagicMock name='build_html' id='140017474442688'>> = <MagicMock name='build_html' id='140017474442688'>.assert_called_with
E        +      where <MagicMock name='build_html' id='140017474442688'> = HtmlBuilder.build_html

当我忽略这样的用户参数时:

assert HtmlBuilder.build_html.assert_called_with(True)

然后我运行测试,测试失败,但是这次pytest输出暗示了我最初认为我能够做的事情:

E       AssertionError: Expected call: build_html_for_default_route(True)
E       Actual call: build_htmle(<Foo.Models.Foo.User object at 0x7f20c0b0fc18>, True)
E       
E       pytest introspection follows:
E       
E       Args:
E       assert (<Foo...0x7f20c0b0fc18>, True) == (True,)
E         At index 0 diff: <Foo.Models.Foo.User object at 0x7f20c0b0fc18> != True
E         Left contains more items, first extra item: True
E         Full diff:
E         - (<Foo.Models.Foo.User object at 0x7f20c0b0fc18>, True)
E         + (True,)

0 个答案:

没有答案