Files
OKTP_SERVER/tests/test_metrics.py
T

136 lines
5.6 KiB
Python

import json
import threading
import unittest
from contextlib import contextmanager
from datetime import datetime, timedelta, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from unittest.mock import patch
from urllib.error import HTTPError
from urllib.request import Request, urlopen
from metrics_agent import Sampler, make_handler as agent_handler
from server import make_handler as site_handler, validate_metrics
TOKEN = 'test-only-token-' * 4
def sample():
return {'sampled_at': datetime.now(timezone.utc).isoformat(),
'cpu': {'percent': 12},
'memory': {'percent': 50, 'used_bytes': 512, 'total_bytes': 1024},
'disk': {'percent': 25, 'used_bytes': 256, 'total_bytes': 1024, 'path': '/'}}
@contextmanager
def serving(handler):
server = ThreadingHTTPServer(('127.0.0.1', 0), handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
yield f'http://127.0.0.1:{server.server_port}'
finally:
server.shutdown()
server.server_close()
thread.join()
class MetricsTests(unittest.TestCase):
def test_real_host_sample(self):
self.assertEqual(validate_metrics(Sampler('/').collect())['disk']['path'], '/')
def test_reject_invalid_samples(self):
for key, value in [('percent', float('nan')), ('percent', -1), ('percent', 101), ('percent', True)]:
data = sample()
data['cpu'][key] = value
with self.assertRaises(ValueError):
validate_metrics(data)
data = sample()
data['memory']['used_bytes'] = 2048
with self.assertRaises(ValueError):
validate_metrics(data)
def test_stale_sample_rejected(self):
data = sample()
data['sampled_at'] = (datetime.now(timezone.utc) - timedelta(seconds=30)).isoformat()
with self.assertRaises(ValueError):
validate_metrics(data)
def test_sampler_expiry(self):
sampler = Sampler('/')
sampler.snapshot = sample()
sampler.sampled_at = 100
with patch('metrics_agent.time.monotonic', return_value=121):
self.assertIsNone(sampler.get())
def test_failed_collection_clears_snapshot(self):
sampler = Sampler('/')
sampler.snapshot = sample()
stop = threading.Event()
def fail():
stop.set()
raise OSError('Disk unavailable')
with patch.object(sampler, 'collect', side_effect=fail):
sampler.run(stop)
self.assertIsNone(sampler.get())
def test_agent_authentication(self):
sampler = Sampler('/')
with serving(agent_handler(sampler, TOKEN)) as base:
for token in ('', 'wrong'):
with self.assertRaises(HTTPError) as error:
urlopen(Request(base + '/metrics', headers={'Authorization': token}))
self.assertEqual(error.exception.code, 401)
with self.assertRaises(HTTPError) as error:
urlopen(Request(base + '/metrics', headers={'Authorization': 'Bearer ' + TOKEN}))
self.assertEqual(error.exception.code, 503)
def test_proxy_success_and_static_isolation(self):
sampler = Sampler('/')
with patch.object(sampler, 'get', return_value=sample()):
with serving(agent_handler(sampler, TOKEN)) as agent:
with serving(site_handler(agent + '/metrics', TOKEN)) as site:
with urlopen(site + '/api/metrics') as response:
body = response.read().decode()
self.assertEqual(response.headers['Cache-Control'], 'no-store')
self.assertEqual(json.loads(body)['cpu']['percent'], 12)
self.assertNotIn(TOKEN, body)
for path in ('/', '/style.css', '/app.js'):
with urlopen(site + path) as response:
self.assertEqual(response.status, 200)
for path in ('/metrics_agent.py', '/server.py', '/.env.metrics', '/docs/content.md'):
with self.assertRaises(HTTPError) as error:
urlopen(site + path)
self.assertEqual(error.exception.code, 404)
def test_unconfigured_proxy(self):
with serving(site_handler()) as site:
with self.assertRaises(HTTPError) as error:
urlopen(site + '/api/metrics')
self.assertEqual(error.exception.code, 503)
self.assertEqual(json.load(error.exception)['error'], 'metrics_not_configured')
def test_wrong_upstream_token(self):
with serving(agent_handler(Sampler('/'), TOKEN)) as agent:
with serving(site_handler(agent + '/metrics', 'wrong')) as site:
with self.assertRaises(HTTPError) as error:
urlopen(site + '/api/metrics')
self.assertEqual(error.exception.code, 502)
def test_malformed_or_redirecting_upstream(self):
class Upstream(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(302 if self.path == '/redirect' else 200)
self.send_header('Location', '/should-not-follow')
self.end_headers()
self.wfile.write(b'not JSON')
with serving(Upstream) as upstream:
for path in ('/malformed', '/redirect'):
with serving(site_handler(upstream + path, TOKEN)) as site:
with self.assertRaises(HTTPError) as error:
urlopen(site + '/api/metrics')
self.assertEqual(error.exception.code, 502)
if __name__ == '__main__':
unittest.main()