简体   繁体   中英

Python requests.post fails in 421

I have the following code in the implementation ( 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()

I'm using HTTPretty's to simulate this in a test:

@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"})

However, MisRedirectedRequest is never raised. The test doesn't pass. By debugging, I get this in the implementation:

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

The weird thing is that I tried with other HTTP error codes and it works fine (eg 420 , 500 ).

After hours of debugging, I found our that HTTPretty's did not support 421. I created a PR but meanwhile, this is the workaround:

from httpretty.http import STATUSES

STATUSES[421] = "Misdirected Request"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM