Search code examples
pythonpython-requestspytesthttpretty

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 (e.g. 420, 500).


Solution

  • After hours of debugging, I discovered that HTTPretty did not support 421. I created a PR but meanwhile, this is the workaround:

    from httpretty.http import STATUSES
    
    STATUSES[421] = "Misdirected Request"
    

    Update: PR is merged.