"""Exercise the loopback API with a simulated NUT server. Never enables real shutdown.""" import datetime import json import os from pathlib import Path import socket import subprocess import sys import tempfile import threading import time import urllib.error import urllib.request def main(*command): mode = 'OL' with socket.create_server(('127.0.0.1', 0)) as probe: port = probe.getsockname()[1] nut = socket.create_server(('127.0.0.1', 0)) def serve(): while True: conn, _ = nut.accept() with conn, conn.makefile('rb') as reader: request = reader.readline() if request == b'LIST VAR h1000m\n': body = f'BEGIN LIST VAR h1000m\nVAR h1000m ups.status "{mode}"\nEND LIST VAR h1000m\n' errors = {'stale': b'ERR DATA-STALE\n', 'disconnected': b'ERR DRIVER-NOT-CONNECTED\n'} conn.sendall(errors.get(mode, body.encode())) elif request == b'LIST UPS\n': conn.sendall(b'BEGIN LIST UPS\nUPS h1000m "Test UPS"\nEND LIST UPS\n') threading.Thread(target=serve, daemon=True).start() http = urllib.request.build_opener(urllib.request.ProxyHandler({})) with tempfile.TemporaryDirectory() as temp: token_path = Path(temp) / 'agent.token' env = dict(os.environ, LANUPS_AGENT_PORT=str(port), LANUPS_AGENT_TOKEN=str(token_path)) subprocess.run([*command, '--provision'], env=env, check=True) token = token_path.read_text().strip() endpoint = {'host': '127.0.0.1', 'port': nut.getsockname()[1], 'name': 'h1000m'} token_path.with_suffix('.json').write_text(json.dumps(endpoint)) # Config written by older agents. def call(path, method='GET', body=None, auth=True): headers = {'X-LanUps-Token': token} if auth else {} data = None if body is not None: headers['Content-Type'] = 'application/json' data = json.dumps(body).encode() request = urllib.request.Request(f'http://127.0.0.1:{port}/{path}', data=data, headers=headers, method=method) with http.open(request, timeout=2) as response: return json.load(response) def wait(predicate, seconds=9): deadline = time.monotonic() + seconds state = None while time.monotonic() < deadline: try: state = call('status') if predicate(state): return state except (ConnectionError, urllib.error.URLError) as error: if isinstance(error, urllib.error.HTTPError): raise time.sleep(.2) raise AssertionError(state) def flag(state): reading = state['update']['lastReading'] return reading and reading['values']['ups.status'] def denied(path, code, method='GET', body=None, auth=True): try: call(path, method, body, auth) except urllib.error.HTTPError as error: assert error.code == code, error.code else: raise AssertionError('Expected HTTP error') def start(): return subprocess.Popen(command, env=env, stdout=subprocess.DEVNULL) process = start() try: assert wait(lambda state: state['dryRun'])['shutdownImmediately'] is False denied('status', 401, auth=False) assert call('endpoint', 'PUT', endpoint) == endpoint assert call(f"ups?host=127.0.0.1&port={endpoint['port']}") == ['h1000m'] assert wait(lambda state: flag(state) == 'OL')['update']['nutServerOnline'] is True mode = 'disconnected' disconnected = wait(lambda state: state['update']['error'] == 'ERR DRIVER-NOT-CONNECTED') assert disconnected['update']['nutServerOnline'] is True with socket.socket() as offline: offline.bind(('127.0.0.1', 0)) # Reserve a port without starting a listener. call('endpoint', 'PUT', dict(endpoint, port=offline.getsockname()[1])) unavailable = wait(lambda state: state['update']['nutServerOnline'] is False) assert unavailable['update']['error'] and unavailable['update']['lastReading'] is None call('endpoint', 'PUT', endpoint) mode = 'stale' assert wait(lambda state: state['update']['error'] == 'ERR DATA-STALE')['update']['nutServerOnline'] is True print('PASS: separate NUT server and UPS connection status', flush=True) mode = 'OB FSD' first = wait(lambda state: state['pending'])['pending']['id'] denied('endpoint', 409, 'PUT', dict(endpoint, port=1)) assert call(f'shutdown/{first}/cancel', 'POST') == 'cancel' wait(lambda state: state['lastAction'] == '用户取消' and not state['pending']) denied(f'shutdown/{first}/confirm', 409, 'POST') mode = 'OL' wait(lambda state: flag(state) == 'OL') mode = 'OB FSD' second = wait(lambda state: state['pending'])['pending']['id'] assert call(f'shutdown/{second}/confirm', 'POST') == 'confirm' wait(lambda state: '已模拟关机' in (state['lastAction'] or '')) mode = 'OL' wait(lambda state: flag(state) == 'OL') immediate = dict(endpoint, shutdownImmediately=True) assert call('settings', 'PUT', immediate) == immediate process.terminate() process.wait() process = start() assert wait(lambda state: flag(state) == 'OL')['shutdownImmediately'] is True mode = 'OB FSD' result = wait(lambda state: (state['lastAction'] or '').startswith('收到关机指令,立即执行'), 7) assert result['pending'] is None and '已模拟关机' in result['lastAction'] print('PASS: immediate shutdown preference persists and bypasses countdown in dry-run mode', flush=True) call('settings', 'PUT', dict(endpoint, shutdownImmediately=False)) mode = 'OL' wait(lambda state: flag(state) == 'OL') mode = 'OB FSD' pending = wait(lambda state: state['pending'])['pending'] deadline = datetime.datetime.fromisoformat(pending['deadline']) assert 56 < (deadline - datetime.datetime.now(datetime.timezone.utc)).total_seconds() <= 61 process.terminate() process.wait() process = start() assert wait(lambda state: state['pending'])['pending'] == pending print('PASS: local authorization, settings, discovery, stale data, cancel, confirm, restart recovery', flush=True) result = wait(lambda state: (state['lastAction'] or '').startswith('60 秒内无响应'), 65) assert result['pending'] is None and datetime.datetime.now(datetime.timezone.utc) >= deadline print('PASS: 60-second automatic dry-run shutdown', flush=True) finally: process.terminate() process.wait() if __name__ == '__main__': main(*sys.argv[1:])