Initialize public HG Inschrijvingen source
This commit is contained in:
commit
c84fea26a0
23 files changed
+1623
No files matched your search
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify that concurrent reservations cannot exceed capacity on staging."""
|
||||
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from wordpress import WordPress, add_wordpress_arguments
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
add_wordpress_arguments(parser)
|
||||
wp = WordPress(parser.parse_args())
|
||||
fixture = wp.json(r"""
|
||||
$activity = wp_insert_post(['post_type' => 'hgr_activity', 'post_status' => 'publish',
|
||||
'post_title' => 'Temporary capacity 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() + 172800),
|
||||
'ends_at' => wp_date('Y-m-d\TH:i', time() + 176400),
|
||||
'location' => 'Test location', 'capacity' => 3, 'state' => 'open']);
|
||||
if (is_wp_error($moment)) {
|
||||
wp_delete_post($activity, true);
|
||||
WP_CLI::error($moment->get_error_message());
|
||||
}
|
||||
echo wp_json_encode(['activity' => $activity, 'moment' => $moment]);
|
||||
""")
|
||||
moment = int(fixture['moment'])
|
||||
activity = int(fixture['activity'])
|
||||
try:
|
||||
def attempt(_index):
|
||||
return wp.json(f"""
|
||||
$result = hgr_reserve({moment}, ['contact_name' => 'Test contact',
|
||||
'contact_email' => 'registrant@example.test', 'participants' => ['Test participant']],
|
||||
hash('sha256', wp_generate_uuid4()));
|
||||
echo wp_json_encode(!is_wp_error($result));
|
||||
""")
|
||||
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
results = list(pool.map(attempt, range(8)))
|
||||
capacity = wp.json(f'echo wp_json_encode(hgr_capacity({moment}));')
|
||||
assert sum(results) == 3, results
|
||||
assert capacity['reserved'] == 3 and capacity['available'] == 0, capacity
|
||||
print('Eight parallel requests respected the three-place capacity.')
|
||||
finally:
|
||||
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);
|
||||
""")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
/** Isolated staging fixture for the HTTP integration test. */
|
||||
|
||||
if (!defined('ABSPATH')) exit;
|
||||
if (wp_get_environment_type() !== 'staging') return;
|
||||
|
||||
define('HGR_TEST_MAIL_BLOCKED', true);
|
||||
add_filter('pre_wp_mail', '__return_true', PHP_INT_MAX);
|
||||
add_action('send_headers', static function (): void {
|
||||
header('X-HGR-Test-Mail: blocked');
|
||||
});
|
||||
@@ -0,0 +1,198 @@
|
||||
#!/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()
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
// Run only on a disposable development/staging installation: wp eval-file tests/integration.php.
|
||||
if (!defined('WP_CLI') || !WP_CLI || wp_get_environment_type()!=='staging') throw new RuntimeException('Alleen via WP-CLI op staging uitvoeren.');
|
||||
global $wpdb;
|
||||
$activity=0;$moments=[];
|
||||
$assert=function($ok,$message){if(!$ok)throw new RuntimeException($message);};
|
||||
$old=get_option('hgr_settings',null);$mail=[];$mail_mode='ok';
|
||||
$mail_filter=function($pre,$args)use(&$mail,&$mail_mode){$mail[]=$args;if($mail_mode==='fail')return false;if($mail_mode==='partial')return count($mail)%2===1;return true;};
|
||||
add_filter('pre_wp_mail',$mail_filter,PHP_INT_MAX,2);
|
||||
try {
|
||||
update_option('hgr_settings',['recipient'=>'organizer@example.test','max_participants'=>20]);
|
||||
$activity=wp_insert_post(['post_type'=>'hgr_activity','post_status'=>'publish','post_title'=>'HG tijdelijke integratietest']);
|
||||
$start=wp_date('Y-m-d\TH:i',time()+DAY_IN_SECONDS);$end=wp_date('Y-m-d\TH:i',time()+DAY_IN_SECONDS+3600);
|
||||
$moment_input=['activity_id'=>$activity,'starts_at'=>$start,'ends_at'=>$end,'location'=>'Tijdelijke testlocatie','capacity'=>3,'state'=>'open'];
|
||||
$id=hgr_save_moment($moment_input);$assert(!is_wp_error($id),'Moment aanmaken');$moments[]=$id;
|
||||
$input=['contact_name'=>'Testcontact','contact_email'=>'registrant@example.test','phone'=>'','organization'=>'','participants'=>['Persoon A','Persoon B']];
|
||||
$key=hash('sha256',wp_generate_uuid4());$result=hgr_reserve($id,$input,$key);$assert(!is_wp_error($result)&&$result['new'],'Reserveren');$rid=$result['id'];
|
||||
$assert(hgr_capacity($id)['reserved']===2 && hgr_capacity($id)['available']===1,'Capaciteit na reserveren');
|
||||
$replay=hgr_reserve($id,$input,$key);$assert(!$replay['new']&&$replay['id']===$rid,'Idempotente dubbele aanvraag');
|
||||
$assert(is_wp_error(hgr_reserve($id,$input,hash('sha256',wp_generate_uuid4()))),'Overboeking geweigerd');
|
||||
$assert(is_wp_error(hgr_save_moment(array_merge($moment_input,['id'=>$id,'capacity'=>1]))),'Capaciteit verkleinen geweigerd');
|
||||
$assert(is_wp_error(hgr_save_moment(array_merge($moment_input,['id'=>$id,'location'=>'Andere locatie']))),'Geboekt moment verplaatsen geweigerd');
|
||||
$assert(hgr_set_status($rid,'confirmed')===true,'Bevestigen');$assert(hgr_capacity($id)['confirmed']===2&&hgr_capacity($id)['reserved']===0,'Bevestiging houdt plaatsen vast');
|
||||
$assert(hgr_notify($rid),'Mailinhoud en verzending');$assert(count($mail)===2,'Twee meldingen');
|
||||
$expected=apply_filters('wp_mail',['to'=>'registrant@example.test','subject'=>'','message'=>'','headers'=>[]]);
|
||||
$assert($mail[0]['to']==='organizer@example.test' && $mail[1]['to']===$expected['to'],'Mailontvangers en eventuele staging-omleiding');
|
||||
$assert(str_contains($mail[0]['message'],'Aantal deelnemers: 2') && str_contains($mail[1]['message'],'Je deelname is bevestigd.'),'Mail bevat deelnemers en status');
|
||||
hgr_notify($rid);$assert(count($mail)===2,'Meldingen niet dubbel verstuurd');
|
||||
$assert(hgr_set_status($rid,'cancelled')===true,'Annuleren');$assert(hgr_capacity($id)['available']===3,'Annulering geeft plaatsen vrij');
|
||||
$input['participants']=['Persoon C','Persoon D','Persoon E'];$next=hgr_reserve($id,$input,hash('sha256',wp_generate_uuid4()));$assert(!is_wp_error($next),'Vrijgekomen plaatsen reserveren');
|
||||
$assert(is_wp_error(hgr_set_status($rid,'confirmed')),'Geen overboeking bij heractiveren');
|
||||
$assert(hgr_capacity($id)['available']===0,'Volgeboekt');
|
||||
$html=do_shortcode('[hg_registrations activity="'.$activity.'"]');$assert(str_contains($html,'Volgeboekt')&&!str_contains($html,'name="participants[]"'),'Geen formulier bij vol');
|
||||
$mail_mode='fail';$assert(!hgr_notify($next['id']),'Mailfalen zichtbaar');$assert(hgr_registration($next['id'])->notice_state==='failed','Mailstatus bewaard');$assert(hgr_capacity($id)['reserved']===3,'Mailfalen verliest reservering niet');
|
||||
$mail_mode='ok';$assert(hgr_notify($next['id']),'Mislukte berichten opnieuw versturen');
|
||||
hgr_set_status($next['id'],'declined');$assert(hgr_capacity($id)['available']===3,'Afwijzing geeft plaatsen vrij');
|
||||
$assert(hgr_check_token(hgr_form_token($id,time()-4),$id),'Geldig ondertekend formulier');
|
||||
$assert(!hgr_check_token(hgr_form_token($id,time()-8000),$id),'Verlopen formulier geweigerd');
|
||||
$assert(!hgr_check_token(hgr_form_token($id,time()-4),$id+1),'Formulier aan moment gebonden');
|
||||
$assert(is_wp_error(hgr_clean_registration(['contact_name'=>['x'],'participants'=>['x']])),'Ongeldige gegevens geweigerd');
|
||||
$assert(wp_delete_post($activity,true)===false,'Activiteit met momenten niet permanent verwijderen');
|
||||
$caps=map_meta_cap('edit_post',0,$activity);$assert(in_array('manage_options',$caps,true),'Activiteiten alleen door beheerders bewerken');
|
||||
WP_CLI::success('Reserveringen, capaciteit, statussen, mail, duplicaten en validatie gecontroleerd; geen echte e-mails verzonden.');
|
||||
} finally {
|
||||
foreach($moments as $id){$wpdb->delete(hgr_table('registrations'),['moment_id'=>$id]);$wpdb->delete(hgr_table('moments'),['id'=>$id]);}
|
||||
if($activity)wp_delete_post($activity,true);
|
||||
if($old===null)delete_option('hgr_settings');else update_option('hgr_settings',$old);
|
||||
remove_filter('pre_wp_mail',$mail_filter,PHP_INT_MAX);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
"""WP-CLI access for the isolated registrations test scripts."""
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
|
||||
|
||||
def add_wordpress_arguments(parser):
|
||||
parser.add_argument('--wp-path', required=True, help='WordPress root of the staging installation')
|
||||
parser.add_argument('--wp-cli', default='wp', help='WP-CLI executable')
|
||||
|
||||
|
||||
class WordPress:
|
||||
def __init__(self, args):
|
||||
self.command = [args.wp_cli, '--path=' + args.wp_path, 'eval', 'eval(stream_get_contents(STDIN));']
|
||||
self.info = self.json("""
|
||||
if (wp_get_environment_type() !== 'staging' || !function_exists('hgr_reserve')) {
|
||||
WP_CLI::error('Use a staging installation with HG Inschrijvingen active.');
|
||||
}
|
||||
echo wp_json_encode([
|
||||
'home' => home_url(), 'admin' => admin_url(), 'login' => wp_login_url(),
|
||||
'mail_blocked' => defined('HGR_TEST_MAIL_BLOCKED'),
|
||||
]);
|
||||
""")
|
||||
|
||||
def eval(self, code):
|
||||
result = subprocess.run(self.command, input=code, text=True, capture_output=True, timeout=20)
|
||||
if result.returncode:
|
||||
raise RuntimeError(result.stderr.strip())
|
||||
return result.stdout
|
||||
|
||||
def json(self, code):
|
||||
return json.loads(self.eval(code))
|
||||
Reference in new issue
Block a user