diff --git a/tests/test_proxy.py b/tests/test_proxy.py index 21c9c43..9fb1bfa 100644 --- a/tests/test_proxy.py +++ b/tests/test_proxy.py @@ -93,6 +93,7 @@ class FakeAi: self.slots = {b.key: SimpleNamespace(backend=b) for b in backends} self.up = {b.key: True for b in backends} self.calls = [] + self.pending = 0 # claims without a matching release: handler threads still working self.error = None self.wait_for_client = False # act like a claim waiting for the other server @@ -108,9 +109,11 @@ class FakeAi: if gone(): raise RouteError("while waiting for Strata to finish", CLIENT_GONE) time.sleep(0.05) + self.pending += 1 return self.slots[key].backend def release(self, key): + self.pending -= 1 self.calls.append(("release", key)) @@ -142,19 +145,37 @@ class ProxyTest(unittest.TestCase): def setUp(self): self.upstream.requests.clear() self.ai.calls.clear() + self.ai.pending = 0 self.ai.up = {"strata": True, "llama": True} self.ai.error = None self.ai.wait_for_client = False self.llama.port = self.upstream.port self.upstream.release_slow.clear() + def tearDown(self): + self.settle() # no handler thread may still append to ai.calls for the next test + + def settle(self, timeout=5): + """Wait until every claimed request has been released. + + The proxy's handler thread records release() after the client already has its reply + (and http.client closes the connection before that), so assertions on ai.calls must + wait for the bookkeeping instead of racing it. + """ + deadline = time.monotonic() + timeout + while self.ai.pending > 0 and time.monotonic() < deadline: + time.sleep(0.01) + self.assertEqual(self.ai.pending, 0, f"unfinished claims: {self.ai.calls}") + def request(self, method, path, body=None, headers=None, chunked=False): connection = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10) try: base = {"Host": f"127.0.0.1:{self.port}", **(headers or {})} connection.request(method, path, body=body, headers=base, encode_chunked=chunked) response = connection.getresponse() - return response.status, dict(response.getheaders()), response.read() + data = response.read() + self.settle() + return response.status, dict(response.getheaders()), data finally: connection.close()