Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion python_dependency_linter/config.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import re
from dataclasses import dataclass
from pathlib import Path

Expand Down Expand Up @@ -38,12 +39,20 @@ def _parse_allow_deny(data: dict | None) -> AllowDeny | None:
)


_RULE_NAME_PATTERN = re.compile(r"^[a-zA-Z0-9_-]+$")


def _parse_rules(rules_data: list[dict]) -> list[Rule]:
rules = []
for r in rules_data:
name = r["name"]
if not _RULE_NAME_PATTERN.match(name):
raise ValueError(
f"Invalid rule name '{name}'. Rule names must match [a-zA-Z0-9_-]+"
)
rules.append(
Rule(
name=r["name"],
name=name,
modules=r["modules"],
allow=_parse_allow_deny(r.get("allow")),
deny=_parse_allow_deny(r.get("deny")),
Expand Down
54 changes: 54 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from pathlib import Path

import pytest

from python_dependency_linter.config import find_config, load_config

FIXTURES = Path(__file__).parent / "fixtures"
Expand Down Expand Up @@ -127,3 +129,55 @@ def test_find_config_skips_pyproject_without_section(tmp_path, monkeypatch):
(tmp_path / "pyproject.toml").write_text("[tool.other]\nfoo = 1\n")
monkeypatch.chdir(tmp_path)
assert find_config() is None


def test_valid_rule_names(tmp_path):
config_content = """\
rules:
- name: attribute-matches-type
modules: src.*
- name: bool_method
modules: src.*
- name: rule1
modules: src.*
"""
config_file = tmp_path / "config.yaml"
config_file.write_text(config_content)
config = load_config(config_file)
assert len(config.rules) == 3


def test_invalid_rule_name_with_space(tmp_path):
config_content = """\
rules:
- name: "my rule"
modules: src.*
"""
config_file = tmp_path / "config.yaml"
config_file.write_text(config_content)
with pytest.raises(ValueError, match=r"Invalid rule name 'my rule'"):
load_config(config_file)


def test_invalid_rule_name_with_special_char(tmp_path):
config_content = """\
rules:
- name: "rule!name"
modules: src.*
"""
config_file = tmp_path / "config.yaml"
config_file.write_text(config_content)
with pytest.raises(ValueError, match=r"Invalid rule name 'rule!name'"):
load_config(config_file)


def test_invalid_rule_name_with_mixed(tmp_path):
config_content = """\
rules:
- name: "rule name 123"
modules: src.*
"""
config_file = tmp_path / "config.yaml"
config_file.write_text(config_content)
with pytest.raises(ValueError, match=r"Invalid rule name 'rule name 123'"):
load_config(config_file)
Loading