Files
tap/tests/attachments-recovery.browser.py
T

184 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Browser regressions against a disposable local production instance.
Requires Python Playwright and APP_URL, INITIAL_ADMIN_PASSWORD, QA_PASSWORD.
Only accepts the temporary DATA_DIR created by the isolated test runner.
"""
import json
import os
import re
from pathlib import Path
from urllib.parse import urlparse
from playwright.sync_api import sync_playwright, expect
origin = os.environ['APP_URL']
assert urlparse(origin).hostname == '127.0.0.1'
assert Path(os.environ['DATA_DIR']).name.startswith('demand-scope-browser-db-')
output = Path(os.environ.get('ATTACHMENT_QA_OUTPUT', '/private/tmp/attachment-fixes-qa'))
output.mkdir(exist_ok=True)
checks = []
def post(context, path, data):
response = context.request.post(origin + path, data=data, headers={'Origin': origin})
assert response.ok, (response.status, response.text())
return response.json()
def new_form(page, title):
page.get_by_role('button', name=re.compile('登记新需求$')).first.click()
page.get_by_label(re.compile('^需求标题')).fill(title)
page.get_by_role('button', name=re.compile('数据与参考材料')).click()
def close_form(page):
page.get_by_role('button', name='关闭登记窗口', exact=True).click()
page.get_by_role('button', name='放弃修改并关闭', exact=True).click()
expect(page.get_by_role('dialog')).not_to_be_attached()
def upload(context, name):
response = context.request.post(origin + '/api/attachments', headers={'Origin': origin}, multipart={
'file': {'name': name, 'mimeType': 'text/plain', 'buffer': b'attachment test'},
})
assert response.status == 201, response.text()
return response.json()['attachment']
def cleanup(context, files):
for file in files:
response = context.request.delete(origin + '/api/attachments/' + file['id'], headers={'Origin': origin})
assert response.ok, response.text()
with sync_playwright() as p:
browser = p.chromium.launch(headless=True, channel='chrome')
context = browser.new_context(viewport={'width': 1440, 'height': 1000})
post(context, '/api/auth/login', {'username': 'scope_qa', 'password': os.environ['INITIAL_ADMIN_PASSWORD']})
post(context, '/api/auth/password', {'currentPassword': os.environ['INITIAL_ADMIN_PASSWORD'], 'newPassword': os.environ['QA_PASSWORD']})
first = context.new_page()
second = context.new_page()
errors = []
first.on('pageerror', lambda error: errors.append(str(error)))
second.on('pageerror', lambda error: errors.append(str(error)))
for page in [first, second]:
page.goto(origin)
page.wait_for_load_state('networkidle')
new_form(first, '窗口 A:保留正在使用的附件')
first.get_by_label('选择文件附件', exact=True).set_input_files({
'name': 'A-still-editing.txt', 'mimeType': 'text/plain', 'buffer': b'demand A content',
})
expect(first.get_by_role('button', name='上传附件', exact=True)).to_be_enabled()
own_file = context.request.get(origin + '/api/attachments').json()['attachments'][0]
new_form(second, '窗口 B:取消不影响窗口 A')
second.get_by_text('找回未保存的附件(1)', exact=True).click()
second.get_by_role('button', name='选用 A-still-editing.txt', exact=True).click()
deletes = []
second.on('request', lambda request: deletes.append(request.url) if request.method == 'DELETE' else None)
close_form(second)
assert not deletes, deletes
assert context.request.get(origin + '/api/attachments/' + own_file['id']).body() == b'demand A content'
checks.append('cancelling a second window does not delete a recovered attachment')
new_form(second, '窗口 B:移除找回附件仅取消选用')
second.get_by_text('找回未保存的附件(1)', exact=True).click()
second.get_by_role('button', name='选用 A-still-editing.txt', exact=True).click()
second.get_by_role('button', name='移除 A-still-editing.txt', exact=True).click()
close_form(second)
assert not deletes, deletes
first.get_by_role('button', name='保存草稿', exact=True).click()
expect(first.get_by_role('heading', name='窗口 A:保留正在使用的附件', exact=True)).to_be_attached()
record = context.request.get(origin + '/api/demands').json()['demands'][0]
assert record['attachments'][0]['id'] == own_file['id']
checks.append('removing a recovered selection preserves the original and the first window can save')
new_form(second, '本窗口新上传仍可清理')
second.get_by_label('选择文件附件', exact=True).set_input_files({
'name': 'new-in-B.txt', 'mimeType': 'text/plain', 'buffer': b'new upload',
})
expect(second.get_by_role('button', name='上传附件', exact=True)).to_be_enabled()
own_new = context.request.get(origin + '/api/attachments').json()['attachments'][0]
with second.expect_response(lambda response: own_new['id'] in response.url and response.request.method == 'DELETE') as removed:
close_form(second)
assert removed.value.status == 200
assert context.request.get(origin + '/api/attachments/' + own_new['id']).status == 404
checks.append('cancelling still cleans up files newly uploaded by that window')
staged = [upload(context, f'previous-{i}.txt') for i in range(10)]
failure_mode = {'enabled': True}
listing_calls = []
def fail_listing(route):
if route.request.method == 'GET':
listing_calls.append(route.request.url)
if failure_mode['enabled']:
route.fulfill(status=503, content_type='application/json', body='{"error":"模拟暂时无法加载"}')
return
route.continue_()
second.route('**/api/attachments', fail_listing)
new_form(second, '加载失败后保留表单并重试')
expect(second.get_by_text('未保存附件列表加载失败:模拟暂时无法加载', exact=True)).to_be_attached()
expect(second.get_by_role('button', name='重新加载未保存附件', exact=True)).to_be_enabled()
second.set_viewport_size({'width': 390, 'height': 844})
second.get_by_role('button', name='重新加载未保存附件', exact=True).scroll_into_view_if_needed()
assert second.get_by_role('dialog').evaluate('(el)=>el.scrollWidth<=el.clientWidth+1')
second.screenshot(path=str(output / 'recovery-error-mobile.png'), animations='disabled')
failure_mode['enabled'] = False
second.get_by_role('button', name='重新加载未保存附件', exact=True).click()
expect(second.get_by_text('找回未保存的附件(10)', exact=True)).to_be_attached()
expect(second.get_by_role('button', name='重新加载未保存附件', exact=True)).not_to_be_attached()
second.get_by_text('找回未保存的附件(10)', exact=True).click()
second.get_by_role('button', name='选用 previous-0.txt', exact=True).click()
second.get_by_role('button', name='保存草稿', exact=True).click()
expect(second.get_by_role('heading', name='加载失败后保留表单并重试', exact=True)).to_be_attached()
saved = context.request.get(origin + '/api/demands').json()['demands'][0]
assert saved['fields']['title'] == '加载失败后保留表单并重试'
assert saved['attachments'][0]['id'] == staged[0]['id']
checks.append('manual retry loads recovered files and preserves all current form input')
cleanup(context, staged[1:])
second.get_by_role('button', name='关闭需求详情', exact=True).click()
second.set_viewport_size({'width': 1440, 'height': 1000})
new_form(second, '达到暂存上限后自动刷新')
expect(second.get_by_role('button', name='刷新未保存附件', exact=True)).to_be_enabled()
assert second.get_by_text(re.compile('找回未保存的附件')).count() == 0
# Another window uploads after this form loaded its initially empty list.
staged = [upload(context, f'concurrent-{i}.txt') for i in range(10)]
calls_before = len(listing_calls)
second.get_by_label('选择文件附件', exact=True).set_input_files([
{'name': 'quota-1.txt', 'mimeType': 'text/plain', 'buffer': b'one'},
{'name': 'quota-2.txt', 'mimeType': 'text/plain', 'buffer': b'two'},
])
expect(second.get_by_role('button', name='上传附件', exact=True)).to_be_enabled()
expect(second.get_by_text(re.compile('未保存附件已达 10 个'))).to_be_attached()
expect(second.get_by_role('button', name='选用 concurrent-0.txt', exact=True)).to_be_visible()
assert len(listing_calls) == calls_before + 1
expect(second.get_by_text('本批剩余文件尚未上传,请先选用或清理未保存附件,再重新选择文件。', exact=True)).to_be_attached()
second.get_by_text('找回未保存的附件(10)', exact=True).scroll_into_view_if_needed()
second.locator('.toast').wait_for(state='hidden')
second.screenshot(path=str(output / 'quota-recovery-desktop.png'), animations='disabled')
checks.append('staging quota rejection refreshes and opens recovery without retrying the full batch')
close_form(second)
cleanup(context, staged)
failure_mode['enabled'] = True
new_form(second, '自动刷新失败仍可手动重试')
expect(second.get_by_role('button', name='重新加载未保存附件', exact=True)).to_be_enabled()
staged = [upload(context, f'retry-{i}.txt') for i in range(10)]
calls_before = len(listing_calls)
second.get_by_label('选择文件附件', exact=True).set_input_files({'name': 'quota-again.txt', 'mimeType': 'text/plain', 'buffer': b'file'})
expect(second.get_by_role('button', name='上传附件', exact=True)).to_be_enabled()
expect(second.get_by_role('button', name='重新加载未保存附件', exact=True)).to_be_enabled()
assert len(listing_calls) == calls_before + 1
failure_mode['enabled'] = False
second.get_by_role('button', name='重新加载未保存附件', exact=True).click()
expect(second.get_by_role('button', name='选用 retry-0.txt', exact=True)).to_be_visible()
close_form(second)
cleanup(context, staged)
checks.append('a failed automatic recovery refresh remains manually retryable')
assert not errors, errors
print(json.dumps({'result': 'passed', 'checks': checks, 'screenshots': str(output)}, ensure_ascii=False), flush=True)
browser.close()