Debian Codegraph @

tests/test_jsonexporter.py

raw
1 import filecmp
2 import os
3 from tempfile import NamedTemporaryFile
4
5 from anytree import AnyNode
6 from anytree.exporter import JsonExporter
7
8 from .helper import eq_
9
10
11 def test_json_exporter():
12 """Json Exporter."""
13 root = AnyNode(id="root")
14 s0 = AnyNode(id="sub0", parent=root)
15 AnyNode(id="sub0B", parent=s0)
16 AnyNode(id="sub0A", parent=s0)
17 s1 = AnyNode(id="sub1", parent=root)
18 AnyNode(id="sub1A", parent=s1)
19 AnyNode(id="sub1B", parent=s1)
20 s1c = AnyNode(id="sub1C", parent=s1)
21 AnyNode(id="sub1Ca", parent=s1c)
22
23 exporter = JsonExporter(indent=2, sort_keys=True)
24 exported = exporter.export(root).splitlines()
25 exported = [e.rstrip() for e in exported] # just a fix for a strange py2x behavior.
26 lines = [
27 "{",
28 ' "children": [',
29 " {",
30 ' "children": [',
31 " {",
32 ' "id": "sub0B"',
33 " },",
34 " {",
35 ' "id": "sub0A"',
36 " }",
37 " ],",
38 ' "id": "sub0"',
39 " },",
40 " {",
41 ' "children": [',
42 " {",
43 ' "id": "sub1A"',
44 " },",
45 " {",
46 ' "id": "sub1B"',
47 " },",
48 " {",
49 ' "children": [',
50 " {",
51 ' "id": "sub1Ca"',
52 " }",
53 " ],",
54 ' "id": "sub1C"',
55 " }",
56 " ],",
57 ' "id": "sub1"',
58 " }",
59 " ],",
60 ' "id": "root"',
61 "}",
62 ]
63 eq_(exported, lines)
64
65 exporter = JsonExporter(indent=2, sort_keys=True, maxlevel=2)
66 exported = exporter.export(root).splitlines()
67 exported = [e.rstrip() for e in exported] # just a fix for a strange py2x behavior.
68 limitedlines = [
69 "{",
70 ' "children": [',
71 " {",
72 ' "id": "sub0"',
73 " },",
74 " {",
75 ' "id": "sub1"',
76 " }",
77 " ],",
78 ' "id": "root"',
79 "}",
80 ]
81
82 eq_(exported, limitedlines)
83
84 try:
85 with NamedTemporaryFile(mode="w+", delete=False) as ref:
86 with NamedTemporaryFile(mode="w+", delete=False) as gen:
87 ref.write("\n".join(lines))
88 exporter.write(root, gen)
89 # on Windows, you must close the files before comparison
90 filecmp.cmp(ref.name, gen.name)
91 finally:
92 os.remove(ref.name)
93 os.remove(gen.name)