From 1e45aa5de9ff58f632ef1fc7d5cc20eefdcd43bc Mon Sep 17 00:00:00 2001
From: Fabio Manganiello <fabio@manganiello.tech>
Date: Thu, 4 Jan 2024 23:24:25 +0100
Subject: [PATCH] A more robust logic to wait for the app to start in the
 tests.

---
 tests/conftest.py | 33 +++++++++++++++++++++++++++------
 1 file changed, 27 insertions(+), 6 deletions(-)

diff --git a/tests/conftest.py b/tests/conftest.py
index 9e3013ddb..c8c50a94c 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -4,12 +4,13 @@ import time
 from threading import Thread
 
 import pytest
+import requests
 
 from platypush import Application, Config
 
 from .utils import config_file, set_base_url
 
-app_start_timeout = 5
+app_start_timeout = 15
 
 
 def clear_loggers():
@@ -25,6 +26,30 @@ def clear_loggers():
             logger.removeHandler(handler)
 
 
+def _wait_for_app(app: Application, timeout: int = app_start_timeout):
+    logging.info('Waiting for the app to start')
+    start_time = time.time()
+    http = None
+    success = False
+
+    while not http and time.time() - start_time < timeout:
+        http = (app.backends or {}).get('http')
+        time.sleep(1)
+
+    assert http, f'HTTP backend not started after {timeout} seconds'
+
+    while not success and time.time() - start_time < timeout:
+        try:
+            response = requests.get(f'http://localhost:{http.port}/')
+            response.raise_for_status()
+            success = True
+        except Exception as e:
+            logging.debug('App not ready yet: %s', e)
+            time.sleep(1)
+
+    assert success, f'App not ready after {timeout} seconds'
+
+
 @pytest.fixture(scope='session', autouse=True)
 def app():
     logging.info('Starting Platypush test service')
@@ -37,11 +62,7 @@ def app():
         redis_port=16379,
     )
     Thread(target=_app.run).start()
-    logging.info(
-        'Sleeping %d seconds while waiting for the daemon to start up',
-        app_start_timeout,
-    )
-    time.sleep(app_start_timeout)
+    _wait_for_app(_app)
     yield _app
 
     logging.info('Stopping Platypush test service')