import pytest from unittest.mock import patch, MagicMock import cluster_aggregator @patch("consul_client.get_cluster_services") @patch("litefs_client.get_node_status") @patch("nomad_client.get_job_allocations") @patch("nomad_client.get_node_map") def test_aggregate_cluster_status(mock_node_map, mock_nomad_allocs, mock_litefs, mock_consul): """Test aggregating Nomad, Consul and LiteFS data.""" mock_node_map.return_value = {"id": "name"} # Mock Nomad allocations mock_nomad_allocs.return_value = [ {"id": "alloc1", "node": "node1", "ip": "1.1.1.1"}, {"id": "alloc2", "node": "node2", "ip": "1.1.1.2"} ] # Mock Consul data (only node1 is registered as primary) mock_consul.return_value = [ {"node": "node1", "address": "1.1.1.1", "role": "primary", "status": "passing", "check_output": "OK"} ] # Mock LiteFS data def litefs_side_effect(addr, **kwargs): if addr == "1.1.1.1": return {"is_primary": True, "candidate": True, "uptime": 100, "dbs": {"db1": {"txid": "0000000000000001", "checksum": "abc"}}} return {"is_primary": False, "candidate": True, "uptime": 50, "dbs": {"db1": {"txid": "0000000000000001", "checksum": "abc"}}} mock_litefs.side_effect = litefs_side_effect cluster_data = cluster_aggregator.get_cluster_status("http://consul:8500") assert cluster_data["health"] == "Healthy" assert len(cluster_data["nodes"]) == 2 node1 = next(n for n in cluster_data["nodes"] if n["node"] == "node1") assert node1["litefs_primary"] is True assert node1["candidate"] is True assert "db1" in node1["dbs"] @patch("consul_client.get_cluster_services") @patch("litefs_client.get_node_status") @patch("nomad_client.get_job_allocations") @patch("nomad_client.get_allocation_logs") @patch("nomad_client.get_node_map") def test_aggregate_cluster_status_unhealthy(mock_node_map, mock_nomad_logs, mock_nomad_allocs, mock_litefs, mock_consul): """Test health calculation when primary is unregistered or failing.""" mock_node_map.return_value = {"id": "name"} mock_nomad_allocs.return_value = [ {"id": "alloc1", "node": "node1", "ip": "1.1.1.1"} ] # Primary in LiteFS but missing in Consul mock_litefs.return_value = {"is_primary": True, "candidate": True, "uptime": 100, "dbs": {"db1": {"txid": "1", "checksum": "abc"}}} mock_consul.return_value = [] mock_nomad_logs.return_code = 0 mock_nomad_logs.return_value = "error logs" cluster_data = cluster_aggregator.get_cluster_status("http://consul:8500") assert cluster_data["health"] == "Unhealthy" assert cluster_data["nodes"][0]["status"] == "unregistered" assert cluster_data["nodes"][0]["nomad_logs"] == "error logs"