Files
Investidor-V2/tools/portal-stability-final-consumers.py
nala 287e991486
tests / ci (push) Waiting to run
oportunidades 7
2026-10-13 11:40:29 +02:00

30 lines
8.0 KiB
Python

from pathlib import Path
ROOT=Path(__file__).resolve().parent.parent
prefix=(ROOT/'tools/portal-stability-consumers-chromium.cjs').read_text(encoding='utf-8').split('try{\nif(remaining)')[0]
prefix=prefix.replace('portal-stability-consumers-chromium.json','portal-stability-final-consumers.json')
body=r'''try{
const simOnly=process.argv.includes('--sim-only');
if(simOnly){const prior=JSON.parse(fs.readFileSync(receipt));assert.equal(prior.checks.length,13);Object.assign(proof,prior);delete proof.failure;delete proof.result;}
if(!simOnly){
async function newDesk(title){await open('/balcao-virtual/painel');await page.getByText('Preparar acompanhamento de um projecto',{exact:true}).click();await page.getByLabel('Título do projecto',{exact:true}).fill(title);await page.getByLabel('Autorizo reutilizar os dados seleccionados').check();await page.getByRole('button',{name:'Preparar dossier',exact:true}).click();await page.waitForURL(/\/balcao-virtual\/dossiers\/[a-f0-9-]+$/);return new URL(page.url()).pathname;}
await actor('promoter');const direct=await newDesk('Synthetic stability independent desk creation');proof.direct_case=direct;proof.checks.push({component:'desk-panel',criterion:'direct dossier creation persisted with compatible UUID',route:direct,passed:true});save();
await page.getByRole('button',{name:'Preparar rascunho de pedido',exact:true}).click();await page.waitForURL(/\/balcao-virtual\/pedidos\/[a-f0-9-]+$/);proof.direct_request=new URL(page.url()).pathname;await recover(proof.direct_request,'direct request created from case recovered');proof.checks.push({component:'desk-case',passed:true});save();
await open('/parcerias/salas/1');for(let n=1;n<=2;n++){const text='After stabilization: consecutive room message '+n;await page.getByLabel('Mensagem privada',{exact:true}).fill(text);const response=page.waitForResponse(r=>r.request().method()==='POST'&&new URL(r.url()).pathname==='/parcerias/salas/1/mensagens');await page.getByRole('button',{name:'Enviar mensagem',exact:true}).click();const r=await response;const sent=r.request().postDataJSON();assert.equal(sent.body,text);assert(r.status()<400);await page.getByText(text,{exact:true}).waitFor();}
await recover('/parcerias/salas/1','consecutive partnership messages preserved after processing lock correction');proof.checks.push({component:'partnership-room',two_messages_visible:true,passed:true});save();
await actor('outsider');for(const route of [direct,proof.direct_request,'/investimentos/d8ac9133-65b6-4ed4-964e-e230bc656a02','/management/territory-geometry-import','/management/profile-install']){const r=await open(route);assert([403,404].includes(r.status()));proof.checks.push({criterion:'unauthorized private/privileged consumer denied',role,route,status:r.status(),passed:true});save();}
await actor('public');const publicCase=await newDesk('Synthetic stability profile evidence');proof.profile_case=publicCase;const original=Buffer.from('Synthetic QA technical fixture. This is not an identity document or an external attestation.\n');
await page.getByLabel('Ficheiro privado',{exact:true}).setInputFiles({name:'synthetic-stability-profile-evidence.txt',mimeType:'text/plain',buffer:original});await page.getByLabel('Proveniência e referência',{exact:true}).fill('Synthetic QA fixture generated for technical permissions and real antimalware test');await page.getByLabel('Autorizo associar este documento ao dossier privado.').check();
const uploaded=page.waitForResponse(r=>r.request().method()==='POST'&&new URL(r.url()).pathname===publicCase+'/documentos');await page.getByRole('button',{name:'Associar documento',exact:true}).click();assert((await uploaded).status()<400);await page.getByText(/synthetic-stability-profile-evidence.txt/).waitFor();
const cp=require('node:child_process');cp.execFileSync('C:/laragon/bin/php/php-8.5.11-Win32-vs17-x64/php.exe',[path.join(ROOT,'tools/portal-stability-queue.php')],{cwd:ROOT,timeout:90000,stdio:['ignore','pipe','pipe']});await page.reload({waitUntil:'networkidle'});await page.getByText(/synthetic-stability-profile-evidence.txt.*clean/).waitFor();
const download=page.getByRole('link',{name:/Descarregar com verificação/}).last();const url=await download.getAttribute('href');const bytes=await page.evaluate(async url=>{const r=await fetch(url);return {status:r.status,bytes:[...new Uint8Array(await r.arrayBuffer())]};},url);assert.equal(bytes.status,200);assert(Buffer.from(bytes.bytes).equals(original));proof.checks.push({criterion:'private original uploaded through UI/real ClamD/queue and exact authorized recovery',sha256:crypto.createHash('sha256').update(original).digest('hex'),passed:true});save();
await open('/perfil/promotor');await page.getByLabel('investment_project',{exact:true}).check();await page.getByLabel('Fundamentação',{exact:true}).fill('Synthetic QA profile request: infrastructure demonstration only, no real representation claimed');
const start=proof.operations.length;const invalid=page.waitForResponse(r=>r.request().method()==='POST'&&new URL(r.url()).pathname==='/perfil/promotor');await page.getByRole('button',{name:'Submeter pedido de perfil',exact:true}).click();assert.equal((await invalid).status(),422);await page.getByLabel('synthetic-stability-profile-evidence.txt',{exact:true}).check();
const submitted=page.waitForResponse(r=>r.request().method()==='POST'&&new URL(r.url()).pathname==='/perfil/promotor');await page.getByRole('button',{name:'Submeter pedido de perfil',exact:true}).click();const success=await submitted;assert.equal(success.status(),201);const response=await success.json();proof.profile_request_id=response.id;assert.equal(proof.operations[start].key_sha256,proof.operations[start+1].key_sha256);await page.getByText(response.id+' — pending',{exact:true}).waitFor();await recover('/perfil/promotor','request and pending state recovered; no role activated');proof.checks.push({component:'profile-request',validation_retry_same_key:true,role_activated:false,passed:true});save();
}
if(ctx)await ctx.close();ctx=await browser.newContext({ignoreHTTPSErrors:false});await ctx.addInitScript(()=>Object.defineProperty(Crypto.prototype,'randomUUID',{value:undefined,configurable:true}));page=await ctx.newPage();page.setDefaultTimeout(35000);await open('/simulador-fiscal');
const autosaved=page.waitForResponse(r=>new URL(r.url()).pathname==='/api/v1/simulation-drafts'&&r.request().method()==='POST');await page.getByLabel('Nível de detalhe (obrigatório)',{exact:true}).click();await page.getByRole('option',{name:'Simples',exact:true}).click();await page.getByLabel('O que pretende fazer? (obrigatório)',{exact:true}).click();await page.getByRole('option',{name:'Apenas simular',exact:true}).click();const saved=await autosaved;assert(saved.status()<300);const data=await saved.json();proof.anonymous_draft_id=data.data.id;const key=saved.request().headers()['idempotency-key'];assert.match(key,/^[0-9a-f-]{36}$/);await page.getByText(/Rascunho guardado no servidor/).first().waitFor();await page.reload({waitUntil:'networkidle'});assert.equal(await page.getByLabel('Nível de detalhe (obrigatório)',{exact:true}).inputValue(),'Simples');proof.checks.push({component:'simulation-form',criterion:'anonymous autosave/header UUID/refresh retrieval',key_sha256:crypto.createHash('sha256').update(key).digest('hex'),passed:true});await page.screenshot({path:path.join(DIR,'portal-stability-public-autosave.png')});save();
assert.equal(proof.errors.length,0);proof.result='passed';save();console.log(JSON.stringify({result:proof.result,checks:proof.checks.length,operations:proof.operations.length,active_writes:0}));
}catch(e){proof.result='failed';proof.failure=redact(e);if(page&&!page.isClosed()){proof.last_route=new URL(page.url()).pathname;proof.visible_status=await page.getByRole('status').allTextContents();proof.visible_alerts=await page.getByRole('alert').allTextContents();}save();console.log(JSON.stringify({result:'failed',failure:proof.failure,checks:proof.checks.length,active_writes:0}));process.exitCode=1;}finally{if(ctx)await ctx.close();await browser.close();}})();
'''
(ROOT/'tools/portal-stability-final-consumers.cjs').write_text(prefix+body,encoding='utf-8')