This repo outlines a few techniques for unit testing external APIs with pytest.
- poetry
- an API key for OpenWeather
git clone https://github.com/jonwhittlestone/today-i-learned.git
cd pytest/api-testing
poetry install
-
In the virtualenv, add API key as env var and run the Flask-based implementation
poetry shell; export API_KEY=changeme; python3 api_testing/__init__.py
visit http://127.0.0.0.1:8000
-
Run tests individually
-
Using mocks, specifically
pytest-mock
export API_KEY=changeme; alias t1="pytest tests -k 'test_retrieve_weather_using_mocks';" t1
-
Using
responses
which interceptsrequests
calls and patches them avoiding the length set up.export API_KEY=changeme; alias t2="pytest tests -k 'test_retrieve_weather_using_responses';" t2
-
Using dependency injection to inject a fake adapter during test time.
This way the behaviour doesn't change if we decide to change the implementation because all we've done is change the adapters (from one that uses
responses
to one that usesurllib
for example)export API_KEY=changeme; alias t3="pytest tests -k 'test_retrieve_weather_using_adapter'"; t3
-
Using
VCR.py
change the casette stored API Key
# cassettes/test_retrieve_weather_using_vcr.yaml - uri: https://api.openweathermap.org/data/2.5/weather?q=London&appid={changeme}&units=metric + uri: https://api.openweathermap.org/data/2.5/weather?q=London&appid={actual_api_key}&units=metric
export API_KEY=changeme; alias t4="pytest tests -k 'test_retrieve_weather_using_vcr'" t4
-