import importlib import sys from datetime import datetime as real_datetime import logging import pytest def import_registrator_safely(monkeypatch): """ registrator.py configure logging.basicConfig(filename='/sdsat/logs/..') au top-level. En CI, ce chemin peut ne pas exister et casser l'import. On neutralise basicConfig avant import. """ monkeypatch.setattr(logging, "basicConfig", lambda *args, **kwargs: None) if "registrator" in sys.modules: del sys.modules["registrator"] return importlib.import_module("registrator") def test_get_hostname_success(monkeypatch): registrator = import_registrator_safely(monkeypatch) monkeypatch.setattr(registrator.socket, "gethostname", lambda: "my-host") assert registrator.get_hostname() == "my-host" def test_get_hostname_exception(monkeypatch): registrator = import_registrator_safely(monkeypatch) def boom(): raise Exception("fail") monkeypatch.setattr(registrator.socket, "gethostname", boom) assert registrator.get_hostname() is None def test_get_public_ip_success(monkeypatch): registrator = import_registrator_safely(monkeypatch) class FakeResp: def json(self): return {"origin": "1.2.3.4"} monkeypatch.setattr(registrator.requests, "get", lambda url: FakeResp()) assert registrator.get_public_ip() == "1.2.3.4" def test_get_public_ip_multiple_addresses(monkeypatch): registrator = import_registrator_safely(monkeypatch) class FakeResp: def json(self): return {"origin": "1.2.3.4, 5.6.7.8"} monkeypatch.setattr(registrator.requests, "get", lambda url: FakeResp()) assert registrator.get_public_ip() == "1.2.3.4" def test_get_public_ip_exception_returns_fallback(monkeypatch): registrator = import_registrator_safely(monkeypatch) def boom(url): raise Exception("network down") monkeypatch.setattr(registrator.requests, "get", boom) assert registrator.get_public_ip() == "69.69.69.69" def test_send_to_api_posts_expected_payload(monkeypatch): registrator = import_registrator_safely(monkeypatch) # Fixe la date pour un test déterministe class FakeDateTime: @staticmethod def now(): return real_datetime(2025, 1, 2, 3, 4, 5) monkeypatch.setattr(registrator, "datetime", FakeDateTime) captured = {} class FakePostResp: status_code = 200 text = "OK" def fake_post(url, json): captured["url"] = url captured["json"] = json return FakePostResp() monkeypatch.setattr(registrator.requests, "post", fake_post) registrator.send_to_api("my-host", "8.8.8.8") assert captured["url"] == "http://api.sdsat.fr:8000/registrator" assert captured["json"]["host"] == "my-host" # IMPORTANT : # Ce test suppose que tu as corrigé registrator.py : # "IP": IP assert captured["json"]["IP"] == "8.8.8.8" assert captured["json"]["Date_registration"] == "2025-01-02T03:04:05"