Skip to content
Myr

Fixed encoding issues, added timeouts to event waits and refactored Server

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Braulio Valdivielso Martínez · committed by Braulio Valdivielso Martínez · parent 2416563 · Browse files · 1 file+14 added−11 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+14 added−11 removed

  • other:+14 added−11 removed

1 file+14 added−11 removed

modified:testserver/server.py+14 added-11 removed
9 unmodified lines
10 content = ""11 more_to_read = select.select([sock], [], [], timeout)[0]1213 while more_to_read:14 new_content = sock.recv(chunks).decode("utf-8")14 new_content = sock.recv(chunks)1516 if not new_content:17 break18
2 unmodified lines
21 more_to_read = select.select([sock], [], [], timeout)[0] 2223 return content24252627class Server(threading.Thread):28 """ Dummy server using for unit testing """29 WAIT_EVENT_TIMEOUT = 53031 def __init__(self, handler, host='localhost', port=0, requests_to_handle=1, wait_to_close_event=None):32 threading.Thread.__init__(self)33
11 unmodified lines
45 @classmethod46 def text_response_server(cls, text, request_timeout=0.5, **kwargs):47 def text_response_handler(sock):48 request_content = consume_socket_content(sock, timeout=request_timeout)46 sock.send(text.encode())49 sock.send(text.encode('utf-8'))5051 return request_content5253
13 unmodified lines
67 sock = self._create_socket_and_bind()68 # in case self.port = 069 self.port = sock.getsockname()[1]70 self.ready_event.set()68 self._handle_requests_and_close_server(sock)71 self._handle_requests(sock)7273 if self.wait_to_close_event:74 self.wait_to_close_event.wait(self.WAIT_EVENT_TIMEOUT)75 finally:76 self.ready_event.set() # just in case of exception77 sock.close()78 self.stop_event.set()
3 unmodified lines
82 sock.bind((self.host, self.port))83 sock.listen(0)84 return sock8580 def _handle_requests_and_close_server(self, server_sock):86 def _handle_requests(self, server_sock):87 for _ in range(self.requests_to_handle):88 sock = server_sock.accept()[0]89 handler_result = self.handler(sock)9091 self.handler_results.append(handler_result)92 87 if self.wait_to_close_event:88 self.wait_to_close_event.wait()89 93 def __enter__(self):94 self.start()92 self.ready_event.wait()95 self.ready_event.wait(self.WAIT_EVENT_TIMEOUT)96 return self.host, self.port97 98 def __exit__(self, exc_type, exc_value, traceback):99 if exc_type is None:97 self.stop_event.wait()100 self.stop_event.wait(self.WAIT_EVENT_TIMEOUT)101 else:102 if self.wait_to_close_event:100 # avoid server from blocking if an exception is found101 # in the main thread103 # avoid server from waiting for event timeouts 104 # if an exception is found in the main thread 105 self.wait_to_close_event.set() 106 return False # allow exceptions to propagate 107