BlueGit

projects-timfalken-com verhalenboek

Files

verhalenboek / web / tests / pwa.py

pwa.py

feat: maak Verhalenboek installeerbaar als webapp
timfa project_87242033_bot_b167a9be22027ad5a4b431d0ad8426c6 · pushed by timfa · 6 weeks ago
944696d3 History
pwa.py 9.3 KiB Download Raw
1#!/usr/bin/env python3
2"""Manifest, pictogrammen en service worker, met de juiste scope onder /verhaaltjesboek/."""
3import json
4import os
5import socket
6import struct
7import subprocess
8import tempfile
9import time
10import urllib.error
11import urllib.request
12from pathlib import Path
13
14WEB = Path(__file__).resolve().parents[1]
15ROOT = WEB.parent
16PREFIX = '/verhaaltjesboek'
17checks = 0
18
19def check(value, label):
20 global checks
21 checks += 1
22 assert value, label
23
24def png_size(path):
25 data = path.read_bytes()
26 check(data.startswith(b'\x89PNG\r\n\x1a\n') and data[12:16] == b'IHDR', f'{path.name} is een PNG')
27 return struct.unpack('>II', data[16:24])
28
29manifest = json.loads((WEB / 'manifest.webmanifest').read_text())
30check(manifest['name'] == 'Verhalenboek' and manifest['short_name'] == 'Verhalenboek', 'Naam van de webapp')
31check(manifest['lang'] == 'nl' and manifest['display'] == 'standalone', 'Taal en standalone-weergave')
32check(manifest['start_url'] == PREFIX + '/' and manifest['scope'] == PREFIX + '/', 'start_url en scope blijven in de submap')
33check(manifest['id'] == PREFIX + '/', 'App-id blijft de submap')
34check(manifest['start_url'].startswith(manifest['scope']), 'start_url valt binnen scope')
35check(manifest['theme_color'] == '#f4efe6' and manifest['background_color'] == '#f4efe6', 'Kleuren volgen de pagina')
36icons = {(icon['sizes'], icon['purpose']): icon for icon in manifest['icons']}
37for size, purpose in [('192x192', 'any'), ('512x512', 'any'), ('192x192', 'maskable'), ('512x512', 'maskable')]:
38 icon = icons.get((size, purpose))
39 check(icon is not None, f'Icoon {size} ({purpose})')
40 check(icon['src'].startswith(PREFIX + '/assets/'), f'Icoonpad blijft in de submap: {icon["src"]}')
41 file = WEB / icon['src'].removeprefix(PREFIX + '/')
42 check(file.is_file() and png_size(file) == tuple(int(part) for part in size.split('x')), f'{file.name} is {size}')
43
44check(png_size(WEB / 'assets/apple-touch-icon.png') == (180, 180), 'apple-touch-icon is 180')
45check(png_size(WEB / 'assets/favicon-32.png') == (32, 32), 'favicon-32 is 32')
46svg = (WEB / 'assets/favicon.svg').read_text()
47check('f4a261' in svg.lower() and '3f63d4' in svg.lower(), 'Favicon blijft een blauw boek met oranje bladwijzer')
48check('<svg' in (WEB / 'assets/mask-icon.svg').read_text(), 'mask-icon is svg')
49
50worker = (WEB / 'sw.js').read_text()
51check("request.method !== 'GET'" in worker, 'Service worker laat schrijfacties met rust')
52check('api' in worker and 'auth' in worker and 'callback' in worker, 'Service worker slaat api en login over')
53check("pathname.endsWith('/sw.js')" in worker, 'Service worker cachet zichzelf niet')
54registrar = (WEB / 'assets/pwa.js').read_text()
55check("new URL('sw.js', scope)" in registrar and 'scope: scope.href' in registrar, 'Registratie gebruikt de map van de pagina')
56
57router = r'''<?php
58declare(strict_types=1);
59$root = getenv('VERHALENBOEK_WEBROOT');
60$prefix = '/verhaaltjesboek';
61$path = rawurldecode(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/');
62if ($path === $prefix) {
63 header('Location: '.$prefix.'/');
64 return true;
65}
66if (!is_string($root) || $root === '' || !str_starts_with($path, $prefix.'/')) {
67 http_response_code(404);
68 header('Content-Type: text/plain; charset=utf-8');
69 echo 'Niet gevonden';
70 return true;
71}
72$rel = substr($path, strlen($prefix));
73if (preg_match('#^/api\.php(?:/|$)#', $rel)) {
74 $_SERVER['SCRIPT_NAME'] = $prefix.'/api.php';
75 require $root.'/api.php';
76 return true;
77}
78if ($rel === '/' || $rel === '') {
79 $_SERVER['SCRIPT_NAME'] = $prefix.'/index.php';
80 require $root.'/index.php';
81 return true;
82}
83$file = $root.$rel;
84if (str_ends_with(strtolower($rel), '.php') && is_file($file)) {
85 $_SERVER['SCRIPT_NAME'] = $prefix.$rel;
86 require $file;
87 return true;
88}
89if (is_file($file)) {
90 $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
91 $type = match ($extension) {
92 'webmanifest' => 'application/manifest+json; charset=utf-8',
93 'js' => 'application/javascript; charset=utf-8',
94 'css' => 'text/css; charset=utf-8',
95 'svg' => 'image/svg+xml',
96 'png' => 'image/png',
97 default => 'application/octet-stream',
98 };
99 header('Content-Type: '.$type);
100 if ($extension === 'webmanifest' || basename($file) === 'sw.js') header('Cache-Control: no-cache');
101 readfile($file);
102 return true;
103}
104http_response_code(404);
105header('Content-Type: text/plain; charset=utf-8');
106echo 'Niet gevonden';
107return true;
108'''
109
110def free_port():
111 with socket.socket() as sock:
112 sock.bind(('127.0.0.1', 0))
113 return sock.getsockname()[1]
114
115def wait_for(url):
116 for _ in range(100):
117 try:
118 urllib.request.urlopen(url).close()
119 return
120 except urllib.error.URLError:
121 time.sleep(0.05)
122 raise RuntimeError('server startte niet: ' + url)
123
124def fetch(url, method='GET', data=None, headers=None):
125 request = urllib.request.Request(url, data=data, headers=headers or {}, method=method)
126 try:
127 response = urllib.request.urlopen(request)
128 except urllib.error.HTTPError as error:
129 response = error
130 with response:
131 body = response.read()
132 return response.status, {key.lower(): value for key, value in response.headers.items()}, body
133
134with tempfile.TemporaryDirectory(prefix='pwa-', dir=WEB / 'tests/artifacts') as tmp:
135 tmp_path = Path(tmp)
136 (tmp_path / 'data').mkdir()
137 router_path = tmp_path / 'router.php'
138 router_path.write_text(router)
139 port = free_port()
140 base = f'http://127.0.0.1:{port}{PREFIX}'
141 log = (tmp_path / 'server.log').open('w')
142 process = subprocess.Popen(
143 ['php', '-d', 'opcache.enable=0', '-S', f'127.0.0.1:{port}', '-t', str(tmp_path), str(router_path)],
144 stdout=log, stderr=log, start_new_session=True,
145 env={**os.environ, 'VERHALENBOEK_DATA_DIR': str(tmp_path / 'data'), 'VERHALENBOEK_WEBROOT': str(WEB)},
146 )
147 try:
148 wait_for(base + '/')
149 status, headers, body = fetch(base + '/manifest.webmanifest')
150 check(status == 200 and headers.get('content-type', '').startswith('application/manifest+json'), 'Manifest heeft het juiste type')
151 served = json.loads(body)
152 check(served['start_url'] == PREFIX + '/' and served['scope'] == PREFIX + '/', 'Geserveerd manifest blijft in de submap')
153 status, headers, html = fetch(base + '/')
154 page = html.decode()
155 check(status == 200 and '<title>Verhalenboek</title>' in page, 'Startpagina onder de submap')
156 check('rel="manifest" href="manifest.webmanifest"' in page, 'Manifestlink is relatief')
157 check('href="/manifest' not in page and 'href="/assets/' not in page and 'src="/' not in page, 'Geen absolute paden vanaf de domeinwortel')
158 check('apple-mobile-web-app-capable' in page and 'apple-mobile-web-app-title' in page and 'Verhalenboek' in page, 'iOS-meta voor toevoegen aan beginscherm')
159 check('assets/apple-touch-icon.png' in page and 'assets/favicon.svg' in page and 'assets/pwa.js' in page, 'Favicon, aanraakicoon en registratie')
160 check('name="theme-color"' in page and '#f4efe6' in page, 'Thema-kleur')
161 for name in ['icon-192.png', 'icon-512.png', 'icon-maskable-512.png', 'apple-touch-icon.png', 'favicon.svg']:
162 status, headers, payload = fetch(base + '/assets/' + name)
163 check(status == 200 and len(payload) > 32, name + ' is bereikbaar')
164 status, headers, script = fetch(base + '/sw.js')
165 check(status == 200 and b"method !== 'GET'" in script and headers.get('content-type', '').startswith('application/javascript'), 'Service worker onder de submap')
166 status, _, me = fetch(base + '/api.php/me', headers={'Accept': 'application/json'})
167 profile = json.loads(me)
168 check(status == 200 and profile['user']['name'] == 'test_user_1', 'API GET onder de submap blijft werken')
169 status, _, denied = fetch(
170 base + '/api.php/days',
171 method='POST',
172 data=b'{}',
173 headers={'Accept': 'application/json', 'Content-Type': 'application/json'},
174 )
175 check(status == 403 and 'Ongeldige sessie' in json.loads(denied)['error'], 'API POST onder de submap blijft naar PHP gaan')
176 status, doc_headers, docs = fetch(base + '/docs.php')
177 check(status == 200 and 'rel="manifest" href="manifest.webmanifest"' in docs.decode(), 'Documentatie deelt het manifest')
178 finally:
179 process.kill()
180 process.wait(timeout=5)
181 log.close()
182
183root_port = free_port()
184with tempfile.TemporaryDirectory(prefix='pwa-root-', dir=WEB / 'tests/artifacts') as tmp:
185 env = {**os.environ, 'VERHALENBOEK_DATA_DIR': str(Path(tmp) / 'data')}
186 Path(tmp, 'data').mkdir()
187 log = Path(tmp, 'server.log').open('w')
188 process = subprocess.Popen(
189 ['php', '-d', 'opcache.enable=0', '-S', f'127.0.0.1:{root_port}', '-t', str(WEB), str(WEB / 'router.php')],
190 stdout=log, stderr=log, start_new_session=True, env=env,
191 )
192 try:
193 wait_for(f'http://127.0.0.1:{root_port}/')
194 status, headers, body = fetch(f'http://127.0.0.1:{root_port}/manifest.webmanifest')
195 check(status == 200 and headers.get('content-type', '').startswith('application/manifest+json'), 'Lokale router zet het manifest-type')
196 check(b'"scope"' in body, 'Lokale router levert het manifest')
197 finally:
198 process.kill()
199 process.wait(timeout=5)
200 log.close()
201
202print(f'PWA: {checks} controles geslaagd.')