#!/usr/bin/env python3 """Test the running Compose stack; only deletes records created by this script. Run --phase create, recreate containers WITHOUT deleting volumes, then --phase verify. Credentials and test record IDs are kept in ignored .local files. """ import argparse import base64 import hashlib import http.cookiejar import json from pathlib import Path import time import urllib.error import urllib.parse import urllib.request import uuid parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--base', default='http://127.0.0.1:8088') parser.add_argument('--env-file', default='.local/container-test.env') parser.add_argument('--state', default='.local/container-test-state.json') parser.add_argument('--phase', choices=['create', 'verify'], required=True) args = parser.parse_args() env = dict(line.split('=', 1) for line in Path(args.env_file).read_text().splitlines() if '=' in line and not line.startswith('#')) state_path = Path(args.state) jar = http.cookiejar.CookieJar() client = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar)) csrf = {} checks = [] def check(condition, label): if not condition: raise AssertionError(label) checks.append(label) print('PASS:', label, flush=True) def request(path, method='GET', body=None, content_type=None, expected=200, protected=True): headers = {} if isinstance(body, dict): body = json.dumps(body).encode() content_type = 'application/json' if content_type: headers['Content-Type'] = content_type if protected and csrf and method != 'GET': headers[csrf['headerName']] = csrf['token'] req = urllib.request.Request(args.base + path, data=body, headers=headers, method=method) try: response = client.open(req, timeout=30) except urllib.error.HTTPError as error: response = error data = response.read() if response.status != expected: raise AssertionError(f'{method} {path}: expected {expected}, got {response.status}: {data[:300]!r}') return data, response.headers def api(path, **kwargs): data, _ = request('/api/v1' + path, **kwargs) return json.loads(data) if data else None def login(): global csrf csrf = api('/auth/csrf') form = urllib.parse.urlencode({'username': env['ADMIN_USERNAME'], 'password': env['ADMIN_PASSWORD']}).encode() api('/auth/login', method='POST', body=form, content_type='application/x-www-form-urlencoded') csrf = api('/auth/csrf') check(api('/auth/me')['username'] == env['ADMIN_USERNAME'], 'account login through Nginx') for attempt in range(40): try: request('/api/v1/auth/csrf') break except (OSError, AssertionError): if attempt == 39: raise time.sleep(1) html, _ = request('/') check(b'
' in html, 'frontend built HTML served') api('/notes', expected=401) check(True, 'unauthenticated notes rejected') csrf = api('/auth/csrf') api('/auth/login', method='POST', body=b'username=admin&password=wrong', content_type='application/x-www-form-urlencoded', expected=401) login() if args.phase == 'create': if state_path.exists(): raise SystemExit('State already exists; finish --phase verify before creating another test.') baseline = api('/dashboard') note = dict(title='容器验收 ' + uuid.uuid4().hex[:8], body='# 容器持久化\n\n真实 PostgreSQL', category='技术笔记', tag='容器测试', star=True, version=0) api('/notes', method='POST', body=note, protected=False, expected=403) check(True, 'CSRF required for writes') created = api('/notes', method='POST', body=note, expected=201) state = {'note': created['id'], 'assets': [], 'baseline': baseline} state_path.write_text(json.dumps(state)) state_path.chmod(0o600) note['body'] += '\n\n更新成功' updated = api('/notes/' + created['id'], method='PUT', body=note) check(updated['version'] == 1, 'note update increments version') api('/notes/' + created['id'], method='PUT', body=note, expected=409) check(True, 'stale note version rejected') found = api('/notes?' + urllib.parse.urlencode({'q': note['title'], 'starred': 'true', 'category': '技术笔记'})) check(len(found) == 1 and found[0]['id'] == created['id'], 'note search, category and favorite filters') files = [('container-test.txt', b'Container upload persists across recreation.\n'), ('container-test.png', base64.b64decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII='))] for name, payload in files: boundary = 'MySpace' + uuid.uuid4().hex body = (f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="{name}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode() + payload + f'\r\n--{boundary}--\r\n'.encode()) uploaded = api('/assets', method='POST', body=body, content_type='multipart/form-data; boundary=' + boundary, expected=201) state['assets'].append({'id': uploaded['id'], 'sha256': hashlib.sha256(payload).hexdigest(), 'name': name, 'size': len(payload)}) state_path.write_text(json.dumps(state)) content, headers = request('/api/v1/assets/' + uploaded['id'] + '/content') check(content == payload, name + ' upload and exact-byte download') check(headers['X-Content-Type-Options'] == 'nosniff', name + ' safe response headers') check(headers['Content-Type'] == ('image/png' if name.endswith('.png') else 'application/octet-stream'), name + ' detected media type') boundary = 'MySpaceLimitTest' prefix = (f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="too-large.bin"\r\nContent-Type: application/octet-stream\r\n\r\n').encode() suffix = f'\r\n--{boundary}--\r\n'.encode() request('/api/v1/assets', method='POST', body=prefix + bytes(15 * 1024 * 1024 + 1) + suffix, content_type='multipart/form-data; boundary=' + boundary, expected=413) check(True, '15 MB file limit enforced through Nginx and Spring') request('/api/v1/assets', method='POST', body=prefix + suffix, content_type='multipart/form-data; boundary=' + boundary, expected=400) check(True, 'empty upload rejected') current = api('/dashboard') check(current['notes'] == baseline['notes'] + 1 and current['assets'] == baseline['assets'] + 2 and current['storageBytes'] == baseline['storageBytes'] + sum(a['size'] for a in state['assets']), 'dashboard reflects stored notes and assets') print('CREATE COMPLETE: recreate containers while preserving volumes, then run --phase verify.') else: state = json.loads(state_path.read_text()) note = api('/notes/' + state['note']) check(note['version'] == 1 and note['body'].endswith('更新成功'), 'note persists after container recreation') for asset in state['assets']: content, headers = request('/api/v1/assets/' + asset['id'] + '/content?download=true') check(hashlib.sha256(content).hexdigest() == asset['sha256'], asset['name'] + ' persists byte-for-byte after recreation') check('attachment' in headers['Content-Disposition'], 'download disposition') api('/assets/' + asset['id'], method='DELETE', expected=204) api('/assets/' + asset['id'] + '/content', expected=404) api('/notes/' + state['note'], method='DELETE', expected=204) api('/notes/' + state['note'], expected=404) current = api('/dashboard') check(all(current[k] == state['baseline'][k] for k in ['notes', 'assets', 'storageBytes', 'starred']), 'cleanup restores dashboard baseline') state_path.unlink() print('VERIFY COMPLETE: persistence and deletion passed.') api('/auth/logout', method='POST', expected=204) api('/auth/me', expected=401) check(True, 'logout invalidates session') if args.phase == 'create': api('/assets/' + state['assets'][0]['id'] + '/content', expected=401) check(True, 'uploaded file remains private after logout') print(f'{len(checks)} checks passed.')