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