We test with external services to check if our code works well when it talks to other programs or websites.
0
0
Testing with external services in PyTest
Introduction
When your app needs to get data from a website or API.
When you want to check if your code handles responses from a payment service.
When your program sends emails through an external email service.
When you want to make sure your app works with a database or cloud service.
When you want to test how your code behaves if the external service is slow or down.
Syntax
PyTest
import pytest import requests from unittest.mock import patch @patch('requests.get') def test_external_service(mock_get): mock_get.return_value.status_code = 200 mock_get.return_value.json.return_value = {'key': 'value'} response = requests.get('https://api.example.com/data') assert response.status_code == 200 assert response.json() == {'key': 'value'}
Use @patch to replace the real external call with a fake one during tests.
This helps tests run fast and not depend on the real service being available.
Examples
This example mocks a POST request to an external service and checks the response code.
PyTest
from unittest.mock import patch @patch('requests.post') def test_post_service(mock_post): mock_post.return_value.status_code = 201 response = requests.post('https://api.example.com/create') assert response.status_code == 201
This test calls the real service but is skipped if the service is not available.
PyTest
import pytest import requests @pytest.mark.skip(reason='External service not available') def test_real_service_call(): response = requests.get('https://api.example.com/data') assert response.status_code == 200
Sample Program
This test replaces the real HTTP GET call with a fake one that returns a fixed response. It then checks if the code correctly handles that response.
PyTest
import pytest import requests from unittest.mock import patch @patch('requests.get') def test_fetch_data(mock_get): # Setup mock response mock_get.return_value.status_code = 200 mock_get.return_value.json.return_value = {'name': 'Test User', 'id': 123} # Call the function that uses requests.get response = requests.get('https://api.example.com/user') # Check the response assert response.status_code == 200 assert response.json() == {'name': 'Test User', 'id': 123}
OutputSuccess
Important Notes
Always mock external services in tests to avoid slow or unreliable tests.
Use unittest.mock.patch to replace external calls with fake responses.
Test how your code handles errors like timeouts or bad responses from external services.
Summary
Testing with external services means faking those services during tests.
This makes tests faster and more reliable.
Use mocking tools like patch to do this easily.