Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Settings.pyenvs to _actually_ use basepath by default #344

Merged
merged 2 commits into from
Jul 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion fawltydeps/packages.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@ def pyenv_sources(*pyenv_paths: Path) -> Set[PyEnvSource]:
for path in pyenv_paths:
package_dirs = set(LocalPackageResolver.find_package_dirs(path))
if not package_dirs:
logger.warning(f"Could not find a Python env at {path}!")
logger.debug(f"Could not find a Python env at {path}!")
ret.update(PyEnvSource(d) for d in package_dirs)
if pyenv_paths and not ret:
raise ValueError(f"Could not find any Python env in {pyenv_paths}!")
Expand Down
16 changes: 11 additions & 5 deletions fawltydeps/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ class Settings(BaseSettings): # type: ignore
output_format: OutputFormat = OutputFormat.HUMAN_SUMMARY
code: Set[PathOrSpecial] = {Path(".")}
deps: Set[Path] = {Path(".")}
pyenvs: Set[Path] = set()
pyenvs: Set[Path] = {Path(".")}
custom_mapping: Optional[CustomMapping] = None
ignore_undeclared: Set[str] = set()
ignore_unused: Set[str] = set()
Expand Down Expand Up @@ -189,11 +189,17 @@ def create(cls, cmdline_args: argparse.Namespace) -> "Settings":
if base_paths:
code_paths = args_dict.setdefault("code", base_paths)
deps_paths = args_dict.setdefault("deps", base_paths)
if code_paths != base_paths and deps_paths != base_paths:
pyenv_paths = args_dict.setdefault("pyenvs", base_paths)
if (
code_paths != base_paths
and deps_paths != base_paths
and pyenv_paths != base_paths
):
msg = (
"All three path specifications (code, deps, and base)"
f"have been used. Use at most 2. basepaths={base_paths}, "
f"code_paths={code_paths}, deps_paths={deps_paths}"
"All four path specifications (code, deps, pyenvs, and base)"
f"have been used. Use at most 3. basepaths={base_paths}, "
f"code_paths={code_paths}, deps_paths={deps_paths}, "
f"pyenv_paths={pyenv_paths}"
)
raise argparse.ArgumentError(argument=None, message=msg)

Expand Down
4 changes: 2 additions & 2 deletions tests/test_cmdline.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def make_json_settings_dict(**kwargs):
"actions": ["check_undeclared", "check_unused"],
"code": ["."],
"deps": ["."],
"pyenvs": [],
"pyenvs": ["."],
"custom_mapping": None,
"output_format": "human_summary",
"ignore_undeclared": [],
Expand Down Expand Up @@ -850,7 +850,7 @@ def test_cmdline_on_ignored_undeclared_option(
output_format = 'human_detailed'
# code = ['.']
deps = ['foobar']
# pyenvs = []
# pyenvs = ['.']
# ignore_undeclared = []
# ignore_unused = []
# deps_parser_choice = ...
Expand Down
101 changes: 75 additions & 26 deletions tests/test_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,21 @@
import string
import sys
from dataclasses import dataclass, field
from itertools import chain, permutations, product
from itertools import chain, combinations, permutations, product
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Set, Tuple, Type, TypeVar, Union
from typing import (
Any,
Dict,
Iterable,
Iterator,
List,
Optional,
Set,
Tuple,
Type,
TypeVar,
Union,
)

import pytest
from hypothesis import given, strategies
Expand All @@ -27,7 +39,7 @@
actions={Action.REPORT_UNDECLARED, Action.REPORT_UNUSED},
code={Path(".")},
deps={Path(".")},
pyenvs=set(),
pyenvs={Path(".")},
custom_mapping_file=set(),
custom_mapping=None,
output_format=OutputFormat.HUMAN_SUMMARY,
Expand Down Expand Up @@ -69,37 +81,69 @@ def _inner(**kwargs: str):

safe_string = strategies.text(alphabet=string.ascii_letters + string.digits, min_size=1)
nonempty_string_set = strategies.sets(safe_string, min_size=1)
three_different_string_groups = strategies.tuples(
nonempty_string_set, nonempty_string_set, nonempty_string_set
).filter(lambda ss: ss[0] != ss[1] and ss[0] != ss[2] and ss[1] != ss[2])
four_different_string_groups = strategies.tuples(
*([nonempty_string_set] * 4),
jherland marked this conversation as resolved.
Show resolved Hide resolved
).filter(lambda ss: all(a != b for a, b in combinations(ss, 2)))


@given(code_deps_base=three_different_string_groups)
def test_code_deps_and_base_unequal__raises_error(code_deps_base):
code, deps, base = code_deps_base
args = list(base) + ["--code"] + list(code) + ["--deps"] + list(deps)
@given(code_deps_pyenvs_base=four_different_string_groups)
def test_code_deps_pyenvs_and_base_unequal__raises_error(code_deps_pyenvs_base):
code, deps, pyenvs, base = code_deps_pyenvs_base
args = [*base, "--code", *code, "--deps", *deps, "--pyenv", *pyenvs]
with pytest.raises(argparse.ArgumentError):
run_build_settings(args)


path_options = { # options (-> settings members) that interact with basepath
"--code": "code",
"--deps": "deps",
"--pyenv": "pyenvs",
}

Item = TypeVar("Item")


def subsets(
items: Set[Item],
min_size: int = 0,
max_size: int = sys.maxsize,
Nour-Mws marked this conversation as resolved.
Show resolved Hide resolved
) -> Iterator[Set[Item]]:
"""Generate all subsets of the given set within the given size constraints.

This is equivalent to the "power set" with a size filter applied.
"""
max_size = min(max_size, len(items))
for size in range(min_size, max_size + 1):
for tpl in combinations(items, size):
yield set(tpl)


@given(basepaths=nonempty_string_set, fillers=nonempty_string_set)
@pytest.mark.parametrize(["filled", "unfilled"], [("code", "deps"), ("deps", "code")])
def test_base_path_respects_path_already_filled_via_cli(
basepaths, filled, unfilled, fillers
):
args = list(basepaths) + [f"--{filled}"] + list(fillers)
@pytest.mark.parametrize(
["filled", "unfilled"],
[
pytest.param(opts, path_options.keys() - opts, id="Passing " + ", ".join(opts))
for opts in subsets(set(path_options.keys()), 1, len(path_options) - 1)
],
)
def test_path_option_overrides_base_path(basepaths, filled, unfilled, fillers):
assert filled and unfilled and (unfilled | filled) == path_options.keys()
args = list(basepaths)
for option in filled:
args += [option] + list(fillers)
settings = run_build_settings(args)
assert getattr(settings, filled) == to_path_set(fillers)
assert getattr(settings, unfilled) == to_path_set(basepaths)
for option in filled:
assert getattr(settings, path_options[option]) == to_path_set(fillers)
for option in unfilled:
assert getattr(settings, path_options[option]) == to_path_set(basepaths)


@given(basepaths=nonempty_string_set)
def test_base_path_fills_code_and_deps_when_other_path_settings_are_absent(basepaths):
def test_base_path_fills_path_options_when_other_path_settings_are_absent(basepaths):
# Nothing else through CLI nor through config file
settings = run_build_settings(cmdl=list(basepaths))
expected = to_path_set(basepaths)
assert settings.code == expected
assert settings.deps == expected
assert all(getattr(settings, memb) == expected for memb in path_options.values())


@pytest.mark.parametrize(
Expand All @@ -108,17 +152,23 @@ def test_base_path_fills_code_and_deps_when_other_path_settings_are_absent(basep
pytest.param(conf_sett, base, id=test_name)
for conf_sett, base, test_name in [
(None, {"single-base"}, "empty-config"),
(dict(code=["test-code"]), {"base1", "base2"}, "only-code-set"),
(dict(deps=["deps-test"]), {"single-base"}, "only-deps-set"),
({"code": ["test-code"]}, {"base1", "base2"}, "only-code-set"),
({"deps": ["deps-test"]}, {"single-base"}, "only-deps-set"),
({"pyenvs": ["pyenvs-test"]}, {"single-base"}, "only-pyenvs-set"),
(
dict(code=["code-test"], deps=["test-deps"]),
{"code": ["code-test"], "deps": ["test-deps"]},
{"base1", "base2"},
"code-and-deps-set",
),
(
{"code": ["code-test"], "deps": ["test-deps"], "pyenvs": ["abc"]},
{"base1", "base2"},
"all-three-set",
),
]
],
)
def test_base_path_overrides_config_file_code_and_deps(
def test_base_path_overrides_config_file_for_all_path_options(
config_settings,
basepaths,
setup_fawltydeps_config,
Expand All @@ -129,8 +179,7 @@ def test_base_path_overrides_config_file_code_and_deps(

settings = run_build_settings(cmdl=list(basepaths), config_file=config_file)
expected = to_path_set(basepaths)
assert settings.code == expected
assert settings.deps == expected
assert all(getattr(settings, memb) == expected for memb in path_options.values())


OPTION_VALUES = {
Expand Down