| 1 |
# mypy: allow-untyped-defs |
| 2 |
from __future__ import annotations |
| 3 |
|
| 4 |
import argparse |
| 5 |
import locale |
| 6 |
import os |
| 7 |
from pathlib import Path |
| 8 |
import shlex |
| 9 |
import subprocess |
| 10 |
import sys |
| 11 |
|
| 12 |
from _pytest.config import argparsing as parseopt |
| 13 |
from _pytest.config.exceptions import UsageError |
| 14 |
from _pytest.monkeypatch import MonkeyPatch |
| 15 |
from _pytest.pytester import Pytester |
| 16 |
import pytest |
| 17 |
|
| 18 |
|
| 19 |
@pytest.fixture |
| 20 |
def parser() -> parseopt.Parser: |
| 21 |
return parseopt.Parser(_ispytest=True) |
| 22 |
|
| 23 |
|
| 24 |
class TestParser: |
| 25 |
def test_no_help_by_default(self) -> None: |
| 26 |
parser = parseopt.Parser(usage="xyz", _ispytest=True) |
| 27 |
with pytest.raises(UsageError): |
| 28 |
parser.parse(["-h"]) |
| 29 |
|
| 30 |
def test_custom_prog(self, parser: parseopt.Parser) -> None: |
| 31 |
"""Custom prog can be set for `argparse.ArgumentParser`.""" |
| 32 |
assert parser.optparser.prog == argparse.ArgumentParser().prog |
| 33 |
parser.prog = "custom-prog" |
| 34 |
assert parser.prog == "custom-prog" |
| 35 |
assert parser.optparser.prog == "custom-prog" |
| 36 |
|
| 37 |
def test_argument(self) -> None: |
| 38 |
parser = argparse.ArgumentParser() |
| 39 |
|
| 40 |
action = parser.add_argument("-a") |
| 41 |
argument = parseopt.Argument(action) |
| 42 |
assert argument.names() == ["-a"] |
| 43 |
assert argument.dest == "a" |
| 44 |
|
| 45 |
action = parser.add_argument("-b", "--boop") |
| 46 |
argument = parseopt.Argument(action) |
| 47 |
assert argument.names() == ["-b", "--boop"] |
| 48 |
assert argument.dest == "boop" |
| 49 |
|
| 50 |
action = parser.add_argument("-c", "--coop", dest="abc") |
| 51 |
argument = parseopt.Argument(action) |
| 52 |
assert argument.dest == "abc" |
| 53 |
assert ( |
| 54 |
str(argument) |
| 55 |
== "Argument(opts: ['-c', '--coop'], dest: 'abc', default: None)" |
| 56 |
) |
| 57 |
|
| 58 |
def test_argument_type(self) -> None: |
| 59 |
parser = argparse.ArgumentParser() |
| 60 |
|
| 61 |
action = parser.add_argument("-a", dest="aa", type=int) |
| 62 |
argument = parseopt.Argument(action) |
| 63 |
assert argument.type is int |
| 64 |
|
| 65 |
action = parser.add_argument("-b", dest="bb", type=str) |
| 66 |
argument = parseopt.Argument(action) |
| 67 |
assert argument.type is str |
| 68 |
|
| 69 |
action = parser.add_argument("-c", dest="cc", type=float) |
| 70 |
argument = parseopt.Argument(action) |
| 71 |
assert argument.type is float |
| 72 |
|
| 73 |
action = parser.add_argument("-d", dest="dd", type=str, choices=["red", "blue"]) |
| 74 |
argument = parseopt.Argument(action) |
| 75 |
assert argument.type is str |
| 76 |
|
| 77 |
def test_group_add_and_get(self, parser: parseopt.Parser) -> None: |
| 78 |
group = parser.getgroup("hello") |
| 79 |
assert group.name == "hello" |
| 80 |
|
| 81 |
def test_getgroup_simple(self, parser: parseopt.Parser) -> None: |
| 82 |
group = parser.getgroup("hello") |
| 83 |
assert group.name == "hello" |
| 84 |
group2 = parser.getgroup("hello") |
| 85 |
assert group2 is group |
| 86 |
|
| 87 |
def test_group_ordering(self, parser: parseopt.Parser) -> None: |
| 88 |
parser.getgroup("1") |
| 89 |
parser.getgroup("2") |
| 90 |
parser.getgroup("3", after="1") |
| 91 |
groups = parser._groups |
| 92 |
groups_names = [x.name for x in groups] |
| 93 |
assert groups_names == ["_anonymous", "1", "3", "2"] |
| 94 |
|
| 95 |
def test_group_addoption(self) -> None: |
| 96 |
optparser = argparse.ArgumentParser() |
| 97 |
arggroup = optparser.add_argument_group("hello") |
| 98 |
group = parseopt.OptionGroup(arggroup, "hello", None, _ispytest=True) |
| 99 |
group.addoption("--option1", action="store_true") |
| 100 |
assert len(group.options) == 1 |
| 101 |
assert isinstance(group.options[0], parseopt.Argument) |
| 102 |
|
| 103 |
def test_group_addoption_conflict(self) -> None: |
| 104 |
optparser = argparse.ArgumentParser() |
| 105 |
arggroup = optparser.add_argument_group("hello again") |
| 106 |
group = parseopt.OptionGroup(arggroup, "hello again", None, _ispytest=True) |
| 107 |
group.addoption("--option1", "--option-1", action="store_true") |
| 108 |
with pytest.raises(ValueError) as err: |
| 109 |
group.addoption("--option1", "--option-one", action="store_true") |
| 110 |
assert str({"--option1"}) in str(err.value) |
| 111 |
|
| 112 |
def test_group_shortopt_lowercase(self, parser: parseopt.Parser) -> None: |
| 113 |
group = parser.getgroup("hello") |
| 114 |
with pytest.raises(ValueError): |
| 115 |
group.addoption("-x", action="store_true") |
| 116 |
assert len(group.options) == 0 |
| 117 |
group._addoption("-x", action="store_true") |
| 118 |
assert len(group.options) == 1 |
| 119 |
|
| 120 |
def test_parser_addoption(self, parser: parseopt.Parser) -> None: |
| 121 |
group = parser.getgroup("custom options") |
| 122 |
assert len(group.options) == 0 |
| 123 |
group.addoption("--option1", action="store_true") |
| 124 |
assert len(group.options) == 1 |
| 125 |
|
| 126 |
def test_parse(self, parser: parseopt.Parser) -> None: |
| 127 |
parser.addoption("--hello", dest="hello", action="store") |
| 128 |
args = parser.parse(["--hello", "world"]) |
| 129 |
assert args.hello == "world" |
| 130 |
assert not getattr(args, parseopt.FILE_OR_DIR) |
| 131 |
|
| 132 |
def test_parse2(self, parser: parseopt.Parser) -> None: |
| 133 |
args = parser.parse([Path(".")]) |
| 134 |
assert getattr(args, parseopt.FILE_OR_DIR)[0] == "." |
| 135 |
|
| 136 |
# Warning ignore because of: |
| 137 |
# https://github.com/python/cpython/issues/85308 |
| 138 |
# Can be removed once Python<3.12 support is dropped. |
| 139 |
@pytest.mark.filterwarnings("ignore:'encoding' argument not specified") |
| 140 |
def test_parse_from_file(self, parser: parseopt.Parser, tmp_path: Path) -> None: |
| 141 |
tests = [".", "some.py::Test::test_method[param0]", "other/test_file.py"] |
| 142 |
args_file = tmp_path / "tests.txt" |
| 143 |
args_file.write_text("\n".join(tests), encoding="utf-8") |
| 144 |
args = parser.parse([f"@{args_file.absolute()}"]) |
| 145 |
assert getattr(args, parseopt.FILE_OR_DIR) == tests |
| 146 |
|
| 147 |
def test_parse_known_args(self, parser: parseopt.Parser) -> None: |
| 148 |
parser.parse_known_args([Path(".")]) |
| 149 |
parser.addoption("--hello", action="store_true") |
| 150 |
ns = parser.parse_known_args(["x", "--y", "--hello", "this"]) |
| 151 |
assert ns.hello is True |
| 152 |
assert ns.file_or_dir == ["x", "this"] |
| 153 |
|
| 154 |
def test_parse_known_and_unknown_args(self, parser: parseopt.Parser) -> None: |
| 155 |
parser.addoption("--hello", action="store_true") |
| 156 |
ns, unknown = parser.parse_known_and_unknown_args( |
| 157 |
["x", "--y", "--hello", "this"] |
| 158 |
) |
| 159 |
assert ns.hello is True |
| 160 |
assert ns.file_or_dir == ["x", "this"] |
| 161 |
assert unknown == ["--y"] |
| 162 |
|
| 163 |
def test_parse_will_set_default(self, parser: parseopt.Parser) -> None: |
| 164 |
parser.addoption("--hello", dest="hello", default="x", action="store") |
| 165 |
option = parser.parse([]) |
| 166 |
assert option.hello == "x" |
| 167 |
|
| 168 |
def test_parse_set_options(self, parser: parseopt.Parser) -> None: |
| 169 |
parser.addoption("--hello", dest="hello", action="store") |
| 170 |
parser.addoption("--world", dest="world", default=42) |
| 171 |
|
| 172 |
option = argparse.Namespace() |
| 173 |
parser.parse(["--hello", "world"], option) |
| 174 |
assert option.hello == "world" |
| 175 |
assert option.world == 42 |
| 176 |
assert getattr(option, parseopt.FILE_OR_DIR) == [] |
| 177 |
|
| 178 |
def test_parse_special_destination(self, parser: parseopt.Parser) -> None: |
| 179 |
parser.addoption("--ultimate-answer", type=int) |
| 180 |
args = parser.parse(["--ultimate-answer", "42"]) |
| 181 |
assert args.ultimate_answer == 42 |
| 182 |
|
| 183 |
def test_parse_split_positional_arguments(self, parser: parseopt.Parser) -> None: |
| 184 |
parser.addoption("-R", action="store_true") |
| 185 |
parser.addoption("-S", action="store_false") |
| 186 |
args = parser.parse(["-R", "4", "2", "-S"]) |
| 187 |
assert getattr(args, parseopt.FILE_OR_DIR) == ["4", "2"] |
| 188 |
args = parser.parse(["-R", "-S", "4", "2", "-R"]) |
| 189 |
assert getattr(args, parseopt.FILE_OR_DIR) == ["4", "2"] |
| 190 |
assert args.R is True |
| 191 |
assert args.S is False |
| 192 |
args = parser.parse(["-R", "4", "-S", "2"]) |
| 193 |
assert getattr(args, parseopt.FILE_OR_DIR) == ["4", "2"] |
| 194 |
assert args.R is True |
| 195 |
assert args.S is False |
| 196 |
|
| 197 |
def test_drop_short_helper(self) -> None: |
| 198 |
parser = argparse.ArgumentParser( |
| 199 |
formatter_class=parseopt.DropShorterLongHelpFormatter, allow_abbrev=False |
| 200 |
) |
| 201 |
parser.add_argument( |
| 202 |
"-t", "--twoword", "--duo", "--two-word", "--two", help="foo" |
| 203 |
) |
| 204 |
# throws error on --deux only! |
| 205 |
parser.add_argument( |
| 206 |
"-d", "--deuxmots", "--deux-mots", action="store_true", help="foo" |
| 207 |
) |
| 208 |
parser.add_argument("-s", action="store_true", help="single short") |
| 209 |
parser.add_argument("--abc", "-a", action="store_true", help="bar") |
| 210 |
parser.add_argument("--klm", "-k", "--kl-m", action="store_true", help="bar") |
| 211 |
parser.add_argument( |
| 212 |
"-P", "--pq-r", "-p", "--pqr", action="store_true", help="bar" |
| 213 |
) |
| 214 |
parser.add_argument( |
| 215 |
"--zwei-wort", "--zweiwort", "--zweiwort", action="store_true", help="bar" |
| 216 |
) |
| 217 |
parser.add_argument( |
| 218 |
"-x", "--exit-on-first", "--exitfirst", action="store_true", help="spam" |
| 219 |
) |
| 220 |
parser.add_argument("files_and_dirs", nargs="*") |
| 221 |
args = parser.parse_args(["-k", "--duo", "hallo", "--exitfirst"]) |
| 222 |
assert args.twoword == "hallo" |
| 223 |
assert args.klm is True |
| 224 |
assert args.zwei_wort is False |
| 225 |
assert args.exit_on_first is True |
| 226 |
assert args.s is False |
| 227 |
args = parser.parse_args(["--deux-mots"]) |
| 228 |
with pytest.raises(AttributeError): |
| 229 |
assert args.deux_mots is True |
| 230 |
assert args.deuxmots is True |
| 231 |
args = parser.parse_args(["file", "dir"]) |
| 232 |
assert "|".join(args.files_and_dirs) == "file|dir" |
| 233 |
|
| 234 |
def test_drop_short_0(self, parser: parseopt.Parser) -> None: |
| 235 |
parser.addoption("--funcarg", "--func-arg", action="store_true") |
| 236 |
parser.addoption("--abc-def", "--abc-def", action="store_true") |
| 237 |
parser.addoption("--klm-hij", action="store_true") |
| 238 |
with pytest.raises(UsageError): |
| 239 |
parser.parse(["--funcarg", "--k"]) |
| 240 |
|
| 241 |
def test_drop_short_2(self, parser: parseopt.Parser) -> None: |
| 242 |
parser.addoption("--func-arg", "--doit", action="store_true") |
| 243 |
args = parser.parse(["--doit"]) |
| 244 |
assert args.func_arg is True |
| 245 |
|
| 246 |
def test_drop_short_3(self, parser: parseopt.Parser) -> None: |
| 247 |
parser.addoption("--func-arg", "--funcarg", "--doit", action="store_true") |
| 248 |
args = parser.parse(["abcd"]) |
| 249 |
assert args.func_arg is False |
| 250 |
assert args.file_or_dir == ["abcd"] |
| 251 |
|
| 252 |
def test_drop_short_help0(self, parser: parseopt.Parser) -> None: |
| 253 |
parser.addoption("--func-args", "--doit", help="foo", action="store_true") |
| 254 |
parser.parse([]) |
| 255 |
help = parser.optparser.format_help() |
| 256 |
assert "--func-args, --doit foo" in help |
| 257 |
|
| 258 |
# testing would be more helpful with all help generated |
| 259 |
def test_drop_short_help1(self, parser: parseopt.Parser) -> None: |
| 260 |
group = parser.getgroup("general") |
| 261 |
group.addoption("--doit", "--func-args", action="store_true", help="foo") |
| 262 |
group._addoption( |
| 263 |
"-h", |
| 264 |
"--help", |
| 265 |
action="store_true", |
| 266 |
dest="help", |
| 267 |
help="show help message and configuration info", |
| 268 |
) |
| 269 |
parser.parse(["-h"]) |
| 270 |
help = parser.optparser.format_help() |
| 271 |
assert "-doit, --func-args foo" in help |
| 272 |
|
| 273 |
def test_multiple_metavar_help(self, parser: parseopt.Parser) -> None: |
| 274 |
""" |
| 275 |
Help text for options with a metavar tuple should display help |
| 276 |
in the form "--preferences=value1 value2 value3" (#2004). |
| 277 |
""" |
| 278 |
group = parser.getgroup("general") |
| 279 |
group.addoption( |
| 280 |
"--preferences", metavar=("value1", "value2", "value3"), nargs=3 |
| 281 |
) |
| 282 |
group._addoption("-h", "--help", action="store_true", dest="help") |
| 283 |
parser.parse(["-h"]) |
| 284 |
help = parser.optparser.format_help() |
| 285 |
assert "--preferences=value1 value2 value3" in help |
| 286 |
|
| 287 |
|
| 288 |
def test_argcomplete(pytester: Pytester, monkeypatch: MonkeyPatch) -> None: |
| 289 |
if sys.version_info >= (3, 11): |
| 290 |
# New in Python 3.11, ignores utf-8 mode |
| 291 |
encoding = locale.getencoding() |
| 292 |
else: |
| 293 |
encoding = locale.getpreferredencoding(False) |
| 294 |
try: |
| 295 |
bash_version = subprocess.run( |
| 296 |
["bash", "--version"], |
| 297 |
stdout=subprocess.PIPE, |
| 298 |
stderr=subprocess.DEVNULL, |
| 299 |
check=True, |
| 300 |
text=True, |
| 301 |
encoding=encoding, |
| 302 |
).stdout |
| 303 |
except (OSError, subprocess.CalledProcessError): |
| 304 |
pytest.skip("bash is not available") |
| 305 |
if "GNU bash" not in bash_version: |
| 306 |
# See #7518. |
| 307 |
pytest.skip("not a real bash") |
| 308 |
|
| 309 |
script = str(pytester.path.joinpath("test_argcomplete")) |
| 310 |
|
| 311 |
with open(str(script), "w", encoding="utf-8") as fp: |
| 312 |
# redirect output from argcomplete to stdin and stderr is not trivial |
| 313 |
# http://stackoverflow.com/q/12589419/1307905 |
| 314 |
# so we use bash |
| 315 |
fp.write( |
| 316 |
f'COMP_WORDBREAKS="$COMP_WORDBREAKS" {shlex.quote(sys.executable)} -m pytest 8>&1 9>&2' |
| 317 |
) |
| 318 |
# alternative would be extended Pytester.{run(),_run(),popen()} to be able |
| 319 |
# to handle a keyword argument env that replaces os.environ in popen or |
| 320 |
# extends the copy, advantage: could not forget to restore |
| 321 |
monkeypatch.setenv("_ARGCOMPLETE", "1") |
| 322 |
monkeypatch.setenv("_ARGCOMPLETE_IFS", "\x0b") |
| 323 |
monkeypatch.setenv("COMP_WORDBREAKS", " \\t\\n\"\\'><=;|&(:") |
| 324 |
|
| 325 |
arg = "--fu" |
| 326 |
monkeypatch.setenv("COMP_LINE", "pytest " + arg) |
| 327 |
monkeypatch.setenv("COMP_POINT", str(len("pytest " + arg))) |
| 328 |
result = pytester.run("bash", str(script), arg) |
| 329 |
if result.ret == 255: |
| 330 |
# argcomplete not found |
| 331 |
pytest.skip("argcomplete not available") |
| 332 |
elif not result.stdout.str(): |
| 333 |
pytest.skip( |
| 334 |
f"bash provided no output on stdout, argcomplete not available? (stderr={result.stderr.str()!r})" |
| 335 |
) |
| 336 |
else: |
| 337 |
result.stdout.fnmatch_lines(["--funcargs", "--fulltrace"]) |
| 338 |
os.mkdir("test_argcomplete.d") |
| 339 |
arg = "test_argc" |
| 340 |
monkeypatch.setenv("COMP_LINE", "pytest " + arg) |
| 341 |
monkeypatch.setenv("COMP_POINT", str(len("pytest " + arg))) |
| 342 |
result = pytester.run("bash", str(script), arg) |
| 343 |
result.stdout.fnmatch_lines(["test_argcomplete", "test_argcomplete.d/"]) |
| 344 |
|
| 345 |
|
| 346 |
def test_argument_repr_uninitialized() -> None: |
| 347 |
"""Argument.__repr__ should not crash if _action is not set yet.""" |
| 348 |
arg = parseopt.Argument.__new__(parseopt.Argument) |
| 349 |
assert repr(arg) == "Argument(<uninitialized>)" |
| 350 |
|
| 351 |
|
| 352 |
def test_argument_repr_initialized(parser: parseopt.Parser) -> None: |
| 353 |
"""Argument.__repr__ with properly initialized options.""" |
| 354 |
# Without type |
| 355 |
parser.addoption("--myflag", dest="myflag", help="test flag") |
| 356 |
option = parser._anonymous.options[-1] |
| 357 |
assert repr(option) == "Argument(opts: ['--myflag'], dest: 'myflag', default: None)" |
| 358 |
|
| 359 |
# With type |
| 360 |
parser.addoption("--count", type=int, dest="count", help="count") |
| 361 |
option = parser._anonymous.options[-1] |
| 362 |
assert ( |
| 363 |
repr(option) |
| 364 |
== "Argument(opts: ['--count'], dest: 'count', type: <class 'int'>, default: None)" |
| 365 |
) |