Skip to content
Myr

test_types.py

This file

Path

tests/test_types.py

234 lines · 7.0 KiB · Python

Last changed by

Merge branch '8.1.x'David Lordbefore adoptiond9af5cf

History of this file

Take it

1import os.path2import pathlib3import tempfile45import pytest67import click8from click import FileError91011@pytest.mark.parametrize(12    ("type", "value", "expect"),13    [14        (click.IntRange(0, 5), "3", 3),15        (click.IntRange(5), "5", 5),16        (click.IntRange(5), "100", 100),17        (click.IntRange(max=5), "5", 5),18        (click.IntRange(max=5), "-100", -100),19        (click.IntRange(0, clamp=True), "-1", 0),20        (click.IntRange(max=5, clamp=True), "6", 5),21        (click.IntRange(0, min_open=True, clamp=True), "0", 1),22        (click.IntRange(max=5, max_open=True, clamp=True), "5", 4),23        (click.FloatRange(0.5, 1.5), "1.2", 1.2),24        (click.FloatRange(0.5, min_open=True), "0.51", 0.51),25        (click.FloatRange(max=1.5, max_open=True), "1.49", 1.49),26        (click.FloatRange(0.5, clamp=True), "-0.0", 0.5),27        (click.FloatRange(max=1.5, clamp=True), "inf", 1.5),28    ],29)30def test_range(type, value, expect):31    assert type.convert(value, None, None) == expect323334@pytest.mark.parametrize(35    ("type", "value", "expect"),36    [37        (click.IntRange(0, 5), "6", "6 is not in the range 0<=x<=5."),38        (click.IntRange(5), "4", "4 is not in the range x>=5."),39        (click.IntRange(max=5), "6", "6 is not in the range x<=5."),40        (click.IntRange(0, 5, min_open=True), 0, "0<x<=5"),41        (click.IntRange(0, 5, max_open=True), 5, "0<=x<5"),42        (click.FloatRange(0.5, min_open=True), 0.5, "x>0.5"),43        (click.FloatRange(max=1.5, max_open=True), 1.5, "x<1.5"),44    ],45)46def test_range_fail(type, value, expect):47    with pytest.raises(click.BadParameter) as exc_info:48        type.convert(value, None, None)4950    assert expect in exc_info.value.message515253def test_float_range_no_clamp_open():54    with pytest.raises(TypeError):55        click.FloatRange(0, 1, max_open=True, clamp=True)5657    sneaky = click.FloatRange(0, 1, max_open=True)58    sneaky.clamp = True5960    with pytest.raises(RuntimeError):61        sneaky.convert("1.5", None, None)626364@pytest.mark.parametrize(65    ("nargs", "multiple", "default", "expect"),66    [67        (2, False, None, None),68        (2, False, (None, None), (None, None)),69        (None, True, None, ()),70        (None, True, (None, None), (None, None)),71        (2, True, None, ()),72        (2, True, [(None, None)], ((None, None),)),73        (-1, None, None, ()),74    ],75)76def test_cast_multi_default(runner, nargs, multiple, default, expect):77    if nargs == -1:78        param = click.Argument(["a"], nargs=nargs, default=default)79    else:80        param = click.Option(["-a"], nargs=nargs, multiple=multiple, default=default)8182    cli = click.Command("cli", params=[param], callback=lambda a: a)83    result = runner.invoke(cli, standalone_mode=False)84    assert result.exception is None85    assert result.return_value == expect868788@pytest.mark.parametrize(89    ("cls", "expect"),90    [91        (None, "a/b/c.txt"),92        (str, "a/b/c.txt"),93        (bytes, b"a/b/c.txt"),94        (pathlib.Path, pathlib.Path("a", "b", "c.txt")),95    ],96)97def test_path_type(runner, cls, expect):98    cli = click.Command(99        "cli",100        params=[click.Argument(["p"], type=click.Path(path_type=cls))],101        callback=lambda p: p,102    )103    result = runner.invoke(cli, ["a/b/c.txt"], standalone_mode=False)104    assert result.exception is None105    assert result.return_value == expect106107108def _symlinks_supported():109    with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:110        target = os.path.join(tempdir, "target")111        open(target, "w").close()112        link = os.path.join(tempdir, "link")113114        try:115            os.symlink(target, link)116            return True117        except OSError:118            return False119120121@pytest.mark.skipif(122    not _symlinks_supported(), reason="The current OS or FS doesn't support symlinks."123)124def test_path_resolve_symlink(tmp_path, runner):125    test_file = tmp_path / "file"126    test_file_str = os.fspath(test_file)127    test_file.write_text("")128129    path_type = click.Path(resolve_path=True)130    param = click.Argument(["a"], type=path_type)131    ctx = click.Context(click.Command("cli", params=[param]))132133    test_dir = tmp_path / "dir"134    test_dir.mkdir()135136    abs_link = test_dir / "abs"137    abs_link.symlink_to(test_file)138    abs_rv = path_type.convert(os.fspath(abs_link), param, ctx)139    assert abs_rv == test_file_str140141    rel_link = test_dir / "rel"142    rel_link.symlink_to(pathlib.Path("..") / "file")143    rel_rv = path_type.convert(os.fspath(rel_link), param, ctx)144    assert rel_rv == test_file_str145146147def _non_utf8_filenames_supported():148    with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:149        try:150            f = open(os.path.join(tempdir, "\udcff"), "w")151        except OSError:152            return False153154        f.close()155        return True156157158@pytest.mark.skipif(159    not _non_utf8_filenames_supported(),160    reason="The current OS or FS doesn't support non-UTF-8 filenames.",161)162def test_path_surrogates(tmp_path, monkeypatch):163    monkeypatch.chdir(tmp_path)164    type = click.Path(exists=True)165    path = pathlib.Path("\udcff")166167    with pytest.raises(click.BadParameter, match="'�' does not exist"):168        type.convert(path, None, None)169170    type = click.Path(file_okay=False)171    path.touch()172173    with pytest.raises(click.BadParameter, match="'�' is a file"):174        type.convert(path, None, None)175176    path.unlink()177    type = click.Path(dir_okay=False)178    path.mkdir()179180    with pytest.raises(click.BadParameter, match="'�' is a directory"):181        type.convert(path, None, None)182183    path.rmdir()184185    def no_access(*args, **kwargs):186        """Test environments may be running as root, so we have to fake the result of187        the access tests that use os.access188        """189        p = args[0]190        assert p == path, f"unexpected os.access call on file not under test: {p!r}"191        return False192193    path.touch()194    type = click.Path(readable=True)195196    with pytest.raises(click.BadParameter, match="'�' is not readable"):197        with monkeypatch.context() as m:198            m.setattr(os, "access", no_access)199            type.convert(path, None, None)200201    type = click.Path(readable=False, writable=True)202203    with pytest.raises(click.BadParameter, match="'�' is not writable"):204        with monkeypatch.context() as m:205            m.setattr(os, "access", no_access)206            type.convert(path, None, None)207208    type = click.Path(readable=False, executable=True)209210    with pytest.raises(click.BadParameter, match="'�' is not executable"):211        with monkeypatch.context() as m:212            m.setattr(os, "access", no_access)213            type.convert(path, None, None)214215    path.unlink()216217218@pytest.mark.parametrize(219    "type",220    [221        click.File(mode="r"),222        click.File(mode="r", lazy=True),223    ],224)225def test_file_surrogates(type, tmp_path):226    path = tmp_path / "\udcff"227228    with pytest.raises(click.BadParameter, match="�': No such file or directory"):229        type.convert(path, None, None)230231232def test_file_error_surrogates():233    message = FileError(filename="\udcff").format_message()234    assert message == "Could not open file '�': unknown error"