Home > database >  Test an API with Python
Test an API with Python

Time:10-06

I am writing some tests for an API using Python and PyTest.

The tests are something like this:

def test_stackoverflow():
    response = stackoverflow(parameter1, parameter2)
    assert response.status_code == HTTPStatus.OK
    data = response.json()
    assert type(data['name']) is str
    assert data['lastname'] == "Wilson"

which call a function in another file containing the real API call:

def stackoverflow(parameter1, parameter2):
    return my_session.post("/api/endpoint",
                        params={
                            "parameter1": parameter1,
                            "parameter2": parameter2
                        })

This structure has two main problems:

  1. When I write a test I have to remember/recheck the name of the parameters (like name and lastname in the example).
  2. If the name of a parameter changes, I have to manually change it everywhere.

How could I fix these problems?

CodePudding user response:

I had a problem similar to your second. I had to update multiple test scripts with new URLs for each deployed system. I used a PowerShell script to update all the variables in my Python scripts and then to run the tests automatically after. PS executes a global search for variable names and overwrites old vales for new ones in a config file. I'm sure you can accomplish the same thing with Python, but with PS, you can use cmdletbinding to define your function and how you need your parameters to behave.

CodePudding user response:

So I'm not a 100% sure, I understand your problem, but let me state two things:

(1) My function stackoverflow has parameters hardcoded. Can we not change that?

Yes, we can! Read up on the proper usage of kwargs, which introduces key-word-arguments, so that you can formulate your API-calling function can be formulated as follows:

def stackoverflow(**kwargs):
    return my_session.post("/api/endpoint", params=kwargs)

Just, that in this case you would have to call the function as follows:

response = stackoverflow(key1=val1, key2=val2)

which would then pass two query/url-parameters to your API-call, namely key1 and key2 with values val1 and val2, respectively.

(2) I have to fix parameters for every test. Can I not do that globally for all tests that I need?

Yes sir/mam! Using the very useful fixture-decorator can heavily simplify life with defining parameters for wherever you need them.

Little note on the side: try to use isinstance for type-assertions, e.g. isinstance(data['name'], str).

  • Related