Spaces:
Running
Running
File size: 5,148 Bytes
3939ca3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | import json,re
from playwright.sync_api import sync_playwright
from pathlib import Path
folder=Path(__file__).parent
def bundled_html():
html=(folder/'index.html').read_text()
css=(folder/'style.css').read_text()
scripts=[]
for nm in ('core.js','worldbank.js','demo-data.js','app.js'):
body=(folder/nm).read_text()
body=re.sub(r'^import [^\n]+\n','',body,flags=re.MULTILINE)
body=re.sub(r'\bexport (?!\{)', '',body)
scripts.append(body)
html=html.replace('<link rel="stylesheet" href="style.css"/>','<style>'+css+'</style>')
html=html.replace('<script type="module" src="app.js"></script>','<script>'+'\n'.join(scripts)+'</script>')
return html
html=bundled_html()
checks=[];errors=[]
def ok(name,condition=True):
if not condition:raise AssertionError(name)
checks.append('PASS: '+name)
with sync_playwright() as p:
browser=p.chromium.launch(headless=True,executable_path='/usr/bin/chromium',args=['--no-sandbox','--disable-dev-shm-usage'])
context=browser.new_context(accept_downloads=True,viewport={'width':1440,'height':1100},device_scale_factor=1)
page=context.new_page();page.on('pageerror',lambda e:errors.append(str(e)))
page.set_content(html,wait_until='load');page.wait_for_timeout(700)
ok('Demo badge initially visible',page.locator('#mode-pill').inner_text()=='SYNTHETIC DEMO')
ok('Synthetic data populated',int(page.locator('#metric-obs').inner_text().replace(',',''))>0)
ok('Overview shows country ranking',page.locator('#rank-bars .rank-row').count()==6)
page.screenshot(path=str(folder/'Education_Data_Lab_DESKTOP_PREVIEW.png'),full_page=True)
for tab,selector in [('trends','#line-chart svg'),('gaps','#gap-result'),('relations','#scatter-chart svg'),('quality','#coverage-matrix table'),('brief','#brief-text h3')]:
page.locator(f'button[data-view="{tab}"]').click()
ok('Tab '+tab+' updates content',page.locator(selector).count()>0)
page.locator('button[data-view="trends"]').click();ok('Line series has paths',page.locator('#line-chart svg line').count()>5)
page.locator('button[data-view="gaps"]').click();page.locator('#gap-year').fill('2020');page.locator('#gap-year').dispatch_event('change');ok('Exact-year gap computed',page.locator('#gap-result .numberline').count()==1)
page.locator('button[data-view="brief"]').click()
with page.expect_download() as d:page.locator('#export-md').click()
ok('Markdown report exported',d.value.suggested_filename.endswith('.md'))
with page.expect_download() as d:page.locator('#export-json').click()
path=d.value.path();data=json.loads(Path(path).read_text())
ok('Reproducible JSON includes rows',len(data['rows'])>0 and data['format']=='edlab-session-v1')
with page.expect_download() as d:page.locator('#download-csv').click()
ok('CSV dataset exported',d.value.suggested_filename.endswith('.csv'))
# import prior session
page.locator('#import-file').set_input_files({'name':'session.json','mimeType':'application/json','buffer':json.dumps(data).encode()})
ok('Session import acknowledged',page.locator('#mode-pill').inner_text()=='IMPORTED DATA')
# live mocked data via route; test code's API parsing and mode, not actual live endpoint
from urllib.parse import urlparse
def route_handler(route):
rows=[]
for country in ['ARG','BOL','BRA','CHL','COL','PRY']:
for ind in ['SE.PRM.CMPT.ZS','SE.SEC.ENRR','SE.TER.ENRR','SE.XPD.TOTL.GD.ZS','SE.ADT.LITR.ZS','IT.NET.USER.ZS','NY.GDP.PCAP.CD','SP.POP.TOTL']:
for year in range(2010,2026):
rows.append({'countryiso3code':country,'date':str(year),'indicator':{'id':ind},'value':float(60+(year-2010)+(len(country)+len(ind))%10),'footnote':[]})
route.fulfill(status=200,content_type='application/json',body=json.dumps([{'pages':1,'per_page':20000,'total':len(rows)},rows]))
page.route('https://api.worldbank.org/**',route_handler)
page.locator('#load-live').click();page.wait_for_timeout(300)
ok('Mock World Bank response processed',page.locator('#mode-pill').inner_text()=='WORLD BANK LIVE')
ok('Official mode displays source attribution', 'World Bank' in page.locator('#status-title').inner_text())
# Error route should preserve most recent data
page.unroute('https://api.worldbank.org/**')
page.route('https://api.worldbank.org/**',lambda route:route.fulfill(status=500,body='error'))
page.locator('#load-live').click();page.wait_for_timeout(300)
ok('Fetch error visible and prior data retained', 'could not be loaded' in page.locator('#alert').inner_text() and page.locator('#mode-pill').inner_text()=='WORLD BANK LIVE')
mobile=browser.new_context(viewport={'width':390,'height':844},device_scale_factor=1,accept_downloads=True,is_mobile=True,has_touch=True)
pg=mobile.new_page();pg.on('pageerror',lambda e:errors.append(str(e)));pg.set_content(html,wait_until='load');pg.wait_for_timeout(400)
pg.screenshot(path=str(folder/'Education_Data_Lab_MOBILE_PREVIEW.png'),full_page=True)
ok('Mobile responsive without horizontal overflow',pg.evaluate('document.documentElement.scrollWidth <= innerWidth + 2'))
ok('No JavaScript page errors',len(errors)==0)
browser.close()
print('\n'.join(checks));print(f'RESULT: {len(checks)} browser checks passed; JS errors: {errors}')
|