diff --git a/pip_check_reqs/__init__.py b/pip_check_reqs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..384551fdc60eb96921f08b9a2bc796511e4d2204 --- /dev/null +++ b/pip_check_reqs/__init__.py @@ -0,0 +1,3 @@ +"""Package for finding missing and extra requirements.""" + +__version__ = "3.1.0" diff --git a/pip_check_reqs/common.py b/pip_check_reqs/common.py new file mode 100644 index 0000000000000000000000000000000000000000..42c7e19bc2c25dbeed47ce32df7639bceb9467cb --- /dev/null +++ b/pip_check_reqs/common.py @@ -0,0 +1,575 @@ +"""Common functions.""" + +from __future__ import annotations + +import ast +import fnmatch +import importlib.metadata +import logging +import os +import sys +from dataclasses import dataclass, field +from functools import cache +from importlib.util import find_spec +from pathlib import Path +from typing import TYPE_CHECKING + +from packaging.markers import Marker +from packaging.utils import NormalizedName, canonicalize_name +from pip._internal.commands.show import ( + _PackageInfo, # pyright: ignore[reportPrivateUsage] + search_packages_info, +) +from pip._internal.network.session import PipSession +from pip._internal.req.constructors import install_req_from_line +from pip._internal.req.req_file import ParsedRequirement, parse_requirements + +from . import __version__ + +if TYPE_CHECKING: + import argparse + from collections.abc import Callable, Generator, Iterable + from typing import NoReturn, TextIO + +log = logging.getLogger(__name__) + + +@cache +def cached_resolve_path(path: Path) -> Path: + return path.resolve() + + +# This is a slow operation. +# It only happens once when calling the CLI, but it is hit many times in +# tests. +# We cache the result to speed up tests. +@cache +def get_packages_info() -> list[_PackageInfo]: + all_pkgs: list[str] = [ + dist.metadata["Name"] # pyright: ignore[reportUnknownMemberType] + for dist in importlib.metadata.distributions() + ] + + return list(search_packages_info(query=all_pkgs, include_files=True)) + + +@dataclass +class FoundModule: + """A module with uses in the source.""" + + modname: str + filename: Path + locations: list[tuple[str, int]] = field( + default_factory=list[tuple[str, int]], + ) + + def __post_init__(self) -> None: + self.filename = Path(self.filename).resolve() + + +@dataclass +class ImportedModules: + """The modules which the scanned source imports.""" + + found: dict[str, FoundModule] + """Modules which we found in the environment, keyed by module name.""" + + uninstalled: dict[str, list[tuple[str, int]]] + """Top-level modules which are not installed, keyed by module name. + + Each value is the list of ``(filename, line number)`` locations which + import the module. + """ + + +_IMPORT_ERROR_NAMES = frozenset({"ImportError", "ModuleNotFoundError"}) + + +def _catches_import_error(*, handler: ast.ExceptHandler) -> bool: + """Whether an ``except`` clause catches an import which is not installed. + + A bare ``except`` catches everything, so it counts. + """ + if handler.type is None: + return True + + caught = ( + handler.type.elts + if isinstance(handler.type, ast.Tuple) + else [handler.type] + ) + for exception in caught: + if isinstance(exception, ast.Name): + name = exception.id + elif isinstance(exception, ast.Attribute): + # An exception may be given by a dotted path, as + # ``builtins.ImportError`` is. + name = exception.attr + else: + continue + if name in _IMPORT_ERROR_NAMES: + return True + return False + + +class _ImportVisitor(ast.NodeVisitor): + def __init__(self, ignore_modules_function: Callable[[str], bool]) -> None: + super().__init__() + self._ignore_modules_function = ignore_modules_function + self._modules: dict[str, FoundModule] = {} + self._uninstalled: dict[str, list[tuple[str, int]]] = {} + self._location: str | None = None + self._optional_import_depth = 0 + + def set_location(self, *, location: str) -> None: + self._location = location + + # Ignore the name error as we are overriding the method. + def visit_Import( # pylint: disable=invalid-name + self, + node: ast.Import, + ) -> None: + for alias in node.names: + self._add_module(alias.name, node.lineno) + + # Ignore the name error as we are overriding the method. + def visit_ImportFrom( # pylint: disable=invalid-name + self, + node: ast.ImportFrom, + ) -> None: + if node.module == "__future__": + # not an actual module + return + if node.module is None or node.level != 0: + # relative import + return + if not self._module_exists(modname=node.module): + self._record_uninstalled(modname=node.module, lineno=node.lineno) + return + for alias in node.names: + self._add_module(node.module + "." + alias.name, node.lineno) + + # Ignore the name error as we are overriding the method. + def visit_Try( # pylint: disable=invalid-name + self, + node: ast.Try, + ) -> None: + """Visit a ``try`` statement, noting imports it makes optional. + + A soft dependency is imported in a ``try`` block which catches + ``ImportError``, so the code runs whether or not it is installed. + Such an import is deliberately optional, so we do not report it as + an import we could not resolve. + """ + optional = any( + _catches_import_error(handler=handler) for handler in node.handlers + ) + self._optional_import_depth += int(optional) + for statement in node.body: + self.visit(statement) + self._optional_import_depth -= int(optional) + + # An import in a handler, in ``else`` or in ``finally`` is not + # guarded by this ``try``, so we treat it as any other import. + unguarded: list[ast.AST] = [ + *node.handlers, + *node.orelse, + *node.finalbody, + ] + for node_to_visit in unguarded: + self.visit(node_to_visit) + + @staticmethod + def _module_exists(*, modname: str) -> bool: + modname_parts_progress: list[str] = [] + for modname_part in modname.split("."): + name = ".".join([*modname_parts_progress, modname_part]) + try: + module_spec = find_spec(name=name) + except (ModuleNotFoundError, ValueError): + return False + if module_spec is None: + return False + modname_parts_progress.append(modname_part) + return True + + def _record_uninstalled(self, *, modname: str, lineno: int) -> None: + """Note an import which we could not resolve to an installed module. + + We only note the import when its top-level module is missing, which + is what an uninstalled distribution looks like. A missing sub-module + of an installed distribution is a different problem, and the + distribution which would provide it is checked already. + """ + if self._optional_import_depth: + # The import is a soft dependency, so the code tolerates the + # module not being installed and there is nothing to report. + return + + top_level_name = modname.split(".", maxsplit=1)[0] + # An ignore glob may name either the dotted import path, as it may + # for an installed module, or just the top-level module which we + # report. + if self._ignore_modules_function(modname) or ( + self._ignore_modules_function(top_level_name) + ): + return + + try: + module_spec = find_spec(name=top_level_name) + except ValueError: + # The module has no ``__spec__`` attribute, as ``__main__`` does + # not, so it is available rather than missing. + return + + if module_spec is not None: + return + + assert isinstance(self._location, str) + locations = self._uninstalled.setdefault(top_level_name, []) + locations.append((self._location, lineno)) + + def _add_module(self, modname: str, lineno: int) -> None: + if self._ignore_modules_function(modname): + return + + modname_parts_progress: list[str] = [] + for modname_part in modname.split("."): + name = ".".join([*modname_parts_progress, modname_part]) + try: + module_spec = find_spec(name=name) + except ValueError: + # The module has no __spec__ attribute. + # For example, if importing __main__. + return + + if module_spec is None: + # The component specified at this point is not installed. + self._record_uninstalled(modname=name, lineno=lineno) + return + + if module_spec.origin is None: + modname_parts_progress.append(modname_part) + continue + + modpath = module_spec.origin + + if modpath == "frozen": + # Frozen modules are modules written in Python whose compiled + # byte-code object is incorporated into a custom-built Python + # interpreter by Python's freeze utility. + continue + + modpath_path = Path(modpath) + modname = module_spec.name + + if modname not in self._modules: + if modpath_path.is_file(): + if modpath_path.name == "__init__.py": + modpath_path = modpath_path.parent + else: + # We have this empty "else" so that we are + # not tempted to combine the "is file" and "is + # __init__" checks, and to make sure we have coverage + # for this case. + pass + self._modules[modname] = FoundModule( + modname=modname, + filename=modpath_path, + ) + assert isinstance(self._location, str) + self._modules[modname].locations.append((self._location, lineno)) + return + + def finalise(self) -> dict[str, FoundModule]: + return self._modules + + def uninstalled(self) -> dict[str, list[tuple[str, int]]]: + return self._uninstalled + + +def pyfiles(root: Path) -> Generator[Path, None, None]: + if not root.exists(): + msg = f"source path not found: {root}" + raise FileNotFoundError(msg) + + if root.is_file(): + if root.suffix == ".py": + yield root.absolute() + else: + msg = f"{root} is not a python file or directory" + raise ValueError(msg) + else: + for item in root.rglob("*.py"): + yield item.absolute() + + +def validate_requirements_file(*, path: Path) -> None: + if not path.is_file(): + msg = f"requirements file not found: {path}" + raise FileNotFoundError(msg) + + +def report_input_error( + *, + parser: argparse.ArgumentParser, + debug: bool, + error: OSError | ValueError, +) -> NoReturn: + if debug: + raise error + parser.error(str(error)) + + +def log_level(*, debug: bool, verbose: bool) -> int: + if debug: + return logging.DEBUG + if verbose: + return logging.INFO + return logging.WARNING + + +def source_module_names(*, paths: Iterable[Path]) -> set[str]: + """Return the top-level module names which the scanned source provides. + + A module of the source we scan is not expected to be installed, so we + must not report it as uninstalled. We do not import the source, so we + take the names from the file system: any file or directory name at or + below a path we scan can name a module of the source. + """ + names: set[str] = set() + for path in paths: + absolute_path = path.absolute() + for filename in pyfiles(path): + names.add(filename.stem) + if absolute_path.is_dir(): + relative_filename = filename.relative_to(absolute_path) + names.update(relative_filename.parts[:-1]) + names.add(absolute_path.stem) + return names + + +def find_imported_modules( + *, + paths: Iterable[Path], + ignore_files_function: Callable[[str], bool], + ignore_modules_function: Callable[[str], bool], +) -> ImportedModules: + # We take the names the source provides before scanning, as an ignored + # file still gives a module which the source, and not an installed + # distribution, provides. + provided_names = source_module_names(paths=paths) + vis = _ImportVisitor(ignore_modules_function=ignore_modules_function) + for path in paths: + for filename in pyfiles(path): + if ignore_files_function(str(filename)): + log.info("ignoring: %s", filename) + continue + log.debug("scanning: %s", filename) + content = filename.read_text(encoding="utf-8") + vis.set_location(location=str(filename)) + try: + tree = ast.parse(content, str(filename)) + except SyntaxError as exc: + # ``ast`` knows where the problem is, but the default traceback + # buries that behind a stack trace, so we surface it as an + # input error with the file and line which could not be parsed. + msg = f"could not parse {filename}:{exc.lineno}: {exc.msg}" + raise ValueError(msg) from exc + vis.visit(tree) + + uninstalled = { + modname: locations + for modname, locations in vis.uninstalled().items() + if modname not in provided_names + } + return ImportedModules(found=vis.finalise(), uninstalled=uninstalled) + + +def find_required_modules( + *, + ignore_requirements_function: Callable[ + [str | ParsedRequirement], + bool, + ], + skip_incompatible: bool, + requirements_filename: Path, +) -> set[NormalizedName]: + explicit: set[NormalizedName] = set() + for requirement in parse_requirements( + str(requirements_filename), + session=PipSession(), + ): + requirement_name = install_req_from_line( + requirement.requirement, + ).name + if requirement_name is None: + # A direct URL such as ``git+ssh://git@example.com/org/repo.git`` + # carries no distribution name, and pip will not learn one without + # fetching the project. Skipping the line would silently drop a + # requirement and report the modules it provides as missing, so + # ask for the name instead of guessing at it. + hint = "Add an '#egg=' fragment naming the distribution." + msg = f"requirement has no name: {requirement.requirement}. {hint}" + raise ValueError(msg) + + if ignore_requirements_function(requirement): + log.debug("ignoring requirement: %s", requirement_name) + continue + + if skip_incompatible: + requirement_string = requirement.requirement + if not has_compatible_markers(full_requirement=requirement_string): + log.debug( + "ignoring requirement (incompatible environment " + "marker): %s", + requirement_string, + ) + continue + + log.debug("found requirement: %s", requirement_name) + explicit.add(canonicalize_name(requirement_name)) + + return explicit + + +def has_compatible_markers(*, full_requirement: str) -> bool: + if ";" not in full_requirement: + return True # No environment marker. + + enviroment_marker = full_requirement.split(";")[1] + if not enviroment_marker: + return True # Empty environment marker. + + return Marker(enviroment_marker).evaluate() + + +def package_path(*, path: Path) -> Path | None: + """Return the package path for a given Python package sentinel file. + + Return None if the path is not a sentinel file. + + A sentinel file is the __init__.py or its compiled variants. + """ + if path.parent == path.parent.parent: + return None + + if path.name not in ("__init__.py", "__init__.pyc", "__init__.pyo"): + return None + + return path.parent + + +def _null_ignorer(_: str | ParsedRequirement) -> bool: + return False + + +def ignorer(*, ignore_cfg: list[str]) -> Callable[..., bool]: + if not ignore_cfg: + return _null_ignorer + + def ignorer_function( + candidate: str | ParsedRequirement, + ignore_cfg: list[str] = ignore_cfg, + ) -> bool: + working_directory = Path.cwd() + for ignore in ignore_cfg: + if isinstance(candidate, str): + candidate_path = candidate + else: + optional_candidate_path = install_req_from_line( + candidate.requirement, + ).name + assert isinstance(optional_candidate_path, str) + candidate_path = optional_candidate_path + + if fnmatch.fnmatch(candidate_path, ignore): + return True + + # Files are given as absolute paths, while an ignore glob is + # usually written relative to the working directory, so we match + # against the relative path as well. + # A path may contain ``..``, for example when the source to scan + # was given as ``scripts/../src``, so we normalize it before + # comparing. + # We use ``Path`` rather than ``os.path.relpath``, which raises + # ``ValueError`` on Windows for a path on a different drive to the + # working directory. + absolute_candidate = Path( + os.path.normpath(working_directory / candidate_path), + ) + if absolute_candidate.is_relative_to(working_directory): + relative_candidate = absolute_candidate.relative_to( + working_directory, + ) + if fnmatch.fnmatch(str(relative_candidate), ignore): + return True + return False + + return ignorer_function + + +def _yellow(*, message: str) -> str: + yellow = "\033[33m" + reset = "\033[0m" + return f"{yellow}{message}{reset}" + + +def wrong_environment_warning( + *, + running_prefix: Path, + active_virtualenv: str | None, + color: bool, +) -> str | None: + """Return a warning if we do not run from the active virtual environment. + + Return ``None`` when there is nothing to warn about, which is when no + virtual environment is active or when we run from the active one. + + A shell caches the paths of the commands it has run, so right after + ``pip install pip-check-reqs`` in a new virtual environment, the shell + can still resolve ``pip-missing-reqs`` to a command from another + environment. + That command inspects the packages installed alongside it, not the ones + in the active environment, so the results describe the wrong environment. + """ + if not active_virtualenv: + return None + + active_prefix = Path(active_virtualenv).resolve() + resolved_running_prefix = running_prefix.resolve() + if active_prefix == resolved_running_prefix: + return None + + message = ( + f"WARNING: Running from {resolved_running_prefix}, but the active " + f"virtual environment is {active_prefix}. " + "Results describe the environment pip-check-reqs is installed in. " + "Install pip-check-reqs in the active virtual environment, and " + 'run "hash -r" ("rehash" in zsh), to check that environment.' + ) + if color: + return _yellow(message=message) + return message + + +def report_wrong_environment(*, stream: TextIO) -> None: + """Write a warning to ``stream`` if we run from the wrong environment.""" + warning = wrong_environment_warning( + running_prefix=Path(sys.prefix), + active_virtualenv=os.environ.get("VIRTUAL_ENV"), + color=stream.isatty(), + ) + if warning is not None: + stream.write(warning + "\n") + + +def version_info() -> str: + major, minor, patch = sys.version_info[:3] + python_version = f"{major}.{minor}.{patch}" + parent_directory = Path(__file__).parent.resolve() + return ( + f"pip-check-reqs {__version__} " + f"from {parent_directory} " + f"(python {python_version})" + ) diff --git a/pip_check_reqs/find_extra_reqs.py b/pip_check_reqs/find_extra_reqs.py new file mode 100644 index 0000000000000000000000000000000000000000..91a59772701897cae115a496329d4d1eba9e6f5f --- /dev/null +++ b/pip_check_reqs/find_extra_reqs.py @@ -0,0 +1,241 @@ +"""Find extra requirements.""" + +from __future__ import annotations + +import argparse +import collections +import logging +import sys +from pathlib import Path +from typing import TYPE_CHECKING + +from packaging.utils import NormalizedName, canonicalize_name + +from pip_check_reqs import common + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable + + from pip._internal.req.req_file import ParsedRequirement + +log = logging.getLogger(__name__) + + +def find_extra_reqs( + *, + requirements_filename: Path, + paths: Iterable[Path], + ignore_files_function: Callable[[str], bool], + ignore_modules_function: Callable[[str], bool], + ignore_requirements_function: Callable[ + [str | ParsedRequirement], + bool, + ], + skip_incompatible: bool, +) -> list[str]: + # 1. find files used by imports in the code (as best we can without + # executing) + used_modules = common.find_imported_modules( + paths=paths, + ignore_files_function=ignore_files_function, + ignore_modules_function=ignore_modules_function, + ).found + + installed_files: dict[Path, str] = {} + packages_info = common.get_packages_info() + installed_names: set[NormalizedName] = set() + + for package in packages_info: + package_name = package.name + package_location = package.location + installed_names.add(canonicalize_name(package_name)) + + log.debug( + "installed package: %s (at %s)", + package_name, + package_location, + ) + for item in package.files or []: + path = Path(package_location) / item + path = common.cached_resolve_path(path=path) + + installed_files[path] = package_name + package_path = common.package_path(path=path) + if package_path: + # we've seen a package file so add the bare package directory + # to the installed list as well as we might want to look up + # a package by its directory path later + installed_files[package_path] = package_name + + # 3. match imported modules against those packages + used: collections.defaultdict[ + NormalizedName, + list[common.FoundModule], + ] = collections.defaultdict(list) + + for modname, info in used_modules.items(): + # probably standard library if it's not in the files list + if info.filename in installed_files: + used_name = canonicalize_name(installed_files[info.filename]) + log.debug( + "used module: %s (from package %s)", + modname, + installed_files[info.filename], + ) + used[used_name].append(info) + else: + log.debug( + "used module: %s (from file %s, assuming stdlib or local)", + modname, + info.filename, + ) + + # 4. compare with requirements + explicit = common.find_required_modules( + ignore_requirements_function=ignore_requirements_function, + skip_incompatible=skip_incompatible, + requirements_filename=requirements_filename, + ) + + extras: list[str] = [] + for name in explicit: + if name in used: + continue + + if name not in installed_names: + # We know which modules a requirement provides by looking at the + # files of the installed distribution, so a requirement which is + # not installed looks unused even when the code imports it. + # Reporting it would be a false positive, so we say what we could + # not check instead. + log.warning( + "%s is not installed, so we cannot tell whether it is used", + name, + ) + continue + + extras.append(name) + + return extras + + +def main(arguments: list[str] | None = None) -> None: + """pip-extra-reqs entry point.""" + parser = argparse.ArgumentParser() + parser.add_argument("paths", type=Path, nargs="*") + parser.add_argument( + "--requirements-file", + dest="requirements_filename", + type=Path, + metavar="PATH", + default=Path("requirements.txt"), + help='path to the requirements file (defaults to "requirements.txt")', + ) + parser.add_argument( + "-f", + "--ignore-file", + dest="ignore_files", + action="append", + default=[], + help="file paths globs to ignore", + ) + parser.add_argument( + "-m", + "--ignore-module", + dest="ignore_mods", + action="append", + default=[], + help="used module names (globs are ok) to ignore", + ) + parser.add_argument( + "-r", + "--ignore-requirement", + dest="ignore_reqs", + action="append", + default=[], + help="reqs in requirements to ignore", + ) + parser.add_argument( + "-s", + "--skip-incompatible", + dest="skip_incompatible", + action="store_true", + default=False, + help="skip requirements that have incompatible environment markers", + ) + parser.add_argument( + "-v", + "--verbose", + dest="verbose", + action="store_true", + default=False, + help="be more verbose", + ) + parser.add_argument( + "-d", + "--debug", + dest="debug", + action="store_true", + default=False, + help="be *really* verbose", + ) + parser.add_argument( + "-V", + "--version", + dest="version", + action="store_true", + default=False, + help="display version information", + ) + + parse_result = parser.parse_args(arguments) + + if parse_result.version: + sys.stdout.write(common.version_info() + "\n") + sys.exit(0) + + if not parse_result.paths: + parser.error("no source files or directories specified") + + ignore_files = common.ignorer(ignore_cfg=parse_result.ignore_files) + ignore_mods = common.ignorer(ignore_cfg=parse_result.ignore_mods) + ignore_reqs = common.ignorer(ignore_cfg=parse_result.ignore_reqs) + + logging.basicConfig(format="%(message)s") + level = common.log_level( + debug=parse_result.debug, + verbose=parse_result.verbose, + ) + log.setLevel(level) + common.log.setLevel(level) + + log.info(common.version_info()) + common.report_wrong_environment(stream=sys.stderr) + + try: + common.validate_requirements_file( + path=parse_result.requirements_filename, + ) + extras = find_extra_reqs( + requirements_filename=parse_result.requirements_filename, + paths=parse_result.paths, + ignore_files_function=ignore_files, + ignore_modules_function=ignore_mods, + ignore_requirements_function=ignore_reqs, + skip_incompatible=parse_result.skip_incompatible, + ) + except (OSError, ValueError) as error: + common.report_input_error( + parser=parser, + debug=parse_result.debug, + error=error, + ) + + if extras: + log.warning("Extra requirements:") + for name in extras: + message = f"{name} in {parse_result.requirements_filename}" + log.warning(message) + + if extras: + sys.exit(1) diff --git a/pip_check_reqs/find_missing_reqs.py b/pip_check_reqs/find_missing_reqs.py new file mode 100644 index 0000000000000000000000000000000000000000..9e753bd68f0777e41fcc597179dbceefc1d08263 --- /dev/null +++ b/pip_check_reqs/find_missing_reqs.py @@ -0,0 +1,244 @@ +"""Find missing requirements.""" + +from __future__ import annotations + +import argparse +import collections +import logging +import sys +from pathlib import Path +from typing import TYPE_CHECKING + +from packaging.utils import NormalizedName, canonicalize_name + +from pip_check_reqs import common + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable + +log = logging.getLogger(__name__) + + +def find_missing_reqs( + requirements_filename: Path, + paths: Iterable[Path], + ignore_files_function: Callable[[str], bool], + ignore_modules_function: Callable[[str], bool], + additional_requirements_filenames: Iterable[Path] = (), +) -> list[tuple[NormalizedName, list[common.FoundModule]]]: + # 1. find files used by imports in the code (as best we can without + # executing) + imported_modules = common.find_imported_modules( + paths=paths, + ignore_files_function=ignore_files_function, + ignore_modules_function=ignore_modules_function, + ) + used_modules = imported_modules.found + + installed_files: dict[Path, str] = {} + packages_info = common.get_packages_info() + + for package in packages_info: + package_name = package.name + package_location = package.location + + log.debug( + "installed package: %s (at %s)", + package_name, + package_location, + ) + for item in package.files or []: + path = Path(package_location) / item + path = common.cached_resolve_path(path=path) + + installed_files[path] = package_name + package_path = common.package_path(path=path) + if package_path: + # we've seen a package file so add the bare package directory + # to the installed list as well as we might want to look up + # a package by its directory path later + installed_files[package_path] = package_name + + # 3. match imported modules against those packages + used: collections.defaultdict[ + NormalizedName, + list[common.FoundModule], + ] = collections.defaultdict(list) + for modname, info in used_modules.items(): + # probably standard library if it's not in the files list + if info.filename in installed_files: + used_name = canonicalize_name(name=installed_files[info.filename]) + log.debug( + "used module: %s (from package %s)", + modname, + installed_files[info.filename], + ) + used[used_name].append(info) + else: + log.debug( + "used module: %s (from file %s, assuming stdlib or local)", + modname, + info.filename, + ) + + # 4. compare with requirements + explicit: set[NormalizedName] = set() + for filename in [ + requirements_filename, + *additional_requirements_filenames, + ]: + explicit |= common.find_required_modules( + ignore_requirements_function=common.ignorer(ignore_cfg=[]), + skip_incompatible=False, + requirements_filename=filename, + ) + + _report_uninstalled_imports( + uninstalled=imported_modules.uninstalled, + explicit=explicit, + ) + + return [(name, used[name]) for name in used if name not in explicit] + + +def _report_uninstalled_imports( + *, + uninstalled: dict[str, list[tuple[str, int]]], + explicit: set[NormalizedName], +) -> None: + """Warn about imports of modules which are not installed. + + We tell which distribution provides a module from the files of the + installed distribution, so we cannot tell whether a module which is not + installed is required. Such an import was silently ignored, which hid + both an import of the wrong name and a package uninstalled by mistake. + """ + for modname, locations in uninstalled.items(): + if canonicalize_name(modname) in explicit: + # The requirement is listed but not installed, so there is + # nothing to report: the import is accounted for. + continue + + for filename, lineno in locations: + log.warning( + "%s:%s module=%s is not installed, so we cannot tell which " + "requirement provides it", + filename, + lineno, + modname, + ) + + +def main(arguments: list[str] | None = None) -> None: + parser = argparse.ArgumentParser() + parser.add_argument("paths", type=Path, nargs="*") + parser.add_argument( + "--requirements-file", + dest="requirements_filenames", + metavar="PATH", + type=Path, + action="append", + help=( + "path to a requirements file; may be repeated " + '(defaults to "requirements.txt")' + ), + ) + parser.add_argument( + "-f", + "--ignore-file", + dest="ignore_files", + action="append", + default=[], + help="file paths globs to ignore", + ) + parser.add_argument( + "-m", + "--ignore-module", + dest="ignore_mods", + action="append", + default=[], + help="used module names (globs are ok) to ignore", + ) + parser.add_argument( + "-v", + "--verbose", + dest="verbose", + action="store_true", + default=False, + help="be more verbose", + ) + parser.add_argument( + "-d", + "--debug", + dest="debug", + action="store_true", + default=False, + help="be *really* verbose", + ) + parser.add_argument( + "-V", + "--version", + dest="version", + action="store_true", + default=False, + help="display version information", + ) + + parse_result = parser.parse_args(arguments) + + if parse_result.version: + sys.stdout.write(common.version_info() + "\n") + sys.exit(0) + + if not parse_result.paths: + parser.error("no source files or directories specified") + + requirements_filenames = parse_result.requirements_filenames or [ + Path("requirements.txt"), + ] + ignore_files = common.ignorer(ignore_cfg=parse_result.ignore_files) + ignore_mods = common.ignorer(ignore_cfg=parse_result.ignore_mods) + + logging.basicConfig(format="%(message)s") + level = common.log_level( + debug=parse_result.debug, + verbose=parse_result.verbose, + ) + log.setLevel(level) + common.log.setLevel(level) + + log.info(common.version_info()) + common.report_wrong_environment(stream=sys.stderr) + + try: + for requirements_filename in requirements_filenames: + common.validate_requirements_file(path=requirements_filename) + missing = find_missing_reqs( + requirements_filename=requirements_filenames[0], + paths=parse_result.paths, + ignore_files_function=ignore_files, + ignore_modules_function=ignore_mods, + additional_requirements_filenames=requirements_filenames[1:], + ) + except (OSError, ValueError) as error: + common.report_input_error( + parser=parser, + debug=parse_result.debug, + error=error, + ) + + if missing: + log.warning("Missing requirements:") + for name, uses in missing: + for use in uses: + for filename, lineno in use.locations: + log.warning( + "%s:%s dist=%s module=%s", + filename, + lineno, + name, + use.modname, + ) + + if missing: + sys.exit(1) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..76df6a0d80a1ca491c9eb7f9363fe78a1af842e7 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +packaging >= 26.3 +pip >= 26.2.1 diff --git a/test-requirements.txt b/test-requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..ec9be3c849fdda302e64385c51ec991541dc049a --- /dev/null +++ b/test-requirements.txt @@ -0,0 +1,11 @@ +actionlint-py==1.7.12.24 +mypy==2.3.0 +pyenchant==3.3.0 +pylint==4.0.7 +pyproject-fmt==2.27.1 +pyright==1.1.411 +pyroma==5.0.1 +pytest==9.1.1 +pytest-cov==7.1.0 +ruamel.yaml==0.19.1 +ruff==0.16.3 diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_common.py b/tests/test_common.py new file mode 100644 index 0000000000000000000000000000000000000000..8d1cc4ad78e7b362172cc584988a90a0953b0d1f --- /dev/null +++ b/tests/test_common.py @@ -0,0 +1,873 @@ +"""Tests for `common.py`.""" + +from __future__ import annotations + +import logging +import platform +import re +import sys +import textwrap +import types +import uuid +from pathlib import Path + +import pytest + +import __main__ +from pip_check_reqs import __version__, common + + +@pytest.mark.parametrize( + ("path", "result"), + [ + (Path("/"), None), + (Path("/ham/spam/other.py"), None), + (Path("/ham/spam"), None), + # a top-level file like this has no package path + (Path("__init__.py"), None), + (Path("/__init__.py"), None), # no package name + (Path("spam/__init__.py"), Path("spam")), + (Path("spam/__init__.pyc"), Path("spam")), + (Path("spam/__init__.pyo"), Path("spam")), + (Path("ham/spam/__init__.py"), Path("ham/spam")), + (Path("/ham/spam/__init__.py"), Path("/ham/spam")), + ], +) +def test_package_path(*, path: Path, result: Path) -> None: + assert common.package_path(path=path) == result, path + + +def test_found_module() -> None: + found_module = common.FoundModule(modname="spam", filename=Path("ham")) + assert found_module.modname == "spam" + assert found_module.filename == Path("ham").resolve() + assert not found_module.locations + + +def test_pyfiles_file(tmp_path: Path) -> None: + python_file = tmp_path / "example.py" + python_file.touch() + assert list(common.pyfiles(root=python_file)) == [python_file] + + +def test_pyfiles_file_no_dice(tmp_path: Path) -> None: + not_python_file = tmp_path / "example" + not_python_file.touch() + + with pytest.raises( + expected_exception=ValueError, + match=re.escape( + f"{not_python_file} is not a python file or directory", + ), + ): + list(common.pyfiles(root=not_python_file)) + + +def test_pyfiles_package(tmp_path: Path) -> None: + python_file = tmp_path / "example.py" + nested_python_file = tmp_path / "subdir" / "example.py" + not_python_file = tmp_path / "example" + + python_file.touch() + nested_python_file.parent.mkdir() + nested_python_file.touch() + + not_python_file.touch() + + assert list(common.pyfiles(root=tmp_path)) == [ + python_file, + nested_python_file, + ] + + +@pytest.mark.parametrize( + argnames=("statement", "expected_module_names"), + argvalues=[ + pytest.param("import ast", {"ast"}), + pytest.param("import ast, pathlib", {"ast", "pathlib"}), + pytest.param("from pathlib import Path", {"pathlib"}), + pytest.param("from string import hexdigits", {"string"}), + pytest.param("import urllib.request", {"urllib"}), + pytest.param("import spam", set[str](), id="The file we are in"), + pytest.param("from .foo import bar", set[str](), id="Relative import"), + pytest.param("from . import baz", set[str]()), + pytest.param( + "import re", + {"re"}, + id="Useful to confirm that the next test is valid", + ), + pytest.param( + "import typing.re", + {"typing"}, + id="Submodule has same name as a top-level module", + ), + ], +) +def test_find_imported_modules_simple( + *, + statement: str, + expected_module_names: set[str], + tmp_path: Path, +) -> None: + """Test for the basic ability to find imported modules.""" + spam = tmp_path / "spam.py" + spam.write_text(data=statement) + + result = common.find_imported_modules( + paths=[tmp_path], + ignore_files_function=common.ignorer(ignore_cfg=[]), + ignore_modules_function=common.ignorer(ignore_cfg=[]), + ).found + + assert set(result.keys()) == expected_module_names + for value in result.values(): + assert str(value.filename) not in sys.path + assert value.filename.name != "__init__.py" + assert value.filename.is_absolute() + assert value.filename.exists() + + +def test_find_imported_modules_frozen( + tmp_path: Path, +) -> None: + """Frozen modules are not included in the result.""" + frozen_item_names: list[str] = [] + sys_module_items = list(sys.modules.items()) + for name, value in sys_module_items: + try: + spec = value.__spec__ + # No coverage as this does not occur on Python 3.13 + # with our current requirements. + except AttributeError: # pragma: no cover + continue + + if spec is not None and spec.origin == "frozen": + frozen_item_names.append(name) + + assert frozen_item_names, ( + "This test is only valid if there are frozen modules in sys.modules" + ) + + spam = tmp_path / "spam.py" + statement = f"import {frozen_item_names[0]}" + spam.write_text(data=statement) + + result = common.find_imported_modules( + paths=[tmp_path], + ignore_files_function=common.ignorer(ignore_cfg=[]), + ignore_modules_function=common.ignorer(ignore_cfg=[]), + ).found + + assert set(result.keys()) == set() + + +@pytest.mark.skipif( + condition=platform.system() == "Windows", + reason=( + "Test not supported on Windows, where __main__.__spec__ is not None" + ), +) +def test_find_imported_modules_main( + tmp_path: Path, +) -> None: # pragma: no cover + spam = tmp_path / "spam.py" + statement = "import __main__" + spam.write_text(data=statement) + + message = ( + "This test is only valid if __main__.__spec__ is None. " + "That is not the case when running pytest as 'python -m pytest' " + "which modifies sys.modules. " + "See https://docs.pytest.org/en/7.1.x/how-to/usage.html#calling-pytest-from-python-code" + ) + assert __main__.__spec__ is None, message + + result = common.find_imported_modules( + paths=[tmp_path], + ignore_files_function=common.ignorer(ignore_cfg=[]), + ignore_modules_function=common.ignorer(ignore_cfg=[]), + ).found + + assert set(result.keys()) == set() + + +def test_find_imported_modules_no_spec(tmp_path: Path) -> None: + """Modules without a __spec__ are not included in the result. + + This is often __main__. + However, it is also possible to create a module without a __spec__. + We prefer to test with a realistic case, but on Windows under `pytest`, + `__main__.__spec__` is not None as `__main__` is replaced by pytest. + + Therefore we need this test to create a module without a __spec__. + """ + spam = tmp_path / "spam.py" + name = "a" + uuid.uuid4().hex + statement = f"import {name}" + spam.write_text(data=statement) + module = types.ModuleType(name=name) + module.__spec__ = None + sys.modules[name] = module + + try: + result = common.find_imported_modules( + paths=[tmp_path], + ignore_files_function=common.ignorer(ignore_cfg=[]), + ignore_modules_function=common.ignorer(ignore_cfg=[]), + ).found + finally: + del sys.modules[name] + assert set(result.keys()) == set() + + +def test_find_imported_modules_syntax_error(tmp_path: Path) -> None: + """A file which cannot be parsed gives an error naming file and line.""" + spam = tmp_path / "spam.py" + spam.write_text( + data=textwrap.dedent( + text="""\ + import os + + def ( + """, + ), + ) + + expected_message = f"could not parse {spam}:3: invalid syntax" + with pytest.raises( + expected_exception=ValueError, + match=f"^{re.escape(expected_message)}$", + ): + common.find_imported_modules( + paths=[tmp_path], + ignore_files_function=common.ignorer(ignore_cfg=[]), + ignore_modules_function=common.ignorer(ignore_cfg=[]), + ) + + +def test_find_imported_modules_period(tmp_path: Path) -> None: + """Imported modules are found if the package name contains a period. + + An example of this is the module name `"ruamel.yaml"`. + https://pypi.org/project/ruamel.yaml/ + + In particular, `ruamel.yaml` is in `sys.modules` with a period in the name. + """ + spam = tmp_path / "spam.py" + statement = "import ruamel.yaml" + spam.write_text(data=statement) + + result = common.find_imported_modules( + paths=[tmp_path], + ignore_files_function=common.ignorer(ignore_cfg=[]), + ignore_modules_function=common.ignorer(ignore_cfg=[]), + ).found + + assert set(result.keys()) == {"ruamel.yaml"} + + +@pytest.mark.parametrize( + "parent_name", + [ + "pytest", + "pprint", + ], +) +def test_find_imported_modules_missing_from_submodule( + parent_name: str, + tmp_path: Path, +) -> None: + """A missing sub-module is not attributed to its installed parent.""" + source_dir = tmp_path / "source" + source_dir.mkdir() + (source_dir / "example.py").write_text( + f"from {parent_name}.missing import attribute", + ) + + result = common.find_imported_modules( + paths=[source_dir], + ignore_files_function=common.ignorer(ignore_cfg=[]), + ignore_modules_function=common.ignorer(ignore_cfg=[]), + ).found + + assert not result + + +@pytest.mark.parametrize( + ("ignore_ham", "ignore_hashlib", "expect", "locs"), + [ + ( + False, + False, + ["ast", "pathlib", "hashlib", "sys"], + [ + ("spam.py", 2), + ("ham.py", 2), + ], + ), + ( + False, + True, + ["ast", "pathlib", "sys"], + [("spam.py", 2), ("ham.py", 2)], + ), + (True, False, ["ast", "sys"], [("spam.py", 2)]), + (True, True, ["ast", "sys"], [("spam.py", 2)]), + ], +) +def test_find_imported_modules_advanced( + *, + caplog: pytest.LogCaptureFixture, + ignore_ham: bool, + ignore_hashlib: bool, + expect: list[str], + locs: list[tuple[str, int]], + tmp_path: Path, +) -> None: + root = tmp_path + spam = root / "spam.py" + ham = root / "ham.py" + + spam_file_contents = textwrap.dedent( + """\ + from __future__ import annotations + import ast, sys + from . import friend + """, + ) + ham_file_contents = textwrap.dedent( + """\ + from pathlib import Path + import ast, hashlib + """, + ) + + spam.write_text(data=spam_file_contents) + ham.write_text(data=ham_file_contents) + + caplog.set_level(logging.INFO) + + def ignore_files(path: str) -> bool: + return bool(Path(path).name == "ham.py" and ignore_ham) + + def ignore_mods(module: str) -> bool: + return bool(module == "hashlib" and ignore_hashlib) + + result = common.find_imported_modules( + paths=[root], + ignore_files_function=ignore_files, + ignore_modules_function=ignore_mods, + ).found + assert set(result) == set(expect) + absolute_locations = result["ast"].locations + relative_locations = [ + (str(Path(item[0]).relative_to(root)), item[1]) + for item in absolute_locations + ] + assert sorted(relative_locations) == sorted(locs) + + if ignore_ham: + assert caplog.records[0].message == f"ignoring: {ham}" + + +def test_find_imported_modules_uninstalled(tmp_path: Path) -> None: + """An import of a module which is not installed is reported.""" + source_dir = tmp_path / "source" + source_dir.mkdir() + source_file = source_dir / "spam.py" + name = "a" + uuid.uuid4().hex + source_file.write_text( + data=textwrap.dedent( + text=f"""\ + import re + import {name} + from {name}.ham import eggs + """, + ), + ) + + result = common.find_imported_modules( + paths=[source_dir], + ignore_files_function=common.ignorer(ignore_cfg=[]), + ignore_modules_function=common.ignorer(ignore_cfg=[]), + ) + + assert set(result.found) == {"re"} + assert result.uninstalled == { + name: [(str(source_file), 2), (str(source_file), 3)], + } + + +@pytest.mark.parametrize( + "statement", + [ + pytest.param("import {name}.ham\n", id="Import"), + pytest.param("from {name}.ham import eggs\n", id="ImportFrom"), + ], +) +@pytest.mark.parametrize( + "ignore_glob", + [ + pytest.param("{name}", id="Top-level module name"), + pytest.param("{name}*", id="Glob"), + pytest.param("{name}.ham", id="Dotted import path"), + ], +) +def test_find_imported_modules_uninstalled_ignored( + *, + ignore_glob: str, + statement: str, + tmp_path: Path, +) -> None: + """An ignored module which is not installed is not reported.""" + source_dir = tmp_path / "source" + source_dir.mkdir() + name = "a" + uuid.uuid4().hex + (source_dir / "spam.py").write_text(data=statement.format(name=name)) + + result = common.find_imported_modules( + paths=[source_dir], + ignore_files_function=common.ignorer(ignore_cfg=[]), + ignore_modules_function=common.ignorer( + ignore_cfg=[ignore_glob.format(name=name)], + ), + ) + + assert not result.uninstalled + + +def test_find_imported_modules_uninstalled_no_spec(tmp_path: Path) -> None: + """A module without a ``__spec__`` is available, so is not reported. + + See ``test_find_imported_modules_no_spec`` for how such a module comes + about. + """ + source_dir = tmp_path / "source" + source_dir.mkdir() + name = "a" + uuid.uuid4().hex + (source_dir / "spam.py").write_text(data=f"from {name}.ham import eggs\n") + module = types.ModuleType(name=name) + module.__spec__ = None + sys.modules[name] = module + + try: + result = common.find_imported_modules( + paths=[source_dir], + ignore_files_function=common.ignorer(ignore_cfg=[]), + ignore_modules_function=common.ignorer(ignore_cfg=[]), + ) + finally: + del sys.modules[name] + + assert not result.uninstalled + + +def test_find_imported_modules_uninstalled_submodule(tmp_path: Path) -> None: + """A missing sub-module of an installed package is not reported. + + The distribution which would provide the sub-module is installed, so + there is no requirement which we cannot check. + """ + source_dir = tmp_path / "source" + source_dir.mkdir() + (source_dir / "spam.py").write_text( + data=textwrap.dedent( + text="""\ + import pytest.missing + from pytest.missing import attribute + """, + ), + ) + + result = common.find_imported_modules( + paths=[source_dir], + ignore_files_function=common.ignorer(ignore_cfg=[]), + ignore_modules_function=common.ignorer(ignore_cfg=[]), + ) + + assert not result.uninstalled + + +@pytest.mark.parametrize( + "handler", + [ + pytest.param("except ImportError:", id="ImportError"), + pytest.param("except ModuleNotFoundError:", id="ModuleNotFoundError"), + pytest.param("except builtins.ImportError:", id="Dotted path"), + pytest.param("except (ValueError, ImportError):", id="Tuple"), + pytest.param("except (*errors, ImportError):", id="Tuple with a star"), + pytest.param("except: # noqa: E722", id="Bare except"), + ], +) +@pytest.mark.parametrize( + "statement", + [ + pytest.param("import {name}", id="Import"), + pytest.param("from {name} import ham", id="ImportFrom"), + ], +) +def test_find_imported_modules_uninstalled_optional( + *, + handler: str, + statement: str, + tmp_path: Path, +) -> None: + """An import which the source tolerates failing is not reported. + + A soft dependency is imported in a ``try`` block which catches + ``ImportError``, so the code runs whether or not it is installed. + """ + source_dir = tmp_path / "source" + source_dir.mkdir() + name = "a" + uuid.uuid4().hex + (source_dir / "spam.py").write_text( + data=textwrap.dedent( + text="""\ + try: + {statement} + {handler} + pass + """, + ).format(statement=statement.format(name=name), handler=handler), + ) + + result = common.find_imported_modules( + paths=[source_dir], + ignore_files_function=common.ignorer(ignore_cfg=[]), + ignore_modules_function=common.ignorer(ignore_cfg=[]), + ) + + assert not result.uninstalled + + +@pytest.mark.parametrize( + "source", + [ + pytest.param( + """\ + try: + {statement} + except ValueError: + pass + """, + id="Handler which does not catch ImportError", + ), + pytest.param( + """\ + try: + pass + except ImportError: + {statement} + """, + id="Import in the handler", + ), + pytest.param( + """\ + try: + pass + except ImportError: + pass + else: + {statement} + """, + id="Import in the else block", + ), + pytest.param( + """\ + try: + pass + except ImportError: + pass + finally: + {statement} + """, + id="Import in the finally block", + ), + pytest.param( + """\ + try: + pass + except ImportError: + pass + {statement} + """, + id="Import after the try statement", + ), + ], +) +def test_find_imported_modules_uninstalled_not_optional( + *, + source: str, + tmp_path: Path, +) -> None: + """An import which the ``try`` does not guard is still reported.""" + source_dir = tmp_path / "source" + source_dir.mkdir() + source_file = source_dir / "spam.py" + name = "a" + uuid.uuid4().hex + source_file.write_text( + data=textwrap.dedent(text=source).format(statement=f"import {name}"), + ) + + result = common.find_imported_modules( + paths=[source_dir], + ignore_files_function=common.ignorer(ignore_cfg=[]), + ignore_modules_function=common.ignorer(ignore_cfg=[]), + ) + + assert set(result.uninstalled) == {name} + + +def test_find_imported_modules_optional_installed(tmp_path: Path) -> None: + """An optional import of an installed module is still a use of it. + + A soft dependency which is installed and listed in the requirements is + used, so ``pip-extra-reqs`` must not report it as extra. + """ + source_dir = tmp_path / "source" + source_dir.mkdir() + (source_dir / "spam.py").write_text( + data=textwrap.dedent( + text="""\ + try: + import pytest + except ImportError: + pass + """, + ), + ) + + result = common.find_imported_modules( + paths=[source_dir], + ignore_files_function=common.ignorer(ignore_cfg=[]), + ignore_modules_function=common.ignorer(ignore_cfg=[]), + ) + + assert set(result.found) == {"pytest"} + + +@pytest.mark.parametrize( + "statement", + [ + pytest.param("import spam", id="Module in the source"), + pytest.param("import ham", id="Package in the source"), + pytest.param("from ham.eggs import scrambled", id="Source submodule"), + pytest.param("import source", id="Directory we scan"), + pytest.param("import ignored", id="Ignored file in the source"), + ], +) +def test_find_imported_modules_source_module( + *, + statement: str, + tmp_path: Path, +) -> None: + """A module which the scanned source provides is not reported. + + Such a module is not expected to be installed, so reporting it would be + a false positive. + """ + source_dir = tmp_path / "source" + source_dir.mkdir() + (source_dir / "spam.py").write_text(data=statement) + (source_dir / "ignored.py").touch() + package_dir = source_dir / "ham" + package_dir.mkdir() + (package_dir / "__init__.py").touch() + (package_dir / "eggs.py").touch() + + result = common.find_imported_modules( + paths=[source_dir], + ignore_files_function=common.ignorer(ignore_cfg=["*ignored.py"]), + ignore_modules_function=common.ignorer(ignore_cfg=[]), + ) + + assert not result.uninstalled + + +def test_source_module_names_file(tmp_path: Path) -> None: + """A single source file gives its own module name.""" + source_file = tmp_path / "spam.py" + source_file.touch() + + result = common.source_module_names(paths=[source_file]) + + assert result == {"spam"} + + +@pytest.mark.parametrize( + ("ignore_cfg", "candidate", "result"), + [ + ([], "spam", False), + ([], "ham", False), + (["spam"], "spam", True), + (["spam"], "spam.ham", False), + (["spam"], "eggs", False), + (["spam*"], "spam", True), + (["spam*"], "spam.ham", True), + (["spam*"], "eggs", False), + (["spam"], str(Path.cwd() / "spam"), True), + (["eggs"], str(Path.cwd() / "spam"), False), + (["spam"], str(Path.cwd() / "eggs" / ".." / "spam"), True), + (["spam"], str(Path("eggs") / ".." / "spam"), True), + (["spam"], str(Path.cwd().parent / "spam"), False), + ], +) +def test_ignorer( + *, + ignore_cfg: list[str], + candidate: str, + result: bool, +) -> None: + ignorer = common.ignorer(ignore_cfg=ignore_cfg) + assert ignorer(candidate) == result + + +@pytest.mark.skipif( + condition=platform.system() != "Windows", + reason="Only Windows has drives, which is what this test is about", +) +def test_ignorer_other_drive() -> None: # pragma: no cover + """A candidate on another drive than the working directory is handled. + + Making such a path relative to the working directory is impossible, and + that used to raise an error. + """ + working_directory_drive = Path.cwd().drive + other_drive = "Y:" if working_directory_drive.upper() == "Z:" else "Z:" + ignorer = common.ignorer(ignore_cfg=["eggs"]) + + assert not ignorer(rf"{other_drive}\eggs\spam.py") + + +def test_find_required_modules(tmp_path: Path) -> None: + fake_requirements_file = tmp_path / "requirements.txt" + fake_requirements_file.write_text("foobar==1\nbarfoo==2") + + reqs = common.find_required_modules( + ignore_requirements_function=common.ignorer(ignore_cfg=["barfoo"]), + skip_incompatible=False, + requirements_filename=fake_requirements_file, + ) + assert reqs == {"foobar"} + + +def test_find_required_modules_env_markers(tmp_path: Path) -> None: + fake_requirements_file = tmp_path / "requirements.txt" + fake_requirements_file.write_text( + 'spam==1; python_version<"2.0"\nham==2;\neggs==3\n', + ) + + reqs = common.find_required_modules( + ignore_requirements_function=common.ignorer(ignore_cfg=[]), + skip_incompatible=True, + requirements_filename=fake_requirements_file, + ) + assert reqs == {"ham", "eggs"} + + +def test_find_required_modules_unnamed_requirement(tmp_path: Path) -> None: + fake_requirements_file = tmp_path / "requirements.txt" + url = "git+ssh://git@example.com/org/repo.git" + fake_requirements_file.write_text(f"foobar==1\n{url}\n") + + with pytest.raises(ValueError, match="requirement has no name") as excinfo: + common.find_required_modules( + ignore_requirements_function=common.ignorer(ignore_cfg=[]), + skip_incompatible=False, + requirements_filename=fake_requirements_file, + ) + + hint = "Add an '#egg=' fragment naming the distribution." + expected_message = f"requirement has no name: {url}. {hint}" + assert str(excinfo.value) == expected_message + + +def test_find_required_modules_egg_fragment_names_requirement( + tmp_path: Path, +) -> None: + fake_requirements_file = tmp_path / "requirements.txt" + url = "git+ssh://git@example.com/org/repo.git#egg=repo" + fake_requirements_file.write_text(f"foobar==1\n{url}\n") + + reqs = common.find_required_modules( + ignore_requirements_function=common.ignorer(ignore_cfg=[]), + skip_incompatible=False, + requirements_filename=fake_requirements_file, + ) + assert reqs == {"foobar", "repo"} + + +def test_version_info_shows_version_number() -> None: + major, minor, patch = sys.version_info[:3] + python_version = f"{major}.{minor}.{patch}" + parent_directory = Path(common.__file__).parent.resolve() + expected_version_info = ( + f"pip-check-reqs {__version__} " + f"from {parent_directory} " + f"(python {python_version})" + ) + assert common.version_info() == expected_version_info + + +def test_no_wrong_environment_warning_without_active_virtualenv( + tmp_path: Path, +) -> None: + warning = common.wrong_environment_warning( + running_prefix=tmp_path, + active_virtualenv=None, + color=False, + ) + assert warning is None + + +def test_no_wrong_environment_warning_from_active_virtualenv( + tmp_path: Path, +) -> None: + warning = common.wrong_environment_warning( + running_prefix=tmp_path, + active_virtualenv=str(tmp_path), + color=False, + ) + assert warning is None + + +def test_wrong_environment_warning(tmp_path: Path) -> None: + # We resolve the paths as the warning shows resolved paths, and a + # temporary directory is reached through a symbolic link on some hosts. + active_prefix = (tmp_path / "active").resolve() + running_prefix = (tmp_path / "running").resolve() + + warning = common.wrong_environment_warning( + running_prefix=running_prefix, + active_virtualenv=str(active_prefix), + color=False, + ) + + expected_warning = ( + f"WARNING: Running from {running_prefix}, but the active " + f"virtual environment is {active_prefix}. " + "Results describe the environment pip-check-reqs is installed in. " + "Install pip-check-reqs in the active virtual environment, and " + 'run "hash -r" ("rehash" in zsh), to check that environment.' + ) + assert warning == expected_warning + + +def test_wrong_environment_warning_in_color(tmp_path: Path) -> None: + active_prefix = (tmp_path / "active").resolve() + running_prefix = (tmp_path / "running").resolve() + + warning = common.wrong_environment_warning( + running_prefix=running_prefix, + active_virtualenv=str(active_prefix), + color=True, + ) + + plain_warning = common.wrong_environment_warning( + running_prefix=running_prefix, + active_virtualenv=str(active_prefix), + color=False, + ) + yellow = "\033[33m" + reset = "\033[0m" + assert warning == f"{yellow}{plain_warning}{reset}" diff --git a/tests/test_find_extra_reqs.py b/tests/test_find_extra_reqs.py new file mode 100644 index 0000000000000000000000000000000000000000..244f2965a325726b1b2ec9e4a82e1be8feed010a --- /dev/null +++ b/tests/test_find_extra_reqs.py @@ -0,0 +1,345 @@ +"""Tests for `find_extra_reqs.py`.""" + +from __future__ import annotations + +import logging +import re +import sys +import textwrap +from pathlib import Path + +import pip # This happens to be installed in the test environment. +import pytest + +from pip_check_reqs import common, find_extra_reqs + + +def test_find_extra_reqs(tmp_path: Path) -> None: + installed_not_imported_required_package = pytest + installed_imported_required_package = pip + + fake_requirements_file = tmp_path / "requirements.txt" + fake_requirements_file.write_text( + textwrap.dedent( + f"""\ + not_installed_package_12345==1 + {installed_imported_required_package.__name__} + {installed_not_imported_required_package.__name__} + """, + ), + ) + + source_dir = tmp_path / "source" + source_dir.mkdir() + + source_file = source_dir / "source.py" + source_file.write_text( + textwrap.dedent( + f"""\ + import pprint + + import {installed_imported_required_package.__name__} + """, + ), + ) + + result = find_extra_reqs.find_extra_reqs( + requirements_filename=fake_requirements_file, + paths=[source_dir], + ignore_files_function=common.ignorer(ignore_cfg=[]), + ignore_modules_function=common.ignorer(ignore_cfg=[]), + ignore_requirements_function=common.ignorer(ignore_cfg=[]), + skip_incompatible=False, + ) + expected_result = [installed_not_imported_required_package.__name__] + assert result == expected_result + + +def test_uninstalled_requirement_is_not_extra( + *, + caplog: pytest.LogCaptureFixture, + tmp_path: Path, +) -> None: + """An uninstalled requirement is reported as unchecked, not as extra. + + We tell which modules a requirement provides from the files of the + installed distribution, so we cannot tell whether an uninstalled + requirement is used, even when the code imports it. + """ + fake_requirements_file = tmp_path / "requirements.txt" + fake_requirements_file.write_text("not_installed_package_12345==1\n") + + source_dir = tmp_path / "source" + source_dir.mkdir() + + source_file = source_dir / "source.py" + source_file.write_text("import not_installed_package_12345\n") + + caplog.set_level(logging.WARNING) + + result = find_extra_reqs.find_extra_reqs( + requirements_filename=fake_requirements_file, + paths=[source_dir], + ignore_files_function=common.ignorer(ignore_cfg=[]), + ignore_modules_function=common.ignorer(ignore_cfg=[]), + ignore_requirements_function=common.ignorer(ignore_cfg=[]), + skip_incompatible=False, + ) + + assert not result + expected_message = ( + "not-installed-package-12345 is not installed, so we cannot tell " + "whether it is used" + ) + assert [record.message for record in caplog.records] == [expected_message] + + +def test_main_failure( + *, + caplog: pytest.LogCaptureFixture, + tmp_path: Path, +) -> None: + installed_not_imported_required_package = pytest + + requirements_file = tmp_path / "requirements.txt" + requirements_file.write_text( + installed_not_imported_required_package.__name__, + ) + + source_dir = tmp_path / "source" + source_dir.mkdir() + + caplog.set_level(logging.WARNING) + + with pytest.raises(SystemExit) as excinfo: + find_extra_reqs.main( + arguments=[ + "--requirements", + str(requirements_file), + str(source_dir), + ], + ) + + assert excinfo.value.code == 1 + + assert caplog.records[0].message == "Extra requirements:" + expected_message = ( + f"{installed_not_imported_required_package.__name__} in " + f"{requirements_file}" + ) + assert caplog.records[1].message == expected_message + + +def test_main_no_spec(capsys: pytest.CaptureFixture[str]) -> None: + with pytest.raises(SystemExit) as excinfo: + find_extra_reqs.main(arguments=[]) + + expected_code = 2 + assert excinfo.value.code == expected_code + err = capsys.readouterr().err + assert err.endswith("error: no source files or directories specified\n") + + +def test_main_missing_requirements_file( + capsys: pytest.CaptureFixture[str], + tmp_path: Path, +) -> None: + source_dir = tmp_path / "source" + source_dir.mkdir() + requirements_file = tmp_path / "missing-requirements.txt" + + with pytest.raises(SystemExit) as excinfo: + find_extra_reqs.main( + arguments=[ + "--requirements", + str(requirements_file), + str(source_dir), + ], + ) + + expected_code = 2 + assert excinfo.value.code == expected_code + err = capsys.readouterr().err + assert err.endswith( + f"error: requirements file not found: {requirements_file}\n", + ) + + +def test_main_missing_source_path( + capsys: pytest.CaptureFixture[str], + tmp_path: Path, +) -> None: + requirements_file = tmp_path / "requirements.txt" + requirements_file.touch() + source_dir = tmp_path / "missing-source" + + with pytest.raises(SystemExit) as excinfo: + find_extra_reqs.main( + arguments=[ + "--requirements", + str(requirements_file), + str(source_dir), + ], + ) + + expected_code = 2 + assert excinfo.value.code == expected_code + err = capsys.readouterr().err + assert err.endswith(f"error: source path not found: {source_dir}\n") + + +def test_main_source_file_parse_error( + capsys: pytest.CaptureFixture[str], + tmp_path: Path, +) -> None: + requirements_file = tmp_path / "requirements.txt" + requirements_file.touch() + source_dir = tmp_path / "source" + source_dir.mkdir() + source_file = source_dir / "spam.py" + source_file.write_text(data="def (\n") + + with pytest.raises(SystemExit) as excinfo: + find_extra_reqs.main( + arguments=[ + "--requirements", + str(requirements_file), + str(source_dir), + ], + ) + + expected_code = 2 + assert excinfo.value.code == expected_code + err = capsys.readouterr().err + assert err.endswith( + f"error: could not parse {source_file}:1: invalid syntax\n", + ) + + +def test_main_debug_reraises_input_error(tmp_path: Path) -> None: + source_dir = tmp_path / "source" + source_dir.mkdir() + requirements_file = tmp_path / "missing-requirements.txt" + + with pytest.raises( + FileNotFoundError, + match=re.escape(f"requirements file not found: {requirements_file}"), + ): + find_extra_reqs.main( + arguments=[ + "--debug", + "--requirements", + str(requirements_file), + str(source_dir), + ], + ) + + +@pytest.mark.parametrize( + ("expected_log_levels", "verbose_cfg", "debug_cfg"), + [ + ({logging.WARNING}, False, False), + ({logging.INFO, logging.WARNING}, True, False), + ({logging.DEBUG, logging.INFO, logging.WARNING}, False, True), + ({logging.DEBUG, logging.INFO, logging.WARNING}, True, True), + ], +) +def test_logging_config( + *, + caplog: pytest.LogCaptureFixture, + expected_log_levels: set[int], + tmp_path: Path, + verbose_cfg: bool, + debug_cfg: bool, +) -> None: + source_dir = tmp_path / "source" + source_dir.mkdir() + + requirements_file = tmp_path / "requirements.txt" + requirements_file.touch() + + arguments = [str(source_dir), "--requirements", str(requirements_file)] + if verbose_cfg: + arguments.append("--verbose") + if debug_cfg: + arguments.append("--debug") + + find_extra_reqs.main(arguments=arguments) + + for event in [ + (logging.DEBUG, "debug"), + (logging.INFO, "info"), + (logging.WARNING, "warn"), + ]: + find_extra_reqs.log.log(*event) + + log_levels = {r.levelno for r in caplog.records} + assert log_levels == expected_log_levels + + +def test_main_version(capsys: pytest.CaptureFixture[str]) -> None: + with pytest.raises(SystemExit): + find_extra_reqs.main(arguments=["--version"]) + + assert capsys.readouterr().out == common.version_info() + "\n" + + +def test_main_warns_when_run_from_another_environment( + capsys: pytest.CaptureFixture[str], + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + requirements_file = tmp_path / "requirements.txt" + requirements_file.touch() + + source_dir = tmp_path / "source" + source_dir.mkdir() + (source_dir / "source.py").write_text("import pprint") + + # We resolve the path as the warning shows resolved paths, and a + # temporary directory is reached through a symbolic link on some hosts. + active_prefix = (tmp_path / "active").resolve() + monkeypatch.setenv("VIRTUAL_ENV", str(active_prefix)) + + find_extra_reqs.main( + arguments=[ + "--requirements-file", + str(requirements_file), + str(source_dir), + ], + ) + + running_prefix = Path(sys.prefix).resolve() + expected_stderr = ( + f"WARNING: Running from {running_prefix}, but the active " + f"virtual environment is {active_prefix}. " + "Results describe the environment pip-check-reqs is installed in. " + "Install pip-check-reqs in the active virtual environment, and " + 'run "hash -r" ("rehash" in zsh), to check that environment.\n' + ) + assert capsys.readouterr().err == expected_stderr + + +def test_main_does_not_warn_when_run_from_the_active_environment( + capsys: pytest.CaptureFixture[str], + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + requirements_file = tmp_path / "requirements.txt" + requirements_file.touch() + + source_dir = tmp_path / "source" + source_dir.mkdir() + (source_dir / "source.py").write_text("import pprint") + + monkeypatch.setenv("VIRTUAL_ENV", sys.prefix) + + find_extra_reqs.main( + arguments=[ + "--requirements-file", + str(requirements_file), + str(source_dir), + ], + ) + + assert capsys.readouterr().err == "" diff --git a/tests/test_find_missing_reqs.py b/tests/test_find_missing_reqs.py new file mode 100644 index 0000000000000000000000000000000000000000..e901cbe1b65d3f852c7ccd27fb730c200877c8a9 --- /dev/null +++ b/tests/test_find_missing_reqs.py @@ -0,0 +1,520 @@ +"""Tests for `find_missing_reqs.py`.""" + +from __future__ import annotations + +import logging +import re +import sys +import textwrap +from pathlib import Path + +import pip # This happens to be installed in the test environment. +import pytest + +from pip_check_reqs import common, find_missing_reqs + + +def test_find_missing_reqs(tmp_path: Path) -> None: + installed_imported_not_required_package = pytest + installed_imported_required_package = pip + + fake_requirements_file = tmp_path / "requirements.txt" + fake_requirements_file.write_text( + textwrap.dedent( + f"""\ + not_installed_package_12345==1 + {installed_imported_required_package.__name__} + """, + ), + ) + + source_dir = tmp_path / "source" + source_dir.mkdir() + + source_file = source_dir / "source.py" + source_file.write_text( + textwrap.dedent( + f"""\ + import pprint + + import {installed_imported_not_required_package.__name__} + import {installed_imported_required_package.__name__} + """, + ), + ) + + result = find_missing_reqs.find_missing_reqs( + requirements_filename=fake_requirements_file, + paths=[source_dir], + ignore_files_function=common.ignorer(ignore_cfg=[]), + ignore_modules_function=common.ignorer(ignore_cfg=[]), + ) + expected_result = [ + ( + installed_imported_not_required_package.__name__, + [ + common.FoundModule( + modname=installed_imported_not_required_package.__name__, + filename=Path( + installed_imported_not_required_package.__file__, + ).parent, + locations=[(str(source_file), 3)], + ), + ], + ), + ] + assert result == expected_result + + +def test_uninstalled_import_is_reported( + *, + caplog: pytest.LogCaptureFixture, + tmp_path: Path, +) -> None: + """An import of a module which is not installed is reported. + + We know which requirement provides a module from the files of the + installed distribution, so we cannot tell whether such an import is + required, and we say so rather than passing it over. + """ + fake_requirements_file = tmp_path / "requirements.txt" + fake_requirements_file.write_text("pytest\n") + + source_dir = tmp_path / "source" + source_dir.mkdir() + + source_file = source_dir / "source.py" + source_file.write_text("import not_installed_package_12345\n") + + caplog.set_level(logging.WARNING) + + result = find_missing_reqs.find_missing_reqs( + requirements_filename=fake_requirements_file, + paths=[source_dir], + ignore_files_function=common.ignorer(ignore_cfg=[]), + ignore_modules_function=common.ignorer(ignore_cfg=[]), + ) + + assert not result + expected_message = ( + f"{source_file}:1 module=not_installed_package_12345 is not " + "installed, so we cannot tell which requirement provides it" + ) + assert [record.message for record in caplog.records] == [expected_message] + + +def test_uninstalled_import_of_requirement_is_not_reported( + *, + caplog: pytest.LogCaptureFixture, + tmp_path: Path, +) -> None: + """An import of a listed but uninstalled requirement is not reported. + + The requirement is in the requirements file, so nothing is missing. + """ + fake_requirements_file = tmp_path / "requirements.txt" + fake_requirements_file.write_text("Not-Installed-Package-12345==1\n") + + source_dir = tmp_path / "source" + source_dir.mkdir() + (source_dir / "source.py").write_text("import not_installed_package_12345") + + caplog.set_level(logging.WARNING) + + result = find_missing_reqs.find_missing_reqs( + requirements_filename=fake_requirements_file, + paths=[source_dir], + ignore_files_function=common.ignorer(ignore_cfg=[]), + ignore_modules_function=common.ignorer(ignore_cfg=[]), + ) + + assert not result + assert not caplog.records + + +def test_main_uninstalled_import_does_not_fail( + *, + caplog: pytest.LogCaptureFixture, + tmp_path: Path, +) -> None: + """An uninstalled import is a warning rather than a failure. + + An import which we cannot resolve is not always a mistake, as a module + of the source may be given by a path we do not scan, so we do not fail + the run for it. + """ + requirements_file = tmp_path / "requirements.txt" + requirements_file.touch() + + source_dir = tmp_path / "source" + source_dir.mkdir() + source_file = source_dir / "source.py" + source_file.write_text("import not_installed_package_12345\n") + + caplog.set_level(logging.WARNING) + + find_missing_reqs.main( + arguments=[ + "--requirements", + str(requirements_file), + str(source_dir), + ], + ) + + expected_message = ( + f"{source_file}:1 module=not_installed_package_12345 is not " + "installed, so we cannot tell which requirement provides it" + ) + assert [record.message for record in caplog.records] == [expected_message] + + +def test_main_ignore_module_silences_uninstalled_import( + *, + caplog: pytest.LogCaptureFixture, + tmp_path: Path, +) -> None: + requirements_file = tmp_path / "requirements.txt" + requirements_file.touch() + + source_dir = tmp_path / "source" + source_dir.mkdir() + (source_dir / "source.py").write_text("import not_installed_package_12345") + + caplog.set_level(logging.WARNING) + + find_missing_reqs.main( + arguments=[ + "--requirements", + str(requirements_file), + "--ignore-module", + "not_installed_package_12345", + str(source_dir), + ], + ) + + assert not caplog.records + + +def test_main_multiple_requirements_files( + *, + caplog: pytest.LogCaptureFixture, + tmp_path: Path, +) -> None: + first_requirements_file = tmp_path / "requirements.txt" + first_requirements_file.write_text("pip\n") + second_requirements_file = tmp_path / "test-requirements.txt" + second_requirements_file.write_text("pytest\n") + + source_dir = tmp_path / "source" + source_dir.mkdir() + (source_dir / "source.py").write_text("import pip\nimport pytest\n") + + find_missing_reqs.main( + arguments=[ + "--requirements-file", + str(first_requirements_file), + "--requirements-file", + str(second_requirements_file), + str(source_dir), + ], + ) + + assert not caplog.records + + +def test_main_failure( + *, + caplog: pytest.LogCaptureFixture, + tmp_path: Path, +) -> None: + requirements_file = tmp_path / "requirements.txt" + requirements_file.touch() + + source_dir = tmp_path / "source" + source_dir.mkdir() + + source_file = source_dir / "source.py" + # We need to import something which is installed. + # We choose `pytest` because we know it is installed. + source_file.write_text("import pytest") + + caplog.set_level(logging.WARNING) + + with pytest.raises(SystemExit) as excinfo: + find_missing_reqs.main( + arguments=[ + "--requirements", + str(requirements_file), + str(source_dir), + ], + ) + + assert excinfo.value.code == 1 + + assert caplog.records[0].message == "Missing requirements:" + assert ( + caplog.records[1].message + == f"{source_file}:1 dist=pytest module=pytest" + ) + + +def test_main_no_spec(capsys: pytest.CaptureFixture[str]) -> None: + with pytest.raises(SystemExit) as excinfo: + find_missing_reqs.main(arguments=[]) + + expected_code = 2 + assert excinfo.value.code == expected_code + err = capsys.readouterr().err + assert err.endswith("error: no source files or directories specified\n") + + +def test_main_missing_requirements_file( + capsys: pytest.CaptureFixture[str], + tmp_path: Path, +) -> None: + source_dir = tmp_path / "source" + source_dir.mkdir() + requirements_file = tmp_path / "missing-requirements.txt" + + with pytest.raises(SystemExit) as excinfo: + find_missing_reqs.main( + arguments=[ + "--requirements", + str(requirements_file), + str(source_dir), + ], + ) + + expected_code = 2 + assert excinfo.value.code == expected_code + err = capsys.readouterr().err + assert err.endswith( + f"error: requirements file not found: {requirements_file}\n", + ) + + +def test_main_missing_source_path( + capsys: pytest.CaptureFixture[str], + tmp_path: Path, +) -> None: + requirements_file = tmp_path / "requirements.txt" + requirements_file.touch() + source_dir = tmp_path / "missing-source" + + with pytest.raises(SystemExit) as excinfo: + find_missing_reqs.main( + arguments=[ + "--requirements", + str(requirements_file), + str(source_dir), + ], + ) + + expected_code = 2 + assert excinfo.value.code == expected_code + err = capsys.readouterr().err + assert err.endswith(f"error: source path not found: {source_dir}\n") + + +def test_main_source_file_parse_error( + capsys: pytest.CaptureFixture[str], + tmp_path: Path, +) -> None: + requirements_file = tmp_path / "requirements.txt" + requirements_file.touch() + source_dir = tmp_path / "source" + source_dir.mkdir() + source_file = source_dir / "spam.py" + source_file.write_text(data="def (\n") + + with pytest.raises(SystemExit) as excinfo: + find_missing_reqs.main( + arguments=[ + "--requirements", + str(requirements_file), + str(source_dir), + ], + ) + + expected_code = 2 + assert excinfo.value.code == expected_code + err = capsys.readouterr().err + assert err.endswith( + f"error: could not parse {source_file}:1: invalid syntax\n", + ) + + +def test_main_unnamed_requirement( + capsys: pytest.CaptureFixture[str], + tmp_path: Path, +) -> None: + requirements_file = tmp_path / "requirements.txt" + url = "git+ssh://git@example.com/org/repo.git" + requirements_file.write_text(f"{url}\n") + source_dir = tmp_path / "source" + source_dir.mkdir() + (source_dir / "source.py").write_text("import pytest\n") + + with pytest.raises(SystemExit) as excinfo: + find_missing_reqs.main( + arguments=[ + "--requirements", + str(requirements_file), + str(source_dir), + ], + ) + + expected_code = 2 + assert excinfo.value.code == expected_code + err = capsys.readouterr().err + hint = "Add an '#egg=' fragment naming the distribution." + assert err.endswith(f"error: requirement has no name: {url}. {hint}\n") + + +def test_main_egg_fragment_names_requirement( + *, + caplog: pytest.LogCaptureFixture, + tmp_path: Path, +) -> None: + requirements_file = tmp_path / "requirements.txt" + url = "git+ssh://git@example.com/org/repo.git#egg=pytest" + requirements_file.write_text(f"{url}\n") + source_dir = tmp_path / "source" + source_dir.mkdir() + (source_dir / "source.py").write_text("import pytest\n") + + find_missing_reqs.main( + arguments=[ + "--requirements", + str(requirements_file), + str(source_dir), + ], + ) + + assert not caplog.records + + +def test_main_debug_reraises_input_error(tmp_path: Path) -> None: + source_dir = tmp_path / "source" + source_dir.mkdir() + requirements_file = tmp_path / "missing-requirements.txt" + + with pytest.raises( + FileNotFoundError, + match=re.escape(f"requirements file not found: {requirements_file}"), + ): + find_missing_reqs.main( + arguments=[ + "--debug", + "--requirements", + str(requirements_file), + str(source_dir), + ], + ) + + +@pytest.mark.parametrize( + ("verbose_cfg", "debug_cfg", "expected_log_levels"), + [ + (False, False, {logging.WARNING}), + (True, False, {logging.INFO, logging.WARNING}), + (False, True, {logging.DEBUG, logging.INFO, logging.WARNING}), + (True, True, {logging.DEBUG, logging.INFO, logging.WARNING}), + ], +) +def test_logging_config( + *, + caplog: pytest.LogCaptureFixture, + verbose_cfg: bool, + debug_cfg: bool, + expected_log_levels: set[int], + tmp_path: Path, +) -> None: + source_dir = tmp_path / "source" + source_dir.mkdir() + + arguments = [str(source_dir)] + if verbose_cfg: + arguments.append("--verbose") + if debug_cfg: + arguments.append("--debug") + + find_missing_reqs.main(arguments=arguments) + + for event in [ + (logging.DEBUG, "debug"), + (logging.INFO, "info"), + (logging.WARNING, "warn"), + ]: + find_missing_reqs.log.log(*event) + + log_levels = {r.levelno for r in caplog.records} + assert log_levels == expected_log_levels + + +def test_main_version(capsys: pytest.CaptureFixture[str]) -> None: + with pytest.raises(SystemExit): + find_missing_reqs.main(arguments=["--version"]) + + assert capsys.readouterr().out == common.version_info() + "\n" + + +def test_main_warns_when_run_from_another_environment( + capsys: pytest.CaptureFixture[str], + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + requirements_file = tmp_path / "requirements.txt" + requirements_file.touch() + + source_dir = tmp_path / "source" + source_dir.mkdir() + (source_dir / "source.py").write_text("import pprint") + + # We resolve the path as the warning shows resolved paths, and a + # temporary directory is reached through a symbolic link on some hosts. + active_prefix = (tmp_path / "active").resolve() + monkeypatch.setenv("VIRTUAL_ENV", str(active_prefix)) + + find_missing_reqs.main( + arguments=[ + "--requirements-file", + str(requirements_file), + str(source_dir), + ], + ) + + running_prefix = Path(sys.prefix).resolve() + expected_stderr = ( + f"WARNING: Running from {running_prefix}, but the active " + f"virtual environment is {active_prefix}. " + "Results describe the environment pip-check-reqs is installed in. " + "Install pip-check-reqs in the active virtual environment, and " + 'run "hash -r" ("rehash" in zsh), to check that environment.\n' + ) + assert capsys.readouterr().err == expected_stderr + + +def test_main_does_not_warn_when_run_from_the_active_environment( + capsys: pytest.CaptureFixture[str], + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + requirements_file = tmp_path / "requirements.txt" + requirements_file.touch() + + source_dir = tmp_path / "source" + source_dir.mkdir() + (source_dir / "source.py").write_text("import pprint") + + monkeypatch.setenv("VIRTUAL_ENV", sys.prefix) + + find_missing_reqs.main( + arguments=[ + "--requirements-file", + str(requirements_file), + str(source_dir), + ], + ) + + assert capsys.readouterr().err == ""