Skip to content

Commit 7f2b973

Browse files
committed
test(frozen_dataclass): add example tests for sealable dataclass functionality
1 parent 4a51e69 commit 7f2b973

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
#!/usr/bin/env python3
2+
"""Basic examples of frozen_dataclass_sealable usage.
3+
4+
This file contains examples extracted from the docstring of the
5+
frozen_dataclass_sealable decorator, to demonstrate its functionality with
6+
working code examples.
7+
"""
8+
9+
import pytest
10+
11+
from dataclasses import dataclass, field
12+
from typing import Optional
13+
14+
from libtmux._internal.frozen_dataclass_sealable import (
15+
frozen_dataclass_sealable,
16+
is_sealable,
17+
)
18+
19+
20+
def test_basic_usage():
21+
"""Test basic usage of frozen_dataclass_sealable."""
22+
@frozen_dataclass_sealable
23+
class Config:
24+
name: str
25+
26+
values: dict[str, int] = field(
27+
default_factory=dict,
28+
metadata={"mutable_during_init": True}
29+
)
30+
31+
# Create an instance
32+
config = Config(name="test-config")
33+
assert config.name == "test-config"
34+
35+
# Cannot modify immutable fields
36+
with pytest.raises(AttributeError):
37+
config.name = "modified"
38+
39+
# Can modify mutable fields
40+
config.values["key1"] = 100
41+
assert config.values["key1"] == 100
42+
43+
# Check sealable property
44+
assert is_sealable(config)
45+
46+
# Seal the object
47+
config.seal()
48+
assert hasattr(config, "_sealed") and config._sealed
49+
50+
# Can still modify contents of mutable containers after sealing
51+
config.values["key2"] = 200
52+
assert config.values["key2"] == 200
53+
54+
55+
def test_deferred_sealing():
56+
"""Test deferred sealing with linked nodes."""
57+
@frozen_dataclass_sealable
58+
class Node:
59+
value: int
60+
61+
next_node: Optional['Node'] = field(
62+
default=None,
63+
metadata={"mutable_during_init": True}
64+
)
65+
66+
# Create a linked list (not circular to avoid recursion issues)
67+
node1 = Node(value=1)
68+
node2 = Node(value=2)
69+
node1.next_node = node2
70+
71+
# Verify structure
72+
assert node1.value == 1
73+
assert node2.value == 2
74+
assert node1.next_node is node2
75+
76+
# Verify sealable property
77+
assert is_sealable(node1)
78+
assert is_sealable(node2)
79+
80+
# Seal nodes individually
81+
node1.seal()
82+
node2.seal()
83+
84+
# Verify both nodes are sealed
85+
assert hasattr(node1, "_sealed") and node1._sealed
86+
assert hasattr(node2, "_sealed") and node2._sealed
87+
88+
# Verify immutability after sealing
89+
with pytest.raises(AttributeError):
90+
node1.value = 10
91+
92+
93+
if __name__ == "__main__":
94+
pytest.main(["-xvs", __file__])

0 commit comments

Comments
 (0)