MCPcopy Create free account
hub / github.com/anthropics/anthropic-sdk-python / test_copy_build_request

Method test_copy_build_request

tests/test_client.py:283–342  ·  view source on GitHub ↗
(self, client: Anthropic)

Source from the content-addressed store, hash-verified

281
282 @pytest.mark.skipif(sys.version_info >= (3, 10), reason="fails because of a memory leak that started from 3.12")
283 def test_copy_build_request(self, client: Anthropic) -> None:
284 options = FinalRequestOptions(method="get", url="/foo")
285
286 def build_request(options: FinalRequestOptions) -> None:
287 client_copy = client.copy()
288 client_copy._build_request(options)
289
290 # ensure that the machinery is warmed up before tracing starts.
291 build_request(options)
292 gc.collect()
293
294 tracemalloc.start(1000)
295
296 snapshot_before = tracemalloc.take_snapshot()
297
298 ITERATIONS = 10
299 for _ in range(ITERATIONS):
300 build_request(options)
301
302 gc.collect()
303 snapshot_after = tracemalloc.take_snapshot()
304
305 tracemalloc.stop()
306
307 def add_leak(leaks: list[tracemalloc.StatisticDiff], diff: tracemalloc.StatisticDiff) -> None:
308 if diff.count == 0:
309 # Avoid false positives by considering only leaks (i.e. allocations that persist).
310 return
311
312 if diff.count % ITERATIONS != 0:
313 # Avoid false positives by considering only leaks that appear per iteration.
314 return
315
316 for frame in diff.traceback:
317 if any(
318 frame.filename.endswith(fragment)
319 for fragment in [
320 # to_raw_response_wrapper leaks through the @functools.wraps() decorator.
321 #
322 # removing the decorator fixes the leak for reasons we don't understand.
323 "anthropic/_response.py",
324 # pydantic.BaseModel.model_dump || pydantic.BaseModel.dict leak memory for some reason.
325 "anthropic/_compat.py",
326 # Standard library leaks we don't care about.
327 "/logging/__init__.py",
328 ]
329 ):
330 return
331
332 leaks.append(diff)
333
334 leaks: list[tracemalloc.StatisticDiff] = []
335 for diff in snapshot_after.compare_to(snapshot_before, "traceback"):
336 add_leak(leaks, diff)
337 if leaks:
338 for leak in leaks:
339 print("MEMORY LEAK:", leak)
340 for frame in leak.traceback:

Callers

nothing calls this directly

Calls 3

FinalRequestOptionsClass · 0.90
startMethod · 0.45
stopMethod · 0.45

Tested by

no test coverage detected