Files

45 lines
2.1 KiB
Python
Raw Permalink Normal View History

import importlib
import sqlite3
from datetime import datetime, timedelta
import pytest
MB = 1_000_000
FMT = '%Y-%m-%d %H:%M:%S'
@pytest.fixture
def api(tmp_path, monkeypatch):
"""OpenVPNAPI on a temporary migrated database (the module creates a global instance on import)."""
monkeypatch.chdir(tmp_path)
monkeypatch.setenv("OVPMON_OPENVPN_MONITOR_DB_PATH", str(tmp_path / "api.db"))
monkeypatch.delenv("OVPMON_AUTO_MIGRATE", raising=False)
module = importlib.import_module("openvpn_api_v3")
return module.OpenVPNAPI()
def test_aggregated_history_speed_is_bucket_average(api):
now = datetime.utcnow()
full = (now - timedelta(hours=5)).replace(minute=0, second=0, microsecond=0) # complete hourly bucket
current = now - timedelta(seconds=1800) # bucket started 30 minutes ago: lasts 1800 s, not 3600 s
conn = sqlite3.connect(api.db_manager.db_path)
conn.execute("INSERT INTO clients (common_name) VALUES ('alice')")
cid = conn.execute("SELECT id FROM clients WHERE common_name='alice'").fetchone()[0]
for ts in (full, current):
conn.execute("INSERT INTO stats_hourly (timestamp, client_id, bytes_received, bytes_sent) VALUES (?,?,?,?)",
(ts.strftime(FMT), cid, 450 * MB, 90 * MB))
conn.commit()
conn.close()
res = api.get_client_history('alice', now - timedelta(days=7), now, resolution='hourly')
full_row, current_row = res['data']
# 450 MB over 3600 s = 1.0 Mbps (rx), 90 MB over 3600 s = 0.2 Mbps (tx)
assert full_row['bytes_received_rate_mbps'] == pytest.approx(1.0)
assert full_row['bytes_sent_rate_mbps'] == pytest.approx(0.2)
# the same volume over 1800 s: twice as fast
assert current_row['bytes_received_rate_mbps'] == pytest.approx(2.0, rel=0.01)
assert current_row['bytes_sent_rate_mbps'] == pytest.approx(0.4, rel=0.01)
# Analytics 7d reads the same table: the sum of clients per timestamp, speed is non-zero
history = api.get_analytics_data('7d')['global_history_24h']
assert max(p['total_rx_rate'] for p in history) == pytest.approx(2.0, rel=0.01)