How to simulate timeout response

Question:

I’m creating a Python script that is always checking if a webapp is ok, because it was usual to send timeout response to several requests.

This script uses httplib:

conn = httplib.HTTPConnection("10.255.255.1")
conn.request("HEAD", "/")
ping = conn.getresponse()

Then simply analyses the http code returned.

I do not control the webapp, so I can’t create a endpoint that would return whatever I want, so my question is: How can I simulate that I’ve received a timeout?

Asked By: pedrorijo91

||

Answers:

You can simulate some httplib errors by looking up some of the exceptions at here (specifically, look at the exceptions).

Very surprisingly, I noticed the timeout it throws is a socket.timeout; from a different package. Actually, I discovered this by giving an unrealistically small timeout as argument to httplib.HTTPConnection of 0.0001 seconds.

Thus, you can simulate the error by raising the socket.timeout:

def requestResultingInTimeout():
    # Pretend to request
    raise socket.timeout

Don’t forget to import socket though.

You might handle it like such:

from socket import timeout
try:
    requestResultingInTimeout()
except timeout:
    print("Now that I got a timeout, I'll print this message instead")
Answered By: PascalVKooten

The more modern approach is to use responses library:

def call_some_api(agrs):
    # here prepare request payload/auth
    try:
       response = requests.post(
            'https://some-api.com/path/',
            headers=headers,
            data=payload,
            timeout=60
       )
    except ConnectTimeout as error:
       # handle exception if needed

tests:

import responses
from requests.exceptions import ReadTimeout, ConnectTimeout

from my_app import call_some_api

@responses.activate
def test_error_timeout(self):
    """test time-out exception handling"""
    responses.add(
        responses.POST,
        'https://some-api.com/path/',
        body=ConnectTimeout(),
    )
    result = call_some_api(test_agrs) 
    # here is the assertion of results of your code 
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.