mirror of
https://github.com/deunix-educ/voice-assistant.git
synced 2026-11-26 20:19:43 +01:00
F6 : la configuration en plusieurs fichiers (include, motifs), sections dans server/conf/
config.yaml peut inclure d'autres fichiers par la clé include : chemins relatifs au fichier qui inclut, motifs (*, ?, **) triés par nom, un fichier inclus peut en inclure d'autres (8 niveaux, boucle refusée). Les mappings s'additionnent (home.rooms peut venir de plusieurs fichiers) ; une même valeur définie dans deux fichiers est une erreur qui nomme les deux, les listes ne se concatènent pas. mqtt reste dans config.yaml : le Makefile y lit mqtt.host. Un config.yaml sans include fonctionne comme avant. server/conf/home.yaml, machines.yaml et access.yaml (access + fingerprint) reprennent les sections et leurs commentaires ; la configuration lue est identique à celle d'avant, comparée valeur par valeur. Le serveur s'arrête sur une configuration invalide avec un message, sans trace d'appels. tools/finger.py indique server/conf/access.yaml. Tests : 28 pour l'inclusion (simple, liste, motifs, fusion, conflits, boucle, profondeur, types invalides, démarrage du serveur) ; conftest.py copie la configuration pour les tests qui la réécrivaient (droits, journal, empreintes). Documentation : README FR/EN, CONTEXT.md. server/config.yaml garde mqtt.host 10.42.0.1 : l'adresse locale de l'utilisateur n'est pas commitée. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
"""Fixtures communes aux tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
SERVER_DIR = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def config_copy(tmp_path: Path) -> Path:
|
||||
"""Copie de config.yaml et des fichiers qu'il inclut (server/conf) : modifiable sans toucher aux vrais.
|
||||
|
||||
Rend le chemin du config.yaml copié ; les fichiers inclus sont dans le dossier conf voisin.
|
||||
"""
|
||||
destination = tmp_path / "server"
|
||||
destination.mkdir()
|
||||
shutil.copy2(SERVER_DIR / "config.yaml", destination / "config.yaml")
|
||||
shutil.copytree(SERVER_DIR / "conf", destination / "conf")
|
||||
return destination / "config.yaml"
|
||||
@@ -168,13 +168,14 @@ def test_project_config_is_valid() -> None:
|
||||
assert not policy.check(DOOR_OPEN, "Pierre").allowed
|
||||
|
||||
|
||||
def test_yaml_boolean_keys_are_read_as_on_off(tmp_path: Path) -> None:
|
||||
def test_yaml_boolean_keys_are_read_as_on_off(config_copy: Path) -> None:
|
||||
"""« light: {on: standard} » sans guillemets : YAML lit True, le chargeur rend « on »."""
|
||||
text = (Path(__file__).resolve().parents[1] / "config.yaml").read_text(encoding="utf-8")
|
||||
config = tmp_path / "config.yaml"
|
||||
config.write_text(text.replace('{"on": standard, "off": standard}', "{on: standard, off: standard}"),
|
||||
access = config_copy.parent / "conf" / "access.yaml"
|
||||
text = access.read_text(encoding="utf-8")
|
||||
assert '{"on": standard, "off": standard}' in text
|
||||
access.write_text(text.replace('{"on": standard, "off": standard}', "{on: standard, off: standard}"),
|
||||
encoding="utf-8")
|
||||
assert load_settings(config).access.rules["light"] == {"on": "standard", "off": "standard"}
|
||||
assert load_settings(config_copy).access.rules["light"] == {"on": "standard", "off": "standard"}
|
||||
|
||||
|
||||
def test_unknown_rule_action_is_rejected() -> None:
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
"""Étape F6 : config.yaml peut inclure d'autres fichiers (clé « include », motifs admis)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import textwrap
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from voice_server.__main__ import main
|
||||
from voice_server.settings import read_config
|
||||
|
||||
SERVER_DIR = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def write(path: Path, text: str) -> Path:
|
||||
"""Écrit un fichier YAML de test (dossiers créés au besoin)."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(textwrap.dedent(text), encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- cas simples
|
||||
|
||||
def test_without_include_the_file_is_read_as_is(tmp_path: Path) -> None:
|
||||
config = write(tmp_path / "config.yaml", "audio:\n sample_rate: 16000\n")
|
||||
assert read_config(config) == {"audio": {"sample_rate": 16000}}
|
||||
|
||||
|
||||
def test_empty_file_gives_nothing(tmp_path: Path) -> None:
|
||||
assert read_config(write(tmp_path / "config.yaml", "")) == {}
|
||||
|
||||
|
||||
def test_include_one_path_or_a_list(tmp_path: Path) -> None:
|
||||
write(tmp_path / "a.yaml", "home:\n topic_prefix: home\n")
|
||||
write(tmp_path / "b.yaml", "machines:\n topic_prefix: agent\n")
|
||||
one = write(tmp_path / "one.yaml", "include: a.yaml\naudio: {bits: 16}\n")
|
||||
many = write(tmp_path / "many.yaml", "include: [a.yaml, b.yaml]\n")
|
||||
assert read_config(one) == {"audio": {"bits": 16}, "home": {"topic_prefix": "home"}}
|
||||
assert read_config(many) == {"home": {"topic_prefix": "home"}, "machines": {"topic_prefix": "agent"}}
|
||||
|
||||
|
||||
def test_paths_are_relative_to_the_including_file(tmp_path: Path) -> None:
|
||||
write(tmp_path / "conf" / "home.yaml", "include: pieces/salon.yaml\nhome: {topic_prefix: home}\n")
|
||||
write(tmp_path / "conf" / "pieces" / "salon.yaml", "home:\n rooms: {salon: du salon}\n")
|
||||
config = write(tmp_path / "config.yaml", "include: conf/home.yaml\n")
|
||||
assert read_config(config) == {"home": {"topic_prefix": "home", "rooms": {"salon": "du salon"}}}
|
||||
|
||||
|
||||
def test_absolute_path_is_accepted(tmp_path: Path) -> None:
|
||||
other = write(tmp_path / "ailleurs" / "x.yaml", "a: 1\n")
|
||||
config = write(tmp_path / "config.yaml", f"include: {other}\n")
|
||||
assert read_config(config) == {"a": 1}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- fusion
|
||||
|
||||
def test_mappings_add_up_across_files(tmp_path: Path) -> None:
|
||||
write(tmp_path / "a.yaml", "home:\n rooms: {salon: du salon}\n")
|
||||
write(tmp_path / "b.yaml", "home:\n rooms: {cuisine: de la cuisine}\n boards: {esp32-01: salon}\n")
|
||||
config = write(tmp_path / "config.yaml", "include: [a.yaml, b.yaml]\nhome: {topic_prefix: home}\n")
|
||||
assert read_config(config) == {"home": {
|
||||
"topic_prefix": "home",
|
||||
"rooms": {"salon": "du salon", "cuisine": "de la cuisine"},
|
||||
"boards": {"esp32-01": "salon"},
|
||||
}}
|
||||
|
||||
|
||||
def test_numeric_keys_add_up_too(tmp_path: Path) -> None:
|
||||
"""fingerprint.users a des clés entières : deux fichiers peuvent nommer des doigts différents."""
|
||||
write(tmp_path / "a.yaml", "fingerprint:\n users: {1: Denis}\n")
|
||||
write(tmp_path / "b.yaml", "fingerprint:\n users: {2: Jessica}\n")
|
||||
config = write(tmp_path / "config.yaml", "include: [a.yaml, b.yaml]\n")
|
||||
assert read_config(config)["fingerprint"]["users"] == {1: "Denis", 2: "Jessica"}
|
||||
|
||||
|
||||
def test_same_value_in_two_files_is_an_error_naming_both(tmp_path: Path) -> None:
|
||||
write(tmp_path / "conf" / "a.yaml", "home:\n topic_prefix: home\n")
|
||||
config = write(tmp_path / "config.yaml", "include: conf/a.yaml\nhome:\n topic_prefix: maison\n")
|
||||
with pytest.raises(ValueError, match=r"« home\.topic_prefix » est défini à la fois dans config\.yaml "
|
||||
r"et dans conf[/\\]a\.yaml"):
|
||||
read_config(config)
|
||||
|
||||
|
||||
def test_same_finger_in_two_files_is_an_error(tmp_path: Path) -> None:
|
||||
write(tmp_path / "a.yaml", "fingerprint:\n users: {1: Denis}\n")
|
||||
write(tmp_path / "b.yaml", "fingerprint:\n users: {1: Jessica}\n")
|
||||
config = write(tmp_path / "config.yaml", "include: [a.yaml, b.yaml]\n")
|
||||
with pytest.raises(ValueError, match=r"fingerprint\.users\.1 »"):
|
||||
read_config(config)
|
||||
|
||||
|
||||
def test_a_mapping_and_a_value_under_the_same_key_is_an_error(tmp_path: Path) -> None:
|
||||
write(tmp_path / "a.yaml", "home: {rooms: {salon: du salon}}\n")
|
||||
config = write(tmp_path / "config.yaml", "include: a.yaml\nhome:\n rooms: tous\n")
|
||||
with pytest.raises(ValueError, match=r"« home\.rooms » est défini à la fois"):
|
||||
read_config(config)
|
||||
|
||||
|
||||
def test_lists_are_never_concatenated(tmp_path: Path) -> None:
|
||||
write(tmp_path / "a.yaml", "access:\n confirm: [door.open]\n")
|
||||
config = write(tmp_path / "config.yaml", "include: a.yaml\naccess:\n confirm: [machine.reboot]\n")
|
||||
with pytest.raises(ValueError, match=r"« access\.confirm » est défini à la fois"):
|
||||
read_config(config)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- motifs
|
||||
|
||||
def test_pattern_loads_matching_files_sorted_by_name(tmp_path: Path) -> None:
|
||||
for name in ("cuisine", "salon", "bureau"):
|
||||
write(tmp_path / "pieces" / f"{name}.yaml", f"home:\n rooms: {{{name}: de la {name}}}\n")
|
||||
write(tmp_path / "pieces" / "notes.txt", "pas du YAML : { ignoré\n")
|
||||
config = write(tmp_path / "config.yaml", "include: 'pieces/*.yaml'\n")
|
||||
rooms = read_config(config)["home"]["rooms"]
|
||||
assert list(rooms) == ["bureau", "cuisine", "salon"]
|
||||
|
||||
|
||||
def test_recursive_pattern(tmp_path: Path) -> None:
|
||||
write(tmp_path / "machines" / "bureau" / "pc.yaml", "machines:\n list: {pc-bureau: {name: le PC}}\n")
|
||||
write(tmp_path / "machines" / "nas.yaml", "machines:\n list: {nas: {name: le NAS}}\n")
|
||||
config = write(tmp_path / "config.yaml", "include: 'machines/**/*.yaml'\n")
|
||||
assert sorted(read_config(config)["machines"]["list"]) == ["nas", "pc-bureau"]
|
||||
|
||||
|
||||
def test_pattern_without_match_warns_but_is_not_an_error(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
|
||||
config = write(tmp_path / "config.yaml", "include: 'pieces/*.yaml'\naudio: {bits: 16}\n")
|
||||
with caplog.at_level(logging.WARNING, logger="voice_server.settings"):
|
||||
assert read_config(config) == {"audio": {"bits": 16}}
|
||||
assert "pieces/*.yaml" in caplog.text
|
||||
|
||||
|
||||
def test_overlapping_patterns_read_a_file_once(tmp_path: Path) -> None:
|
||||
write(tmp_path / "pieces" / "salon.yaml", "home:\n rooms: {salon: du salon}\n")
|
||||
config = write(tmp_path / "config.yaml", "include: ['pieces/*.yaml', 'pieces/salon.yaml']\n")
|
||||
assert read_config(config) == {"home": {"rooms": {"salon": "du salon"}}}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- erreurs
|
||||
|
||||
def test_missing_file_is_an_error(tmp_path: Path) -> None:
|
||||
config = write(tmp_path / "config.yaml", "include: conf/absent.yaml\n")
|
||||
with pytest.raises(ValueError, match=r"fichier introuvable : conf[/\\]absent\.yaml"):
|
||||
read_config(config)
|
||||
|
||||
|
||||
def test_include_loop_is_an_error(tmp_path: Path) -> None:
|
||||
write(tmp_path / "a.yaml", "include: b.yaml\n")
|
||||
write(tmp_path / "b.yaml", "include: a.yaml\n")
|
||||
config = write(tmp_path / "config.yaml", "include: a.yaml\n")
|
||||
with pytest.raises(ValueError, match=r"boucle d'inclusion \(config\.yaml → a\.yaml → b\.yaml → a\.yaml\)"):
|
||||
read_config(config)
|
||||
|
||||
|
||||
def test_a_file_matching_its_own_pattern_is_a_loop(tmp_path: Path) -> None:
|
||||
write(tmp_path / "conf" / "all.yaml", "include: '*.yaml'\n")
|
||||
config = write(tmp_path / "config.yaml", "include: conf/all.yaml\n")
|
||||
with pytest.raises(ValueError, match="boucle d'inclusion"):
|
||||
read_config(config)
|
||||
|
||||
|
||||
def test_too_many_levels_is_an_error(tmp_path: Path) -> None:
|
||||
for number in range(12):
|
||||
write(tmp_path / f"f{number}.yaml", f"include: f{number + 1}.yaml\n")
|
||||
write(tmp_path / "f12.yaml", "a: 1\n")
|
||||
with pytest.raises(ValueError, match="plus de 8 niveaux"):
|
||||
read_config(tmp_path / "f0.yaml")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["3", "{a: b}", "[1, 2]", "['']"])
|
||||
def test_include_must_be_a_path_or_a_list_of_paths(tmp_path: Path, value: str) -> None:
|
||||
config = write(tmp_path / "config.yaml", f"include: {value}\n")
|
||||
with pytest.raises(ValueError, match="« include » doit être un chemin ou une liste de chemins"):
|
||||
read_config(config)
|
||||
|
||||
|
||||
def test_included_file_must_be_a_mapping(tmp_path: Path) -> None:
|
||||
write(tmp_path / "liste.yaml", "- a\n- b\n")
|
||||
config = write(tmp_path / "config.yaml", "include: liste.yaml\n")
|
||||
with pytest.raises(ValueError, match=r"liste\.yaml : un mapping YAML est attendu"):
|
||||
read_config(config)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- le config.yaml du dépôt
|
||||
|
||||
def test_project_config_takes_its_sections_from_conf() -> None:
|
||||
"""Les sections découpées arrivent bien de server/conf, et « include » ne reste pas dans le résultat."""
|
||||
config = read_config(SERVER_DIR / "config.yaml")
|
||||
assert "include" not in config
|
||||
for section in ("audio", "mqtt", "stt", "home", "machines", "access", "fingerprint"):
|
||||
assert section in config, section
|
||||
raw = (SERVER_DIR / "config.yaml").read_text(encoding="utf-8")
|
||||
for moved in ("home", "machines", "access", "fingerprint"):
|
||||
assert f"\n{moved}:" not in raw, f"{moved} devrait vivre dans conf/"
|
||||
|
||||
|
||||
def test_mqtt_host_stays_readable_by_the_makefile() -> None:
|
||||
"""Le Makefile lit mqtt.host dans config.yaml avec awk : la section mqtt doit y rester."""
|
||||
inside = False
|
||||
host = ""
|
||||
for line in (SERVER_DIR / "config.yaml").read_text(encoding="utf-8").splitlines():
|
||||
if line.startswith("mqtt:"):
|
||||
inside = True
|
||||
continue
|
||||
if inside and line.split()[:1] == ["host:"]:
|
||||
host = line.split()[1]
|
||||
break
|
||||
assert host
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- démarrage du serveur
|
||||
|
||||
def test_server_refuses_to_start_on_a_conflict_and_says_why(config_copy: Path, capsys: pytest.CaptureFixture[str]) -> None:
|
||||
"""Deux fichiers définissent access.default : pas de trace d'appels, le message nomme les deux fichiers."""
|
||||
config_copy.write_text(config_copy.read_text(encoding="utf-8") + "\naccess:\n default: standard\n", encoding="utf-8")
|
||||
assert main(["--config", str(config_copy)]) == 1
|
||||
error = capsys.readouterr().err
|
||||
assert "configuration invalide" in error
|
||||
assert "« access.default » est défini à la fois dans" in error
|
||||
assert "config.yaml" in error and "access.yaml" in error
|
||||
|
||||
|
||||
def test_server_refuses_to_start_on_a_missing_included_file(config_copy: Path, capsys: pytest.CaptureFixture[str]) -> None:
|
||||
(config_copy.parent / "conf" / "home.yaml").unlink()
|
||||
assert main(["--config", str(config_copy)]) == 1
|
||||
assert "fichier introuvable" in capsys.readouterr().err
|
||||
@@ -69,21 +69,22 @@ def test_project_config_loads() -> None:
|
||||
assert all(isinstance(number, int) and number >= 0 and name for number, name in users.items())
|
||||
|
||||
|
||||
def config_with_fingerprint(tmp_path: Path, section: str) -> Path:
|
||||
"""Copie de config.yaml dont la section fingerprint est remplacée (indépendant des doigts de l'utilisateur)."""
|
||||
text = CONFIG.read_text(encoding="utf-8")
|
||||
path = tmp_path / "config.yaml"
|
||||
path.write_text(text[: text.index("\nfingerprint:")] + "\nfingerprint:\n" + section, encoding="utf-8")
|
||||
return path
|
||||
def config_with_fingerprint(config: Path, section: str) -> Path:
|
||||
"""config.yaml copié dont la section fingerprint (conf/access.yaml) est remplacée : indépendant des doigts
|
||||
de l'utilisateur."""
|
||||
access = config.parent / "conf" / "access.yaml"
|
||||
text = access.read_text(encoding="utf-8")
|
||||
access.write_text(text[: text.index("\nfingerprint:")] + "\nfingerprint:\n" + section, encoding="utf-8")
|
||||
return config
|
||||
|
||||
|
||||
def test_config_validation(tmp_path: Path) -> None:
|
||||
good = config_with_fingerprint(tmp_path, " users: {1: Denis, 2: Denis}\n")
|
||||
def test_config_validation(config_copy: Path) -> None:
|
||||
good = config_with_fingerprint(config_copy, " users: {1: Denis, 2: Denis}\n")
|
||||
assert load_settings(good).fingerprint.users == {1: "Denis", 2: "Denis"}
|
||||
assert load_settings(config_with_fingerprint(tmp_path, " users: {}\n")).fingerprint.users == {}
|
||||
assert load_settings(config_with_fingerprint(config_copy, " users: {}\n")).fingerprint.users == {}
|
||||
for wrong in ("{abc: Denis}", "{-1: Denis}", "{1: ''}"):
|
||||
with pytest.raises(ValueError, match="fingerprint.users"):
|
||||
load_settings(config_with_fingerprint(tmp_path, f" users: {wrong}\n"))
|
||||
load_settings(config_with_fingerprint(config_copy, f" users: {wrong}\n"))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- phrases
|
||||
@@ -131,7 +132,7 @@ def test_enroll_picks_the_free_slot_and_prints_the_config_line(caplog: pytest.Lo
|
||||
("done", None))})
|
||||
assert command_enroll(board, BOOK, "Marie", None) == 0
|
||||
assert board.sent[1] == {"cmd": "fp_enroll", "id": 4} # 1, 2, 5 nommés, 3 occupé
|
||||
assert "A ajouter dans server/config.yaml" in caplog.text and "4: Marie" in caplog.text
|
||||
assert "A ajouter dans server/conf/access.yaml" in caplog.text and "4: Marie" in caplog.text
|
||||
|
||||
|
||||
def test_enroll_reuses_a_slot_already_named_for_that_person_but_empty(caplog: pytest.LogCaptureFixture) -> None:
|
||||
|
||||
@@ -61,9 +61,9 @@ def test_log_file_receives_the_journal(tmp_path: Path, restore_logging: None) ->
|
||||
assert "essai du journal" in settings.log_file.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_log_file_is_optional(tmp_path: Path) -> None:
|
||||
text = CONFIG.read_text(encoding="utf-8").replace("file: logs/voice-server.log", "file:")
|
||||
config = tmp_path / "config.yaml"
|
||||
config.write_text(text, encoding="utf-8")
|
||||
assert load_settings(config).log_file is None
|
||||
def test_log_file_is_optional(config_copy: Path) -> None:
|
||||
text = config_copy.read_text(encoding="utf-8")
|
||||
assert "file: logs/voice-server.log" in text
|
||||
config_copy.write_text(text.replace("file: logs/voice-server.log", "file:"), encoding="utf-8")
|
||||
assert load_settings(config_copy).log_file is None
|
||||
assert load_settings(CONFIG).log_file == (CONFIG.parent / "logs" / "voice-server.log").resolve()
|
||||
|
||||
Reference in New Issue
Block a user