import os import sys import importlib import xml.etree.ElementTree as ET PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) if PROJECT_ROOT not in sys.path: sys.path.insert(0, PROJECT_ROOT) def import_hostname(): module_name = "scripts.hostname" if module_name in sys.modules: del sys.modules[module_name] return importlib.import_module(module_name) def test_generate_random_string_length_and_charset(): hostname = import_hostname() s = hostname.generate_random_string(10) assert len(s) == 10 assert s.islower() assert s.isalpha() def test_update_config_hostname_updates_xml(tmp_path): hostname = import_hostname() xml_path = tmp_path / "config.xml" xml_path.write_text( "OLD1", encoding="utf-8", ) old, changed = hostname.update_config_hostname(str(xml_path), "NEWNAME") assert changed is True assert old == "OLD" # Vérifie que le fichier a été modifié tree = ET.parse(str(xml_path)) root = tree.getroot() assert root.find("hostname").text == "NEWNAME" def test_update_config_hostname_no_hostname_element(tmp_path): hostname = import_hostname() xml_path = tmp_path / "config.xml" xml_path.write_text("1", encoding="utf-8") old, changed = hostname.update_config_hostname(str(xml_path), "NEWNAME") assert changed is False assert old is None def test_main_does_nothing_when_hostname_different(monkeypatch): hostname = import_hostname() # Hostname différent => pas de changement monkeypatch.setattr(hostname.socket, "gethostname", lambda: "already-set") calls = {"apply": 0, "update": 0} def fake_update(path, new): calls["update"] += 1 return ("OLD", True) def fake_apply(new): calls["apply"] += 1 return 0 monkeypatch.setattr(hostname, "update_config_hostname", fake_update) monkeypatch.setattr(hostname, "apply_hostname", fake_apply) monkeypatch.setattr(hostname, "configure_logging", lambda: None) hostname.main(expected_hostname="sd-satxx.dtx.io", config_path="/tmp/config.xml") assert calls["update"] == 0 assert calls["apply"] == 0 def test_main_changes_when_expected_hostname(monkeypatch): hostname = import_hostname() # Hostname attendu => change monkeypatch.setattr(hostname.socket, "gethostname", lambda: "sd-satxx.dtx.io") monkeypatch.setattr(hostname, "configure_logging", lambda: None) # Fige le random monkeypatch.setattr(hostname, "generate_random_string", lambda n: "abcdefghij") captured = {"new": None, "config_path": None, "applied": None} def fake_update(path, new): captured["config_path"] = path captured["new"] = new return ("OLDHOST", True) def fake_apply(new): captured["applied"] = new return 0 monkeypatch.setattr(hostname, "update_config_hostname", fake_update) monkeypatch.setattr(hostname, "apply_hostname", fake_apply) hostname.main(expected_hostname="sd-satxx.dtx.io", config_path="/conf/config.xml") assert captured["new"] == "DTX-SDSAT-abcdefghij" assert captured["applied"] == "DTX-SDSAT-abcdefghij" assert captured["config_path"] == "/conf/config.xml"