Engineering
15 min read
Pytest/Unittest: Listing common cases in Testing your Code
H
Hemachandra Routhu
Project Leader
Published On
April 25, 2025
Testing Checklist
Pytest & Unittest Common Cases
Introduction
Many articles have already been written about Pytest and unittest. This guide serves as a quick checklist or a reference for common situations you'll encounter while testing your Python code.
Unittest
Available natively in Python. Inspired by JUnit, it follows the xUnit style where test cases are organized into classes derived from unittest.TestCase.
Pytest
A popular third-party framework that makes testing simpler and more expressive. It supports fixtures, plain assert statements, and powerful parameterization.
Installation
terminal
python -m pip install pytest pytest-mock requests requests_mockCommon Cases
1. Using requests_mock as a Context Manager
import requests_mock
from main import process_get_request
def test_process_get_request():
url = 'https://api.github.com'
with requests_mock.Mocker() as mocker:
mock_response = {"key": "value"}
mocker.get(url, json=mock_response, status_code=200)
result = process_get_request(url)
assert result == {"key": "value"}2. Using the Mocker Fixture
def test_process_get_request_with_mocker(mocker):
mock_response = mocker.Mock(status_code=200)
mock_response.json.return_value = {"key": "value"}
mocker.patch("requests.get", return_value=mock_response)
result = process_get_request('https://api.github.com')
assert result == {"key": "value"}3. Parameterize for Multiple Scenarios
@pytest.mark.parametrize(
"url, expected_status, expected_result",
[
("https://api.github.com/data", 200, {"key": "value"}),
("https://api.github.com/404", 404, None),
],
)
def test_process_get_request(url, expected_status, expected_result):
with requests_mock.Mocker() as mocker:
mocker.get(url, json=expected_result, status_code=expected_status)
result = process_get_request(url)
assert result == expected_result4. Patching Methods with patch.object
def test_search_repo_with_patch_object():
search_repo_obj = SearchRepo()
with unittest.mock.patch.object(search_repo_obj, "call_http_class") as mock_call:
mock_call.return_value = {"repos": ["repo1", "repo2"]}
result = search_repo_obj.search_repo_with_name('url', "repo2")
assert result is True5. Testing if an Exception occurred
def test_exception_raised():
with pytest.raises(ValueError, match="No response received from the API"):
trigger_error_condition()Until then, your friend here, Hemachandra, is signing off…
For more courses, visit my website here.
Stay ahead of the curve
Get the latest technical insights on Python, Security, and Cloud Architecture delivered to your inbox.
Spread the Word
Browse More Articles