Files
manage/backend/tests/test_targets.py
T

110 lines
3.5 KiB
Python

"""Tests for Prometheus file-based service discovery target generation."""
from pathlib import Path
import pytest
from media_library_viewer_api.services.settings_store import SettingsStore
from media_library_viewer_api.services.targets import (
build_node_exporter_targets,
write_prometheus_targets,
)
@pytest.fixture
def store(tmp_path: Path) -> SettingsStore:
db = SettingsStore(tmp_path / "settings.sqlite")
db.init_schema()
return db
class TestBuildNodeExporterTargets:
def test_disabled_machine_excluded(self, store: SettingsStore):
store.upsert_machine(
{
"name": "remote1",
"mode": "ssh",
"host": "10.0.0.5",
"username": "u",
"node_exporter_enabled": False,
"node_exporter_port": 9200,
}
)
assert build_node_exporter_targets(store) == []
def test_ssh_enabled_machine_included(self, store: SettingsStore):
machine = store.upsert_machine(
{
"name": "remote1",
"mode": "ssh",
"host": "10.0.0.5",
"username": "u",
"node_exporter_enabled": True,
"node_exporter_port": 9200,
"node_exporter_scrape_host": "1.2.3.4",
}
)
targets = build_node_exporter_targets(store)
assert len(targets) == 1
assert targets[0]["targets"] == ["1.2.3.4:9200"]
assert targets[0]["labels"]["machine_id"] == machine["id"]
assert targets[0]["labels"]["machine_name"] == "remote1"
assert targets[0]["labels"]["job"] == "node-exporter-remote"
def test_scrape_host_defaults_to_machine_host(self, store: SettingsStore):
store.upsert_machine(
{
"name": "remote2",
"mode": "ssh",
"host": "remote2.example.com",
"username": "u",
"node_exporter_enabled": True,
"node_exporter_port": 9100,
}
)
targets = build_node_exporter_targets(store)
assert targets[0]["targets"] == ["remote2.example.com:9100"]
def test_local_machine_excluded(self, store: SettingsStore):
store.upsert_machine(
{
"name": "This machine",
"mode": "local",
"host": "localhost",
"username": "",
"node_exporter_enabled": True,
}
)
assert build_node_exporter_targets(store) == []
def test_missing_host_excluded(self, store: SettingsStore):
store.upsert_machine(
{
"name": "remote3",
"mode": "ssh",
"host": "",
"username": "u",
"node_exporter_enabled": True,
}
)
assert build_node_exporter_targets(store) == []
class TestWritePrometheusTargets:
def test_writes_valid_json(self, store: SettingsStore, tmp_path: Path):
store.upsert_machine(
{
"name": "remote1",
"mode": "ssh",
"host": "10.0.0.5",
"username": "u",
"node_exporter_enabled": True,
"node_exporter_port": 9200,
}
)
file_path = write_prometheus_targets(store, tmp_path)
assert file_path.exists()
assert file_path.name == "node_exporter_targets.json"
targets = build_node_exporter_targets(store)
assert len(targets) == 1