import importlib import logging import sys from datetime import datetime as real_datetime import requests import os import sys 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_registrator_safely(monkeypatch): """ Neutralise logging.basicConfig avant import pour éviter les erreurs liées au fichier de log. Importe scripts.registrator (car le fichier est dans scripts/). """ monkeypatch.setattr(logging, "basicConfig", lambda *args, **kwargs: None) module_name = "scripts.registrator" if module_name in sys.modules: del sys.modules[module_name] return importlib.import_module(module_name) 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"