41 lines
2.0 KiB
Python
41 lines
2.0 KiB
Python
import importlib
|
|||
|
|
import sqlite3
|
||
|
|
|
||
|
|
import pytest
|
||
|
|
|
||
|
|
FMT_SINCE = '2026-11-12 10:00:00'
|
||
|
|
|
||
|
|
|
||
|
|
@pytest.fixture
|
||
|
|
def api(tmp_path, monkeypatch):
|
||
|
|
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_stats_include_sessions(api):
|
||
|
|
conn = sqlite3.connect(api.db_manager.db_path)
|
||
|
|
for cn, status in (('alice', 'Active'), ('bob', 'Active'), ('carol', 'Disconnected')):
|
||
|
|
conn.execute("INSERT INTO clients (common_name, status, real_address) VALUES (?,?,?)",
|
||
|
|
(cn, status, '1.1.1.1:1000'))
|
||
|
|
ids = {cn: i for i, cn in conn.execute("SELECT id, common_name FROM clients")}
|
||
|
|
mb = 1024 * 1024
|
||
|
|
for cn, addr, rx, tx in (('alice', '1.1.1.1:1000', 2 * mb, mb), ('alice', '2.2.2.2:2000', 0, 0),
|
||
|
|
('bob', '3.3.3.3:3000', mb, mb)):
|
||
|
|
conn.execute("INSERT INTO active_sessions (client_id, common_name, real_address, bytes_received,"
|
||
|
|
" bytes_sent, connected_since, last_seen, session_id) VALUES (?,?,?,?,?,?,?,?)",
|
||
|
|
(ids[cn], cn, addr, rx, tx, FMT_SINCE, FMT_SINCE, None))
|
||
|
|
conn.commit()
|
||
|
|
conn.close()
|
||
|
|
|
||
|
|
by_cn = {c['common_name']: c for c in api.get_current_stats()}
|
||
|
|
assert by_cn['alice']['sessions_count'] == 2
|
||
|
|
assert {s['real_address'] for s in by_cn['alice']['sessions']} == {'1.1.1.1:1000', '2.2.2.2:2000'}
|
||
|
|
first = next(s for s in by_cn['alice']['sessions'] if s['real_address'] == '1.1.1.1:1000')
|
||
|
|
assert (first['received_mb'], first['sent_mb'], first['connected_since']) == (2.0, 1.0, FMT_SINCE)
|
||
|
|
assert by_cn['bob']['sessions_count'] == 1
|
||
|
|
assert by_cn['carol']['sessions_count'] == 0 and by_cn['carol']['sessions'] == []
|
||
|
|
# existing fields are unchanged
|
||
|
|
assert by_cn['alice']['real_address'] == '1.1.1.1:1000' and by_cn['alice']['status'] == 'Active'
|