from unittest.mock import Mock, patch import pytest from apitesting.services import get_todos, get_uncompleted_todos def test_request_response(): with patch('apitesting.services.requests.get') as mock_get: mock_get.return_value.ok = True response = get_todos() assert response is not None def test_getting_todos_when_response_is_ok(): todos = [{ 'userId': 1, 'id': 1, 'title': 'Make the bed', 'completed': False }] with patch('apitesting.services.requests.get') as mock_get: mock_get.return_value.ok = True mock_get.return_value.json.return_value = todos response = get_todos() assert response is not None assert response.json() == todos def testing_getting_todos_when_response_is_not_ok(): with patch('apitesting.services.requests.get') as mock_get: mock_get.return_value.ok = False response = get_todos() assert response is None def test_getting_uncompleted_todos_when_todos_is_not_none(): todo1 = { 'userId': 1, 'id': 1, 'title': 'Make the bed', 'completed': False } todo2 = { 'userId': 1, 'id': 2, 'title': 'Walk the dog', 'completed': True } with patch('apitesting.services.get_todos') as mock_get_todos: mock_get_todos.return_value = Mock() mock_get_todos.return_value.json.return_value = [todo1, todo2] uncompleted_todos = get_uncompleted_todos() assert mock_get_todos.called def testing_getting_uncompleted_todos_when_todos_is_none(): with patch('apitesting.services.get_todos') as mock_get_todos: mock_get_todos.return_value = None uncompleted_todos = get_uncompleted_todos() assert mock_get_todos.called assert uncompleted_todos == [] def test_integration_contract(): actual = get_todos() actual_keys = actual.json().pop().keys() with patch('apitesting.services.requests.get') as mock_get: mock_get.return_value.ok = True mock_get.return_value.json.return_value = [{ 'userId': 1, 'id': 1, 'title': 'Make the bed', 'completed': False }] mocked = get_todos() mocked_keys = mocked.json().pop().keys() assert set(actual_keys) == set(mocked_keys)