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

Method test_copy_build_request

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

Source from the content-addressed store, hash-verified

318
319 @pytest.mark.skipif(sys.version_info >= (3, 10), reason="fails because of a memory leak that started from 3.12")
320 def test_copy_build_request(self, client: Anthropic) -> None:
321 options = FinalRequestOptions(method="get", url="/foo")
322
323 def build_request(options: FinalRequestOptions) -> None:
324 client_copy = client.copy()
325 client_copy._build_request(options)
326
327 # ensure that the machinery is warmed up before tracing starts.
328 build_request(options)
329 gc.collect()
330
331 tracemalloc.start(1000)
332
333 snapshot_before = tracemalloc.take_snapshot()
334
335 ITERATIONS = 10
336 for _ in range(ITERATIONS):
337 build_request(options)
338
339 gc.collect()
340 snapshot_after = tracemalloc.take_snapshot()
341
342 tracemalloc.stop()
343
344 def add_leak(leaks: list[tracemalloc.StatisticDiff], diff: tracemalloc.StatisticDiff) -> None:
345 if diff.count == 0:
346 # Avoid false positives by considering only leaks (i.e. allocations that persist).
347 return
348
349 if diff.count % ITERATIONS != 0:
350 # Avoid false positives by considering only leaks that appear per iteration.
351 return
352
353 for frame in diff.traceback:
354 if any(
355 frame.filename.endswith(fragment)
356 for fragment in [
357 # to_raw_response_wrapper leaks through the @functools.wraps() decorator.
358 #
359 # removing the decorator fixes the leak for reasons we don't understand.
360 "anthropic/_response.py",
361 # pydantic.BaseModel.model_dump || pydantic.BaseModel.dict leak memory for some reason.
362 "anthropic/_compat.py",
363 # Standard library leaks we don't care about.
364 "/logging/__init__.py",
365 ]
366 ):
367 return
368
369 leaks.append(diff)
370
371 leaks: list[tracemalloc.StatisticDiff] = []
372 for diff in snapshot_after.compare_to(snapshot_before, "traceback"):
373 add_leak(leaks, diff)
374 if leaks:
375 for leak in leaks:
376 print("MEMORY LEAK:", leak)
377 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