Files
notplanned/ventures/context-priority/tests/signup.py
T

53 lines
2.4 KiB
Python

"""Check the existing signup service in isolation; never writes production data.
Usage: python3 tests/signup.py /path/to/existing/server.py
"""
import importlib.util
import json
import sys
import tempfile
import threading
import urllib.parse
import urllib.request
from http.server import ThreadingHTTPServer
from pathlib import Path
spec = importlib.util.spec_from_file_location('signup_under_test', sys.argv[1])
server = importlib.util.module_from_spec(spec)
spec.loader.exec_module(server)
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
with tempfile.TemporaryDirectory(prefix='priority-signup-') as directory:
root = Path(directory)
server.DATA = root / 'signups.jsonl'
server.SITES = root / 'sites'
(server.SITES / 'context-priority').mkdir(parents=True)
(server.SITES / 'context-priority/index.html').write_text('isolated published-page fixture')
httpd = ThreadingHTTPServer(('127.0.0.1', 0), server.Handler)
thread = threading.Thread(target=httpd.serve_forever, daemon=True)
thread.start()
url = f'http://127.0.0.1:{httpd.server_port}/api/signup'
opener = urllib.request.build_opener(NoRedirect)
def post(fields):
request = urllib.request.Request(url, data=urllib.parse.urlencode(fields).encode(), headers={'Content-Type': 'application/x-www-form-urlencoded'})
try:
return opener.open(request)
except urllib.error.HTTPError as response:
return response
fields = {'venture':'context-priority','email':'test@example.invalid','plan':'workshop','note':'isolated acceptance','website':''}
response = post(fields)
assert response.code == 303
assert response.headers['Location'] == '/v/context-priority/?joined=1#join'
row = json.loads(server.DATA.read_text())
assert all(row[key] == fields[key] for key in ['venture','email','plan','note'])
before = server.DATA.read_text()
assert post({**fields,'email':'invalid'}).code == 400
assert post({**fields,'website':'bot'}).code == 303
assert server.DATA.read_text() == before
assert post({**fields,'venture':'unpublished'}).code == 404
httpd.shutdown()
httpd.server_close()
print('PASS: real handler, isolated form POST, 303 redirect, record, invalid email, honeypot and unpublished venture guard. No production data written.')