126 lines
5.3 KiB
Python
126 lines
5.3 KiB
Python
"""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'
|
|
conn.sendall(b'ERR DATA-STALE\n' if mode == 'stale' else 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()
|
|
|
|
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:
|
|
wait(lambda state: state['dryRun'])
|
|
denied('status', 401, auth=False)
|
|
endpoint = {'host': '127.0.0.1', 'port': nut.getsockname()[1], 'name': 'h1000m'}
|
|
assert call('endpoint', 'PUT', endpoint) == endpoint
|
|
assert call(f"ups?host=127.0.0.1&port={endpoint['port']}") == ['h1000m']
|
|
wait(lambda state: flag(state) == 'OL')
|
|
mode = 'stale'
|
|
wait(lambda state: state['update']['error'] and not state['pending'])
|
|
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')
|
|
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:])
|