【问题标题】:How can I mock (same request but different answers) requests with the response in Python?如何使用 Python 中的响应模拟(相同的请求但不同的答案)请求?
【发布时间】:2021-08-10 23:35:32
【问题描述】:

我正在尝试使用 Pythons 模拟包来模拟 Pythons 请求模块。让我在以下场景中工作的基本调用是什么?

我有一个函数可以进行各种 requests.post() 调用,每次都有不同的响应 它们具有相同的 URL,仅在 Body 中发生变化,它们是按顺序执行的,首先是一个调用,然后是另一个调用

def myview(request):
  res1 = requests.post(("http://aurl",
                        body='[{"kind": "company"}]',
                        content_type="application/json"))
  res2 = requests.post(("http://aurl",
                        body='[{"kind": "people"}]',
                        content_type="application/json"))

在我的测试类中,我想做这样的事情,但无法弄清楚确切的方法调用

第 1 步:

# Mock the requests module
# when mockedRequests.post('aurl') with body "company" is called then return 'a response'
# when mockedRequests.post('aurl') with body "people" is called then return 'b response'

第 2 步:

verify response contains 'a response', 'b response' , 'c response'

如何完成第 1 步(模拟请求模块)?

【问题讨论】:

    标签: python mocking


    【解决方案1】:

    您有多种选择:

    1. 依赖调用顺序:
    mocked_post.side_effect = ['a response', 'b response', 'c response']
    
    1. 在 mock 中写一点业务逻辑
    MOCKED_POST_RESPONSES = {
      '[{"kind": "company"}]': 'a response',
      '[{"kind": "people"}]': 'b response'
    }
    
    mocked_post.side_effect = lambda url, body, content_type: MOCKED_POST_RESPONSES[body]
    
    1. 或者只是使用 requests-mock 模块和自定义匹配器https://requests-mock.readthedocs.io/en/latest/matching.html#custom-matching

    这是Mock.side_effect上的资料:https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.side_effect

    【讨论】:

    猜你喜欢
    • 2019-07-29
    • 1970-01-01
    • 2014-09-10
    • 1970-01-01
    • 2019-05-07
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    相关资源
    最近更新 更多