@@ -47,11 +47,15 @@ class LiveServer(object):
4747
4848 :param app: The application to run.
4949 :param port: The port to run application.
50+ :param wait: The timeout after which test case is aborted if
51+ application is not started.
5052 """
5153
52- def __init__ (self , app , port ):
54+ def __init__ (self , app , port , wait ):
5355 self .app = app
56+ self .host = 'localhost'
5457 self .port = port
58+ self .wait = wait
5559 self ._process = None
5660
5761 def start (self ):
@@ -64,20 +68,35 @@ def worker(app, port):
6468 )
6569 self ._process .start ()
6670
67- # We must wait for the server to start listening with a maximum
68- # timeout of 5 seconds.
69- timeout = 5
70- while timeout > 0 :
71- time .sleep (1 )
72- try :
73- urlopen (self .url ())
74- timeout = 0
75- except :
76- timeout -= 1
71+ keep_trying = True
72+ start_time = time .time ()
73+ while keep_trying :
74+ elapsed_time = (time .time () - start_time )
75+ if elapsed_time > self .wait :
76+ pytest .fail (
77+ "Failed to start the server after {!s} "
78+ "seconds." .format (self .wait )
79+ )
80+ if self ._is_ready ():
81+ keep_trying = False
82+
83+ def _is_ready (self ):
84+ sock = socket .socket (socket .AF_INET , socket .SOCK_STREAM )
85+ try :
86+ sock .connect ((self .host , self .port ))
87+ except socket .error :
88+ ret = False
89+ else :
90+ ret = True
91+ finally :
92+ sock .close ()
93+ return ret
7794
7895 def url (self , url = '' ):
7996 """Returns the complete url based on server options."""
80- return 'http://localhost:%d%s' % (self .port , url )
97+ return 'http://{host!s}:{port!s}{url!s}' .format (
98+ host = self .host , port = self .port , url = url
99+ )
81100
82101 def stop (self ):
83102 """Stop application process."""
@@ -123,7 +142,8 @@ def test_server_is_up_and_running(live_server):
123142 monkeypatch .setitem (app .config , 'SERVER_NAME' ,
124143 _rewrite_server_name (server_name , str (port )))
125144
126- server = LiveServer (app , port )
145+ wait = request .config .getvalue ('live_server_wait' )
146+ server = LiveServer (app , port , wait )
127147 if request .config .getvalue ('start_live_server' ):
128148 server .start ()
129149
0 commit comments