Python requests.post fails in 421

Question:

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).

Asked By: Luís Soares

||

Answers:

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.

Answered By: Luís Soares