| 1 | import { createRequire } from 'node:module' |
| 2 | import assert from 'node:assert/strict' |
| 3 | import { pathToFileURL } from 'node:url' |
| 4 | const require = createRequire(import.meta.url) |
| 5 | const playwright = process.env.ESTILO_PLAYWRIGHT |
| 6 | ? await import(pathToFileURL(process.env.ESTILO_PLAYWRIGHT + '/index.mjs')) |
| 7 | : require('playwright') |
| 8 | const origin = process.argv[2] |
| 9 | const gis = `window.google={accounts:{oauth2:{ |
| 10 | initTokenClient(c){return {requestAccessToken(){window.requestCount=(window.requestCount||0)+1; |
| 11 | if(new URL(location).searchParams.has('popup')){c.error_callback({type:'popup_failed_to_open'});return} |
| 12 | if(new URL(location).searchParams.has('popup-closed')){c.error_callback({type:'popup_closed'});return} |
| 13 | setTimeout(()=>c.callback(new URL(location).searchParams.has('denied')?{error:'access_denied'}:{access_token:'test-google-bearer',scope:'https://www.googleapis.com/auth/drive.file'}),new URL(location).searchParams.has('slow-auth')?150:10)} }}, |
| 14 | hasGrantedAllScopes(r,s){return r.scope===s} |
| 15 | }}};` |
| 16 | const gapi = `window.gapi={load(name,config){ |
| 17 | window.google.picker={Action:{CANCEL:'cancel',PICKED:'picked'},DocsView:class{setMimeTypes(s){return this}}, |
| 18 | PickerBuilder:class{setDeveloperKey(){return this}setAppId(){return this}setOAuthToken(){return this}setOrigin(){return this}addView(){return this}setCallback(fn){this.callback=fn;return this} |
| 19 | build(){const cb=this.callback;let node;return{setVisible(){node=document.createElement('div');node.id='mock-picker'; |
| 20 | const pick=document.createElement('button');pick.textContent='Pick example';pick.onclick=()=>{const result={action:'picked',docs:[{id:'file_1',name:'Example',mimeType:new URL(location).searchParams.has('shortcut')?'application/vnd.google-apps.shortcut':'application/vnd.google-apps.document'}]};cb(result);if(new URL(location).searchParams.has('duplicate'))cb(result)};node.append(pick); |
| 21 | const cancel=document.createElement('button');cancel.textContent='Cancel picker';cancel.onclick=()=>cb({action:'cancel'});node.append(cancel);document.body.append(node)},dispose(){node?.remove()}}}}}; config.callback()}};` |
| 22 | |
| 23 | for (const engine of (process.env.ESTILO_BROWSERS || 'chromium,webkit').split(',')) { |
| 24 | const browser = await playwright[engine].launch() |
| 25 | try { |
| 26 | const context = await browser.newContext({viewport:{width:320,height:700}}) |
| 27 | const page = await context.newPage() |
| 28 | const violations = [] |
| 29 | const errors = [] |
| 30 | page.on('pageerror',e=>errors.push(e.message)) |
| 31 | await page.addInitScript(()=>document.addEventListener('securitypolicyviolation',e=>console.log('CSP-VIOLATION:'+e.violatedDirective))) |
| 32 | page.on('console',m=>{if(m.text().startsWith('CSP-VIOLATION:'))violations.push(m.text())}) |
| 33 | await context.route('https://accounts.google.com/gsi/client',route=>route.fulfill({contentType:'text/javascript',body:gis})) |
| 34 | await context.route('https://apis.google.com/js/api.js',route=>route.fulfill({contentType:'text/javascript',body:gapi})) |
| 35 | let exportMode = 'ok', calls=0 |
| 36 | await context.route('https://www.googleapis.com/drive/v3/files/**',async route=>{ |
| 37 | calls++ |
| 38 | assert.equal(route.request().headers().authorization,'Bearer test-google-bearer') |
| 39 | assert(!route.request().url().includes('test-google-bearer')) |
| 40 | if(exportMode==='slow')await new Promise(r=>setTimeout(r,250)) |
| 41 | await route.fulfill({status:exportMode==='error'?403:200,headers:{'Access-Control-Allow-Origin':'*'}, |
| 42 | body:exportMode==='error'?'refused':'fixture-export-bytes'}) |
| 43 | }) |
| 44 | const choose=page.locator('[data-google-choose]'), status=page.locator('[data-google-status]') |
| 45 | const start=async query=>{const response=await page.goto(origin+query);assert(!response.headers()['cross-origin-opener-policy']);await choose.waitFor({state:'visible'});await page.waitForFunction(()=>!document.querySelector('[data-google-choose]').disabled)} |
| 46 | const select=async()=>{await choose.click();await page.getByText('Pick example',{exact:true}).click()} |
| 47 | await start('/'); await choose.focus(); await page.keyboard.press('Enter'); await page.getByText('Cancel picker',{exact:true}).click() |
| 48 | assert.match(await status.textContent(),/cancelled/) |
| 49 | assert.equal(await choose.isEnabled(),true) |
| 50 | assert.equal(calls,0) |
| 51 | await select(); await page.waitForURL(origin+'/upload'); assert.equal(await page.textContent('body'),'Imported') |
| 52 | assert.equal(calls,1) |
| 53 | await start('/?popup=1');await choose.click();assert.match(await status.textContent(),/popup/);assert(await choose.isEnabled()) |
| 54 | await start('/?popup-closed=1');await choose.click();assert.match(await status.textContent(),/cancelled/);assert(await choose.isEnabled()) |
| 55 | await page.locator('#file').setInputFiles({name:'previous.docx',mimeType:'application/octet-stream',buffer:Buffer.from('previous export')}) |
| 56 | await page.evaluate(()=>dispatchEvent(new PageTransitionEvent('pageshow',{persisted:true}))) |
| 57 | assert.equal(await page.locator('#file').evaluate(input=>input.files.length),0) |
| 58 | await start('/?denied=1');await choose.click();await page.waitForFunction(()=>document.querySelector('[data-google-status]').textContent.includes('did not allow'));assert(await choose.isEnabled()) |
| 59 | await start('/?shortcut=1');await select();await page.waitForFunction(()=>document.querySelector('[data-google-status]').textContent.includes('could not be exported'));assert.equal(calls,1) |
| 60 | exportMode='error';await start('/');await select();await page.waitForFunction(()=>document.querySelector('[data-google-status]').textContent.includes('did not allow'));assert(await choose.isEnabled()) |
| 61 | exportMode='ok';await select();await page.waitForURL(origin+'/upload');assert.equal(calls,3) |
| 62 | await start('/?slow-auth=1');await choose.click();await page.locator('[data-google-cancel]').click();await page.waitForTimeout(200) |
| 63 | assert.equal(await page.locator('#mock-picker').count(),0);assert.equal(calls,3);assert.match(await status.textContent(),/cancelled/) |
| 64 | await start('/?duplicate=1');await select();await page.waitForURL(origin+'/upload');assert.equal(calls,4) |
| 65 | exportMode='slow';await start('/');await select();await page.locator('[data-google-cancel]').click();await page.waitForTimeout(350) |
| 66 | assert.equal(page.url(),origin+'/');assert.match(await status.textContent(),/cancelled/);assert(await choose.isEnabled()) |
| 67 | exportMode='ok' |
| 68 | await start('/');const box=await choose.boundingBox();assert(box.width>=24&&box.height>=24) |
| 69 | assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)) |
| 70 | assert.deepEqual(await page.evaluate(()=>({local:Object.keys(localStorage),session:Object.keys(sessionStorage)})),{local:[],session:[]}) |
| 71 | await page.goto(origin+'/?disabled=1');assert.equal(await page.locator('[estilo-google-import]').count(),0) |
| 72 | assert.deepEqual(violations,[]);assert.deepEqual(errors,[]) |
| 73 | const noJS=await browser.newContext({javaScriptEnabled:false});const plain=await noJS.newPage();await plain.goto(origin) |
| 74 | assert.equal(await plain.locator('[data-google-choose]').isVisible(),false) |
| 75 | assert.equal(await plain.locator('#file').isVisible(),true) |
| 76 | assert.match(await plain.locator('noscript').textContent(),/JavaScript/) |
| 77 | console.log(engine+': chooser, cancel, popup, denied scope, shortcut, export, retry, multipart, CSP, reflow and scriptless checks passed') |
| 78 | await noJS.close();await context.close() |
| 79 | } finally { await browser.close() } |
| 80 | } |
| 81 | |