def test_is_readable(self, mock_selector): mock_fileobj = unittest.mock.Mock() mock_selector = mock_selector.return_value.__enter__.return_value mock_selector.register = unittest.mock.Mock() # NB: the return value should actually be List[Tuple[SelectorKey, Events]], but our code only # cares that _some_ event happened so we choose a simpler mock here. See # https://docs.python.org/3/library/selectors.html#selectors.BaseSelector.select. mock_selector.select = unittest.mock.Mock(return_value=[(1, "")]) self.assertTrue(is_readable(mock_fileobj, timeout=0.1)) mock_selector.select = unittest.mock.Mock(return_value=[]) self.assertFalse(is_readable(mock_fileobj, timeout=0.1))
def handle_request(self): """Override of TCPServer.handle_request() that provides locking. Calling this method has the effect of "maybe" (if the socket does not time out first) accepting a request and (because we mixin in ThreadingMixIn) spawning it on a thread. It should always return within `min(self.timeout, socket.gettimeout())`. N.B. Most of this is copied verbatim from SocketServer.py in the stdlib. """ timeout = self.socket.gettimeout() if timeout is None: timeout = self.timeout elif self.timeout is not None: timeout = min(timeout, self.timeout) if not is_readable(self, timeout=timeout): self.handle_timeout() return # After select tells us we can safely accept, guard the accept and request # handling with the lifecycle lock to avoid abrupt teardown mid-request. with self.lifecycle_lock(): self._handle_request_noblock()