test_indent.py
Overview
The [test_indent.py](/projects/287/67683) file is a test module designed to verify the behavior of the `orjson` JSON serialization library when used with indentation options. Specifically, it focuses on testing the `OPT_INDENT_2` option, which produces pretty-printed JSON output with an indentation level of 2 spaces. The tests ensure that `orjson`’s indented output is functionally equivalent to Python’s built-in `json.dumps` with `indent=2`, and also verify interactions with other serialization options like sorting keys, converting non-string dictionary keys to strings, and handling datetime objects.
This suite is part of a broader testing framework that uses fixtures loaded from compressed JSON files to validate `orjson`’s formatting against known reference data.
Classes and Methods
Class: TestIndentedOutput
A test class decorated with `@needs_data`, indicating that it requires preloaded test data fixtures for some tests (via the `read_fixture_obj` utility). This class contains multiple test methods that use Python's built-in `assert` statements to validate the correctness of `orjson`’s indented JSON serialization.
Methods
test_equivalent(self)
**Purpose:** Verifies that using `orjson.OPT_INDENT_2` produces JSON output equivalent to Python’s `json.dumps` with `indent=2`.
**Parameters:**
self: The instance of the test class.
**Returns:**
None. Raises an AssertionError if the output differs.
**Implementation Detail:**
Serializes a nested dictionary with
orjson.dumpsusingOPT_INDENT_2.Serializes the same dictionary with
json.dumpsusingindent=2.Compares the byte output of
orjsonwith the UTF-8 encoded string output ofjson.dumps.
**Usage Example:**
test = TestIndentedOutput()
test.test_equivalent()
test_sort(self)
**Purpose:** Checks that `orjson` correctly sorts dictionary keys when combined with indentation.
**Parameters:**
self
**Returns:**
None.
**Details:**
Uses
orjson.OPT_INDENT_2 | orjson.OPT_SORT_KEYSoptions.Serializes a dictionary with keys out of order and asserts that output is sorted and indented.
test_non_str(self)
**Purpose:** Tests the ability of `orjson` to convert non-string dictionary keys (e.g., integers) to strings in the output when using `OPT_NON_STR_KEYS` in combination with indentation.
**Parameters:**
self
**Returns:**
None.
**Details:**
Serializes a dictionary with an integer key using
OPT_INDENT_2 | OPT_NON_STR_KEYS.Ensures the integer key
1appears as the string"1"in the output.
test_options(self)
**Purpose:** Validates combined usage of multiple options including indentation, key sorting, non-string keys, and naive UTC datetime formatting.
**Parameters:**
self
**Returns:**
None.
**Details:**
Serializes a dictionary with integer keys, booleans, and a naive datetime object.
Options used:
OPT_INDENT_2 | OPT_SORT_KEYS | OPT_NON_STR_KEYS | OPT_NAIVE_UTCConfirms that datetime is formatted as an ISO8601 string with UTC offset.
test_empty(self)
**Purpose:** Ensures that empty structures (empty dicts, nested empty lists) are serialized with correct indentation.
**Parameters:**
self
**Returns:**
None.
**Details:**
Serializes a complex nested list/dict structure containing empty collections.
Compares result against a hardcoded indented byte string.
test_twitter_pretty(self)
**Purpose:** Tests pretty-printed output of a real-world large JSON fixture (`twitter.json`).
**Parameters:**
self
**Returns:**
None.
**Details:**
Loads JSON data from a compressed fixture file
twitter.json.xz.Asserts that
orjson.dumpswithOPT_INDENT_2matchesjson.dumpswithindent=2andensure_ascii=False.
test_github_pretty(self)
**Purpose:** Similar to `test_twitter_pretty` but using the `github.json` fixture.
**Parameters:**
self
**Returns:**
None.
test_canada_pretty(self)
**Purpose:** Tests pretty printing on `canada.json` fixture.
test_citm_catalog_pretty(self)
**Purpose:** Tests pretty printing on `citm_catalog.json` fixture.
Implementation Details and Algorithms
The tests leverage bitwise OR to combine multiple
orjsonoption flags.orjson.dumpsreturns a UTF-8 encoded bytes object, whilejson.dumpsreturns a string; comparisons encodejson.dumpsoutput to bytes for equality checks.The datetime serialization test uses the
OPT_NAIVE_UTCoption to serialize naivedatetimeobjects as UTC ISO8601 strings.The test class is decorated with
@needs_datato indicate reliance on external fixture data loaded viaread_fixture_obj, suggesting a custom test setup that injects or prepares data for tests.
Interaction with Other Parts of the System
Utilities: Imports
needs_dataandread_fixture_objfrom.util.needs_datais likely a decorator that prepares test data or fixtures before test execution.read_fixture_objloads and decompresses JSON fixture files (e.g.,twitter.json.xz), providing consistent test inputs.
orjson Library: The main subject under test, providing high-performance JSON serialization with optional formatting features.
Python’s json Module: Used as a baseline for expected output, especially for pretty-printing with indentation.
This file functions primarily as a validation layer ensuring that `orjson`'s indentation and formatting options produce output consistent with the standard library's behavior or expected formatting, including complex real-world JSON datasets.
Usage Example
from test_indent import TestIndentedOutput
test = TestIndentedOutput()
# Run equivalence test
test.test_equivalent()
# Run sort keys and indent test
test.test_sort()
# Run combined options test
test.test_options()
Visual Diagram
classDiagram
class TestIndentedOutput {
+test_equivalent()
+test_sort()
+test_non_str()
+test_options()
+test_empty()
+test_twitter_pretty()
+test_github_pretty()
+test_canada_pretty()
+test_citm_catalog_pretty()
}
TestIndentedOutput ..> needs_data : decorator
TestIndentedOutput ..> read_fixture_obj : uses in fixture tests
TestIndentedOutput ..> orjson : tests serialization
TestIndentedOutput ..> json : compares output
Summary
[test_indent.py](/projects/287/67683) is a focused test suite validating the `orjson` library’s pretty-printing capabilities. It ensures that indentation with two spaces matches Python’s standard library JSON formatting and verifies the correct combination of sorting keys, handling non-string keys, and datetime serialization. It also validates indented output on large, realistic JSON fixtures to detect regressions or formatting inconsistencies. This file is integral in maintaining the correctness and usability of `orjson`’s indentation features within the broader project.