Debian Codegraph @

tests/config/test_json.py

raw symbols SCIP
1 import json
2 from pathlib import Path
3 from textwrap import dedent
4
5 import pytest
6
7 from cyclopts import App, CycloptsError
8 from cyclopts.config._json import Json
9
10
11 def test_config_json(tmp_path):
12 fn = tmp_path / "test.yaml"
13 fn.write_text(
14 dedent(
15 """\
16 {
17 "foo": {
18 "key1": "foo1",
19 "key2": "foo2",
20 "function1": {
21 "key1": "bar1",
22 "key2": "bar2"
23 }
24 }
25 }
26 """
27 )
28 )
29 config = Json(fn)
30 assert config.config == {
31 "foo": {
32 "key1": "foo1",
33 "key2": "foo2",
34 "function1": {
35 "key1": "bar1",
36 "key2": "bar2",
37 },
38 }
39 }
40
41
42 """
43 Test file-caching and chdir after app has been instantiated. See discussion:
44 https://github.com/BrianPugh/cyclopts/issues/309
45 """
46
47 app = App(config=Json("config.json"), result_action="return_value")
48
49
50 @app.command
51 def create(name: str, age: int):
52 print(f"{name} is {age} years old.")
53
54
55 @pytest.fixture(autouse=True)
56 def chdir_to_tmp_path(tmp_path, monkeypatch):
57 monkeypatch.chdir(tmp_path)
58
59
60 @pytest.fixture
61 def config_path(tmp_path):
62 return tmp_path / "config.json"
63
64
65 def test_config_1(config_path, capsys, mocker):
66 with config_path.open("w") as f:
67 json.dump({"create": {"name": "Alice", "age": 30}}, f)
68
69 json_config = app.config[0]
70 spy_load_config = mocker.patch.object(json_config, "_load_config", wraps=json_config._load_config) # pyright: ignore[reportAttributeAccessIssue]
71 app("create")
72 assert capsys.readouterr().out == "Alice is 30 years old.\n"
73 assert spy_load_config.call_count == 1
74
75 # Ensure that it doesn't get called again because the file hasn't changed.
76 app("create")
77 assert capsys.readouterr().out == "Alice is 30 years old.\n"
78 assert spy_load_config.call_count == 1
79
80 # If we modify the file, then it should get loaded again.
81 with config_path.open("w") as f:
82 json.dump({"create": {"name": "Bob", "age": 40}}, f)
83
84 app("create")
85 assert capsys.readouterr().out == "Bob is 40 years old.\n"
86 assert spy_load_config.call_count == 2
87
88
89 def test_config_2(config_path, capsys):
90 with config_path.open("w") as f:
91 json.dump({"create": {"name": "Bob", "age": 40}}, f)
92
93 app("create")
94 assert capsys.readouterr().out == "Bob is 40 years old.\n"
95
96
97 def test_config_invalid_json(tmp_path, console):
98 Path("config.json").write_text('{"this is": broken}')
99
100 with pytest.raises(CycloptsError), console.capture() as capture:
101 app("create", error_console=console, exit_on_error=False)
102
103 actual = capture.get()
104 expected = dedent(
105 """\
106 ╭─ Error ────────────────────────────────────────────────────────────╮
107 │ JSONDecodeError: │
108 │ {"this is": broken} │
109 │ ^ │
110 │ Expecting value: line 1 column 13 (char 12) │
111 ╰────────────────────────────────────────────────────────────────────╯
112 """
113 )
114 assert actual == expected