diff --git a/README.md b/README.md index 0a579ee..0664704 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,3 @@ # apitesting +A sample project illustrating how to write tests against nd external APIa \ No newline at end of file diff --git a/apitesting/__init__.py b/apitesting/__init__.py new file mode 100644 index 0000000..a035495 --- /dev/null +++ b/apitesting/__init__.py @@ -0,0 +1 @@ +BASE_URL = 'http://jsonplaceholder.typicode.com' \ No newline at end of file diff --git a/apitesting/services.py b/apitesting/services.py new file mode 100644 index 0000000..45949b3 --- /dev/null +++ b/apitesting/services.py @@ -0,0 +1,16 @@ +from urllib.parse import urljoin + +import requests + +from apitesting import BASE_URL + +TODOS_URL = urljoin(BASE_URL, 'todos') + + +def get_todos(): + """Returns a list of JSON todo elements""" + response = requests.get(TODOS_URL) + if response.ok: + return response + else: + return None diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_todos.py b/tests/test_todos.py new file mode 100644 index 0000000..c9b9499 --- /dev/null +++ b/tests/test_todos.py @@ -0,0 +1,39 @@ +from unittest.mock import Mock, patch +import pytest + +from apitesting.services import get_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