Debian Codegraph @

docs/source/cookbook/unit_testing.rst

raw
1 ============
2 Unit Testing
3 ============
4 It is important to have unit-tests to verify that your CLI is behaving correctly.
5 For unit-testing, we will be using the defacto-standard python unit-testing library, pytest_.
6 This section demonstrates some common scenarios you may encounter when unit-testing your CLI app.
7
8 Lets make a small application that checks PyPI_ if a library name is available:
9
10 .. code-block:: python
11
12 # pypi_checker.py
13 import sys
14 import urllib.error
15 import urllib.request
16 import cyclopts
17
18 def _check_pypi_name_available(name):
19 try:
20 urllib.request.urlopen(f"https://pypi.org/pypi/{name}/json")
21 except urllib.error.HTTPError as e:
22 if e.code == 404:
23 return True # Package does not exist (name is available)
24 return False # Package exists (name is not available)
25
26 app = cyclopts.App(
27 config=[
28 cyclopts.config.Env("PYPI_CHECKER_"),
29 cyclopts.config.Json("config.json"),
30 ],
31 )
32
33 @app.default
34 def pypi_checker(name: str, *, silent: bool = False) -> bool:
35 """Check if a package name is available on PyPI.
36
37 Returns True if available; False otherwise.
38
39 Parameters
40 ----------
41 name: str
42 Name of the package to check.
43 silent: bool
44 Do not print anything to stdout.
45 """
46 is_available = _check_pypi_name_available(name)
47 if not silent:
48 if is_available:
49 print(f"{name} is available.")
50 else:
51 print(f"{name} is not available.")
52 return is_available
53
54 if __name__ == "__main__":
55 app()
56
57 Running the app from the console:
58
59 .. code-block:: console
60
61 $ python pypi_checker.py --help
62 Usage: pypi_checker COMMAND [ARGS] [OPTIONS]
63
64 Check if a package name is available on PyPI.
65
66 Returns True if available; False otherwise.
67
68 ╭─ Commands ────────────────────────────────────────────────────────────────────────────────────────╮
69 │ --help -h Display this message and exit. │
70 │ --version Display application version. │
71 ╰───────────────────────────────────────────────────────────────────────────────────────────────────╯
72 ╭─ Parameters ──────────────────────────────────────────────────────────────────────────────────────╮
73 │ * NAME --name Name of the package to check. [env var: PYPI_CHECKER_NAME] [required] │
74 │ --silent --no-silent Do not print anything to stdout. [env var: PYPI_CHECKER_SILENT] │
75 │ [default: False] │
76 ╰───────────────────────────────────────────────────────────────────────────────────────────────────╯
77
78 $ python pypi_checker.py cyclopts
79 cyclopts is not available.
80
81 $ python pypi_checker.py cyclopts --silent
82 $ echo $? # Check the exit code of the previous command.
83 1
84
85 $ python pypi_checker.py the-next-big-project
86 the-next-big-project is available.
87 $ echo $? # Check the exit code of the previous command.
88 0
89
90 We will slowly introduce unit-testing concepts and build up a fairly comprehensive set of unit-tests for this application.
91
92 -------
93 Mocking
94 -------
95 First off, it's good code-hygiene to separate "business logic" from "user interface."
96 In this example, that means putting all the actual logic of determining whether or not a package name is available into the ``_check_pypi_name_available`` function, and putting all of the CLI logic (like printing to ``stdout`` and exit-codes) in the Cyclopts-decorated function ``pypi_checker``.
97 This makes it easier to unit-test the app because it allows us to `mock <https://docs.python.org/3/library/unittest.mock.html>`_ out portions of our app, allowing us to isolate our CLI unit-tests to just the CLI components.
98
99 We can use `pytest-mock`_ to simplify mocking ``_check_pypi_name_available``. Let's define a `fixture`_ that declares this mock.
100
101 .. code-block:: python
102
103 # test.py
104 import pytest
105 from pypi_checker import app
106
107 @pytest.fixture
108 def mock_check_pypi_name_available(mocker):
109 return mocker.patch("pypi_checker._check_pypi_name_available")
110
111 Unit tests that use this fixture can define it's return value, as well as check the arguments it was called with.
112 This will be demonstrated in the next section.
113
114 ----------
115 Exit Codes
116 ----------
117 Our command function returns a boolean. By default, Cyclopts uses :attr:`~cyclopts.App.result_action` of ``"print_non_int_sys_exit"``, which calls :func:`sys.exit` with the appropriate code: :obj:`True` → ``0`` (success), :obj:`False` → ``1`` (failure).
118
119 .. code-block:: python
120
121 import pytest
122
123 def test_unavailable_name_cli_behavior(mock_check_pypi_name_available):
124 # Set the mock return_value to False (i.e. the name is NOT available).
125 mock_check_pypi_name_available.return_value = False
126 with pytest.raises(SystemExit) as exc_info:
127 app("foo") # Default result_action calls sys.exit
128 mock_check_pypi_name_available.assert_called_once_with("foo")
129 assert exc_info.value.code == 1 # Package unavailable exits with code 1
130
131 We can then run pytest on this file:
132
133 .. code-block:: console
134
135 $ pytest test.py
136 ============================== test session starts ==============================
137 platform darwin -- Python 3.13.0, pytest-8.3.4, pluggy-1.5.0
138 rootdir: /cyclopts-demo
139 configfile: pyproject.toml
140 plugins: cov-6.0.0, anyio-4.8.0, mock-3.14.0
141 collected 1 item
142
143 test.py . [100%]
144
145 =============================== 1 passed in 0.05s ===============================
146
147
148 ---------------
149 Checking stdout
150 ---------------
151 We also want to make sure that our message is displayed to the user.
152 The built-in `capsys`_ fixture gives us access to our application's ``stdout``.
153 We can use this to confirm our app prints the correct statement.
154
155 By passing ``result_action="return_value"`` to the app call, we can get the return value directly without :func:`sys.exit` being called:
156
157 .. code-block:: python
158
159 # test.py - continued from "Exit Codes"
160 def test_unavailable_name_with_output(capsys, mock_check_pypi_name_available):
161 mock_check_pypi_name_available.return_value = False
162 is_available = app("foo", result_action="return_value")
163 mock_check_pypi_name_available.assert_called_once_with("foo")
164 assert is_available is False
165 assert capsys.readouterr().out == "foo is not available.\n"
166
167 .. note::
168 Normal output goes to :attr:`~cyclopts.App.console` (stdout), while errors go to :attr:`~cyclopts.App.error_console` (stderr). Use ``capsys.readouterr().err`` to check error messages, or provide a custom ``error_console`` to capture both streams together.
169
170
171 ---------------------
172 Environment Variables
173 ---------------------
174 Because we configured our :class:`.App` with :class:`cyclopts.config.Env`, we can pass arguments into our application via environment variables.
175 The `pytest monkeypatch fixture`_ allows us to modify environment variables within the context of a unit-test.
176
177 In this test, we only want to test if our environment variable is being passed in correctly.
178 We will use :meth:`.App.parse_args`, which performs all the parsing, but doesn't actually invoke the command.
179
180 .. code-block:: python
181
182 # test.py
183 def test_name_env_var(monkeypatch):
184 from pypi_checker import pypi_checker
185 monkeypatch.setenv("PYPI_CHECKER_NAME", "foo")
186 command, bound, _ = app.parse_args([]) # An empty list - no CLI arguments passed in.
187 assert command == pypi_checker
188 assert bound.arguments['name'] == "foo"
189
190 .. warning::
191
192 A common mistake is accidentally calling ``app()`` or ``app.parse_args()`` with the **intent of providing no arguments**.
193 Calling these methods with no arguments will read from :obj:`sys.argv`, the same as in a typical application.
194 This is rarely the intention in a unit-test, and Cyclopts **will produce a warning.**
195 For example, this code in a unit test:
196
197 .. code-block:: python
198
199 app() # Wrong: will produce a warning
200
201 Will generate this warning:
202
203 .. code-block:: text
204
205 =============================== warnings summary ================================
206 test.py::test_no_args
207 /my_project/test.py:64: UserWarning: Cyclopts application invoked without tokens
208 under unit-test framework "pytest". Did you mean app([])?
209 app()
210
211 The proper way to specify no CLI arguments is to provide an empty string or list:
212
213 .. code-block:: python
214
215 app([])
216
217 -----------
218 File Config
219 -----------
220 To explicitly test that configurations from the :ref:`Cyclopts configuration system <Config Files>` are loading properly, we can create a configuration file in a temporary directory and change our current-working-directory (cwd) to that temporary directory. The pytest built-in ``tmp_path`` fixture gives us a temporary directory, and the ``monkeypatch`` fixture allows us to change the cwd. We have to change the cwd because typically configuration files are discovered relative to the directory where the CLI was invoked. If your CLI searches other locations (such as the home directory), you will need to modify this example appropriately.
221
222 .. code-block:: python
223
224 # test.py
225 import json
226 from pypi_checker import pypi_checker
227
228 @pytest.fixture(autouse=True)
229 def chdir_to_tmp_path(tmp_path, monkeypatch):
230 "Automatically change current directory to tmp_path"
231 monkeypatch.chdir(tmp_path)
232
233 @pytest.fixture
234 def config_path(tmp_path):
235 "Path to JSON configuration file in tmp_path"
236 return tmp_path / "config.json" # same name that was provided to cyclopts.config.Json
237
238 def test_config(config_path):
239 with config_path.open("w") as f:
240 json.dump({"name": "bar"}, f)
241 command, bound, _ = app.parse_args([]) # An empty list - no CLI arguments passed in.
242 assert command == pypi_checker
243 assert bound.arguments['name'] == "bar"
244
245 ---------
246 Help Page
247 ---------
248 Cyclopts uses Rich_ to pretty-print messages to the console.
249 Rich interprets the console environment, and can change how it displays text depending on the terminal's capabilities.
250 For unit testing, we will explicitly set a lot of these parameters in a pytest fixture to make it easier to compare against known good values:
251
252 .. code-block:: python
253
254 @pytest.fixture
255 def console():
256 from rich.console import Console
257 return Console(width=70, force_terminal=True, highlight=False, color_system=None, legacy_windows=False)
258
259 Since the help-page is just printed to ``stdout``, we will be using the `capsys`_ fixture again.
260
261 .. code-block:: python
262
263 import pytest
264 from textwrap import dedent
265
266 def test_help_page(capsys, console):
267 with pytest.raises(SystemExit):
268 app("--help", console=console)
269 actual = capsys.readouterr().out
270 assert actual == dedent(
271 """\
272 Usage: pypi_checker COMMAND [ARGS] [OPTIONS]
273
274 Check if a package name is available on PyPI.
275
276 Returns True if available; False otherwise.
277
278 ╭─ Commands ─────────────────────────────────────────────────────────╮
279 │ --help -h Display this message and exit. │
280 │ --version Display application version. │
281 ╰────────────────────────────────────────────────────────────────────╯
282 ╭─ Parameters ───────────────────────────────────────────────────────╮
283 │ * NAME --name Name of the package to check. [required] │
284 │ --silent --no-silent Do not print anything to stdout. │
285 │ [default: False] │
286 ╰────────────────────────────────────────────────────────────────────╯
287 """
288 )
289
290 The :func:`textwrap.dedent` function allows us to have our expected-help-string nicely indented within our code.
291 Alternatively, we could have used the :meth:`rich.console.Console.capture` context manager to directly capture the :class:`rich.console.Console` output.
292
293 .. note::
294 Unit-testing the help-page is probably overkill for most projects (and may get in the way more often than it helps!).
295
296 .. _PyPI: https://pypi.org
297 .. _pytest: https://docs.pytest.org/en/stable/
298 .. _pytest-mock: https://pytest-mock.readthedocs.io/en/latest/
299 .. _fixture: https://docs.pytest.org/en/stable/explanation/fixtures.html
300 .. _capsys: https://docs.pytest.org/en/stable/how-to/capture-stdout-stderr.html#accessing-captured-output-from-a-test-function
301 .. _pytest monkeypatch fixture: https://docs.pytest.org/en/stable/how-to/monkeypatch.html
302 .. _Rich: https://rich.readthedocs.io/en/stable/