|
6 | 6 | import pytest
|
7 | 7 |
|
8 | 8 | import env
|
9 |
| -from pybind11_tests import PYBIND11_REFCNT_IMMORTAL, ConstructorStats, UserType |
| 9 | +from pybind11_tests import ConstructorStats, UserType |
10 | 10 | from pybind11_tests import class_ as m
|
11 | 11 |
|
| 12 | +UINT32MAX = 2**32 - 1 |
| 13 | + |
| 14 | + |
| 15 | +def refcount_immortal(ob: object) -> int: |
| 16 | + if _is_immortal := getattr(sys, "_is_immortal", None): |
| 17 | + return UINT32MAX if _is_immortal(ob) else sys.getrefcount(ob) |
| 18 | + return sys.getrefcount(ob) |
| 19 | + |
12 | 20 |
|
13 | 21 | def test_obj_class_name():
|
14 | 22 | expected_name = "UserType" if env.PYPY else "pybind11_tests.UserType"
|
@@ -382,23 +390,23 @@ def test_brace_initialization():
|
382 | 390 | @pytest.mark.xfail("env.PYPY or env.GRAALPY")
|
383 | 391 | def test_class_refcount():
|
384 | 392 | """Instances must correctly increase/decrease the reference count of their types (#1029)"""
|
385 |
| - from sys import getrefcount |
386 | 393 |
|
387 | 394 | class PyDog(m.Dog):
|
388 | 395 | pass
|
389 | 396 |
|
390 | 397 | for cls in m.Dog, PyDog:
|
391 |
| - refcount_1 = getrefcount(cls) |
| 398 | + refcount_1 = refcount_immortal(cls) |
392 | 399 | molly = [cls("Molly") for _ in range(10)]
|
393 |
| - refcount_2 = getrefcount(cls) |
| 400 | + refcount_2 = refcount_immortal(cls) |
394 | 401 |
|
395 | 402 | del molly
|
396 | 403 | pytest.gc_collect()
|
397 |
| - refcount_3 = getrefcount(cls) |
| 404 | + refcount_3 = refcount_immortal(cls) |
398 | 405 |
|
| 406 | + # Python may report a large value here (above 30 bits), that's also fine |
399 | 407 | assert refcount_1 == refcount_3
|
400 | 408 | assert (refcount_2 > refcount_1) or (
|
401 |
| - refcount_2 == refcount_1 == PYBIND11_REFCNT_IMMORTAL |
| 409 | + refcount_2 == refcount_1 and refcount_1 >= 2**29 |
402 | 410 | )
|
403 | 411 |
|
404 | 412 |
|
|
0 commit comments