#!/usr/bin/env python3
"""Quick test of mechbase-plc web server."""
import sys
sys.path.insert(0, '.')
import app
import time
import threading
import urllib.request
import json
def run_server():
app.app.run(host='0.0.0.0', port=5003, use_reloader=False)
t = threading.Thread(target=run_server, daemon=True)
t.start()
time.sleep(1.5)
base = 'http://localhost:5003'
tests = [
('Main page', f'{base}/', None),
('Templates', f'{base}/api/templates', None),
('Program', f'{base}/api/program', None),
('Scan', f'{base}/api/scan', '{}'),
]
for name, url, data in tests:
try:
if data:
req = urllib.request.Request(url, data=data.encode(), headers={'Content-Type': 'application/json'})
else:
req = url
r = urllib.request.urlopen(req)
body = r.read().decode()
if name == 'Main page':
print(f'{name}: {r.status} ({len(body)} chars)')
else:
try:
d = json.loads(body)
print(f'{name}: {json.dumps(d, indent=2)[:200]}')
except:
print(f'{name}: {body[:200]}')
except Exception as e:
print(f'{name}: ERROR - {e}')
print('\nServer is running on port 5001. Keeping alive...')
time.sleep(300)