#!/usr/bin/env python3 """Exercise registration and admin workflows on an isolated WordPress site.""" import argparse import base64 from html.parser import HTMLParser from http.cookiejar import CookieJar import json from pathlib import Path import time from urllib.parse import urlencode, urljoin, urlsplit from urllib.request import build_opener, HTTPCookieProcessor, HTTPRedirectHandler from wordpress import WordPress, add_wordpress_arguments class Forms(HTMLParser): def __init__(self): super().__init__(convert_charrefs=True) self.forms = [] self.current = None self.export_url = None def handle_starttag(self, tag, attrs): attrs = dict(attrs) if tag == 'form': self.current = { 'action': attrs.get('action', ''), 'classes': attrs.get('class', '').split(), 'fields': [], } if self.current is not None and tag == 'input' and attrs.get('type') == 'hidden': self.current['fields'].append((attrs['name'], attrs.get('value', ''))) if tag == 'a' and 'action=hgr_export' in attrs.get('href', ''): self.export_url = attrs['href'] def handle_endtag(self, tag): if tag == 'form' and self.current is not None: self.forms.append(self.current) self.current = None def origin(url): parts = urlsplit(url) if not parts.hostname or parts.username or parts.password: raise ValueError('Expected a WordPress URL without embedded credentials.') if parts.scheme != 'https' and (parts.scheme != 'http' or parts.hostname not in ('localhost', '127.0.0.1', '::1')): raise ValueError('Use HTTPS or an HTTP loopback staging URL.') return parts.scheme, parts.hostname, parts.port or (443 if parts.scheme == 'https' else 80) class StagingClient: def __init__(self, home, credentials): self.expected_origin = origin(home) class SameOriginRedirect(HTTPRedirectHandler): def redirect_request(handler, req, fp, code, msg, headers, newurl): self.check_url(newurl) return super().redirect_request(req, fp, code, msg, headers, newurl) self.client = build_opener(HTTPCookieProcessor(CookieJar()), SameOriginRedirect()) if 'preview_user' in credentials or 'preview_password' in credentials: pair = f"{credentials['preview_user']}:{credentials['preview_password']}" self.client.addheaders = [('Authorization', 'Basic ' + base64.b64encode(pair.encode()).decode())] def check_url(self, url): if origin(url) != self.expected_origin: raise ValueError('The staging test encountered a different HTTP origin.') def open(self, url, fields=None): self.check_url(url) data = urlencode(fields).encode() if fields is not None else None return self.client.open(url, data, timeout=15) def create_fixture(wp): return wp.json(r""" $activity = wp_insert_post(['post_type' => 'hgr_activity', 'post_status' => 'publish', 'post_title' => 'Temporary HTTP test'], true); if (is_wp_error($activity)) WP_CLI::error($activity->get_error_message()); $moment = hgr_save_moment(['activity_id' => $activity, 'starts_at' => wp_date('Y-m-d\TH:i', time() + 259200), 'ends_at' => wp_date('Y-m-d\TH:i', time() + 262800), 'location' => 'Test location', 'capacity' => 2, 'state' => 'open']); if (is_wp_error($moment)) { wp_delete_post($activity, true); WP_CLI::error($moment->get_error_message()); } $marker = wp_generate_uuid4(); $page = wp_insert_post(['post_type' => 'page', 'post_status' => 'publish', 'post_title' => 'Temporary registration fixture ' . $marker, 'post_content' => '[hg_registrations activity="' . $activity . '"]'], true); if (is_wp_error($page)) { global $wpdb; $wpdb->delete(hgr_table('moments'), ['id' => $moment]); wp_delete_post($activity, true); WP_CLI::error($page->get_error_message()); } echo wp_json_encode(['activity' => $activity, 'moment' => $moment, 'page' => $page, 'url' => get_permalink($page), 'marker' => $marker]); """) def exercise(wp, client, credentials, fixture): with client.open(fixture['url']) as response: assert response.headers.get('X-HGR-Test-Mail') == 'blocked', 'Staging HTTP mail fixture is inactive.' html = response.read().decode() assert fixture['marker'] in html, 'The HTTP site did not render the staging fixture.' forms = Forms() forms.feed(html) form = next(form for form in forms.forms if 'hgr-form' in form['classes']) assert any(key == 'hgr_token' for key, _value in form['fields']) assert '2 beschikbaar' in html and 'van 2 plaatsen' in html time.sleep(4) form_url = urljoin(fixture['url'], form['action']) fields = form['fields'] + [ ('contact_name', 'Temporary HTTP test'), ('contact_email', 'registrant@example.test'), ('participants[]', 'Testdeelnemer A'), ('participants[]', 'Testdeelnemer B'), ('consent', '1'), ('website', ''), ] with client.open(form_url, fields) as response: assert 'hgr_reserved=1' in response.url html = response.read().decode() assert 'Je aanvraag is ontvangen' in html and '0 beschikbaar' in html and 'Volgeboekt' in html with client.open(form_url, fields) as response: response.read() moment = int(fixture['moment']) current = wp.json(f""" global $wpdb; $query = $wpdb->prepare('SELECT id,seats,status FROM ' . hgr_table('registrations') . ' WHERE moment_id=%d', {moment}); echo wp_json_encode($wpdb->get_results($query)); """) assert len(current) == 1 and int(current[0]['seats']) == 2 and current[0]['status'] == 'reserved' print('HTTP submission, duplicate retry and sold-out state verified.') admin = wp.info['admin'] details = urljoin(admin, 'admin.php?' + urlencode({ 'page': 'hg-registrations', 'tab': 'registrations', 'registration_id': current[0]['id'], })) client.check_url(details) with client.open(wp.info['login']) as response: response.read() with client.open(wp.info['login'], { 'log': credentials['admin_user'], 'pwd': credentials['admin_password'], 'redirect_to': details, 'testcookie': '1', }) as response: assert '/wp-admin/' in response.url html = response.read().decode() assert '2 gereserveerd' in html and '0 beschikbaar' in html and 'Status opslaan' in html forms = Forms() forms.feed(html) status = next(form for form in forms.forms if ('operation', 'status') in form['fields']) with client.open(urljoin(details, status['action']), status['fields'] + [('status', 'confirmed')]) as response: assert '2 bevestigd' in response.read().decode() assert wp.json(f'echo wp_json_encode(hgr_capacity({moment}));')['confirmed'] == 2 print('Authenticated storage of the registration status verified.') registrations = urljoin(admin, 'admin.php?page=hg-registrations&tab=registrations') with client.open(registrations) as response: forms = Forms() forms.feed(response.read().decode()) assert forms.export_url, 'Export link missing.' with client.open(urljoin(registrations, forms.export_url)) as response: assert 'text/csv' in response.headers['Content-Type'] assert 'Testdeelnemer A' in response.read().decode('utf-8-sig') print('Authenticated participant export verified.') def main(): parser = argparse.ArgumentParser(description=__doc__) add_wordpress_arguments(parser) parser.add_argument('--credentials-file', type=Path, required=True, help='Local JSON with staging credentials') args = parser.parse_args() wp = WordPress(args) if not wp.info['mail_blocked']: raise RuntimeError('Install the HTTP test mail fixture on the isolated staging site first.') credentials = json.loads(args.credentials_file.read_text()) for key in ('admin_user', 'admin_password'): if not isinstance(credentials.get(key), str) or not credentials[key]: raise ValueError(f'Missing staging credential {key}.') client = StagingClient(wp.info['home'], credentials) client.check_url(wp.info['login']) client.check_url(wp.info['admin']) fixture = create_fixture(wp) try: exercise(wp, client, credentials, fixture) finally: activity, moment, page = (int(fixture[key]) for key in ('activity', 'moment', 'page')) wp.eval(f""" global $wpdb; $wpdb->delete(hgr_table('registrations'), ['moment_id' => {moment}]); $wpdb->delete(hgr_table('moments'), ['id' => {moment}]); wp_delete_post({activity}, true); wp_delete_post({page}, true); """) if __name__ == '__main__': main()