python assert_called_with自定义断言逻辑或检索呼叫参数的值

发布于 2025-02-01 09:28:58 字数 799 浏览 2 评论 0原文

考虑以下测试方法:

@patch("api.views.my_views.MyViewSet.send_customer_request")
def test_process_customers(self, send_customer_request_mock):

    process_customers(123, 456)
    # The above call eventually results in a call to send_customer_request
    # Note that my test does NOT call send_customer_request() directly.  It's a couple calls deep.

    expected_params = {
        "names": ["Rupert", "Steve"],
    }
    
    send_customer_request_mock.assert_called_with(expected_params)

此测试在某些时候通过,并且其他时间失败。问题在于名称的顺序是无确定的。有时会用[“ rupert”,“ steve”]称呼它,有时会与[史蒂夫(Steve),“ rupert”)一起称呼。

我需要断言这两个名称在列表中,但不需要它们所处的具体顺序。

不幸的是,assert_called_with()期望与模拟方法相关的单个确切值,但不可能知道。正是什么。

理想情况下,我只想检索send_customer_request()被调用的值,然后编写我自己的essert语句/逻辑以测试值。

我该如何实现?

Consider the following test method:

@patch("api.views.my_views.MyViewSet.send_customer_request")
def test_process_customers(self, send_customer_request_mock):

    process_customers(123, 456)
    # The above call eventually results in a call to send_customer_request
    # Note that my test does NOT call send_customer_request() directly.  It's a couple calls deep.

    expected_params = {
        "names": ["Rupert", "Steve"],
    }
    
    send_customer_request_mock.assert_called_with(expected_params)

This test passes some of the time, and fails other times. The problem is that the order of the names is nondeterministic. Sometimes it is called with ["Rupert", "Steve"], and sometimes it is called with ["Steve", "Rupert"].

I need to assert that exactly those two names are in the list, but without requiring the specific order that they're in.

Unfortunately, assert_called_with() expects a single exact value for the mocked method to be called with, but it's impossible to know exactly what it will be.

Ideally, I'd like to just retrieve the values that send_customer_request() gets called with, and then write my own assert statements/logic to test the values.

How can I achieve that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文