This is how I code my unit test:
def test_valid_number():
check = requests.get("http://testing/validateNumber/021844223")
assert True
def test_invalid_number():
check = requests.get("http://testing/validateNumber/02188441")
assert False
My questions are:
How to do assert (with pytest) correctly to check an API response? The first function is to check valid number and it returns result:
{"header":[{"STUDENTNUM":"P56219","STUDENTNAME":"GOLDIE",..... }
The second function is to check invalid number with the expected return:
{"header":[],"headercount":0,"offers":[]}
Pytest provides a fixture monkeypatch
and you can make use of it
def test_valid_number(monkeypatch):
def patched_get():
return {"header":[{"STUDENTNUM":"P56219","STUDENTNAME":"GOLDIE"}
monkeypatch.setattr(requests, 'get', patched_get)
assert check == {"header":[{"STUDENTNUM":"P56219","STUDENTNAME":"GOLDIE"}
To read YAML files, you need PyYAML. Install it with pip
.
import yaml
with open("example.yml", "r") as f:
test_data = yaml.load(f)
def test_valid_number():
response = requests.get(test_data['url']).json()
assert response == test_data['expected']
And the YAML file would look like this:
url: "http://testing/validateNumber/021844223"
expected:
header:
-
STUDENTNUM: "P56219"
STUDENTNAME: "GOLDIE"
......