From 897a3c19b822fe6bbd542a83a6df9ce0c9203f57 Mon Sep 17 00:00:00 2001 From: Tobias Persson Date: Thu, 15 Oct 2020 15:24:55 +0200 Subject: [PATCH] Fix problem with tests failing sometimes Added a connectivity waiter for the webserver to make sure it is ready for the test cases to use. --- tests/conftest.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/tests/conftest.py b/tests/conftest.py index d019cf6..6107b50 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -17,12 +17,20 @@ """Pytest configuration.""" import os import threading +import time +import logging import pytest +from requests.exceptions import HTTPError +from tests.lib.query_handler import GraphQLQueryHandler from eiffel_graphql_api.graphql.api import APP from eiffel_graphql_api.graphql.db.database import get_database from eiffel_graphql_api.graphql.db.database import get_client +logging.basicConfig(level=logging.DEBUG) +LOGGER = logging.getLogger(__name__) + + @pytest.fixture def mock_mongo(): """Inject a MongoDB client connected to a mock server. @@ -39,6 +47,26 @@ def start(): APP.run("127.0.0.1", 12345) +def wait_for_webserver_connection(): + """Wait for the webserver to respond to HTTP requests.""" + LOGGER.info("Testing for webserver connectivity.") + query_handler = GraphQLQueryHandler("http://127.0.0.1:12345/graphql") + timeout = time.time() + 30 + while time.time() < timeout: + try: + query_handler.execute("{nothing}") + LOGGER.info("Up and running") + return + except HTTPError: # BadRequest means the webserver came up. + LOGGER.info("Up and running") + return + except Exception as exception: # pylint: disable=broad-except + LOGGER.error("%r", exception) + LOGGER.warning("Connection could not be established. Trying again in 1s..") + time.sleep(1) + raise TimeoutError("Timeout waiting for the webserver to start.") + + @pytest.fixture(scope="session", autouse=True) def start_server( request, @@ -48,6 +76,7 @@ def start_server( thread = threading.Thread(target=start) thread.daemon = True thread.start() + wait_for_webserver_connection() client.drop_database(os.getenv("MONGODB_DATABASE")) def start_server_fin(): # pylint:disable=unused-variable