matrix-webhook/tests/start.py

78 lines
2.4 KiB
Python
Raw Normal View History

2021-07-11 10:17:09 -04:00
#!/usr/bin/env python
"""Entry point to start an instrumentalized bot for coverage and run tests."""
2021-07-12 19:16:24 -04:00
from os import environ
2021-07-11 10:17:09 -04:00
from subprocess import Popen, run
2021-07-12 19:16:24 -04:00
from time import time
2021-07-11 10:17:09 -04:00
from unittest import main
2021-07-12 19:16:24 -04:00
import httpx
import yaml
from synapse._scripts.register_new_matrix_user import request_registration
BOT_URL = 'http://localhost:4785'
2021-07-13 04:28:40 -04:00
KEY, MATRIX_URL, MATRIX_ID, MATRIX_PW = (environ[v] for v in ['API_KEY', 'MATRIX_URL', 'MATRIX_ID', 'MATRIX_PW'])
FULL_ID = f'@{MATRIX_ID}:{MATRIX_URL.split("/")[2]}'
def bot_req(req=None, key=None, room_id=None):
"""Bot requests boilerplate."""
if key is not None:
req['key'] = key
url = BOT_URL if room_id is None else f'{BOT_URL}/{room_id}'
return httpx.post(url, json=req).json()
2021-07-12 19:16:24 -04:00
def wait_available(url: str, key: str, timeout: int = 10) -> bool:
"""Wait until a service answer correctly or timeout."""
2021-07-13 02:53:10 -04:00
def check_json(url: str, key: str) -> bool:
"""Ensure a service at a given url answers with valid json containing a certain key."""
try:
data = httpx.get(url).json()
return key in data
except httpx.ConnectError:
return False
2021-07-12 19:16:24 -04:00
start = time()
while True:
if check_json(url, key):
return True
if time() > start + timeout:
return False
2021-07-11 10:17:09 -04:00
def run_and_test():
"""Launch the bot and its tests."""
2021-07-13 04:28:40 -04:00
# Start the server, and wait for it
srv = Popen(['python', '-m', 'synapse.app.homeserver', '--config-path', '/srv/homeserver.yaml'])
2021-07-12 19:16:24 -04:00
if not wait_available(f'{MATRIX_URL}/_matrix/client/r0/login', 'flows'):
return False
2021-07-13 04:28:40 -04:00
# Register a user for the bot.
2021-07-12 19:16:24 -04:00
with open('/srv/homeserver.yaml') as f:
secret = yaml.safe_load(f.read()).get("registration_shared_secret", None)
request_registration(MATRIX_ID, MATRIX_PW, MATRIX_URL, secret, admin=True)
2021-07-13 04:28:40 -04:00
# Start the bot, and wait for it
2021-07-11 10:17:09 -04:00
bot = Popen(['coverage', 'run', 'matrix_webhook.py'])
2021-07-12 19:16:24 -04:00
if not wait_available(BOT_URL, 'status'):
return False
2021-07-13 04:28:40 -04:00
# Run the main unittest module
2021-07-11 10:17:09 -04:00
ret = main(module=None, exit=False).result.wasSuccessful()
2021-07-13 04:28:40 -04:00
srv.terminate()
# TODO Check what the bot says when the server is offline
# print(bot_req({'text': 'bye'}, KEY), {'status': 200, 'ret': 'OK'})
2021-07-11 10:17:09 -04:00
bot.terminate()
2021-07-13 04:28:40 -04:00
2021-07-11 10:17:09 -04:00
for cmd in ['report', 'html', 'xml']:
run(['coverage', cmd])
return ret
if __name__ == '__main__':
exit(not run_and_test())