Skip to content

Commit 641f774

Browse files
committed
Move away from timeout
This commit changes the polling approach to a check against the list of supported test cases - if a match is not found with the currently available data, the service waits for more. Signed-off-by: Ionut Mihalcea <[email protected]>
1 parent 2d6d478 commit 641f774

File tree

1 file changed

+30
-20
lines changed

1 file changed

+30
-20
lines changed

parsec_mock/parsec_mock.py

+30-20
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44

55
import socket
66
import os
7-
import sys
87
from os import listdir
98
from os.path import isfile, join
109

@@ -42,30 +41,41 @@ def run_test(test_folder, parsec_socket):
4241
sock.listen(1)
4342

4443
while True:
44+
print("Waiting for connections", flush=True)
4545
connection, client_addr = sock.accept()
4646
try:
47+
print("Connection received from {}".format(client_addr), flush=True)
48+
# Optionally reduce the default connection timeout
49+
# connection.settimeout(10)
4750
received_data = connection.recv(4096)
48-
all_received_data = received_data
49-
# Keep polling the connection until there's no more to read
50-
# for 0.5s.
51-
connection.settimeout(0.5)
52-
while True:
53-
try:
54-
received_data = connection.recv(4096)
55-
all_received_data += received_data
56-
except socket.timeout:
57-
print("Finished reading from socket")
51+
all_received_data = bytearray()
52+
# Read the socket in cycle until we either
53+
# - receive a correct command or
54+
# - fail to receive any data
55+
while received_data:
56+
all_received_data += received_data
57+
b64_received_data = base64.b64encode(all_received_data).decode("ascii")
58+
if b64_received_data in test_cases:
59+
(name, test_case) = test_cases[b64_received_data]
60+
print(
61+
"Received expected request for test case {}".format(name),
62+
flush=True,
63+
)
64+
bin_response = base64.b64decode(test_case.test_data.response)
65+
connection.sendall(bin_response)
5866
break
59-
b64_received_data = base64.b64encode(all_received_data).decode("ascii")
60-
if b64_received_data in test_cases:
61-
(name, test_case) = test_cases[b64_received_data]
62-
print("Received expected request for test case {}".format(name))
63-
bin_response = base64.b64decode(test_case.test_data.response)
64-
connection.sendall(bin_response)
65-
else:
66-
print("Received unexpected request {}".format(b64_received_data))
67+
68+
print(
69+
"Received unexpected request {}".format(b64_received_data),
70+
flush=True,
71+
)
72+
print("Continue receiving", flush=True)
73+
received_data = connection.recv(4096)
74+
75+
if not received_data:
76+
print("No correct command received. No more data to read", flush=True)
6777
finally:
68-
sys.stdout.flush()
78+
print("Closing connection", flush=True)
6979
connection.close()
7080

7181

0 commit comments

Comments
 (0)