Skip to content

Commit 1246911

Browse files
Expand command line argument examples with validation examples (#8610)
* Expand command line argument examples with validation examples This shows how to pass more detailed error messages back to the user when they've provided an incorrect value for a custom command line option. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 634312b commit 1246911

File tree

1 file changed

+60
-4
lines changed

1 file changed

+60
-4
lines changed

doc/en/example/simple.rst

Lines changed: 60 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -139,10 +139,66 @@ And now with supplying a command line option:
139139
FAILED test_sample.py::test_answer - assert 0
140140
1 failed in 0.12s
141141
142-
You can see that the command line option arrived in our test. This
143-
completes the basic pattern. However, one often rather wants to process
144-
command line options outside of the test and rather pass in different or
145-
more complex objects.
142+
You can see that the command line option arrived in our test.
143+
144+
We could add simple validation for the input by listing the choices:
145+
146+
.. code-block:: python
147+
148+
# content of conftest.py
149+
import pytest
150+
151+
152+
def pytest_addoption(parser):
153+
parser.addoption(
154+
"--cmdopt",
155+
action="store",
156+
default="type1",
157+
help="my option: type1 or type2",
158+
choices=("type1", "type2"),
159+
)
160+
161+
Now we'll get feedback on a bad argument:
162+
163+
.. code-block:: pytest
164+
165+
$ pytest -q --cmdopt=type3
166+
ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...]
167+
pytest: error: argument --cmdopt: invalid choice: 'type3' (choose from 'type1', 'type2')
168+
169+
If you need to provide more detailed error messages, you can use the
170+
``type`` parameter and raise ``pytest.UsageError``:
171+
172+
.. code-block:: python
173+
174+
# content of conftest.py
175+
import pytest
176+
177+
178+
def type_checker(value):
179+
msg = "cmdopt must specify a numeric type as typeNNN"
180+
if not value.startswith("type"):
181+
raise pytest.UsageError(msg)
182+
try:
183+
int(value[4:])
184+
except ValueError:
185+
raise pytest.UsageError(msg)
186+
187+
return value
188+
189+
190+
def pytest_addoption(parser):
191+
parser.addoption(
192+
"--cmdopt",
193+
action="store",
194+
default="type1",
195+
help="my option: type1 or type2",
196+
type=type_checker,
197+
)
198+
199+
This completes the basic pattern. However, one often rather wants to
200+
process command line options outside of the test and rather pass in
201+
different or more complex objects.
146202

147203
Dynamically adding command line options
148204
--------------------------------------------------------------

0 commit comments

Comments
 (0)