@@ -47,11 +47,15 @@ class LiveServer(object):
47
47
48
48
:param app: The application to run.
49
49
:param port: The port to run application.
50
+ :param wait: The timeout after which test case is aborted if
51
+ application is not started.
50
52
"""
51
53
52
- def __init__ (self , app , port ):
54
+ def __init__ (self , app , port , wait ):
53
55
self .app = app
56
+ self .host = 'localhost'
54
57
self .port = port
58
+ self .wait = wait
55
59
self ._process = None
56
60
57
61
def start (self ):
@@ -64,20 +68,35 @@ def worker(app, port):
64
68
)
65
69
self ._process .start ()
66
70
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
77
94
78
95
def url (self , url = '' ):
79
96
"""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
+ )
81
100
82
101
def stop (self ):
83
102
"""Stop application process."""
@@ -123,7 +142,8 @@ def test_server_is_up_and_running(live_server):
123
142
monkeypatch .setitem (app .config , 'SERVER_NAME' ,
124
143
_rewrite_server_name (server_name , str (port )))
125
144
126
- server = LiveServer (app , port )
145
+ wait = request .config .getvalue ('live_server_wait' )
146
+ server = LiveServer (app , port , wait )
127
147
if request .config .getvalue ('start_live_server' ):
128
148
server .start ()
129
149
0 commit comments