11import json
22import logging
3+ import time
34from behave import given , when , then , use_step_matcher
45
56import jsocket
@@ -23,14 +24,21 @@ def _process_message(self, obj):
2324
2425@given (r"I start the server" )
2526def start_server (context ):
26- context .jsonserver = MyServer ()
27- context .jsonserver .start ()
27+ # Start a fresh server if one is not present
28+ server = getattr (context , 'jsonserver' , None )
29+ if server is None or not getattr (server , '_isAlive' , False ):
30+ context .jsonserver = MyServer ()
31+ context .jsonserver .start ()
2832
2933
3034@given (r"I connect the client" )
3135def connect_client (context ):
32- context .jsonclient = jsocket .JsonClient ()
33- context .jsonclient .connect ()
36+ # Create a client and connect to the default server
37+ client = getattr (context , 'jsonclient' , None )
38+ if client is None :
39+ context .jsonclient = jsocket .JsonClient ()
40+ if not context .jsonclient .connect ():
41+ raise AssertionError ("client could not connect to server" )
3442
3543
3644@when (r"the client sends the object (\{.*\})" )
@@ -40,6 +48,15 @@ def client_sends_object(context, obj):
4048
4149@when (r"the server sends the object (\{.*\})" )
4250def server_sends_object (context , obj ):
51+ # Ensure a running server and a connected client exist
52+ if not hasattr (context , 'jsonserver' ) or not getattr (context .jsonserver , '_isAlive' , False ):
53+ start_server (context )
54+ if not hasattr (context , 'jsonclient' ):
55+ connect_client (context )
56+ # Wait briefly until the server has an accepted connection
57+ t0 = time .time ()
58+ while not context .jsonserver .connected and (time .time () - t0 ) < 2.0 :
59+ time .sleep (0.05 )
4360 context .jsonserver .send_obj (json .loads (obj ))
4461
4562
@@ -57,7 +74,12 @@ def see_connection(context):
5774
5875@given (r"I stop the server" )
5976def stop_server (context ):
60- context .jsonserver .stop ()
77+ server = getattr (context , 'jsonserver' , None )
78+ if server is None :
79+ # Create a server just to satisfy the step semantics
80+ context .jsonserver = MyServer ()
81+ server = context .jsonserver
82+ server .stop ()
6183
6284
6385@then (r"I see a stopped server" )
@@ -68,4 +90,3 @@ def see_stopped_server(context):
6890@then (r"I close the client" )
6991def close_client (context ):
7092 context .jsonclient .close ()
71-
0 commit comments