diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c9390b..3017370 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## 0.6.0 + +- Analyze `importlib.import_module`, `importlib.__import__`, and built-in `__import__` using the same layer, slice, public API, and app/UI rules as ordinary imports. +- Resolve imported/assigned loader aliases, literal names, constant bindings, concatenation, f-strings, joins, relative packages, and `__import__` fromlists without executing project code. +- Inspect literal `exec`/`eval` code and literal `compile` inputs, including nested dynamic imports. Report violations at the original call site. +- Fail with `dynamic-imports` when a recognized loader target, package, fromlist, executed code, or escaped loader cannot be inspected. Unknown values never count as proof that a recognized dynamic import is valid. +- Respect function/lambda parameter shadowing, class/method lookup, comprehensions and conditional bindings; preserve possible loader provenance across branches. +- Bound recursive code expansion and diagnostics to prevent generated code from making inspection unbounded. +- Add dynamic import, namespace, scope, no-execution, subprocess and installed-wheel regression controls. Custom import hooks and arbitrary runtime behavior are not executed by the checker. + ## 0.5.0 - Replace runtime import checks with static AST analysis. Forbidden layer and sibling-slice imports now fail both under pytest and in standalone Python, without importing project code or requiring pytest-archon. diff --git a/README.md b/README.md index 7d44001..d9d1734 100644 --- a/README.md +++ b/README.md @@ -83,12 +83,23 @@ See the [rule documentation](src/pytest_fsd/rules/) for examples and details. ## Scope and limitations -- Import rules statically inspect Python syntax, including relative imports, package initializers, function-local imports and `if TYPE_CHECKING:` branches. They do not execute project code. Dynamically computed imports (`importlib`, `__import__`, `exec`) and custom import hooks are not resolved. +- Import rules statically inspect Python syntax, including relative imports, package initializers, function-local imports and `if TYPE_CHECKING:` branches. They do not execute project code. Programmatic imports through `importlib.import_module`, `importlib.__import__`, and built-in `__import__` are analyzed too. Loader aliases, literal names, constant bindings, concatenation, f-strings, joins, relative packages and fromlists are supported. Literal `exec`/`eval` strings and literal `compile` inputs are inspected recursively, with bounded expansion. Unresolved recognized loader calls or executed code fail with `[dynamic-imports]`; they do not silently pass. Arbitrary user-defined import hooks and runtime code are not executed. - `no-public-api-sidestep` supports static `__all__` lists/tuples, concatenation, annotations, `+=`, `append` and `extend`. Unresolved dynamic exports are reported as unknown. - Steiger's `inconsistent-naming` and `import-locality` have no direct equivalent here. Consider Ruff's `N` and `TID` rules for Python naming and relative imports; their behavior is not identical to Steiger's rules. - Steiger's `insignificant-slice` needs an import graph and is not implemented. The deprecated `processes` layer is not created by this package; omit it from `layers`. - This package checks Python files and filesystem structure. It does not implement every Steiger rule or every JavaScript-specific convention. +For example, this computed sibling import is rejected: + +```python +import importlib + +layer = "features" +importlib.import_module(f"src.{layer}.other_slice") +``` + +If the target comes from runtime input (`importlib.import_module(requested_module)`), validation fails with `[dynamic-imports]` because the target cannot be proven valid. Replace it with an explicit dispatch between statically known imports. The checker is an architecture linter; it does not emulate arbitrary Python execution or serve as an execution sandbox. + See the [upstream FSD plugin changelog](https://github.com/feature-sliced/steiger/blob/master/packages/steiger-plugin-fsd/CHANGELOG.md) for Steiger's release history. ## License diff --git a/README.ru.md b/README.ru.md index 6accd71..e388308 100644 --- a/README.ru.md +++ b/README.ru.md @@ -83,7 +83,7 @@ extra_rules = [ ## Ограничения -- Правила импортов статически разбирают Python, включая относительные импорты, `__init__.py`, импорты внутри функций и ветки `if TYPE_CHECKING:`. Код проекта не исполняется. Динамические импорты (`importlib`, `__import__`, `exec`) и нестандартные загрузчики не разрешаются. +- Правила импортов статически разбирают Python, включая относительные импорты, `__init__.py`, импорты внутри функций и ветки `if TYPE_CHECKING:`. Код проекта не исполняется. Программные импорты через `importlib.import_module`, `importlib.__import__` и встроенный `__import__` тоже проверяются. Поддерживаются алиасы загрузчиков, литералы, переменные с константными значениями, конкатенация, f-строки, `join`, относительные пакеты и `fromlist`. Строки `exec`/`eval` и константные входы `compile` разбираются рекурсивно с ограничением объёма анализа. Неразрешённые вызовы известных загрузчиков и строки исполняемого кода завершаются ошибкой `[dynamic-imports]`, а не пропускаются. Произвольные пользовательские загрузчики и код проекта не исполняются. - `no-public-api-sidestep` анализирует синтаксис Python и явные списки `__all__`. Динамически собранные экспорты могут давать ложные срабатывания. - Прямых аналогов Steiger `inconsistent-naming` и `import-locality` здесь нет. Для именования Python и относительных импортов можно использовать правила Ruff `N` и `TID`; их поведение не совпадает полностью с правилами Steiger. - `insignificant-slice` требует анализа графа импортов и не реализовано. Устаревший слой `processes` пакет не создаёт — не указывайте его в `layers`. @@ -94,3 +94,5 @@ extra_rules = [ ## Лицензия MIT. См. [LICENSE](LICENSE). + +Вызов `importlib.import_module(f"src.{layer}.tables")` проверяется, если значение `layer` известно. Если имя приходит только во время исполнения, проверка выдаёт `[dynamic-imports]`: замените такой вызов явным выбором между известными импортами. Чекер проверяет архитектуру и не является интерпретатором произвольного Python-кода или средством изоляции исполнения. diff --git a/instructions/SKILL.md b/instructions/SKILL.md index 8d74dfb..8171e62 100644 --- a/instructions/SKILL.md +++ b/instructions/SKILL.md @@ -17,7 +17,7 @@ The `pytest-fsd` library enforces the Feature-Sliced Design (FSD) methodology. I ## Inner Workings -The library acts as a facade over static AST and filesystem checks. Import rules inspect absolute and relative imports, public packages, initializers, local-function imports and `TYPE_CHECKING` branches without executing project code. They raise `AssertionError` under pytest and standalone Python. Dynamic imports and unresolved dynamic exports are outside static resolution; invalid source/configuration fails explicitly. +The library acts as a facade over static AST and filesystem checks. Import rules inspect absolute and relative imports, public packages, initializers, local-function imports and `TYPE_CHECKING` branches without executing project code. They raise `AssertionError` under pytest and standalone Python. Programmatic imports through importlib and __import__, loader aliases, constant expressions, and literal exec/eval/compile code feed the same rules. Unresolved recognized loader calls, executed code, or escaped loaders fail with dynamic-imports. Recursive expansion is bounded. Unresolved dynamic exports, invalid source and invalid configuration fail explicitly. The checker never executes project code or custom import hooks. Configuration is centralized in `pyproject.toml` under the section `[tool.pytest_fsd]`. diff --git a/pyproject.toml b/pyproject.toml index f3932e7..7e5cb76 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "pytest-fsd" -version = "0.5.0" +version = "0.6.0" description = "Validate Feature-Sliced Design architecture in Python projects with pytest" keywords = ["feature-sliced-design", "fsd", "architecture", "pytest", "python", "steiger"] readme = "README.md" diff --git a/src/pytest_fsd/_lib/dynamic_imports.py b/src/pytest_fsd/_lib/dynamic_imports.py new file mode 100644 index 0000000..9c2feb8 --- /dev/null +++ b/src/pytest_fsd/_lib/dynamic_imports.py @@ -0,0 +1,552 @@ +"""Inspect programmatic imports with a bounded, non-executing AST evaluator.""" + +import ast +from dataclasses import dataclass, field +from pathlib import Path +from typing import Dict, List + +from .ast_utils import get_node_location +from .violations import Violation + +UNKNOWN = object() +MAX_TEXT = 65536 +MAX_CODE_DEPTH = 8 + + +@dataclass(frozen=True) +class Symbol: + name: str + + +@dataclass(frozen=True) +class Code: + source: str + mode: str + + +@dataclass +class ImportAnalysis: + imports: List[ast.AST] = field(default_factory=list) + violations: List[Violation] = field(default_factory=list) + + +BUILTINS = {name: Symbol('builtins.' + name) for name in ( + '__import__', 'exec', 'eval', 'compile', 'globals', 'locals', 'getattr', +)} +LOADERS = {'importlib.import_module', 'importlib.__import__', 'builtins.__import__'} + + +def analyze_imports(source: str, tree: ast.AST, file_path: str, base_dir: str) -> ImportAnalysis: + """Resolve known dynamic imports; report recognized calls that remain unknown.""" + package = '.'.join((Path(base_dir).name,) + Path(file_path).relative_to(base_dir).parent.parts) + analyzer = _Analyzer(source, file_path, package) + try: + analyzer.visit(tree) + except RecursionError: + analyzer.error(tree, 'Analysis exceeded the AST nesting limit') + return analyzer.result + + +class _Analyzer(ast.NodeVisitor): + def __init__(self, source, file_path, package): + self.source = source + self.file_path = file_path + self.env: Dict[str, object] = {'__package__': package, '__builtins__': Symbol('builtins')} + self.result = ImportAnalysis() + self.origin = None + self.depth = 0 + self.code_expansions = 0 + self.code_bytes = 0 + self.class_parent = None + + def error(self, node, message): + if len(self.result.violations) >= 64: + return + node = self.origin if self.origin is not None else node + self.result.violations.append(Violation( + rule='dynamic-imports', file_path=self.file_path, + message=message + '. Use an explicit import or a statically resolvable target.', + **get_node_location(node, self.source), + )) + + def record(self, node): + if self.origin is not None: + ast.copy_location(node, self.origin) + self.result.imports.append(node) + + def lookup(self, name): + return self.env.get(name, BUILTINS.get(name, UNKNOWN)) + + def bind(self, target, value=UNKNOWN): + if isinstance(target, ast.Name): + self.env[target.id] = value + elif isinstance(target, (ast.Tuple, ast.List)): + values = value if isinstance(value, (tuple, list)) and len(value) == len(target.elts) else [UNKNOWN] * len(target.elts) + for child, item in zip(target.elts, values): + self.bind(child, item) + else: + # Mutating containers invalidates any previously inferred contents. + root = target + while isinstance(root, (ast.Subscript, ast.Attribute)): + root = root.value + if isinstance(root, ast.Name): + self.env[root.id] = UNKNOWN + + def visit_Import(self, node): + self.record(node) + for alias in node.names: + self.env[alias.asname or alias.name.split('.')[0]] = Symbol(alias.name if alias.asname else alias.name.split('.')[0]) + + def visit_ImportFrom(self, node): + self.record(node) + for alias in node.names: + if alias.name == '*' and not node.level and node.module == 'importlib': + self.env.update({name: Symbol('importlib.' + name) for name in ('import_module', '__import__')}) + continue + self.env[alias.asname or alias.name] = Symbol((node.module or '') + '.' + alias.name) if not node.level else UNKNOWN + + def visit_Assign(self, node): + value = self.expr(node.value) + for target in node.targets: + self.bind(target, value) + + def visit_AnnAssign(self, node): + self.expr(node.annotation) + self.bind(node.target, self.expr(node.value) if node.value else UNKNOWN) + + def visit_AugAssign(self, node): + left, right = self.expr(node.target), self.expr(node.value) + value = self.add(left, right) if isinstance(node.op, ast.Add) else UNKNOWN + self.bind(node.target, value) + + def visit_Delete(self, node): + for target in node.targets: + self.bind(target) + + def visit_Expr(self, node): + self.expr(node.value) + + def visit_Call(self, node): + self.expr(node) + + def visit_NamedExpr(self, node): + self.expr(node) + + def visit_Lambda(self, node): + self.expr(node) + + def scoped(self, node): + for item in getattr(node, 'decorator_list', []): + self.expr(item) + args = getattr(node, 'args', None) + if args: + default_loaders = self.default_loaders(args) + for arg in args.posonlyargs + args.args + args.kwonlyargs + [a for a in (args.vararg, args.kwarg) if a is not None]: + self.expr(arg.annotation) + self.expr(getattr(node, 'returns', None)) + else: + for value in getattr(node, 'bases', []): + self.expr(value) + for keyword in getattr(node, 'keywords', []): + self.expr(keyword.value) + self.env[node.name] = UNKNOWN + outer = self.env + previous_class_parent = self.class_parent + if isinstance(node, ast.ClassDef): + self.class_parent = self.class_parent if self.class_parent is not None else outer + self.env = dict(outer) + else: + self.env = dict(self.class_parent if self.class_parent is not None else outer) + self.class_parent = None + # Python binds locals for the entire function, including before assignment. + if args: + for name in _local_names(node): + self.env[name] = UNKNOWN + for name in default_loaders: + self.env[name] = Symbol('?dynamic') + for statement in node.body: + self.visit(statement) + self.env = outer + self.class_parent = previous_class_parent + + visit_FunctionDef = scoped + visit_AsyncFunctionDef = scoped + visit_ClassDef = scoped + + def visit_If(self, node): + self.expr(node.test) + self.branches([node.body, node.orelse]) + + def branches(self, blocks): + before = dict(self.env) + outcomes = [] + for block in blocks: + self.env = dict(before) + for statement in block: + self.visit(statement) + outcomes.append(self.env) + self.env = self.merge(outcomes) + + def visit_For(self, node): + self.expr(node.iter) + self.bind(node.target) + self.branches([node.body + node.orelse, []]) + + visit_AsyncFor = visit_For + + def visit_While(self, node): + self.expr(node.test) + self.branches([node.body + node.orelse, []]) + + def visit_Try(self, node): + # Inspect every path; uncertain bindings remain unknown after the join. + blocks = [node.body + node.orelse] + for handler in node.handlers: + self.expr(handler.type) + block = list(handler.body) + if handler.name: + block.insert(0, ast.Assign(targets=[ast.Name(id=handler.name, ctx=ast.Store())], value=ast.Constant(value=None))) + blocks.append(block) + self.branches(blocks) + for statement in node.finalbody: + self.visit(statement) + + visit_TryStar = visit_Try + + def visit_Match(self, node): + self.expr(node.subject) + before = dict(self.env) + outcomes = [before] + for case in node.cases: + self.env = dict(before) + for pattern in ast.walk(case.pattern): + for name in _pattern_names(pattern): + self.env[name] = UNKNOWN + self.expr(case.guard) + for statement in case.body: + self.visit(statement) + outcomes.append(self.env) + self.env = self.merge(outcomes) + + def visit_With(self, node): + for item in node.items: + self.expr(item.context_expr) + if item.optional_vars: + self.bind(item.optional_vars) + for statement in node.body: + self.visit(statement) + + visit_AsyncWith = visit_With + + def add(self, left, right): + if isinstance(left, str) and isinstance(right, str) and len(left) + len(right) <= MAX_TEXT: + return left + right + if isinstance(left, (tuple, list)) and type(left) is type(right) and len(left) + len(right) <= 256: + return left + right + return UNKNOWN + + def expr(self, node): + if node is None: + return UNKNOWN + if isinstance(node, ast.Constant): + return node.value + if isinstance(node, ast.Name): + return self.lookup(node.id) + if isinstance(node, ast.Attribute): + value = self.expr(node.value) + if isinstance(value, Symbol): + return Symbol(value.name + '.' + node.attr) + return Symbol('?dynamic') if _may_load(value) else UNKNOWN + if isinstance(node, (ast.Tuple, ast.List, ast.Set)): + return tuple(self.expr(item) for item in node.elts) + if isinstance(node, ast.Dict): + result = {} + known = True + for key, value in zip(node.keys, node.values): + k, v = self.expr(key), self.expr(value) + if not isinstance(k, (str, int)): + known = False + else: + result[k] = v + return result if known else UNKNOWN + if isinstance(node, ast.BinOp): + left, right = self.expr(node.left), self.expr(node.right) + if isinstance(node.op, ast.Add): + return self.add(left, right) + return UNKNOWN + if isinstance(node, ast.JoinedStr): + chunks = [] + known = True + for part in node.values: + if isinstance(part, ast.Constant): + chunks.append(part.value) + else: + value = self.expr(part.value) + self.expr(part.format_spec) + if not isinstance(value, (str, int, float, bool)) or part.format_spec: + known = False + else: + chunks.append(repr(value) if part.conversion == 114 else ascii(value) if part.conversion == 97 else str(value)) + result = ''.join(chunks) + return result if known and len(result) <= MAX_TEXT else UNKNOWN + if isinstance(node, ast.Subscript): + value = self.expr(node.value) + index_node = node.slice.value if isinstance(node.slice, ast.Index) else node.slice + index = self.expr(index_node) + if isinstance(value, (tuple, dict, str)) and isinstance(index, (str, int)): + try: + return value[index] + except (KeyError, IndexError, TypeError): + pass + if isinstance(value, Symbol) and value.name == 'builtins' and isinstance(index, str): + return Symbol('builtins.' + index) + return Symbol('?dynamic') if _may_load(value) else UNKNOWN + if isinstance(node, ast.IfExp): + self.expr(node.test) + before = dict(self.env) + left = self.expr(node.body) + left_env = self.env + self.env = dict(before) + right = self.expr(node.orelse) + right_env = self.env + self.env = self.merge([left_env, right_env]) + if left == right: + return left + return Symbol('?dynamic') if _may_load(left) or _may_load(right) else UNKNOWN + if isinstance(node, ast.BoolOp): + outcomes = [] + values = [] + for child in node.values: + values.append(self.expr(child)) + outcomes.append(dict(self.env)) + self.env = self.merge(outcomes) + return Symbol('?dynamic') if any(_may_load(value) for value in values) else UNKNOWN + if isinstance(node, (ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)): + outer = self.env + self.env = dict(outer) + for generator in node.generators: + self.expr(generator.iter) + self.bind(generator.target) + for condition in generator.ifs: + self.expr(condition) + if isinstance(node, ast.DictComp): + self.expr(node.key) + self.expr(node.value) + else: + self.expr(node.elt) + self.env = outer + for descendant in ast.walk(node): + if isinstance(descendant, ast.NamedExpr): + self.bind(descendant.target) + return UNKNOWN + if isinstance(node, ast.NamedExpr): + value = self.expr(node.value) + self.bind(node.target, value) + return value + if isinstance(node, ast.Lambda): + default_loaders = self.default_loaders(node.args) + outer = self.env + self.env = dict(outer) + for name in _local_names(node): + self.env[name] = UNKNOWN + for name in default_loaders: + self.env[name] = Symbol('?dynamic') + self.expr(node.body) + self.env = outer + return UNKNOWN + if isinstance(node, ast.Call): + return self.call(node) + for child in ast.iter_child_nodes(node): + self.expr(child) + return UNKNOWN + + def merge(self, outcomes): + result = {} + for name in set().union(*(set(outcome) for outcome in outcomes)): + values = [outcome.get(name, BUILTINS.get(name, UNKNOWN)) for outcome in outcomes] + if all(value == values[0] for value in values): + result[name] = values[0] + elif any(_may_load(value) for value in values): + result[name] = Symbol('?dynamic') + else: + result[name] = UNKNOWN + return result + + def default_loaders(self, args): + parameters = args.posonlyargs + args.args + pairs = list(zip(parameters[len(parameters) - len(args.defaults):], args.defaults)) + pairs += [(arg, value) for arg, value in zip(args.kwonlyargs, args.kw_defaults) if value is not None] + return [arg.arg for arg, value in pairs if _may_load(self.expr(value))] + + def call(self, node): + function = self.expr(node.func) + args = [self.expr(arg) for arg in node.args] + keywords = {kw.arg: self.expr(kw.value) for kw in node.keywords} + name = function.name if isinstance(function, Symbol) else None + if name in LOADERS: + return self.load(node, name, args, keywords) + if name and name.startswith('?dynamic'): + self.error(node, 'Cannot resolve conditionally bound dynamic import callable') + return UNKNOWN + if name in ('builtins.exec', 'builtins.eval'): + value = args[0] if args else keywords.get('source', UNKNOWN) + outer = self.env + supplied = args[1:3] if len(args) > 1 else [keywords[key] for key in ('globals', 'locals') if key in keywords] + if supplied: + self.env = dict(outer) + for namespace in supplied: + if isinstance(namespace, dict): + self.env.update(namespace) + elif namespace is not None: + self.error(node, 'Cannot resolve dynamically executed code namespace') + value = self.code(node, value, 'eval' if name == 'builtins.eval' else 'exec') + if supplied: + self.env = outer + return value + if name == 'builtins.compile': + source = args[0] if args else keywords.get('source', UNKNOWN) + mode = args[2] if len(args) > 2 else keywords.get('mode', UNKNOWN) + return Code(source, mode) if isinstance(source, str) and mode in ('exec', 'eval', 'single') else UNKNOWN + if name in ('builtins.globals', 'builtins.locals'): + return dict(self.env) + if name == 'builtins.getattr' and len(args) >= 2: + if isinstance(args[0], Symbol) and isinstance(args[1], str): + return Symbol(args[0].name + '.' + args[1]) + if isinstance(args[0], Symbol) and args[0].name in ('importlib', 'builtins'): + return Symbol('?dynamic') + # Support common constant module-name construction without invoking user code. + if isinstance(node.func, ast.Attribute) and node.func.attr == 'join' and len(args) == 1: + separator = self.expr(node.func.value) + items = args[0] + if isinstance(separator, str) and isinstance(items, tuple) and all(isinstance(x, str) for x in items): + if sum(map(len, items)) + len(separator) * len(items) <= MAX_TEXT: + return separator.join(items) + if any(_may_load(arg) for arg in args + list(keywords.values())): + self.error(node, 'Dynamic import callable escapes static analysis') + # Calls mutating a tracked container make later target construction unknown. + if isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name): + receiver = node.func.value.id + if isinstance(self.env.get(receiver), (tuple, dict)): + self.env[receiver] = UNKNOWN + return UNKNOWN + + def load(self, node, loader, args, keywords): + parameters = ('name', 'package') if loader == 'importlib.import_module' else ('name', 'globals', 'locals', 'fromlist', 'level') + if len(args) > len(parameters) or None in keywords or any(isinstance(arg, ast.Starred) for arg in node.args): + self.error(node, 'Cannot resolve dynamic import arguments') + return UNKNOWN + options = dict(zip(parameters, args)) + if any(key not in parameters or key in options for key in keywords): + self.error(node, 'Cannot resolve dynamic import arguments') + return UNKNOWN + options.update(keywords) + module = options.get('name', UNKNOWN) + if not isinstance(module, str) or len(module) > MAX_TEXT: + self.error(node, 'Cannot resolve dynamic import module name') + return UNKNOWN + names = () + if loader == 'importlib.import_module': + level = len(module) - len(module.lstrip('.')) + package = options.get('package', UNKNOWN) + if level: + module = module[level:] + else: + level = options.get('level', 0) + context = options.get('globals', {}) + package = context.get('__package__', UNKNOWN) if isinstance(context, dict) else UNKNOWN + names = options.get('fromlist', ()) + if names is None: + names = () + if not isinstance(names, (tuple, list)) or not all(isinstance(n, str) for n in names): + self.error(node, 'Cannot resolve dynamic import fromlist') + return UNKNOWN + if not isinstance(level, int) or level < 0: + self.error(node, 'Cannot resolve dynamic import level') + return UNKNOWN + if level: + if not isinstance(package, str) or not package or level > len(package.split('.')): + self.error(node, 'Cannot resolve relative dynamic import package') + return UNKNOWN + module = '.'.join(package.split('.')[:len(package.split('.')) - level + 1] + ([module] if module else [])) + if not module or any(not part or '/' in part or '\\' in part for part in module.split('.')): + self.error(node, 'Cannot resolve dynamic import module name') + return UNKNOWN + reference = ast.ImportFrom(module=module, names=[ast.alias(name=n, asname=None) for n in names], level=0) if names else ast.Import(names=[ast.alias(name=module, asname=None)]) + ast.copy_location(reference, node) + self.record(reference) + return Symbol(module if names or loader == 'importlib.import_module' else module.split('.')[0]) + + def code(self, node, value, mode): + if isinstance(value, Code): + value, mode = value.source, value.mode + self.code_expansions += 1 + self.code_bytes += len(value) if isinstance(value, str) else 0 + if (not isinstance(value, str) or len(value) > MAX_TEXT or self.depth >= MAX_CODE_DEPTH + or self.code_expansions > 64 or self.code_bytes > MAX_TEXT * 4): + self.error(node, 'Cannot inspect dynamically executed code') + return UNKNOWN + try: + tree = ast.parse(value, mode=mode) + except (SyntaxError, ValueError, RecursionError): + self.error(node, 'Cannot parse dynamically executed code') + return UNKNOWN + origin = self.origin + self.origin = origin if origin is not None else node + self.depth += 1 + value = self.expr(tree.body) if isinstance(tree, ast.Expression) else self.visit(tree) + self.depth -= 1 + self.origin = origin + return value if isinstance(tree, ast.Expression) else UNKNOWN + + +def _local_names(node): + names = set() + declarations = set() + args = getattr(node, 'args', None) + if args: + names.update(arg.arg for arg in args.posonlyargs + args.args + args.kwonlyargs) + if args.vararg: + names.add(args.vararg.arg) + if args.kwarg: + names.add(args.kwarg.arg) + + def collect(current): + for child in ast.iter_child_nodes(current): + if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + names.add(child.name) + elif isinstance(child, (ast.Global, ast.Nonlocal)): + declarations.update(child.names) + elif _pattern_names(child): + names.update(_pattern_names(child)) + collect(child) + elif isinstance(child, ast.Lambda): + continue + elif isinstance(child, (ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)): + for descendant in ast.walk(child): + if isinstance(descendant, ast.NamedExpr) and isinstance(descendant.target, ast.Name): + names.add(descendant.target.id) + elif isinstance(child, ast.Name) and isinstance(child.ctx, (ast.Store, ast.Del)): + names.add(child.id) + elif isinstance(child, (ast.Import, ast.ImportFrom)): + names.update(alias.asname or alias.name.split('.')[0] for alias in child.names) + else: + collect(child) + collect(node) + return names - declarations + + +def _may_load(value): + if isinstance(value, (tuple, list)): + return any(_may_load(item) for item in value) + if isinstance(value, dict): + return any(_may_load(item) for item in value.values()) + return isinstance(value, Symbol) and (value.name in LOADERS or value.name in ('importlib', 'builtins') or value.name.startswith('?dynamic')) + + +def _pattern_names(node): + # Match nodes do not exist on Python 3.8/3.9. + if type(node).__name__ in ('MatchAs', 'MatchStar'): + return [node.name] if node.name else [] + if type(node).__name__ == 'MatchMapping': + return [node.rest] if node.rest else [] + return [] diff --git a/src/pytest_fsd/_lib/imports.py b/src/pytest_fsd/_lib/imports.py index af06b45..5ca1bdc 100644 --- a/src/pytest_fsd/_lib/imports.py +++ b/src/pytest_fsd/_lib/imports.py @@ -6,6 +6,7 @@ from typing import Iterator, List, Optional, Tuple from .ast_utils import get_node_location, parse_python_file +from .dynamic_imports import analyze_imports from ..config import FsdConfig @@ -52,9 +53,10 @@ def imported_modules( if parts is not None: result.append(parts) for alias in node.names: - child = Path(base_dir).joinpath(*parts, alias.name) + child_parts = tuple(alias.name.split('.')) + child = Path(base_dir).joinpath(*parts, *child_parts) if alias.name != "*" and (child.is_dir() or child.with_suffix(".py").is_file()): - result.append(parts + (alias.name,)) + result.append(parts + child_parts) elif node.module and not node.level: # `from src import features` (or a nested source root). base = Path(base_dir).resolve() @@ -84,7 +86,6 @@ def iter_imports( if parsed is None: continue # The facade reports unreadable/invalid Python sources. source, tree = parsed - for node in ast.walk(tree): - if isinstance(node, (ast.Import, ast.ImportFrom)): - for target in imported_modules(node, file_path, base_dir, config.layers): - yield file_path, source_parts, target, get_node_location(node, source) + for node in analyze_imports(source, tree, file_path, base_dir).imports: + for target in imported_modules(node, file_path, base_dir, config.layers): + yield file_path, source_parts, target, get_node_location(node, source) diff --git a/src/pytest_fsd/_lib/source_validation.py b/src/pytest_fsd/_lib/source_validation.py index 712bbf3..da89458 100644 --- a/src/pytest_fsd/_lib/source_validation.py +++ b/src/pytest_fsd/_lib/source_validation.py @@ -6,6 +6,7 @@ from typing import List from .violations import Violation +from .dynamic_imports import analyze_imports from ..config import FsdConfig @@ -41,7 +42,9 @@ def unreadable(error: OSError) -> None: file_path = os.path.join(root, filename) try: with tokenize.open(file_path) as handle: - ast.parse(handle.read(), filename=file_path) + source = handle.read() + tree = ast.parse(source, filename=file_path) + violations.extend(analyze_imports(source, tree, file_path, base_dir).violations) except (OSError, UnicodeError, SyntaxError, ValueError, LookupError) as error: violations.append(Violation( rule="python-source", file_path=file_path, diff --git a/src/pytest_fsd/rules/no_public_api_sidestep/__init__.py b/src/pytest_fsd/rules/no_public_api_sidestep/__init__.py index 842e440..07cc6e5 100644 --- a/src/pytest_fsd/rules/no_public_api_sidestep/__init__.py +++ b/src/pytest_fsd/rules/no_public_api_sidestep/__init__.py @@ -6,6 +6,7 @@ from ..._lib.ast_utils import get_exported_names, get_node_location, parse_python_file from ..._lib.fs_utils import get_sliced_layers +from ..._lib.dynamic_imports import analyze_imports from ..._lib.imports import imported_modules, resolve_module from ..._lib.violations import Violation from ...config import FsdConfig @@ -34,7 +35,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: if parsed is None: continue source, tree = parsed - for node in ast.walk(tree): + for node in analyze_imports(source, tree, file_path, base_dir).imports: targets = [] if isinstance(node, ast.Import): for alias in node.names: diff --git a/src/pytest_fsd/rules/no_ui_in_app/__init__.py b/src/pytest_fsd/rules/no_ui_in_app/__init__.py index f464bed..397c2ed 100644 --- a/src/pytest_fsd/rules/no_ui_in_app/__init__.py +++ b/src/pytest_fsd/rules/no_ui_in_app/__init__.py @@ -7,6 +7,7 @@ from ..._lib.ast_utils import get_node_location, parse_python_file from ..._lib.fs_utils import get_layer_by_canonical_name +from ..._lib.dynamic_imports import analyze_imports from ..._lib.violations import Violation from ...config import FsdConfig @@ -58,7 +59,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: continue source, tree = parsed - for node in ast.walk(tree): + for node in analyze_imports(source, tree, file_path, base_dir).imports: if isinstance(node, ast.Import): for alias in node.names: base_import = alias.name.split(".")[0] diff --git a/src/pytest_fsd/rules/no_wildcard_exports/__init__.py b/src/pytest_fsd/rules/no_wildcard_exports/__init__.py index 0fab2d7..c118ad8 100644 --- a/src/pytest_fsd/rules/no_wildcard_exports/__init__.py +++ b/src/pytest_fsd/rules/no_wildcard_exports/__init__.py @@ -6,6 +6,7 @@ from typing import List from ..._lib.ast_utils import get_node_location +from ..._lib.dynamic_imports import analyze_imports from ..._lib.violations import Violation from ...config import FsdConfig @@ -37,7 +38,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: ) continue - for node in ast.walk(tree): + for node in analyze_imports(source, tree, file_path, base_dir).imports: if not isinstance(node, ast.ImportFrom): continue if not any(alias.name == "*" for alias in node.names): diff --git a/tests/installed_smoke.py b/tests/installed_smoke.py index 21d81ed..326d8fb 100644 --- a/tests/installed_smoke.py +++ b/tests/installed_smoke.py @@ -14,6 +14,11 @@ def main(): ("features/auth/api/router.py", "from src.features.tables import value\n", "no-cross-imports"), ("shared/lib/source.py", "from src.features.tables import value\n", "forbidden-imports"), ("features/auth/api/router.py", "from src.shared.lib import value\n", None), + ("features/auth/api/router.py", "import importlib\nlayer = 'features'\nimportlib.import_module(f'src.{layer}.tables')\n", "no-cross-imports"), + ("shared/lib/source.py", "__import__('src.features.tables')\n", "forbidden-imports"), + ("features/auth/api/router.py", "__import__(unknown_target)\n", "dynamic-imports"), + ("features/auth/api/router.py", "exec(\"import src.features.tables\")\n", "no-cross-imports"), + ("features/auth/api/router.py", "import importlib\nimportlib.import_module('src.shared.lib')\n", None), ] for source_path, source, expected_rule in cases: with tempfile.TemporaryDirectory(prefix="pytest-fsd-wheel-") as directory: diff --git a/tests/test_dynamic_imports.py b/tests/test_dynamic_imports.py new file mode 100644 index 0000000..88a18af --- /dev/null +++ b/tests/test_dynamic_imports.py @@ -0,0 +1,367 @@ +"""Dynamic import inspection must enforce boundaries without executing sources.""" + +import os +from pathlib import Path +import subprocess +import sys + +import pytest + +from pytest_fsd import validate_fsd_architecture +from pytest_fsd.config import FsdConfig +from pytest_fsd.rules import forbidden_imports, no_cross_imports, no_public_api_sidestep + + +def write_project(root, source, source_path="features/auth/api/router.py"): + files = { + "features/auth/__init__.py": "__all__ = []\n", + "features/auth/api/__init__.py": "", + "features/tables/__init__.py": "__all__ = ['value']\nvalue = 1\n", + "features/tables/model/value.py": "value = 1\n", + "shared/lib/__init__.py": "value = 1\n", + source_path: source, + } + for name, body in files.items(): + path = root / "src" / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(body, encoding="utf-8") + (root / "pyproject.toml").write_text( + '[tool.pytest_fsd]\nbase_path = "src"\n' + 'layers = ["app", "features", "entities", "shared"]\n', + encoding="utf-8", + ) + return FsdConfig(base_path="src", layers=["app", "features", "entities", "shared"]) + + +@pytest.mark.parametrize("source", [ + "import importlib\nimportlib.import_module('src.features.tables')\n", + "import importlib as loader\nloader.import_module('src.features.tables')\n", + "from importlib import import_module\nimport_module('features.tables')\n", + "from importlib import import_module as load\nload('src.features.tables')\n", + "import importlib\nload = importlib.import_module\nload('src.features.tables')\n", + "from importlib import import_module\nload = import_module\nload('src.features.tables')\n", + "__import__('src.features.tables')\n", + "load = __import__\nload('src.features.tables')\n", + "import importlib\nimportlib.import_module(name='src.features.tables')\n", + "__import__(name='src.features.tables')\n", + "import importlib\nimportlib.import_module('src.' + 'features.tables')\n", + "import importlib\nlayer = 'features'\nname = 'src.' + layer + '.tables'\nimportlib.import_module(name)\n", + "import importlib\nlayer = 'features'\nimportlib.import_module(f'src.{layer}.tables')\n", + "import importlib\nimportlib.import_module('...tables', package='src.features.auth.api')\n", + "import importlib\nimportlib.import_module('...tables', package=__package__)\n", + "__import__('tables', {'__package__': 'src.features.auth.api'}, None, (), 3)\n", + "__import__('tables', globals={'__package__': __package__}, level=3)\n", + "__import__('src.features', fromlist=['tables'])\n", + "__import__('src.features', fromlist=('tables',))\n", + "import importlib\nexec(\"importlib.import_module('src.features.tables')\")\n", + "exec(\"import src.features.tables\")\n", + "exec(\"from src.features import tables\")\n", + "eval(\"__import__('src.features.tables')\")\n", + "code = \"import src.features.tables\"\nexec(code)\n", +]) +def test_dynamic_cross_slice_import_forms(tmp_path, source): + config = write_project(tmp_path, source) + violations = no_cross_imports.check(config, str(tmp_path)) + assert violations, source + assert all(v.rule == "no-cross-imports" for v in violations) + assert all(v.line_number and v.column_number for v in violations) + + +@pytest.mark.parametrize("source", [ + "import importlib\nimportlib.import_module('src.features.tables')\n", + "__import__('src.features.tables')\n", + "exec(\"from src.features.tables import value\")\n", + "eval(\"__import__('src.features.tables')\")\n", +]) +def test_dynamic_upward_imports(tmp_path, source): + config = write_project(tmp_path, source, "shared/lib/source.py") + violations = forbidden_imports.check(config, str(tmp_path)) + assert violations, source + assert all(v.rule == "forbidden-imports" for v in violations) + + +@pytest.mark.parametrize("source", [ + "import importlib\nimportlib.import_module('src.features.tables.model.value')\n", + "__import__('src.features.tables.model.value')\n", + "__import__('src.features.tables', fromlist=['model'])\n", + "__import__('src.features.tables', fromlist=['hidden'])\n", + "exec(\"from src.features.tables.model import value\")\n", + "eval(\"__import__('src.features.tables.model.value')\")\n", +]) +def test_dynamic_public_api_bypasses(tmp_path, source): + config = write_project(tmp_path, source, "app/api/router.py") + violations = no_public_api_sidestep.check(config, str(tmp_path)) + assert violations, source + assert all(v.rule == "no-public-api-sidestep" for v in violations) + + +@pytest.mark.parametrize("source", [ + "import importlib\nimportlib.import_module(get_target())\n", + "from importlib import import_module as load\nload(target)\n", + "__import__(target)\n", + "import importlib\nimportlib.import_module(f'src.{get_layer()}.tables')\n", + "import importlib\nimportlib.import_module('.tables', package=get_package())\n", + "__import__('tables', globals=get_globals(), level=3)\n", + "__import__('src.features', fromlist=get_names())\n", + "__import__('tables', level=get_level())\n", + "exec(code)\n", + "eval(get_code())\n", + "exec(\"import importlib; importlib.import_module(target)\")\n", +]) +def test_unresolved_dynamic_imports_fail_facade(tmp_path, source): + write_project(tmp_path, source) + with pytest.raises(AssertionError, match=r"\[dynamic-imports\]"): + validate_fsd_architecture(str(tmp_path)) + + +@pytest.mark.parametrize("source", [ + "import importlib\nimportlib.import_module('src.shared.lib')\n", + "from importlib import import_module as load\nload('json')\n", + "__import__('json')\n", + "__import__('src.shared.lib', fromlist=['value'])\n", + "exec(\"from src.shared.lib import value\")\n", + "eval(\"__import__('json')\")\n", + "def import_module(name):\n return name\nimport_module(target)\n", + "def __import__(name):\n return name\n__import__(target)\n", + "def exec(code):\n return code\nexec(code)\n", + "def eval(code):\n return code\neval(code)\n", + "from importlib import import_module as load\ndef operation(load):\n return load(target)\n", + "import importlib\ndef operation(importlib):\n return importlib.import_module(target)\n", +]) +def test_allowed_dynamic_imports_and_shadowed_callable_controls(tmp_path, source): + config = write_project(tmp_path, source) + assert no_cross_imports.check(config, str(tmp_path)) == [] + assert forbidden_imports.check(config, str(tmp_path)) == [] + assert no_public_api_sidestep.check(config, str(tmp_path)) == [] + validate_fsd_architecture(str(tmp_path)) + + +def test_dunder_import_public_export_is_allowed(tmp_path): + config = write_project( + tmp_path, "__import__('src.features.tables', fromlist=['value'])\n", "app/api/router.py" + ) + assert no_public_api_sidestep.check(config, str(tmp_path)) == [] + validate_fsd_architecture(str(tmp_path)) + + +def test_dynamic_analysis_is_repeatable_and_does_not_execute_sources(tmp_path): + marker = tmp_path / "executed.txt" + source = ( + "from pathlib import Path\n" + "Path(" + repr(str(marker)) + ").write_text('executed')\n" + "import importlib\n" + "importlib.import_module('src.features.tables')\n" + ) + config = write_project(tmp_path, source) + errors = [] + for _ in range(2): + with pytest.raises(AssertionError, match="no-cross-imports") as error: + validate_fsd_architecture(str(tmp_path)) + errors.append(str(error.value)) + assert errors[0] == errors[1] + assert not marker.exists() + (tmp_path / "src/features/auth/api/router.py").write_text( + "import importlib\nimportlib.import_module('json')\n", encoding="utf-8" + ) + assert no_cross_imports.check(config, str(tmp_path)) == [] + validate_fsd_architecture(str(tmp_path)) + + +@pytest.mark.parametrize("source,rule", [ + ("import importlib\nimportlib.import_module('src.features.tables')\n", "no-cross-imports"), + ("__import__(unknown_target)\n", "dynamic-imports"), + ("exec(unknown_code)\n", "dynamic-imports"), + ("__import__('json')\n", None), +]) +def test_dynamic_facade_exit_status(tmp_path, source, rule): + write_project(tmp_path, source) + env = dict(os.environ, PYTHONPATH=str(Path(__file__).resolve().parents[1] / "src")) + code = ( + "from pytest_fsd import validate_fsd_architecture; " + "validate_fsd_architecture(" + repr(str(tmp_path)) + ")" + ) + result = subprocess.run( + [sys.executable, "-c", code], cwd=tmp_path.parent, env=env, + capture_output=True, text=True, timeout=30, + ) + assert result.returncode == (1 if rule else 0), result.stdout + result.stderr + if rule: + assert "[" + rule + "]" in result.stdout + result.stderr + + +@pytest.mark.parametrize("source", [ + "operation = lambda value=__import__('src.features.tables'): value\n", + "mapping = {**unknown, 'module': __import__('src.features.tables')}\n", + "message = f\"{unknown}{__import__('src.features.tables')}\"\n", + "exec(\"load('src.features.tables')\", {'load': __import__})\n", + "__import__('src.features', fromlist=['tables.model'])\n", +]) +def test_nested_dynamic_import_calls_are_not_skipped(tmp_path, source): + config = write_project(tmp_path, source) + assert no_cross_imports.check(config, str(tmp_path)), source + with pytest.raises(AssertionError, match=r"\[no-cross-imports\]"): + validate_fsd_architecture(str(tmp_path)) + + +def test_conditional_loader_alias_cannot_hide_import(tmp_path): + source = ( + "from importlib import import_module\n" + "load = import_module if condition else other\n" + "load('src.features.tables')\n" + ) + write_project(tmp_path, source) + with pytest.raises(AssertionError, match=r"\[(no-cross-imports|dynamic-imports)\]"): + validate_fsd_architecture(str(tmp_path)) + + +@pytest.mark.parametrize("source", [ + "operation = lambda value=__import__('json'): value\n", + "mapping = {**unknown, 'module': __import__('json')}\n", + "message = f\"{unknown}{__import__('json')}\"\n", + "exec(\"load('json')\", {'load': __import__})\n", +]) +def test_nested_external_import_controls(tmp_path, source): + write_project(tmp_path, source) + validate_fsd_architecture(str(tmp_path)) + + +def test_recursive_literal_exec_has_bounded_analysis_budget(tmp_path): + # A depth limit alone still expands this tiny input exponentially. + source = "code = " + repr("exec(code);" * 5) + "\nexec(code)\n" + write_project(tmp_path, source) + env = dict(os.environ, PYTHONPATH=str(Path(__file__).resolve().parents[1] / "src")) + code = ( + "from pytest_fsd import validate_fsd_architecture; " + "validate_fsd_architecture(" + repr(str(tmp_path)) + ")" + ) + result = subprocess.run( + [sys.executable, "-c", code], cwd=tmp_path.parent, env=env, + capture_output=True, text=True, timeout=5, + ) + assert result.returncode == 1, result.stdout + result.stderr + assert "[dynamic-imports]" in result.stdout + result.stderr + + +@pytest.mark.parametrize('source', [ + "target = 'src.features.tables'\ncondition and (target := 'json')\n__import__(target)\n", + "target = 'src.features.tables'\nvalue = (target := 'json') if condition else None\n__import__(target)\n", + "import importlib\ndef f():\n [x for importlib in items]\n importlib.import_module('src.features.tables')\n", + "from importlib import *\nimport_module('src.features.tables')\n", +]) +def test_branch_and_scope_changes_do_not_hide_dynamic_imports(tmp_path, source): + write_project(tmp_path, source) + with pytest.raises(AssertionError, match='no-cross-imports|dynamic-imports'): + validate_fsd_architecture(str(tmp_path)) + + +def test_comprehension_binding_shadows_builtin_only_inside_comprehension(tmp_path): + write_project(tmp_path, '[eval(value) for eval in handlers]\n') + validate_fsd_architecture(str(tmp_path)) + + +@pytest.mark.parametrize('source', [ + "def f(load=__import__):\n load('src.features.tables')\n", + "f = lambda load=__import__: load('src.features.tables')\n", + "import importlib\nloaders = [importlib.import_module]\nload = loaders[index]\nload('src.features.tables')\n", + "import importlib\nload = {'loader': importlib.import_module}.get(key)\nload('src.features.tables')\n", + "import importlib\nregister([importlib.import_module])\n", +]) +def test_loader_provenance_survives_indirection(tmp_path, source): + write_project(tmp_path, source) + with pytest.raises(AssertionError, match='no-cross-imports|dynamic-imports'): + validate_fsd_architecture(str(tmp_path)) + + +@pytest.mark.parametrize('source', [ + "load = eval('__import__')\nload('src.features.tables')\n", + "getattr(__import__('importlib'), 'import_module')('src.features.tables')\n", + "code = compile(\"import src.features.tables\", '', 'exec')\nexec(code)\n", + "import importlib\nimportlib.import_module('.'.join(('src', 'features', 'tables')))\n", + "def f(x: __import__('src.features.tables')):\n pass\n", + "class X(__import__('src.features.tables').Base):\n pass\n", +]) +def test_computed_loader_and_definition_expressions(tmp_path, source): + config = write_project(tmp_path, source) + assert no_cross_imports.check(config, str(tmp_path)) + + +@pytest.mark.parametrize('source', [ + "load = enabled and __import__\nload('src.features.tables')\n", + "load = __import__ or other\nload('src.features.tables')\n", +]) +def test_boolean_loader_aliases_cannot_hide_imports(tmp_path, source): + write_project(tmp_path, source) + with pytest.raises(AssertionError, match='no-cross-imports|dynamic-imports'): + validate_fsd_architecture(str(tmp_path)) + + +@pytest.mark.parametrize('source', [ + "import importlib\nclass C:\n importlib = object()\n def f(self):\n return importlib.import_module('src.features.tables')\n", + "def f(*args: __import__('src.features.tables').T):\n pass\n", + "def f(**kwargs: __import__('src.features.tables').T):\n pass\n", +]) +def test_method_globals_and_variadic_annotations_are_inspected(tmp_path, source): + config = write_project(tmp_path, source) + assert no_cross_imports.check(config, str(tmp_path)) + + +def test_global_declaration_does_not_shadow_module_loader(tmp_path): + config = write_project(tmp_path, + "import importlib\ndef f():\n global importlib\n" + " importlib.import_module('src.features.tables')\n importlib = object()\n") + assert no_cross_imports.check(config, str(tmp_path)) + + +@pytest.mark.parametrize('source', [ + "__import__('src.features.tables', fromlist=None)\n", + "__import__('', globals={'__package__': 'src.features'}, fromlist=['tables'], level=1)\n", +]) +def test_builtin_import_optional_fromlist_and_relative_empty_name(tmp_path, source): + config = write_project(tmp_path, source) + assert no_cross_imports.check(config, str(tmp_path)) + + +@pytest.mark.parametrize('source', [ + "import importlib\nimportlib.import_module('tkinter')\n", + "__import__('PyQt6.QtWidgets')\n", + "exec(\"import tkinter\")\n", +]) +def test_dynamic_gui_imports_follow_app_rule(tmp_path, source): + from pytest_fsd.rules import no_ui_in_app + config = write_project(tmp_path, source, 'app/api/router.py') + assert no_ui_in_app.check(config, str(tmp_path)) + + +@pytest.mark.parametrize('source', [ + "exec('from .model import *')\n", + "__import__('src.features.tables.model', fromlist=['*'])\n", +]) +def test_dynamic_wildcard_exports_follow_optional_rule(tmp_path, source): + from pytest_fsd.rules import no_wildcard_exports + config = write_project(tmp_path, source, 'features/auth/__init__.py') + assert no_wildcard_exports.check(config, str(tmp_path)) + + +@pytest.mark.skipif(sys.version_info < (3, 10), reason='match requires Python 3.10') +def test_match_branches_do_not_hide_dynamic_imports(tmp_path): + write_project(tmp_path, + "target = 'src.features.tables'\nmatch flag:\n case True:\n target = 'json'\n__import__(target)\n") + with pytest.raises(AssertionError, match='no-cross-imports|dynamic-imports'): + validate_fsd_architecture(str(tmp_path)) + + +@pytest.mark.skipif(sys.version_info < (3, 10), reason='match requires Python 3.10') +def test_match_pattern_binding_shadows_loader(tmp_path): + write_project(tmp_path, + "from importlib import import_module as load\ndef f(flag):\n" + " match flag:\n case {'load': load}:\n load(target)\n") + validate_fsd_architecture(str(tmp_path)) + + +@pytest.mark.skipif(sys.version_info < (3, 11), reason='except* requires Python 3.11') +def test_exception_group_branches_do_not_hide_dynamic_imports(tmp_path): + write_project(tmp_path, + "target = 'src.features.tables'\ntry:\n operation()\nexcept* Exception:\n" + " target = 'json'\n__import__(target)\n") + with pytest.raises(AssertionError, match='no-cross-imports|dynamic-imports'): + validate_fsd_architecture(str(tmp_path)) diff --git a/uv.lock b/uv.lock index 3468e0f..8fabee2 100644 --- a/uv.lock +++ b/uv.lock @@ -177,7 +177,7 @@ wheels = [ [[package]] name = "pytest-fsd" -version = "0.5.0" +version = "0.6.0" source = { editable = "." } dependencies = [ { name = "tomli", marker = "python_full_version < '3.11'" },