在 mock_post 中访问多个通话

Access multiple calls in mock_post

我有一个函数可以触发两个 post 请求,例如:

def send_posts():
    first_response = requests.post(
            url="google.com",
            json={'records': [{'value': message}]},
        )
    second_response = requests.post(
            url="apple.com",
            json={'records': [{'value': message}]},
        )

在我的单元测试中,我有这样的东西:

@patch('requests.post')
def send_e2e_kafka_with_env_vars(mock_post, expect, monkeypatch):
    send_posts()

    args, kwargs = mock_post.call_args // returns kwargs for 2nd post

    # I've tried, but get ' ValueError: too many values to unpack (expected 2)'
    my_first_call = mock_post.mock_calls[0]
    args, kwargs = my_first_call[0]

最终,我希望断言第一个 post 的 URL 是 'google.com'。我该怎么做?

每个模拟调用都有 3 个参数,因此如果您要解压缩它们,则需要匹配它(您可能想忽略第一个,因此 _):

@patch('requests.post')
def send_e2e_kafka_with_env_vars(mock_post, expect, monkeypatch):
    send_posts()

    args, kwargs = mock_post.call_args
    _, args, kwargs = mock_post.mock_calls[0]