Skip to content

Commit

Permalink
chore: error if file content is not a mapping
Browse files Browse the repository at this point in the history
  • Loading branch information
albertodonato committed Jan 3, 2025
1 parent c404f2c commit f70e1b1
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
5 changes: 4 additions & 1 deletion query_exporter/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,10 @@ def _load_config(paths: list[Path]) -> dict[str, t.Any]:
"""Return the combined configuration from provided files."""
config: dict[str, t.Any] = defaultdict(dict)
for path in paths:
data = defaultdict(dict, load_yaml_config(path))
conf = load_yaml_config(path)
if not isinstance(conf, dict):
raise ConfigError(f"File content is not a mapping: {path}")
data = defaultdict(dict, conf)
for key in (field.name for field in dataclasses.fields(Config)):
entries = data.pop(key, None)
if entries is not None:
Expand Down
8 changes: 7 additions & 1 deletion tests/config_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,13 +128,19 @@ def write(data: dict[str, t.Any]) -> Path:


class TestLoadConfig:
def test_load_invalid_format(self, tmp_path: Path) -> None:
def test_load_invalid(self, tmp_path: Path) -> None:
config_file = tmp_path / "invalid.yaml"
config_file.write_text("foo: !env UNSET")
with pytest.raises(ConfigError) as err:
load_config([config_file])
assert "variable UNSET undefined" in str(err.value)

def test_load_not_mapping(self, tmp_path: Path, write_config: ConfigWriter) -> None:
config_file = write_config(["a", "b", "c"])
with pytest.raises(ConfigError) as err:
load_config([config_file])
assert str(err.value) == f"File content is not a mapping: {config_file}"

def test_load_databases_section(self, write_config: ConfigWriter) -> None:
cfg = {
"databases": {
Expand Down

0 comments on commit f70e1b1

Please sign in to comment.