-
-
Notifications
You must be signed in to change notification settings - Fork 113
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Cache generated un/structure functions using linecache
- Loading branch information
Showing
3 changed files
with
156 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
"""Tests for functionality from the gen module.""" | ||
import linecache | ||
from traceback import format_exc | ||
|
||
from attr import define | ||
|
||
from cattr import GenConverter | ||
from cattr.gen import make_dict_structure_fn, make_dict_unstructure_fn | ||
|
||
|
||
def test_structure_linecache(): | ||
"""Linecaching for structuring should work.""" | ||
|
||
@define | ||
class A: | ||
a: int | ||
|
||
c = GenConverter() | ||
try: | ||
c.structure({"a": "test"}, A) | ||
except ValueError: | ||
res = format_exc() | ||
assert "'a'" in res | ||
|
||
|
||
def test_unstructure_linecache(): | ||
"""Linecaching for unstructuring should work.""" | ||
|
||
@define | ||
class Inner: | ||
a: int | ||
|
||
@define | ||
class Outer: | ||
inner: Inner | ||
|
||
c = GenConverter() | ||
try: | ||
c.unstructure(Outer({})) | ||
except AttributeError: | ||
res = format_exc() | ||
assert "'a'" in res | ||
|
||
|
||
def test_no_linecache(): | ||
"""Linecaching should be disableable.""" | ||
|
||
@define | ||
class A: | ||
a: int | ||
|
||
c = GenConverter() | ||
before = len(linecache.cache) | ||
c.structure(c.unstructure(A(1)), A) | ||
after = len(linecache.cache) | ||
|
||
assert after == before + 2 | ||
|
||
@define | ||
class B: | ||
a: int | ||
|
||
before = len(linecache.cache) | ||
c.register_structure_hook( | ||
B, make_dict_structure_fn(B, c, _cattrs_use_linecache=False) | ||
) | ||
c.register_unstructure_hook( | ||
B, make_dict_unstructure_fn(B, c, _cattrs_use_linecache=False) | ||
) | ||
c.structure(c.unstructure(B(1)), B) | ||
|
||
assert len(linecache.cache) == before |