nomadro/scripts/check-social-ui.py
Eric 92bbee3c6c Ship native social weapp: immersive hall chat, SRS live, join pay.
Wire Taro social pages to social_svc (Centrifugo + live RTMP), drop multi-channel chat chrome, and add weapp WXSS sanitize/deploy helpers.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-02 12:33:35 +08:00

337 lines
19 KiB
Python

"""Social UI regression checks.
Requires a running local portal/API and Python Playwright with Chromium:
python -m pip install playwright
python -m playwright install chromium
python scripts/check-social-ui.py
POST/PUT requests in interaction tests are mocked; no real content or payments.
Screenshots and JSON reports are written to a temporary directory.
"""
import argparse
import asyncio
import json
import os
import tempfile
from pathlib import Path
from playwright.async_api import async_playwright, expect
ROUTES = ['', '/people', '/people/m01', '/date', '/chat', '/chat/general', '/meetup', '/meetup/wk-nomad-office', '/coffeechat', '/roster', '/team', '/gigs', '/ebook', '/videos', '/join', '/vip', '/feedback']
async def check_routes():
async with async_playwright() as p:
browser = await p.chromium.launch()
page = await browser.new_page(reduced_motion='reduce')
errors = []
page.on('pageerror', lambda error: errors.append(str(error)))
rows = []
for width in [390, 768, 1440, 320]:
await page.set_viewport_size({'width': width, 'height': 900})
for route in ROUTES:
errors.clear()
response = await page.goto(f'{BASE_URL}/social' + route)
await page.wait_for_timeout(500)
info = await page.evaluate('''() => ({
overflow: document.documentElement.scrollWidth - innerWidth,
title: document.querySelector('h1')?.textContent,
hidden: [...document.querySelectorAll('.reveal:not(.visible)')].length,
offenders: [...document.querySelectorAll('.social-experience *')].filter(e => {
const r=e.getBoundingClientRect(), s=getComputedStyle(e);
return r.width>0 && r.right>innerWidth+2 && s.position!=='fixed' && s.visibility!=='hidden' && !e.closest('canvas,svg,.connection-orbit-scene,.social-quick-rail,.social-filters,.social-emoji-field');
}).slice(0,8).map(e=>e.className)
})''')
rows.append({'route': route or '/', 'width': width, 'status': response.status, **info, 'errors': errors[:]})
if width in [390,1440] and route in ['', '/people', '/team', '/coffeechat', '/roster', '/ebook', '/chat']:
await page.screenshot(path=f'.tmp_social_{width}_{route.strip("/") or "home"}.png', full_page=True)
Path('.tmp_social_audit.json').write_text(json.dumps(rows, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps({"routes": len(ROUTES), "viewports": 4, "checks": len(rows)}))
await browser.close()
assert all(r['status']==200 and r['overflow']<=1 and not r['errors'] and not r['hidden'] for r in rows), 'Route layout audit failed; see JSON report'
async def check_interactions():
results = []
async with async_playwright() as p:
browser = await p.chromium.launch()
context = await browser.new_context(viewport={'width':390,'height':844}, reduced_motion='reduce')
state = {'fail': False, 'posts': []}
async def api(route):
req = route.request
if req.method in ['POST','PUT']:
state['posts'].append({'path':req.url, 'body':req.post_data_json})
if state['fail']:
await route.abort()
else:
await route.fulfill(json={'id':'smoke-1', 'ok':True, 'channelId':'general', 'author':'Smoke', 'text':req.post_data_json.get('text',''), 'at':'2026-11-01T00:00:00Z'})
elif '/realtime/' in req.url:
await route.fulfill(json={'enabled':False})
elif '/roster/me' in req.url:
await route.fulfill(json={'item':None})
else:
await route.fulfill(json={'items':[]})
await context.route('**/api/social/v1/**', api)
await context.route('**/mirotalk.nomadro.cn/**', lambda route: route.fulfill(body='<html><body>Mock video room</body></html>',content_type='text/html'))
page = await context.new_page()
errors = []
page.on('pageerror', lambda e: errors.append(str(e)))
async def check(name, fn):
try:
await fn()
results.append({'name':name,'ok':True})
except Exception as e:
results.append({'name':name,'ok':False,'error':str(e)[:1000]})
Path(f'.tmp_social_failure_{len(results)}.txt').write_text(await page.locator('body').inner_text(),encoding='utf-8')
await page.screenshot(path=f'.tmp_social_failure_{len(results)}.png',full_page=True)
async def go(path):
await page.goto(f'{BASE_URL}/social'+path)
await page.wait_for_timeout(250)
async def follow():
await go('/people/m01')
await page.get_by_role('button', name='关注一下',exact=True).click()
await page.get_by_role('link', name='回去看看大家',exact=True).click()
await page.get_by_role('button',name='我关注的',exact=True).click()
await expect(page.locator('.social-discovery-grid > a')).to_have_count(1)
await expect(page.locator('.social-discovery-grid')).to_contain_text('林悦')
await check('profile follow appears in discovery filter',follow)
async def filters():
await page.get_by_role('button',name='重置筛选',exact=True).click()
await page.get_by_role('searchbox').fill('不会匹配的内容')
await expect(page.locator('.social-empty')).to_be_visible()
await page.get_by_role('button',name='重新看看',exact=True).click()
await expect(page.locator('.social-discovery-grid > a')).to_have_count(12)
assert await page.locator('.social-discovery-grid .reveal:not(.visible)').count()==0
await page.get_by_role('searchbox').fill('清迈')
await page.get_by_role('button',name='清空搜索').click()
await expect(page.get_by_role('searchbox')).to_be_focused()
await check('search empty reset and clear focus',filters)
async def menu():
await page.set_viewport_size({'width':320,'height':640})
await page.get_by_role('button',name='菜单',exact=True).click()
await expect(page.locator('.nav-links')).to_have_class('nav-links open')
await page.get_by_role('button',name='一起做事',exact=False).click()
await page.locator('.nav-group-panel').get_by_role('link',name='说说想法',exact=True).click()
await expect(page).to_have_url(f'{BASE_URL}/social/feedback')
assert await page.evaluate('document.body.style.overflow') != 'hidden'
await page.get_by_role('button',name='菜单',exact=True).click()
await page.keyboard.press('Escape')
await expect(page.get_by_role('button',name='菜单',exact=True)).to_be_focused()
await page.get_by_role('button',name='菜单',exact=True).click()
await page.set_viewport_size({'width':1440,'height':900})
await expect(page.get_by_role('button',name='菜单',exact=True)).not_to_be_visible()
assert await page.evaluate('document.body.style.overflow') != 'hidden'
await page.set_viewport_size({'width':390,'height':844})
await check('320px menu navigation escape resize unlock',menu)
async def contribution():
await go('/ebook')
await page.get_by_role('button',name='我想投稿',exact=True).click()
dialog=page.get_by_role('dialog',name='共创意向',exact=True)
await expect(dialog).to_be_visible()
r=await dialog.bounding_box()
assert abs(r['y']+r['height']-844)<3, r
await dialog.get_by_label('怎么称呼你').fill('Smoke test')
await dialog.get_by_label('联系方式').fill('test@example.invalid')
await dialog.get_by_label('主题 / 暂定标题').fill('响应式测试')
state['fail']=True
await dialog.get_by_role('button',name='提交意向',exact=True).click()
await expect(dialog.get_by_role('status')).to_contain_text('暂时未发送')
await dialog.get_by_role('button',name='关闭',exact=True).click()
await page.get_by_role('button',name='我想投稿',exact=True).click()
await expect(dialog.get_by_label('主题 / 暂定标题')).to_have_value('响应式测试')
state['fail']=False
await dialog.get_by_role('button',name='提交意向',exact=True).click()
await expect(dialog).to_contain_text('共创意向已提交')
assert '响应式测试' in state['posts'][-1]['body']['text']
await page.keyboard.press('Escape')
await expect(dialog).not_to_be_visible()
await expect(page.get_by_role('button',name='我想投稿',exact=True)).to_be_focused()
await check('submission uses API preserves offline draft retries and sheet focus',contribution)
async def deep_link():
await page.locator('.social-library-art').first.click()
await expect(page.get_by_role('dialog')).to_be_visible()
url=page.url
assert '#' in url
await page.reload()
await expect(page.get_by_role('dialog')).to_be_visible()
await page.keyboard.press('Escape')
assert '#' not in page.url
await check('shared resource URL restores and closes detail',deep_link)
async def roles():
await go('/team')
await page.get_by_role('button',name='我想参与',exact=False).first.click()
dialog=page.get_by_role('dialog',name='表达兴趣')
await dialog.get_by_label('怎么称呼你').fill('Smoke test')
await dialog.get_by_label('联系方式',exact=True).fill('test@example.invalid')
await dialog.get_by_role('button',name='发送参与申请',exact=True).click()
await expect(dialog).to_contain_text('已表达兴趣')
await page.keyboard.press('Escape')
await check('team application submits and confirms',roles)
async def review_draft():
await go('/coffeechat')
detail=page.locator('.social-cafe-detail')
await detail.get_by_label('体验',exact=True).fill('Draft survives cafe switching')
await page.reload()
await expect(detail.get_by_label('体验',exact=True)).to_have_value('Draft survives cafe switching',timeout=15000)
await check('cafe review draft survives reload',review_draft)
async def profile():
await go('/roster')
await page.get_by_label('怎么称呼你',exact=True).fill('UI smoke profile')
await page.get_by_label('自我介绍',exact=False).fill('Testing local preview')
await page.get_by_role('checkbox').check()
await page.get_by_role('button',name='保存介绍',exact=True).click()
await expect(page.get_by_role('status').filter(has_text='介绍已保存')).to_have_count(1)
await go('/people')
await expect(page.locator('.social-discovery-grid')).to_contain_text('UI smoke profile')
await page.reload()
await expect(page.locator('.social-discovery-grid > a')).to_have_count(13)
await go('/date')
assert await page.locator('.social-date-card.is-top').inner_text() != 'UI smoke profile'
await check('edited profile survives discovery reload without render loop',profile)
async def feedback():
await go('/feedback')
await page.get_by_label('内容',exact=False).fill('Feedback smoke test')
state['fail']=True
await page.get_by_role('button',name='提交',exact=True).click()
await expect(page.get_by_role('status')).to_contain_text('先留在你这边')
state['fail']=False
await page.get_by_role('button',name='重试',exact=True).click()
await expect(page.get_by_role('status')).to_contain_text('已提交')
await page.get_by_role('button',name='再提一条',exact=True).click()
await expect(page.get_by_label('内容',exact=False)).to_have_value('')
await check('feedback offline retry and reset',feedback)
async def chat():
await go('/chat')
composer=page.get_by_role('textbox',name='消息内容',exact=True)
await page.get_by_role('textbox',name='聊天昵称',exact=True).fill('Smoke')
await composer.fill('offline smoke message')
state['fail']=True
await page.get_by_role('button',name='发送',exact=True).click()
await expect(page.locator('.social-message-tools').get_by_role('button',name='重试',exact=True)).to_be_visible()
await expect(composer).to_have_value('')
state['fail']=False
await page.locator('.social-message-tools').get_by_role('button',name='重试',exact=True).click()
await expect(page.locator('.social-message-tools').get_by_role('button',name='重试',exact=True)).to_have_count(0)
await expect(page.locator('.social-message.mine')).to_contain_text('offline smoke message')
await check('chat nickname offline outbox retries without duplicates',chat)
async def date():
await go('/date')
await page.get_by_role('button',name='想认识',exact=True).click()
dialog=page.get_by_role('dialog')
await expect(dialog).to_be_visible()
before=await page.evaluate("localStorage.getItem('nomadro-social:social-date-swipes')")
await page.keyboard.press('ArrowRight')
await page.wait_for_timeout(350)
after=await page.evaluate("localStorage.getItem('nomadro-social:social-date-swipes')")
assert before==after
await page.keyboard.press('Escape')
await page.get_by_role('button',name='撤销上一次',exact=True).click()
# m01 was already followed before the swipe: undo must preserve that follow.
assert await page.evaluate("JSON.parse(localStorage.getItem('nomadro-social:social-roster-likes')).m01")
await check('swipe modal blocks background shortcuts and undo preserves follow',date)
async def video():
await go('/meetup/wk-nomad-office')
await expect(page.locator('iframe.social-live-iframe')).to_have_count(0)
await page.get_by_role('button',name='进入聊聊',exact=True).click()
frame=page.locator('iframe.social-live-iframe')
await expect(frame).to_have_count(1)
src=await frame.get_attribute('src')
assert 'audio=0' in src and 'video=0' in src
await page.get_by_role('button',name='离开视频',exact=True).click()
await expect(frame).to_have_count(0)
await go('/meetup/not-a-real-room')
await expect(page.locator('.social-empty')).to_contain_text('没有找到这个场次')
await check('video explicit entry muted camera off leave and invalid room',video)
async def theme():
await go('/people')
await page.get_by_role('button',name='切换日间模式',exact=True).click()
await expect(page.locator('html')).to_have_attribute('data-theme','light')
await page.reload()
await expect(page.locator('html')).to_have_attribute('data-theme','light')
await page.screenshot(path='.tmp_social_light_people.png',full_page=True)
await go('/team')
await page.get_by_role('button',name='我想参与',exact=False).first.click()
await page.screenshot(path='.tmp_social_light_dialog.png')
await check('light theme persists and dialog renders',theme)
results.append({'name':'uncaught browser errors','ok':not errors,'errors':errors})
await context.close()
await browser.close()
Path('.tmp_social_interactions.json').write_text(json.dumps(results,ensure_ascii=False,indent=2),encoding='utf-8')
print(json.dumps(results,ensure_ascii=True))
assert all(r['ok'] for r in results), 'Interaction regression failed; see JSON report'
async def check_short_screens():
async with async_playwright() as p:
browser = await p.chromium.launch()
context = await browser.new_context(reduced_motion='reduce')
await context.route('**/mirotalk.nomadro.cn/**', lambda route: route.fulfill(body='<html>Mock room</html>', content_type='text/html'))
page = await context.new_page()
rows = []
for w,h in [(320,568),(844,390),(768,1024)]:
await page.set_viewport_size({'width':w, 'height':h})
for route,selector in [('meetup/wk-nomad-office','.social-live-gate .social-btn'),('date','.social-date-actions .social-date-swipe-like')]:
await page.goto(f'{BASE_URL}/social/'+route)
await page.wait_for_timeout(350)
try:
target=page.locator(selector)
if route=='date': target=page.get_by_role('button',name='想认识',exact=True)
await target.click(timeout=6000)
if route.startswith('meetup'): await expect(page.locator('iframe.social-live-iframe')).to_have_count(1)
else: await expect(page.get_by_role('dialog')).to_be_visible()
rows.append({'size':[w,h],'route':route,'ok':True})
except Exception as e:
rows.append({'size':[w,h],'route':route,'ok':False,'error':str(e)[:1700]})
await page.set_viewport_size({'width':390,'height':844})
await page.goto(f'{BASE_URL}/social/roster')
checkbox = page.locator('.social-publish-toggle input')
dimensions = await checkbox.evaluate('e=>({w:e.getBoundingClientRect().width,h:e.getBoundingClientRect().height,display:getComputedStyle(e.parentElement).display})')
assert dimensions == {'w':20,'h':20,'display':'flex'}, dimensions
await page.goto(f'{BASE_URL}/social/chat')
textarea = page.locator('.social-chat-composer textarea')
dimensions = await textarea.evaluate('e=>({w:e.getBoundingClientRect().width,font:getComputedStyle(e).fontSize})')
assert dimensions['w'] >= 360 and dimensions['font'] == '16px', dimensions
Path('.tmp_social_short.json').write_text(json.dumps(rows, indent=2),encoding='utf-8')
print(json.dumps(rows))
await browser.close()
assert all(r['ok'] for r in rows), 'Short screen interaction failed'
async def run():
suites = {"routes": check_routes, "interactions": check_interactions, "short": check_short_screens}
for name, suite in suites.items():
if ARGS.suite in ("all", name):
print(f"Running {name}", flush=True)
await suite()
print(f"Passed. Reports: {OUTPUT}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--suite", choices=["all", "routes", "interactions", "short"], default="all")
parser.add_argument("--base-url", default="http://localhost:3000")
ARGS = parser.parse_args()
BASE_URL = ARGS.base_url.rstrip("/")
OUTPUT = Path(tempfile.mkdtemp(prefix="nomadro-social-ui-"))
print(f"Reports: {OUTPUT}", flush=True)
os.chdir(OUTPUT)
asyncio.run(run())