【问题标题】:Python requests.post fails in 421Python requests.post 在 421 中失败
【发布时间】:2022-11-19 20:14:16
【问题描述】:

我在实现中有以下代码(uses requests lib):

def call_service(product_ids: Set[str])
   response = requests.post(
      json={"product_ids": product_ids},
      url="http://whatever.com",
   )

   if response.status_code == 421:
      raise MisRedirectedRequest()

我正在使用 HTTPretty's 在测试中对此进行模拟:

@httpretty.activate
def test_http_status_code_421():
    httpretty.register_uri(
        method=httpretty.POST,
        uri="http://whatever.com",
        body="{}",
        status=421,
    )

   with pytest.raises(MisRedirectedRequest):
      call_service({"123", "543"})

然而,MisRedirectedRequest 从未被提出。测试没有通过。 通过调试,我在实现中得到了这个:

requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))

奇怪的是,我尝试使用其他 HTTP 错误代码,但效果很好(例如 420500)。

【问题讨论】:

  • 两个代码块之间的正文(和 http 标头)不相同
  • 但是上面的主体(隐含代码)是要求帖子正文;下面的正文(测试代码)是存根的回复身体..所以他们不匹配是正常的。
  • (如果我在两个地方都从 421 交换到 420,它就可以工作)
  • 它的工作方式类似于 Java 的 WireMock。在这两种情况下,实现都认为它在进行真正的调用。在 Python 中,你甚至不需要注入一个假的/本地主机 URL,因为猴子补丁更聪明。
  • 这是 HTTPretty 的限制:github.com/gabrielfalcao/HTTPretty/pull/458

标签: python python-requests pytest httpretty


【解决方案1】:

经过几个小时的调试,我发现 HTTPretty 不支持 421。 我创建了一个 PR 但与此同时,这是解决方法:

from httpretty.http import STATUSES

STATUSES[421] = "Misdirected Request"

更新:PR 已合并。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-18
    • 2015-08-26
    • 2018-02-09
    • 2019-04-18
    • 2018-06-03
    • 1970-01-01
    • 2018-01-27
    • 2023-03-16
    相关资源
    最近更新 更多