lib-detect-testenv 3.0.6__tar.gz → 3.0.8__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. {lib_detect_testenv-3.0.6 → lib_detect_testenv-3.0.8}/CHANGELOG.md +35 -5
  2. {lib_detect_testenv-3.0.6 → lib_detect_testenv-3.0.8}/PKG-INFO +14 -8
  3. {lib_detect_testenv-3.0.6 → lib_detect_testenv-3.0.8}/README.md +6 -2
  4. {lib_detect_testenv-3.0.6 → lib_detect_testenv-3.0.8}/docs/systemdesign/module_reference.md +18 -15
  5. {lib_detect_testenv-3.0.6 → lib_detect_testenv-3.0.8}/pyproject.toml +14 -8
  6. {lib_detect_testenv-3.0.6 → lib_detect_testenv-3.0.8}/src/lib_detect_testenv/__init__conf__.py +1 -1
  7. {lib_detect_testenv-3.0.6 → lib_detect_testenv-3.0.8}/src/lib_detect_testenv/cli.py +42 -15
  8. {lib_detect_testenv-3.0.6 → lib_detect_testenv-3.0.8}/src/lib_detect_testenv/lib_detect_testenv.py +19 -2
  9. {lib_detect_testenv-3.0.6 → lib_detect_testenv-3.0.8}/tests/test_cli.py +81 -0
  10. {lib_detect_testenv-3.0.6 → lib_detect_testenv-3.0.8}/tests/test_lib_detect_testenv.py +39 -0
  11. {lib_detect_testenv-3.0.6 → lib_detect_testenv-3.0.8}/.gitignore +0 -0
  12. {lib_detect_testenv-3.0.6 → lib_detect_testenv-3.0.8}/LICENSE +0 -0
  13. {lib_detect_testenv-3.0.6 → lib_detect_testenv-3.0.8}/src/lib_detect_testenv/__init__.py +0 -0
  14. {lib_detect_testenv-3.0.6 → lib_detect_testenv-3.0.8}/src/lib_detect_testenv/__main__.py +0 -0
  15. {lib_detect_testenv-3.0.6 → lib_detect_testenv-3.0.8}/src/lib_detect_testenv/behaviors.py +0 -0
  16. {lib_detect_testenv-3.0.6 → lib_detect_testenv-3.0.8}/src/lib_detect_testenv/py.typed +0 -0
  17. {lib_detect_testenv-3.0.6 → lib_detect_testenv-3.0.8}/src/lib_detect_testenv/safe_console.py +0 -0
  18. {lib_detect_testenv-3.0.6 → lib_detect_testenv-3.0.8}/src/lib_detect_testenv/typed_click.py +0 -0
  19. {lib_detect_testenv-3.0.6 → lib_detect_testenv-3.0.8}/tests/conftest.py +0 -0
  20. {lib_detect_testenv-3.0.6 → lib_detect_testenv-3.0.8}/tests/test_behaviors.py +0 -0
  21. {lib_detect_testenv-3.0.6 → lib_detect_testenv-3.0.8}/tests/test_metadata.py +0 -0
  22. {lib_detect_testenv-3.0.6 → lib_detect_testenv-3.0.8}/tests/test_module_entry.py +0 -0
  23. {lib_detect_testenv-3.0.6 → lib_detect_testenv-3.0.8}/tests/test_packaging.py +0 -0
  24. {lib_detect_testenv-3.0.6 → lib_detect_testenv-3.0.8}/tests/test_platform_markers.py +0 -0
  25. {lib_detect_testenv-3.0.6 → lib_detect_testenv-3.0.8}/tests/test_safe_console.py +0 -0
@@ -7,7 +7,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
- ## [3.0.6] 2026-10-15 16:35:25
10
+ ## [3.0.8] - 2026-12-02
11
+
12
+ ### Fixed
13
+
14
+ - The CLI decides the traceback from the `--traceback/--no-traceback` flag as click parses it, the
15
+ last one winning. `main()` used to scan the raw arguments for `--no-traceback`, so
16
+ `--no-traceback --traceback fail` hid the traceback, an option value spelled `--no-traceback`
17
+ turned it off, and `main([])` read the interpreter's own arguments.
18
+ - A usage error (unknown command or option) prints click's message and exits 2. It used to be
19
+ printed as an exception, with a traceback unless `--no-traceback` was given, and exit 1.
20
+ - `notebooks/Quickstart.ipynb` installs the checkout it runs in, so CI's "Execute notebooks" job
21
+ tests the commit under test. It used to install `git+https://github.com/...` every time, which is
22
+ the pushed default branch, so a pull request's notebook run tested the code already there.
23
+ Outside a checkout (a downloaded notebook) it still installs from GitHub.
24
+
25
+ ## [3.0.7] - 2026-10-29
26
+
27
+ ### Fixed
28
+
29
+ - `is_pytest_active()` and `is_testenv_active()` called without an `arg_string` return `True`
30
+ inside a pytest-xdist worker. A worker runs as `python -c`, so its `sys.argv` names neither
31
+ pytest nor a test file and both returned `False` there; they now also check the
32
+ `PYTEST_XDIST_WORKER` variable xdist sets in every worker. A call given an `arg_string` is still
33
+ judged on that string alone.
34
+
35
+ ### Tests
36
+
37
+ - The suite runs in parallel: `pytest-xdist` joins the dev extra and the `workers = 1` setting that
38
+ kept `make test` serial is gone.
39
+
40
+ ## [3.0.6] - 2026-10-15
11
41
 
12
42
  ### Fixed
13
43
 
@@ -28,7 +58,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
28
58
  (`pytest_runtest_setup` in `tests/conftest.py`); registered in `pyproject.toml` alone they skipped
29
59
  nothing, so a test trusting its marker ran everywhere. `tests/test_platform_markers.py` pins it.
30
60
 
31
- ## [3.0.5] 2026-10-15 14:11:33
61
+ ## [3.0.5] - 2026-10-15
32
62
 
33
63
  ### Added
34
64
  - Python 3.15 is a supported version: declared in the classifiers, so CI and `make test-all` run it.
@@ -41,7 +71,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
41
71
  a plain `pip install` from PyPI does not.
42
72
  - `rtoml` floor raised to 0.14.0, the first release with Python 3.15 wheels.
43
73
 
44
- ## [3.0.4] 2026-08-01 00:14:59
74
+ ## [3.0.4] - 2026-08-01
45
75
  ### Fixed
46
76
  - **Console output no longer crashes on a legacy codepage.** A Windows console at codepage 1252
47
77
  hands Python an `errors="strict"` stream, so writing a non-ASCII character such as a check mark
@@ -53,7 +83,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
53
83
  module reaches for `click.echo` or builds an unwrapped `Console(file=sys.stdout)` again.
54
84
 
55
85
 
56
- ## [3.0.3] 2026-07-24 16:01:54
86
+ ## [3.0.3] - 2026-07-24
57
87
 
58
88
  ### Fixed
59
89
  - Fixed CI going red under the latest ruff (0.16 widened its default rule set to ~920 rules on a
@@ -76,7 +106,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
76
106
  to the module top (PLC0415).
77
107
  - Replaced `Optional[X]` with `X | None` throughout `cli.py` (UP045).
78
108
 
79
- ## [3.0.2] 2026-06-14
109
+ ## [3.0.2] - 2026-06-14
80
110
 
81
111
  ### Changed
82
112
  - Added a `typed_click.py` facade wrapping rich-click's `option` / `version_option` decorators behind explicit, fully-known signatures, keeping the CLI strict-clean under pyright (`reportUnknownMemberType`). The repo-wide `reportUnknownMemberType` suppression is retained, but only for the `tomli` backport (untyped on Python 3.10); the rich-click decorators no longer rely on it.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lib_detect_testenv
3
- Version: 3.0.6
3
+ Version: 3.0.8
4
4
  Summary: Detect test environment - pytest, doctest, unittest, or regular execution
5
5
  Project-URL: Homepage, https://github.com/bitranox/lib_detect_testenv
6
6
  Project-URL: Repository, https://github.com/bitranox/lib_detect_testenv.git
@@ -27,18 +27,20 @@ Provides-Extra: dev
27
27
  Requires-Dist: bandit<1.9,>=1.8.6; (python_version < '3.10') and extra == 'dev'
28
28
  Requires-Dist: bandit>=1.9.4; (python_version >= '3.10') and extra == 'dev'
29
29
  Requires-Dist: build>=1.6.1; extra == 'dev'
30
- Requires-Dist: click>=8.5.0; extra == 'dev'
31
- Requires-Dist: hatchling>=1.32.4; extra == 'dev'
30
+ Requires-Dist: certifi>=2026.11.20; extra == 'dev'
31
+ Requires-Dist: click>=8.5.1; extra == 'dev'
32
+ Requires-Dist: hatchling>=1.33.0; extra == 'dev'
32
33
  Requires-Dist: import-linter<2.6,>=2.5.2; (python_version < '3.10') and extra == 'dev'
33
34
  Requires-Dist: import-linter>=2.15; (python_version >= '3.10') and extra == 'dev'
34
35
  Requires-Dist: pip-audit>=2.10.1; extra == 'dev'
35
36
  Requires-Dist: pyright[nodejs]>=1.1.414; extra == 'dev'
36
37
  Requires-Dist: pytest-cov>=7.1.0; extra == 'dev'
38
+ Requires-Dist: pytest-xdist>=3.8.0; extra == 'dev'
37
39
  Requires-Dist: pytest<9,>=8.4.2; (python_version < '3.10') and extra == 'dev'
38
- Requires-Dist: pytest>=9.1.1; (python_version >= '3.10') and extra == 'dev'
40
+ Requires-Dist: pytest>=9.2.0; (python_version >= '3.10') and extra == 'dev'
39
41
  Requires-Dist: rtoml>=0.14.0; extra == 'dev'
40
- Requires-Dist: ruff>=0.17.0; extra == 'dev'
41
- Requires-Dist: setuptools>=84.0.0; extra == 'dev'
42
+ Requires-Dist: ruff>=0.17.6; extra == 'dev'
43
+ Requires-Dist: setuptools>=84.2.1; extra == 'dev'
42
44
  Requires-Dist: textual>=8.2.8; extra == 'dev'
43
45
  Requires-Dist: twine>=7.0.0; extra == 'dev'
44
46
  Description-Content-Type: text/markdown
@@ -254,7 +256,9 @@ else:
254
256
  Returns `True` if any test environment is detected (pytest, doctest, or setup.py test).
255
257
 
256
258
  **Parameters:**
257
- - `arg_string` (optional): If `None`, uses `str(sys.argv())`
259
+ - `arg_string` (optional): If `None`, uses `str(sys.argv())`, and a pytest-xdist worker
260
+ (`PYTEST_XDIST_WORKER` set) counts as pytest: its `sys.argv` does not name pytest. A given
261
+ `arg_string` is judged on its own.
258
262
 
259
263
  **Returns:**
260
264
  - `True` if test environment is detected
@@ -297,7 +301,9 @@ assert is_doctest_active(arg_string="doctest.py") == True
297
301
  Returns `True` if pytest is detected.
298
302
 
299
303
  **Parameters:**
300
- - `arg_string` (optional): If `None`, uses `str(sys.argv())`
304
+ - `arg_string` (optional): If `None`, uses `str(sys.argv())`, and a pytest-xdist worker
305
+ (`PYTEST_XDIST_WORKER` set) counts as pytest: its `sys.argv` does not name pytest. A given
306
+ `arg_string` is judged on its own.
301
307
 
302
308
  **Returns:**
303
309
  - `True` if pytest is detected
@@ -209,7 +209,9 @@ else:
209
209
  Returns `True` if any test environment is detected (pytest, doctest, or setup.py test).
210
210
 
211
211
  **Parameters:**
212
- - `arg_string` (optional): If `None`, uses `str(sys.argv())`
212
+ - `arg_string` (optional): If `None`, uses `str(sys.argv())`, and a pytest-xdist worker
213
+ (`PYTEST_XDIST_WORKER` set) counts as pytest: its `sys.argv` does not name pytest. A given
214
+ `arg_string` is judged on its own.
213
215
 
214
216
  **Returns:**
215
217
  - `True` if test environment is detected
@@ -252,7 +254,9 @@ assert is_doctest_active(arg_string="doctest.py") == True
252
254
  Returns `True` if pytest is detected.
253
255
 
254
256
  **Parameters:**
255
- - `arg_string` (optional): If `None`, uses `str(sys.argv())`
257
+ - `arg_string` (optional): If `None`, uses `str(sys.argv())`, and a pytest-xdist worker
258
+ (`PYTEST_XDIST_WORKER` set) counts as pytest: its `sys.argv` does not name pytest. A given
259
+ `arg_string` is judged on its own.
256
260
 
257
261
  **Returns:**
258
262
  - `True` if pytest is detected
@@ -77,11 +77,12 @@ Behaviors Layer (behaviors.py) ← Demo commands only
77
77
  **Purpose:** Detect if any test environment is active (pytest, doctest, or setup.py test).
78
78
 
79
79
  **Input:**
80
- - `arg_string` (optional): Custom argument string to check. If None, uses `str(sys.argv)`.
80
+ - `arg_string` (optional): Custom argument string to check. If None, uses `str(sys.argv)`, and a
81
+ pytest-xdist worker (`PYTEST_XDIST_WORKER` set) counts as pytest.
81
82
 
82
83
  **Output:** `True` if test environment detected, `False` otherwise.
83
84
 
84
- **Location:** src/lib_detect_testenv/lib_detect_testenv.py:9
85
+ **Location:** src/lib_detect_testenv/lib_detect_testenv.py:10
85
86
 
86
87
  **Example:**
87
88
  ```python
@@ -102,12 +103,14 @@ if is_testenv_active():
102
103
  - Checks for `/pytest/__main__.py` in arguments
103
104
  - Checks for `python -m pytest` pattern
104
105
  - Checks `PYTEST_IS_RUNNING` environment variable
106
+ - Without an `arg_string`, also checks `PYTEST_XDIST_WORKER`: a pytest-xdist worker runs as
107
+ `python -c`, so its `sys.argv` does not name pytest
105
108
 
106
109
  **Input:** `arg_string` (optional): Custom argument string to check.
107
110
 
108
111
  **Output:** `True` if pytest detected, `False` otherwise.
109
112
 
110
- **Location:** src/lib_detect_testenv/lib_detect_testenv.py:68
113
+ **Location:** src/lib_detect_testenv/lib_detect_testenv.py:70
111
114
 
112
115
  **Example:**
113
116
  ```python
@@ -132,7 +135,7 @@ if is_pytest_active():
132
135
 
133
136
  **Output:** `True` if doctest detected, `False` otherwise.
134
137
 
135
- **Location:** src/lib_detect_testenv/lib_detect_testenv.py:38
138
+ **Location:** src/lib_detect_testenv/lib_detect_testenv.py:42
136
139
 
137
140
  ---
138
141
 
@@ -147,7 +150,7 @@ if is_pytest_active():
147
150
 
148
151
  **Output:** `True` if setup.py detected, `False` otherwise.
149
152
 
150
- **Location:** src/lib_detect_testenv/lib_detect_testenv.py:105
153
+ **Location:** src/lib_detect_testenv/lib_detect_testenv.py:108
151
154
 
152
155
  ---
153
156
 
@@ -162,7 +165,7 @@ if is_pytest_active():
162
165
 
163
166
  **Output:** `True` if `setup.py test` detected, `False` otherwise.
164
167
 
165
- **Location:** src/lib_detect_testenv/lib_detect_testenv.py:132
168
+ **Location:** src/lib_detect_testenv/lib_detect_testenv.py:135
166
169
 
167
170
  ---
168
171
 
@@ -174,7 +177,7 @@ if is_pytest_active():
174
177
 
175
178
  **Output:** `True` if docrunner.py found, `False` otherwise.
176
179
 
177
- **Location:** src/lib_detect_testenv/lib_detect_testenv.py:164
180
+ **Location:** src/lib_detect_testenv/lib_detect_testenv.py:167
178
181
 
179
182
  ---
180
183
 
@@ -193,7 +196,7 @@ if is_pytest_active():
193
196
 
194
197
  **Output:** None (modifies sys.path in place)
195
198
 
196
- **Location:** src/lib_detect_testenv/lib_detect_testenv.py:188
199
+ **Location:** src/lib_detect_testenv/lib_detect_testenv.py:198
197
200
 
198
201
  **Example:**
199
202
  ```python
@@ -235,7 +238,7 @@ if lib_detect_testenv check --quiet; then
235
238
  fi
236
239
  ```
237
240
 
238
- **Location:** src/lib_detect_testenv/cli.py:99
241
+ **Location:** src/lib_detect_testenv/cli.py:135
239
242
 
240
243
  ---
241
244
 
@@ -247,7 +250,7 @@ fi
247
250
 
248
251
  **Flags:** Same as check command
249
252
 
250
- **Location:** src/lib_detect_testenv/cli.py:141
253
+ **Location:** src/lib_detect_testenv/cli.py:177
251
254
 
252
255
  ---
253
256
 
@@ -259,7 +262,7 @@ fi
259
262
 
260
263
  **Flags:** Same as check command
261
264
 
262
- **Location:** src/lib_detect_testenv/cli.py:183
265
+ **Location:** src/lib_detect_testenv/cli.py:219
263
266
 
264
267
  ---
265
268
 
@@ -274,7 +277,7 @@ fi
274
277
  - `--arg-string TEXT`: Check custom argument string
275
278
  - `--test-only`: Check only for `setup.py test` (not just setup.py)
276
279
 
277
- **Location:** src/lib_detect_testenv/cli.py:225
280
+ **Location:** src/lib_detect_testenv/cli.py:261
278
281
 
279
282
  ---
280
283
 
@@ -284,7 +287,7 @@ fi
284
287
 
285
288
  **Use Case:** Testing CLI functionality, smoke tests.
286
289
 
287
- **Location:** src/lib_detect_testenv/cli.py:281
290
+ **Location:** src/lib_detect_testenv/cli.py:317
288
291
 
289
292
  ---
290
293
 
@@ -294,7 +297,7 @@ fi
294
297
 
295
298
  **Use Case:** Testing error handling, traceback display.
296
299
 
297
- **Location:** src/lib_detect_testenv/cli.py:291
300
+ **Location:** src/lib_detect_testenv/cli.py:329
298
301
 
299
302
  ---
300
303
 
@@ -302,7 +305,7 @@ fi
302
305
 
303
306
  **Purpose:** Display package metadata (name, version, author, etc.).
304
307
 
305
- **Location:** src/lib_detect_testenv/cli.py:94
308
+ **Location:** src/lib_detect_testenv/cli.py:129
306
309
 
307
310
  ---
308
311
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "lib_detect_testenv"
3
- version = "3.0.6"
3
+ version = "3.0.8"
4
4
  description = "Detect test environment - pytest, doctest, unittest, or regular execution"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -33,14 +33,15 @@ Issues = "https://github.com/bitranox/lib_detect_testenv/issues"
33
33
  [project.optional-dependencies]
34
34
  dev = [
35
35
  "pytest>=8.4.2,<9; python_version<'3.10'",
36
- "pytest>=9.1.1; python_version>='3.10'",
36
+ "pytest>=9.2.0; python_version>='3.10'",
37
37
  "pytest-cov>=7.1.0",
38
- "ruff>=0.17.0",
38
+ "pytest-xdist>=3.8.0",
39
+ "ruff>=0.17.6",
39
40
  "pyright[nodejs]>=1.1.414",
40
41
  "bandit>=1.8.6,<1.9; python_version<'3.10'",
41
42
  "bandit>=1.9.4; python_version>='3.10'",
42
43
  "build>=1.6.1",
43
- "hatchling>=1.32.4",
44
+ "hatchling>=1.33.0",
44
45
  "twine>=7.0.0",
45
46
  # codecov-cli is disabled, not dropped: it requires click<8.3.0, which drags click back to
46
47
  # 8.2.1 - the version with CVE-2026-7246 (command injection in click.edit(), fixed in 8.3.3).
@@ -50,13 +51,14 @@ dev = [
50
51
  # Re-enable once codecov-cli relaxes its click<8.3.0 pin.
51
52
  # "codecov-cli>=11.2.8",
52
53
  # Transitive CVE pins
53
- "click>=8.5.0", # CVE-2026-7246
54
+ "click>=8.5.1", # CVE-2026-7246
54
55
  "pip-audit>=2.10.1",
55
56
  "textual>=8.2.8",
56
57
  "import-linter>=2.5.2,<2.6; python_version<'3.10'",
57
58
  "import-linter>=2.15; python_version>='3.10'",
58
- "setuptools>=84.0.0",
59
+ "setuptools>=84.2.1",
59
60
  "rtoml>=0.14.0",
61
+ "certifi>=2026.11.20", # PYSEC-2026-4320
60
62
  ]
61
63
 
62
64
  [project.scripts]
@@ -122,7 +124,10 @@ convention = "google"
122
124
 
123
125
  [tool.ruff.lint.per-file-ignores]
124
126
  # ignore the "unused import sys" in the jupyter notebook - which we need (it is a linter hickup)
125
- "notebooks/*.ipynb" = ["F401"]
127
+ # A `!cmd` never raises, so CI sees a failing shell command only through
128
+ # `assert _exit_code == N` after it: IPython injects `_exit_code` at run time (F821)
129
+ # and those asserts are the gate (S101).
130
+ "notebooks/*.ipynb" = ["F401", "F821", "S101"]
126
131
  # Tests: assert is standard, test fixtures have passwords, magic values are clearer inline, temp paths are fine.
127
132
  # PLC0415: local/deferred imports are a deliberate test idiom - several tests import inside the test
128
133
  # body to exercise import-time and cache behaviour, so moving them to module top would defeat intent.
@@ -219,4 +224,5 @@ max-line-length = 120
219
224
  ignores = ["E003"]
220
225
 
221
226
  [tool.uv]
222
- exclude-newer = "1 day"
227
+ exclude-newer = "7 days"
228
+ exclude-newer-package = {lib-detect-testenv = false}
@@ -26,7 +26,7 @@ name = "lib_detect_testenv"
26
26
  #: Human-readable summary shown in CLI help output.
27
27
  title = "Detect test environment - pytest, doctest, unittest, or regular execution"
28
28
  #: Current release version pulled from ``pyproject.toml`` by automation.
29
- version = "3.0.6"
29
+ version = "3.0.8"
30
30
  #: Repository homepage presented to users.
31
31
  homepage = "https://github.com/bitranox/lib_detect_testenv"
32
32
  #: Author attribution surfaced in CLI output.
@@ -28,7 +28,7 @@ programmatic usage.
28
28
 
29
29
  from __future__ import annotations
30
30
 
31
- import sys
31
+ from dataclasses import dataclass
32
32
  from typing import TYPE_CHECKING
33
33
 
34
34
  import rich_click as click
@@ -59,6 +59,32 @@ CLICK_CONTEXT_SETTINGS = {"help_option_names": ["-h", "--help"]}
59
59
  console = Console(file=safe_stream())
60
60
 
61
61
 
62
+ @dataclass(slots=True)
63
+ class _TracebackChoice:
64
+ """Whether :func:`main` shows a full traceback for an error: click's parsed ``--traceback`` flag.
65
+
66
+ :func:`main` hands one to click as the context object; the root callback records the flag as
67
+ click parsed it (the last of ``--traceback``/``--no-traceback`` wins). Until that callback runs
68
+ it holds click's own default, so an error raised before it shows a traceback; a usage error
69
+ click raises there is shown as click's message, never with a traceback.
70
+
71
+ Attributes:
72
+ show: True to print the rich traceback with locals, False for the one-line error.
73
+ """
74
+
75
+ show: bool = True
76
+
77
+ def choose(self, *, show: bool) -> None:
78
+ """Record the parsed flag; showing tracebacks also installs rich's handler for uncaught ones.
79
+
80
+ Args:
81
+ show: The ``--traceback/--no-traceback`` flag as click parsed it.
82
+ """
83
+ self.show = show
84
+ if show:
85
+ install_rich_traceback(show_locals=True)
86
+
87
+
62
88
  @click.group(
63
89
  help=__init__conf__.title,
64
90
  context_settings=CLICK_CONTEXT_SETTINGS,
@@ -77,8 +103,10 @@ console = Console(file=safe_stream())
77
103
  )
78
104
  @click.pass_context
79
105
  def cli(ctx: click.Context, *, traceback: bool) -> None:
80
- """Root command storing global flags.
106
+ """Root command recording the traceback flag.
81
107
 
108
+ Records ``--traceback/--no-traceback`` as click parsed it (the last one wins) for :func:`main`,
109
+ which passes the context object; a direct invocation (``CliRunner``) has none and ignores it.
82
110
  When invoked without a subcommand, checks if any test environment is active.
83
111
 
84
112
  Examples
@@ -89,9 +117,9 @@ def cli(ctx: click.Context, *, traceback: bool) -> None:
89
117
  >>> result.exit_code in (0, 1)
90
118
  True
91
119
  """
92
- # Store traceback preference in context
93
- ctx.ensure_object(dict)
94
- ctx.obj["traceback"] = traceback
120
+ choice = ctx.find_object(_TracebackChoice)
121
+ if choice is not None:
122
+ choice.choose(show=traceback)
95
123
 
96
124
  # If no subcommand, run the check command by default
97
125
  if ctx.invoked_subcommand is None:
@@ -335,22 +363,21 @@ def main(
335
363
  Hello World
336
364
  0
337
365
  """
338
- # Check if --no-traceback flag is in arguments (default is to show traceback)
339
- argv_list = list(argv) if argv else sys.argv[1:]
340
- show_traceback = "--no-traceback" not in argv_list
341
-
342
- # Install rich traceback with locals if requested
343
- if show_traceback:
344
- install_rich_traceback(show_locals=True)
345
-
366
+ # click's own parse decides --traceback/--no-traceback (last one wins); a raw scan of argv
367
+ # would also read an option's value or the interpreter's arguments for main([]).
368
+ choice = _TracebackChoice()
346
369
  try:
347
370
  # Use standalone_mode=False to catch exceptions ourselves
348
- cli(args=argv, standalone_mode=False, prog_name=__init__conf__.shell_command)
371
+ cli(args=argv, standalone_mode=False, prog_name=__init__conf__.shell_command, obj=choice)
349
372
  return 0
350
373
  except SystemExit as e:
351
374
  return e.code if isinstance(e.code, int) else (1 if e.code else 0)
375
+ except click.ClickException as exc:
376
+ # A usage error click raises while parsing, before the root callback records the flag.
377
+ exc.show()
378
+ return exc.exit_code
352
379
  except Exception as exc:
353
- if show_traceback:
380
+ if choice.show:
354
381
  # Show full rich traceback with locals
355
382
  tb = Traceback.from_exception(
356
383
  type(exc),
@@ -14,7 +14,8 @@ def is_testenv_active(arg_string: Optional[str] = None) -> bool:
14
14
 
15
15
  Parameter
16
16
  ----------
17
- arg_string : optional, if None : str(sys.argv())
17
+ arg_string : optional, if None : str(sys.argv()), and a pytest-xdist worker
18
+ (PYTEST_XDIST_WORKER set) counts as pytest
18
19
 
19
20
 
20
21
  Result
@@ -32,6 +33,8 @@ def is_testenv_active(arg_string: Optional[str] = None) -> bool:
32
33
 
33
34
  >>> assert is_testenv_active() == True
34
35
  """
36
+ if arg_string is None and _is_pytest_xdist_worker():
37
+ return True
35
38
  arg_string = _get_sys_argv_str(arg_string)
36
39
  return is_doctest_active(arg_string=arg_string) or is_pytest_active(arg_string=arg_string) or is_setup_test_active(arg_string=arg_string)
37
40
 
@@ -71,7 +74,8 @@ def is_pytest_active(arg_string: Optional[str] = None) -> bool:
71
74
 
72
75
  Parameter
73
76
  ----------
74
- arg_string : optional, if None : str(sys.argv())
77
+ arg_string : optional, if None : str(sys.argv()), and a pytest-xdist worker
78
+ (PYTEST_XDIST_WORKER set) counts as pytest
75
79
 
76
80
 
77
81
  Result
@@ -88,6 +92,8 @@ def is_pytest_active(arg_string: Optional[str] = None) -> bool:
88
92
 
89
93
  """
90
94
 
95
+ if arg_string is None and _is_pytest_xdist_worker():
96
+ return True
91
97
  arg_string = _get_sys_argv_str(arg_string)
92
98
  # this is used in our tests when we test cli-commands
93
99
  if os.getenv("PYTEST_IS_RUNNING"):
@@ -167,6 +173,17 @@ def is_doctest_in_arg_string(arg_string: str) -> bool:
167
173
  return "docrunner.py" in arg_string
168
174
 
169
175
 
176
+ def _is_pytest_xdist_worker() -> bool:
177
+ """
178
+ returns True inside a pytest-xdist worker process
179
+
180
+ A worker is started by execnet as "python -c <bootstrap>", so its sys.argv names neither
181
+ pytest nor a test file; pytest-xdist sets PYTEST_XDIST_WORKER (gw0, gw1, ...) in every worker.
182
+ Only a call that reads the real process asks this: an explicit arg_string is judged alone.
183
+ """
184
+ return bool(os.getenv("PYTEST_XDIST_WORKER"))
185
+
186
+
170
187
  def _get_sys_argv_str(arg_string: Optional[str] = None) -> str:
171
188
  """
172
189
  gets the sys.argv as string. backslashes in Windows are replaced with slashes
@@ -5,9 +5,11 @@ from __future__ import annotations
5
5
  from typing import TYPE_CHECKING
6
6
 
7
7
  import pytest
8
+ import rich_click as click
8
9
 
9
10
  from lib_detect_testenv import __init__conf__
10
11
  from lib_detect_testenv import cli as cli_mod
12
+ from lib_detect_testenv.typed_click import option
11
13
 
12
14
  if TYPE_CHECKING:
13
15
  from collections.abc import Callable
@@ -65,6 +67,85 @@ def test_no_traceback_flag_suppresses_traceback(
65
67
  assert "Traceback" not in output or output.count("Traceback") == 0
66
68
 
67
69
 
70
+ @pytest.mark.os_agnostic
71
+ @pytest.mark.parametrize(
72
+ ("flags", "shows_traceback"),
73
+ [(("--no-traceback", "--traceback"), True), (("--traceback", "--no-traceback"), False)],
74
+ )
75
+ def test_the_last_traceback_flag_decides_as_click_parses_it(
76
+ flags: tuple[str, ...],
77
+ shows_traceback: bool,
78
+ capsys: pytest.CaptureFixture[str],
79
+ ) -> None:
80
+ """Of --traceback and --no-traceback the last one wins, as click parses it."""
81
+ exit_code = cli_mod.main([*flags, "fail"])
82
+
83
+ assert exit_code == 1
84
+ captured = capsys.readouterr()
85
+ output = captured.out + captured.err
86
+ assert ("Traceback" in output) is shows_traceback
87
+ assert "I should fail" in output
88
+
89
+
90
+ @pytest.fixture
91
+ def labelled_fail(monkeypatch: pytest.MonkeyPatch) -> None:
92
+ """Register a test-only ``labelled-fail`` command that takes a ``--label`` value and fails."""
93
+
94
+ @click.command("labelled-fail")
95
+ @option("--label", required=True)
96
+ def labelled_fail_command(label: str) -> None:
97
+ raise RuntimeError(f"failed with label {label}")
98
+
99
+ monkeypatch.setitem(cli_mod.cli.commands, "labelled-fail", labelled_fail_command)
100
+
101
+
102
+ @pytest.mark.os_agnostic
103
+ @pytest.mark.usefixtures("labelled_fail")
104
+ def test_an_option_value_spelled_no_traceback_keeps_the_traceback(capsys: pytest.CaptureFixture[str]) -> None:
105
+ """A '--no-traceback' token click reads as an option's value does not turn tracebacks off."""
106
+ exit_code = cli_mod.main(["labelled-fail", "--label", "--no-traceback"])
107
+
108
+ assert exit_code == 1
109
+ captured = capsys.readouterr()
110
+ output = captured.out + captured.err
111
+ assert "failed with label --no-traceback" in output
112
+ assert "Traceback" in output
113
+
114
+
115
+ @pytest.mark.os_agnostic
116
+ @pytest.mark.parametrize("flags", [(), ("--no-traceback",)])
117
+ def test_a_usage_error_prints_click_s_message_and_exits_2(flags: tuple[str, ...], capsys: pytest.CaptureFixture[str]) -> None:
118
+ """click refuses an unknown command before the traceback flag is recorded: its message, exit 2."""
119
+ exit_code = cli_mod.main([*flags, "no-such-command"])
120
+
121
+ assert exit_code == 2
122
+ captured = capsys.readouterr()
123
+ output = captured.out + captured.err
124
+ assert "No such command" in output
125
+ assert "Traceback" not in output
126
+
127
+
128
+ @pytest.mark.os_agnostic
129
+ def test_main_with_an_empty_argument_list_never_reads_the_interpreter_s_arguments(
130
+ monkeypatch: pytest.MonkeyPatch,
131
+ capsys: pytest.CaptureFixture[str],
132
+ ) -> None:
133
+ """main([]) means no arguments: a --no-traceback on the interpreter's own command line is not read."""
134
+
135
+ @click.command("boom")
136
+ def boom() -> None:
137
+ raise RuntimeError("boom without arguments")
138
+
139
+ monkeypatch.setattr("sys.argv", ["lib_detect_testenv", "--no-traceback"])
140
+ monkeypatch.setattr(cli_mod, "cli", boom)
141
+
142
+ exit_code = cli_mod.main([])
143
+
144
+ assert exit_code == 1
145
+ captured = capsys.readouterr()
146
+ assert "Traceback" in captured.out + captured.err
147
+
148
+
68
149
  @pytest.mark.os_agnostic
69
150
  def test_when_hello_is_invoked_the_cli_smiles(cli_runner: CliRunner) -> None:
70
151
  """Hello command should output the canonical greeting."""
@@ -113,6 +113,45 @@ def test_is_pytest_active_with_pytest_env_var(monkeypatch: pytest.MonkeyPatch) -
113
113
  assert is_pytest_active(arg_string="") is True
114
114
 
115
115
 
116
+ #: The argv a pytest-xdist worker process runs with: execnet starts it as ``python -c <bootstrap>``.
117
+ _XDIST_WORKER_ARGV = ["-c"]
118
+
119
+
120
+ @pytest.fixture
121
+ def worker_process_argv(monkeypatch: pytest.MonkeyPatch) -> pytest.MonkeyPatch:
122
+ """Make the process look like an xdist worker's argv, with neither pytest variable set."""
123
+ monkeypatch.setattr(sys, "argv", _XDIST_WORKER_ARGV)
124
+ monkeypatch.delenv("PYTEST_IS_RUNNING", raising=False)
125
+ monkeypatch.delenv("PYTEST_XDIST_WORKER", raising=False)
126
+ return monkeypatch
127
+
128
+
129
+ @pytest.mark.os_agnostic
130
+ def test_a_worker_argv_alone_does_not_read_as_pytest(worker_process_argv: pytest.MonkeyPatch) -> None:
131
+ """The control: with the argv replaced and no xdist variable, nothing names pytest."""
132
+ assert is_pytest_active() is False
133
+ assert is_testenv_active() is False
134
+
135
+
136
+ @pytest.mark.os_agnostic
137
+ def test_an_xdist_worker_reads_as_pytest(worker_process_argv: pytest.MonkeyPatch) -> None:
138
+ """A pytest-xdist worker's argv does not name pytest; xdist sets PYTEST_XDIST_WORKER in it."""
139
+ worker_process_argv.setenv("PYTEST_XDIST_WORKER", "gw0")
140
+
141
+ assert is_pytest_active() is True
142
+ assert is_testenv_active() is True
143
+
144
+
145
+ @pytest.mark.os_agnostic
146
+ def test_an_explicit_arg_string_ignores_the_xdist_worker_variable(worker_process_argv: pytest.MonkeyPatch) -> None:
147
+ """Only a call reading the real process consults the worker variable; a given string is judged alone."""
148
+ worker_process_argv.setenv("PYTEST_XDIST_WORKER", "gw0")
149
+
150
+ assert is_pytest_active(arg_string="") is False
151
+ assert is_pytest_active(arg_string="python test.py") is False
152
+ assert is_testenv_active(arg_string="python script.py") is False
153
+
154
+
116
155
  # ============================================================================
117
156
  # Tests for is_doctest_active()
118
157
  # ============================================================================