Reputation: 33
Suppose there are 2 endpoints to be tested.
Endpoint 1 returns data that needs to be used in a request to endpoint 2.
How to get 2 endpoints tested efficiently?
# file_1.py
def test_endpoint_1():
r = requests.get(...)
assert r.status_code == 200
maybe some JSON Schema validation
return r
# file_2.py
from file_1 import test_endpoint_1
def test_endpoint_2():
needed_data = test_endpoint_1()
r = requests.get(..., payload=needed_data.json())
assert r.status_code == 200
maybe some JSON Schema validation
Above approach kinda works but if I execute the test suite we are testing endpoint_1 twice. I could change the name of test_endpoint_1() to avoid that but maybe there is an easier and more elegant way?
Upvotes: 1
Views: 233
Reputation: 3735
Generally, we "assume" that dependencies are working correctly. In this case, keep it simple and create an hardcoded value in the test.
# file_2.py
def test_endpoint_2():
needed_data = "JSON" # valid return example from test_endpoint_1
r = requests.get(..., payload=needed_data)
assert r.status_code == 200
maybe some JSON Schema validation
If you need this value in many tests, create a fixture instead. This will allows you to edit the "valid value" for endpoint_2 in one place instead of changing it in every tests that depend on it.
I advise you to put your fixtures in a conftest.py
file. This is explained here.
# conftest.py
import pytest
@pytest.fixture
def endpoint_1_value_200():
return "JSON"
# file_2.py
def test_endpoint_2(endpoint_1_value_200):
r = requests.get(..., payload=endpoint_1_value_200)
assert r.status_code == 200
maybe some JSON Schema validation
Upvotes: 0
Reputation: 530853
Accessing endpoint1 is just one way to get a suitable payload for endpoint2. Another is to just provide a hard-coded payload.
# file_2.py
def test_endpoint_2():
needed_data = {"foo": "bar"} # Whatever is appropriate
r = requests.get(..., payload=needed_data.json())
assert r.status_code == 200
maybe some JSON Schema validation
Upvotes: 1
Reputation: 36
Just put it in a separate function :
def check_endpoint_1():
r = requests.get(...)
assert r.status_code == 200
maybe some JSON Schema validation
return r
def test_endpoint_1():
check_endpoint_1()
def test_endpoint_2():
needed_data = check_endpoint_1()
r = requests.get(..., payload=needed_data.json())
assert r.status_code == 200
maybe some JSON Schema validation
Upvotes: 0