mercredi 20 mars 2019

Testing a function based on third party service

I'm trying to figure out how to create unit tests for a function, which behavior is based on a third party service.

Suppose a function like this:

def sync_check():
    delta_secs = 90
    now = datetime.datetime.now().utcnow()
    res = requests.get('<url>')
    alert = SlackAlert()
    last_value = res[-1]['date'] # Last element of the array is the most recent
    secs = (now - last_value).seconds

    if secs >= delta_secs:
        alert.notify("out of sync. Delay: {} seconds".format(secs))
    else:
        alert.notify('in sync')

What's best practice to write unit test for this function? I need to test both if and else branches, but this depends on the third party service.

The first thing that come to my mind is to create a fake webserver and point to that one (changing url) but this way the codebase would include testing logic, like:

if test:
    url = <mock_web_server_url>
else:
    url = <third_party_service_url>

Moreover, unit testing would trigger slack alerts, which doesn't have to happen.

So there I shoulde change again the codebase like:

if secs >= delta_secs:
    if test:
        logging.debug("out of sync alert sent - testing mode")
    else:
        alert.notify("out of sync. Delay: {} seconds".format(secs))
else:
    if test:
        logging.debug("in sync alert sent - testing mode")
    else:
        alert.notify('in sync')

Which I don't really like.

Am I missing any design to solve this problem?

Aucun commentaire:

Enregistrer un commentaire