diff --git a/tests/test_token_tracking.py b/tests/test_token_tracking.py new file mode 100755 index 0000000..60efc7c --- /dev/null +++ b/tests/test_token_tracking.py @@ -0,0 +1,175 @@ +#!/usr/bin/env python3 +""" +Integration test for the token tracking observability system. +Tests the full pipeline from plugin metrics to Grafana dashboard. +""" + +import time +import requests +import subprocess +import sys +import os + +def test_prometheus_metrics_endpoint(): + """Test that the Prometheus metrics endpoint is accessible.""" + print("Testing Prometheus metrics endpoint...") + + try: + # Wait a moment for the service to start + time.sleep(2) + + # Test the metrics endpoint + response = requests.get("http://localhost:8000/metrics", timeout=10) + assert response.status_code == 200, f"Expected 200, got {response.status_code}" + assert "room_llm_input_tokens_total" in response.text, "Missing input tokens metric" + assert "room_llm_output_tokens_total" in response.text, "Missing output tokens metric" + + print("✓ Prometheus metrics endpoint is working") + return True + except Exception as e: + print(f"✗ Prometheus metrics endpoint test failed: {e}") + return False + +def test_prometheus_container(): + """Test that the Prometheus container is running and scraping metrics.""" + print("Testing Prometheus container...") + + try: + # Check if Prometheus container is running + result = subprocess.run(["docker", "ps", "--filter", "name=prometheus", "--format", "{{.Names}}"], + capture_output=True, text=True, timeout=10) + assert "prometheus" in result.stdout, "Prometheus container is not running" + + # Check Prometheus targets + time.sleep(5) # Give Prometheus time to initialize + response = requests.get("http://localhost:9090/api/v1/targets", timeout=10) + assert response.status_code == 200, f"Prometheus targets API failed: {response.status_code}" + + targets_data = response.json() + active_targets = [target for target in targets_data.get("data", {}).get("activeTargets", []) + if target.get("job") == "hermes-agent"] + + assert len(active_targets) > 0, "No active hermes-agent targets found in Prometheus" + assert all(target.get("health") == "up" for target in active_targets), "Not all targets are healthy" + + print("✓ Prometheus container is running and scraping metrics") + return True + except Exception as e: + print(f"✗ Prometheus container test failed: {e}") + return False + +def test_grafana_container(): + """Test that the Grafana container is running and accessible.""" + print("Testing Grafana container...") + + try: + # Check if Grafana container is running + result = subprocess.run(["docker", "ps", "--filter", "name=grafana", "--format", "{{.Names}}"], + capture_output=True, text=True, timeout=10) + assert "grafana" in result.stdout, "Grafana container is not running" + + # Check Grafana is accessible + time.sleep(5) # Give Grafana time to initialize + response = requests.get("http://localhost:3000/api/health", timeout=10) + assert response.status_code == 200, f"Grafana health check failed: {response.status_code}" + + health_data = response.json() + assert health_data.get("database") == "ok", "Grafana database is not healthy" + + print("✓ Grafana container is running and accessible") + return True + except Exception as e: + print(f"✗ Grafana container test failed: {e}") + return False + +def test_dashboard_provisioning(): + """Test that the dashboard is properly provisioned in Grafana.""" + print("Testing Grafana dashboard provisioning...") + + try: + # Wait for provisioning + time.sleep(10) + + # Login to Grafana (default credentials) + session = requests.Session() + login_response = session.post("http://localhost:3000/login", + json={"user": "admin", "password": "admin"}, + timeout=10) + assert login_response.status_code == 200, f"Grafana login failed: {login_response.status_code}" + + # Check for dashboards + dashboards_response = session.get("http://localhost:3000/api/search?query=LLM", timeout=10) + assert dashboards_response.status_code == 200, f"Dashboard search failed: {dashboards_response.status_code}" + + dashboards = dashboards_response.json() + llm_dashboards = [d for d in dashboards if "LLM" in d.get("title", "")] + assert len(llm_dashboards) > 0, "No LLM dashboards found" + + print("✓ Grafana dashboard is properly provisioned") + return True + except Exception as e: + print(f"✗ Grafana dashboard provisioning test failed: {e}") + return False + +def main(): + """Run all integration tests.""" + print("Starting token tracking observability integration tests...\n") + + # Start the monitoring stack + print("Starting monitoring stack with docker-compose...") + try: + subprocess.run([ + "docker-compose", "-f", "docker-compose.prometheus.yml", "up", "-d" + ], cwd="/home/bernd/projekte/Hermes_rocket.chat_Plugin", check=True) + print("✓ Monitoring stack started\n") + except subprocess.CalledProcessError as e: + print(f"✗ Failed to start monitoring stack: {e}") + return 1 + + # Wait for services to initialize + print("Waiting for services to initialize...") + time.sleep(15) + + # Run tests + tests = [ + test_prometheus_metrics_endpoint, + test_prometheus_container, + test_grafana_container, + test_dashboard_provisioning + ] + + results = [] + for test in tests: + try: + result = test() + results.append(result) + except Exception as e: + print(f"✗ Test {test.__name__} failed with exception: {e}") + results.append(False) + print() + + # Clean up + print("Stopping monitoring stack...") + try: + subprocess.run([ + "docker-compose", "-f", "docker-compose.prometheus.yml", "down" + ], cwd="/home/bernd/projekte/Hermes_rocket.chat_Plugin", check=True) + print("✓ Monitoring stack stopped") + except subprocess.CalledProcessError as e: + print(f"Warning: Failed to stop monitoring stack: {e}") + + # Calculate results + passed = sum(results) + total = len(results) + + print(f"\nIntegration Test Results: {passed}/{total} tests passed") + + if passed == total: + print("🎉 All tests passed! The token tracking observability system is working correctly.") + return 0 + else: + print("❌ Some tests failed. Please check the output above for details.") + return 1 + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file