test_arguments.py
This file
Path
tests/test_arguments.py
305 lines · 8.2 KiB · Python
Last changed by
Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
History of this fileTake it
1import sys23import pytest45import click678def test_nargs_star(runner):9 @click.command()10 @click.argument("src", nargs=-1)11 @click.argument("dst")12 def copy(src, dst):13 click.echo(f"src={'|'.join(src)}")14 click.echo(f"dst={dst}")1516 result = runner.invoke(copy, ["foo.txt", "bar.txt", "dir"])17 assert not result.exception18 assert result.output.splitlines() == ["src=foo.txt|bar.txt", "dst=dir"]192021def test_nargs_default(runner):22 with pytest.raises(TypeError, match="nargs=-1"):2324 @click.command()25 @click.argument("src", nargs=-1, default=42)26 def copy(src):27 pass282930def test_nargs_tup(runner):31 @click.command()32 @click.argument("name", nargs=1)33 @click.argument("point", nargs=2, type=click.INT)34 def copy(name, point):35 click.echo(f"name={name}")36 x, y = point37 click.echo(f"point={x}/{y}")3839 result = runner.invoke(copy, ["peter", "1", "2"])40 assert not result.exception41 assert result.output.splitlines() == ["name=peter", "point=1/2"]424344def test_nargs_tup_composite(runner):45 variations = [46 dict(type=(str, int)),47 dict(type=click.Tuple([str, int])),48 dict(nargs=2, type=click.Tuple([str, int])),49 dict(nargs=2, type=(str, int)),50 ]5152 for opts in variations:5354 @click.command()55 @click.argument("item", **opts)56 def copy(item):57 name, id = item58 click.echo(f"name={name} id={id:d}")5960 result = runner.invoke(copy, ["peter", "1"])61 assert not result.exception62 assert result.output.splitlines() == ["name=peter id=1"]636465def test_nargs_err(runner):66 @click.command()67 @click.argument("x")68 def copy(x):69 click.echo(x)7071 result = runner.invoke(copy, ["foo"])72 assert not result.exception73 assert result.output == "foo\n"7475 result = runner.invoke(copy, ["foo", "bar"])76 assert result.exit_code == 277 assert "Got unexpected extra argument (bar)" in result.output787980def test_bytes_args(runner, monkeypatch):81 @click.command()82 @click.argument("arg")83 def from_bytes(arg):84 assert isinstance(85 arg, str86 ), "UTF-8 encoded argument should be implicitly converted to Unicode"8788 # Simulate empty locale environment variables89 monkeypatch.setattr(sys.stdin, "encoding", "utf-8")90 monkeypatch.setattr(sys, "getfilesystemencoding", lambda: "utf-8")91 monkeypatch.setattr(sys, "getdefaultencoding", lambda: "utf-8")9293 runner.invoke(94 from_bytes,95 ["Something outside of ASCII range: 林".encode()],96 catch_exceptions=False,97 )9899100def test_file_args(runner):101 @click.command()102 @click.argument("input", type=click.File("rb"))103 @click.argument("output", type=click.File("wb"))104 def inout(input, output):105 while True:106 chunk = input.read(1024)107 if not chunk:108 break109 output.write(chunk)110111 with runner.isolated_filesystem():112 result = runner.invoke(inout, ["-", "hello.txt"], input="Hey!")113 assert result.output == ""114 assert result.exit_code == 0115 with open("hello.txt", "rb") as f:116 assert f.read() == b"Hey!"117118 result = runner.invoke(inout, ["hello.txt", "-"])119 assert result.output == "Hey!"120 assert result.exit_code == 0121122123def test_path_args(runner):124 @click.command()125 @click.argument("input", type=click.Path(dir_okay=False, allow_dash=True))126 def foo(input):127 click.echo(input)128129 result = runner.invoke(foo, ["-"])130 assert result.output == "-\n"131 assert result.exit_code == 0132133134def test_file_atomics(runner):135 @click.command()136 @click.argument("output", type=click.File("wb", atomic=True))137 def inout(output):138 output.write(b"Foo bar baz\n")139 output.flush()140 with open(output.name, "rb") as f:141 old_content = f.read()142 assert old_content == b"OLD\n"143144 with runner.isolated_filesystem():145 with open("foo.txt", "wb") as f:146 f.write(b"OLD\n")147 result = runner.invoke(inout, ["foo.txt"], input="Hey!", catch_exceptions=False)148 assert result.output == ""149 assert result.exit_code == 0150 with open("foo.txt", "rb") as f:151 assert f.read() == b"Foo bar baz\n"152153154def test_stdout_default(runner):155 @click.command()156 @click.argument("output", type=click.File("w"), default="-")157 def inout(output):158 output.write("Foo bar baz\n")159 output.flush()160161 result = runner.invoke(inout, [])162 assert not result.exception163 assert result.output == "Foo bar baz\n"164165166def test_nargs_envvar(runner):167 @click.command()168 @click.option("--arg", nargs=2)169 def cmd(arg):170 click.echo("|".join(arg))171172 result = runner.invoke(173 cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar"}174 )175 assert not result.exception176 assert result.output == "foo|bar\n"177178 @click.command()179 @click.option("--arg", envvar="X", nargs=2)180 def cmd(arg):181 click.echo("|".join(arg))182183 result = runner.invoke(cmd, [], env={"X": "foo bar"})184 assert not result.exception185 assert result.output == "foo|bar\n"186187188def test_empty_nargs(runner):189 @click.command()190 @click.argument("arg", nargs=-1)191 def cmd(arg):192 click.echo(f"arg:{'|'.join(arg)}")193194 result = runner.invoke(cmd, [])195 assert result.exit_code == 0196 assert result.output == "arg:\n"197198 @click.command()199 @click.argument("arg", nargs=-1, required=True)200 def cmd2(arg):201 click.echo(f"arg:{'|'.join(arg)}")202203 result = runner.invoke(cmd2, [])204 assert result.exit_code == 2205 assert "Missing argument 'ARG...'" in result.output206207208def test_missing_arg(runner):209 @click.command()210 @click.argument("arg")211 def cmd(arg):212 click.echo(f"arg:{arg}")213214 result = runner.invoke(cmd, [])215 assert result.exit_code == 2216 assert "Missing argument 'ARG'." in result.output217218219def test_missing_argument_string_cast():220 ctx = click.Context(click.Command(""))221222 with pytest.raises(click.MissingParameter) as excinfo:223 click.Argument(["a"], required=True).full_process_value(ctx, None)224225 assert str(excinfo.value) == "missing parameter: a"226227228def test_implicit_non_required(runner):229 @click.command()230 @click.argument("f", default="test")231 def cli(f):232 click.echo(f)233234 result = runner.invoke(cli, [])235 assert result.exit_code == 0236 assert result.output == "test\n"237238239def test_eat_options(runner):240 @click.command()241 @click.option("-f")242 @click.argument("files", nargs=-1)243 def cmd(f, files):244 for filename in files:245 click.echo(filename)246 click.echo(f)247248 result = runner.invoke(cmd, ["--", "-foo", "bar"])249 assert result.output.splitlines() == ["-foo", "bar", ""]250251 result = runner.invoke(cmd, ["-f", "-x", "--", "-foo", "bar"])252 assert result.output.splitlines() == ["-foo", "bar", "-x"]253254255def test_nargs_star_ordering(runner):256 @click.command()257 @click.argument("a", nargs=-1)258 @click.argument("b")259 @click.argument("c")260 def cmd(a, b, c):261 for arg in (a, b, c):262 click.echo(arg)263264 result = runner.invoke(cmd, ["a", "b", "c"])265 assert result.output.splitlines() == ["('a',)", "b", "c"]266267268def test_nargs_specified_plus_star_ordering(runner):269 @click.command()270 @click.argument("a", nargs=-1)271 @click.argument("b")272 @click.argument("c", nargs=2)273 def cmd(a, b, c):274 for arg in (a, b, c):275 click.echo(arg)276277 result = runner.invoke(cmd, ["a", "b", "c", "d", "e", "f"])278 assert result.output.splitlines() == ["('a', 'b', 'c')", "d", "('e', 'f')"]279280281def test_defaults_for_nargs(runner):282 @click.command()283 @click.argument("a", nargs=2, type=int, default=(1, 2))284 def cmd(a):285 x, y = a286 click.echo(x + y)287288 result = runner.invoke(cmd, [])289 assert result.output.strip() == "3"290291 result = runner.invoke(cmd, ["3", "4"])292 assert result.output.strip() == "7"293294 result = runner.invoke(cmd, ["3"])295 assert result.exception is not None296 assert "argument a takes 2 values" in result.output297298299def test_multiple_param_decls_not_allowed(runner):300 with pytest.raises(TypeError):301302 @click.command()303 @click.argument("x", click.Choice(["a", "b"]))304 def copy(x):305 click.echo(x)