test_uuid.py
Overview
The `test_uuid.py` file contains a suite of automated tests designed to validate the behavior, properties, and serialization of UUID (Universally Unique Identifier) objects using Python's built-in `uuid` module. It also verifies how these UUIDs interact with the `orjson` library, a high-performance JSON serializer, particularly focusing on the serialization of standard and subclassed UUIDs.
Primarily, the tests ensure:
The immutability of UUID objects.
Correctness of UUID integer representations.
Proper error handling on invalid UUID integer inputs.
Serialization capabilities and limitations with
orjson.Consistency across different UUID creation methods.
This file uses the `pytest` framework to implement these validations, making it integral to the testing and quality assurance process for any system functionality dependent on UUIDs and their JSON serialization.
Detailed Documentation
Class: TestUUID
This test class groups multiple test methods related to UUID creation, properties, immutability, and serialization behavior.
Method: test_uuid_immutable(self)
**Purpose:** Verify that UUID objects are immutable — their attributes cannot be modified once created.
**Details:**
Attempts to assign a new value to the
intattribute of a UUID instance.Expects
TypeErrorto be raised, confirming immutability.
**Usage Example:**
val = uuid.uuid4()
with pytest.raises(TypeError):
val.int = 1 # This should raise an error
Method: test_uuid_int(self)
**Purpose:** Assert that the `.int` property of a UUID is a 128-bit integer with the expected range and value.
**Parameters:** None **Returns:** None (assertions inside the test)
**Key Checks:**
val.intis an integer type.It fits within the range
[2^64, 2^128)(large enough to be 128-bit).Matches a known constant integer value for a specific UUID string.
Method: test_uuid_overflow(self)
**Purpose:** Ensure that creating a UUID object with an invalid integer (`int` too large or negative) raises a `ValueError`.
**Details:**
Attempts to create UUIDs with
int=2**128(too large) andint=-1(negative).These should raise
ValueErrorexceptions, preventing invalid UUID construction.
Method: test_uuid_subclass(self)
**Purpose:** Test that subclasses of `uuid.UUID` are **not** serializable by `orjson`.
**Implementation Detail:**
Defines a subclass
AUUIDofuuid.UUID.Tries to serialize an instance of this subclass using
orjson.dumps.Expects
orjson.JSONEncodeErrorbecauseorjsononly supports serialization of the baseuuid.UUIDclass.
Method: test_serializes_withopt(self)
**Purpose:** Verify that `orjson.dumps` accepts the deprecated option `OPT_SERIALIZE_UUID` to serialize `uuid.UUID` objects as strings.
**Details:**
Serializes a UUID with the deprecated option.
Checks that the output matches the UUID string representation enclosed in quotes.
Method: test_nil_uuid(self)
**Purpose:** Confirm serialization of the nil UUID (`00000000-0000-0000-0000-000000000000`) produces the expected string.
Method: test_all_ways_to_create_uuid_behave_equivalently(self)
**Purpose:** Check that all documented ways of creating the same UUID value result in equivalent UUID objects that serialize identically.
**Key Points:**
Creates UUIDs from different input formats: string with braces, hex string, URN, bytes, little-endian bytes, fields tuple, and integer.
Serializes all UUIDs as a list and verifies the JSON output matches the expected string representations.
Method: test_serializes_correctly_with_leading_zeroes(self)
**Purpose:** Ensure UUIDs with leading zeros in their integer representation serialize correctly as strings.
Method: test_all_uuid_creation_functions_create_serializable_uuids(self)
**Purpose:** Validate that UUIDs generated by common UUID creation functions (`uuid1`, `uuid3`, `uuid4`, `uuid5`) serialize correctly using `orjson.dumps`.
Important Implementation Details and Algorithms
UUID immutability is enforced by the underlying
uuid.UUIDclass in Python, which disallows attribute assignment after instantiation; the test confirms this behavior.Serialization of UUIDs: The tests focus on
orjson's ability to serialize standard UUID objects as JSON strings. Notably,orjsondoes not serialize subclasses of UUID by default.Handling deprecated options: The test involving
OPT_SERIALIZE_UUIDensures backward compatibility with older serialization options.The tests for equivalence of UUID constructors demonstrate that regardless of input format, the UUID's integer value uniquely identifies it and all forms behave equivalently.
The use of
pytest.raisesis the standard way inpytestto assert that exceptions are raised under erroneous conditions.
Interaction with Other System Components
uuidmodule: This standard Python module provides the UUID implementation tested here.pytestframework: Used for structuring and running tests.orjsonlibrary: A third-party JSON serializer tested for its UUID serialization support.
This file likely resides within a test suite verifying the reliability of UUID handling and serialization logic used by other modules or components that depend on UUIDs for unique identification and JSON data interchange.
Usage Summary
Run this test file using `pytest` to ensure that UUID operations and serialization meet expected behaviors:
pytest test_uuid.py
Visual Diagram
classDiagram
class TestUUID {
+test_uuid_immutable()
+test_uuid_int()
+test_uuid_overflow()
+test_uuid_subclass()
+test_serializes_withopt()
+test_nil_uuid()
+test_all_ways_to_create_uuid_behave_equivalently()
+test_serializes_correctly_with_leading_zeroes()
+test_all_uuid_creation_functions_create_serializable_uuids()
}
Summary
`test_uuid.py` is a comprehensive testing module that validates the fundamental properties and serialization behaviors of UUID objects in Python, ensuring robustness and compatibility within JSON serialization workflows, especially when using `orjson`. The tests cover immutability, integer representation, error handling, subclass behavior, and equivalence of multiple UUID construction methods. This file is essential to maintain correctness where UUIDs serve as identifiers exchanged in JSON payloads.