test_reentrant.py


Overview

The [test_reentrant.py](/projects/287/67683) file is a minimalistic test module designed to verify the behavior of the `orjson` JSON parsing library under reentrant and recursive conditions. Specifically, it tests whether `orjson.loads()` can handle being called from within a destructor (`__del__` method) of an object and during the parsing of deeply nested JSON arrays.

This file contains a single class `C` with a destructor that triggers `orjson.loads()` on a large string, and a test function `test_reentrant()` which creates an instance of `C` with a self-reference to induce recursive references, deletes it to invoke the destructor, and subsequently runs another `orjson.loads()` on a large nested JSON array. The test is aimed at uncovering issues such as deadlocks, infinite recursion, or crashes caused by reentrant calls to the JSON parser.


Classes and Functions

Class C

class C:
    c: "C"

    def __del__(self):
        orjson.loads('"' + "a" * 10000 + '"')

Description

Attributes

Methods

Usage Example

c = C()
c.c = c  # Creates a cyclic reference
del c    # Triggers __del__, invoking orjson.loads inside the destructor

Function test_reentrant

def test_reentrant():
    c = C()
    c.c = c
    del c

    orjson.loads("[" + "[]," * 1000 + "[]]")

Description

Parameters

Returns

Usage Example

Simply call the function to run the test:

test_reentrant()

Implementation Details and Algorithms


Interaction with Other Parts of the System


Visual Diagram

classDiagram
    class C {
        +c: C
        +__del__()
    }

    class test_reentrant {
        +test_reentrant()
    }

    test_reentrant --> C : creates instance
    test_reentrant --> orjson : calls loads()
    C --> orjson : calls loads() in __del__

Summary

The [test_reentrant.py](/projects/287/67683) file is a focused test module designed to verify the stability and correctness of the `orjson` JSON parsing library under reentrant conditions, specifically when invoked inside an object's destructor and on large nested JSON inputs. It uses Python's garbage collection intricacies to trigger reentrant calls, ensuring that the JSON parser can safely handle such scenarios without deadlocks or crashes.

This file is intended for use in testing environments to validate the robustness of `orjson` integration and does not form part of the main application logic. It provides a valuable edge-case test to prevent subtle bugs related to reentrancy and recursive data structures.