From 1265b2e20b407cd92cd1a978f4d09a2c0d0fb170 Mon Sep 17 00:00:00 2001 From: androiddrew Date: Thu, 7 Sep 2017 18:40:52 -0400 Subject: [PATCH] Added Mock server fixture and initial test --- tests/conftest.py | 36 ++++++++++++++++++++++++++++++++++++ tests/test_mock_server.py | 10 ++++++++++ tests/test_todos.py | 1 + 3 files changed, 47 insertions(+) create mode 100644 tests/conftest.py create mode 100644 tests/test_mock_server.py diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..0457b4d --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,36 @@ +from http.server import BaseHTTPRequestHandler, HTTPServer +import socket +from threading import Thread + +import pytest +import requests + + + +class MockServerRequestHandler(BaseHTTPRequestHandler): + def do_GET(self): + self.send_response(requests.codes.ok) + self.end_headers() + return + + +def get_free_port(): + """Simple function that acquires a port, closes it, and returns what that port numnber was""" + s = socket.socket(socket.AF_INET, type=socket.SOCK_STREAM) + s.bind(('localhost', 0)) + address, port = s.getsockname() + s.close() + return port + +# TODO determine what scope this fixture should have +@pytest.fixture +def mockserver(): + # Setup + mock_server_port = get_free_port() + mock_server = HTTPServer(('localhost', mock_server_port), MockServerRequestHandler) + mock_server_thread = Thread(target=mock_server.serve_forever) + mock_server_thread.setDaemon(True) + mock_server_thread.start() + + return mock_server_port + diff --git a/tests/test_mock_server.py b/tests/test_mock_server.py new file mode 100644 index 0000000..15d6999 --- /dev/null +++ b/tests/test_mock_server.py @@ -0,0 +1,10 @@ +import requests + +def test_request_response(mockserver): + mock_server_port = mockserver + url = 'http://localhost:{port}/users'.format(port=mock_server_port) + + response = requests.get(url) + + assert response.ok + diff --git a/tests/test_todos.py b/tests/test_todos.py index 5e493ab..bcccf57 100644 --- a/tests/test_todos.py +++ b/tests/test_todos.py @@ -70,6 +70,7 @@ def testing_getting_uncompleted_todos_when_todos_is_none(): def test_integration_contract(): + """Test used to maintain the actual vs mocked API response contract""" actual = get_todos() actual_keys = actual.json().pop().keys()