Skip to content
Myr

test_types.py

This file

Path

tests/test_types.py

252 lines · 7.6 KiB · Python

Last changed by

feat: new method for choice fail (#2622)antazoeybefore adoption4271fe2

History of this file

Take it

1import os.path2import pathlib3import platform4import tempfile56import pytest78import click9from click import FileError101112@pytest.mark.parametrize(13    ("type", "value", "expect"),14    [15        (click.IntRange(0, 5), "3", 3),16        (click.IntRange(5), "5", 5),17        (click.IntRange(5), "100", 100),18        (click.IntRange(max=5), "5", 5),19        (click.IntRange(max=5), "-100", -100),20        (click.IntRange(0, clamp=True), "-1", 0),21        (click.IntRange(max=5, clamp=True), "6", 5),22        (click.IntRange(0, min_open=True, clamp=True), "0", 1),23        (click.IntRange(max=5, max_open=True, clamp=True), "5", 4),24        (click.FloatRange(0.5, 1.5), "1.2", 1.2),25        (click.FloatRange(0.5, min_open=True), "0.51", 0.51),26        (click.FloatRange(max=1.5, max_open=True), "1.49", 1.49),27        (click.FloatRange(0.5, clamp=True), "-0.0", 0.5),28        (click.FloatRange(max=1.5, clamp=True), "inf", 1.5),29    ],30)31def test_range(type, value, expect):32    assert type.convert(value, None, None) == expect333435@pytest.mark.parametrize(36    ("type", "value", "expect"),37    [38        (click.IntRange(0, 5), "6", "6 is not in the range 0<=x<=5."),39        (click.IntRange(5), "4", "4 is not in the range x>=5."),40        (click.IntRange(max=5), "6", "6 is not in the range x<=5."),41        (click.IntRange(0, 5, min_open=True), 0, "0<x<=5"),42        (click.IntRange(0, 5, max_open=True), 5, "0<=x<5"),43        (click.FloatRange(0.5, min_open=True), 0.5, "x>0.5"),44        (click.FloatRange(max=1.5, max_open=True), 1.5, "x<1.5"),45    ],46)47def test_range_fail(type, value, expect):48    with pytest.raises(click.BadParameter) as exc_info:49        type.convert(value, None, None)5051    assert expect in exc_info.value.message525354def test_float_range_no_clamp_open():55    with pytest.raises(TypeError):56        click.FloatRange(0, 1, max_open=True, clamp=True)5758    sneaky = click.FloatRange(0, 1, max_open=True)59    sneaky.clamp = True6061    with pytest.raises(RuntimeError):62        sneaky.convert("1.5", None, None)636465@pytest.mark.parametrize(66    ("nargs", "multiple", "default", "expect"),67    [68        (2, False, None, None),69        (2, False, (None, None), (None, None)),70        (None, True, None, ()),71        (None, True, (None, None), (None, None)),72        (2, True, None, ()),73        (2, True, [(None, None)], ((None, None),)),74        (-1, None, None, ()),75    ],76)77def test_cast_multi_default(runner, nargs, multiple, default, expect):78    if nargs == -1:79        param = click.Argument(["a"], nargs=nargs, default=default)80    else:81        param = click.Option(["-a"], nargs=nargs, multiple=multiple, default=default)8283    cli = click.Command("cli", params=[param], callback=lambda a: a)84    result = runner.invoke(cli, standalone_mode=False)85    assert result.exception is None86    assert result.return_value == expect878889@pytest.mark.parametrize(90    ("cls", "expect"),91    [92        (None, "a/b/c.txt"),93        (str, "a/b/c.txt"),94        (bytes, b"a/b/c.txt"),95        (pathlib.Path, pathlib.Path("a", "b", "c.txt")),96    ],97)98def test_path_type(runner, cls, expect):99    cli = click.Command(100        "cli",101        params=[click.Argument(["p"], type=click.Path(path_type=cls))],102        callback=lambda p: p,103    )104    result = runner.invoke(cli, ["a/b/c.txt"], standalone_mode=False)105    assert result.exception is None106    assert result.return_value == expect107108109def _symlinks_supported():110    with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:111        target = os.path.join(tempdir, "target")112        open(target, "w").close()113        link = os.path.join(tempdir, "link")114115        try:116            os.symlink(target, link)117            return True118        except OSError:119            return False120121122@pytest.mark.skipif(123    not _symlinks_supported(), reason="The current OS or FS doesn't support symlinks."124)125def test_path_resolve_symlink(tmp_path, runner):126    test_file = tmp_path / "file"127    test_file_str = os.fspath(test_file)128    test_file.write_text("")129130    path_type = click.Path(resolve_path=True)131    param = click.Argument(["a"], type=path_type)132    ctx = click.Context(click.Command("cli", params=[param]))133134    test_dir = tmp_path / "dir"135    test_dir.mkdir()136137    abs_link = test_dir / "abs"138    abs_link.symlink_to(test_file)139    abs_rv = path_type.convert(os.fspath(abs_link), param, ctx)140    assert abs_rv == test_file_str141142    rel_link = test_dir / "rel"143    rel_link.symlink_to(pathlib.Path("..") / "file")144    rel_rv = path_type.convert(os.fspath(rel_link), param, ctx)145    assert rel_rv == test_file_str146147148def _non_utf8_filenames_supported():149    with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:150        try:151            f = open(os.path.join(tempdir, "\udcff"), "w")152        except OSError:153            return False154155        f.close()156        return True157158159@pytest.mark.skipif(160    not _non_utf8_filenames_supported(),161    reason="The current OS or FS doesn't support non-UTF-8 filenames.",162)163def test_path_surrogates(tmp_path, monkeypatch):164    monkeypatch.chdir(tmp_path)165    type = click.Path(exists=True)166    path = pathlib.Path("\udcff")167168    with pytest.raises(click.BadParameter, match="'�' does not exist"):169        type.convert(path, None, None)170171    type = click.Path(file_okay=False)172    path.touch()173174    with pytest.raises(click.BadParameter, match="'�' is a file"):175        type.convert(path, None, None)176177    path.unlink()178    type = click.Path(dir_okay=False)179    path.mkdir()180181    with pytest.raises(click.BadParameter, match="'�' is a directory"):182        type.convert(path, None, None)183184    path.rmdir()185186    def no_access(*args, **kwargs):187        """Test environments may be running as root, so we have to fake the result of188        the access tests that use os.access189        """190        p = args[0]191        assert p == path, f"unexpected os.access call on file not under test: {p!r}"192        return False193194    path.touch()195    type = click.Path(readable=True)196197    with pytest.raises(click.BadParameter, match="'�' is not readable"):198        with monkeypatch.context() as m:199            m.setattr(os, "access", no_access)200            type.convert(path, None, None)201202    type = click.Path(readable=False, writable=True)203204    with pytest.raises(click.BadParameter, match="'�' is not writable"):205        with monkeypatch.context() as m:206            m.setattr(os, "access", no_access)207            type.convert(path, None, None)208209    type = click.Path(readable=False, executable=True)210211    with pytest.raises(click.BadParameter, match="'�' is not executable"):212        with monkeypatch.context() as m:213            m.setattr(os, "access", no_access)214            type.convert(path, None, None)215216    path.unlink()217218219@pytest.mark.parametrize(220    "type",221    [222        click.File(mode="r"),223        click.File(mode="r", lazy=True),224    ],225)226def test_file_surrogates(type, tmp_path):227    path = tmp_path / "\udcff"228229    with pytest.raises(click.BadParameter, match="�': No such file or directory"):230        type.convert(path, None, None)231232233def test_file_error_surrogates():234    message = FileError(filename="\udcff").format_message()235    assert message == "Could not open file '�': unknown error"236237238@pytest.mark.skipif(239    platform.system() == "Windows", reason="Filepath syntax differences."240)241def test_invalid_path_with_esc_sequence():242    with pytest.raises(click.BadParameter) as exc_info:243        with tempfile.TemporaryDirectory(prefix="my\ndir") as tempdir:244            click.Path(dir_okay=False).convert(tempdir, None, None)245246    assert "my\\ndir" in exc_info.value.message247248249def test_choice_get_invalid_choice_message():250    choice = click.Choice(["a", "b", "c"])251    message = choice.get_invalid_choice_message("d")252    assert message == "'d' is not one of 'a', 'b', 'c'."