105 lines
11 KiB
Python
105 lines
11 KiB
Python
from pathlib import Path
|
|
import json,urllib.request,urllib.error,urllib.parse,http.cookiejar,hmac,hashlib,base64,struct,time,uuid,subprocess,re,html
|
|
o=Path(__file__).resolve().parent;p=Path('C:/Users/macbook/.config/investmoz/editorial-QA-20261018');f=json.loads((p/'fixture-private.json').read_text('utf8'))
|
|
assert f['url']=='http://127.0.0.1:18548' and f['database']=='editorial_20261018_test'
|
|
checks=[];events=[]
|
|
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
def redirect_request(self,*a,**k):return None
|
|
def session():return urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()),NoRedirect())
|
|
def call(s,path,data=None,method=None,expected=200,rawbody=None,contenttype=None):
|
|
headers={'Accept':'application/json'};body=None
|
|
if data is not None:body=json.dumps(data).encode();headers['Content-Type']='application/json'
|
|
if rawbody is not None:body=rawbody;headers['Content-Type']=contenttype
|
|
# CSRF is obtained from the application's normal cookie, not bypassed.
|
|
for handler in s.handlers:
|
|
if isinstance(handler,urllib.request.HTTPCookieProcessor):
|
|
headers['X-XSRF-TOKEN']=next((urllib.parse.unquote(c.value) for c in handler.cookiejar if c.name=='XSRF-TOKEN'),'')
|
|
try:r=s.open(urllib.request.Request(f['url']+path,data=body,headers=headers,method=method),timeout=100)
|
|
except urllib.error.HTTPError as e:r=e
|
|
raw=r.read();assert r.headers.get('X-QA-Target')=='editorial_20261018_test:55441'
|
|
events.append({'path':path,'method':method or ('POST' if body is not None else 'GET'),'status':r.status,'response_sha256':hashlib.sha256(raw).hexdigest()})
|
|
if r.status not in (expected if isinstance(expected,tuple) else [expected]):
|
|
(o/'ERRO-HTTP.txt').write_bytes(raw);raise AssertionError(f'{path}: {r.status} expected {expected}')
|
|
try:return json.loads(raw)
|
|
except ValueError:
|
|
script=re.search(rb'<script[^>]*data-page="app"[^>]*>(.*?)</script>',raw,re.S)
|
|
if script:return json.loads(script[1])
|
|
match=re.search(rb'data-page="([^"]+)"',raw)
|
|
return json.loads(html.unescape(match[1].decode())) if match else raw
|
|
def login(role):
|
|
s=session();a=f['actors'][role];call(s,'/login');call(s,'/login',{'email':a['email'],'password':a['password']},expected=(200,204,302,303))
|
|
b=hmac.new(base64.b32decode(a['secret']),struct.pack('>Q',int(time.time()/30)),hashlib.sha1).digest();i=b[-1]&15
|
|
call(s,'/two-factor-challenge',{'code':str((struct.unpack('>I',b[i:i+4])[0]&0x7fffffff)%1000000).zfill(6)},expected=(200,204,302,303));return s
|
|
def ck(name,ok,detail=None):
|
|
assert ok,name;checks.append({'criterio':name,'resultado':'observado','evidencia':detail})
|
|
def props(s,path):return call(s,path)['props']
|
|
def upload(s,name,bytes_,mime='text/plain'):
|
|
boundary='qa-'+uuid.uuid4().hex
|
|
b=(f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="{name}"\r\nContent-Type: {mime}\r\n\r\n').encode()+bytes_+(f'\r\n--{boundary}--\r\n').encode()
|
|
call(s,'/management/portal-services/upload',rawbody=b,contenttype='multipart/form-data; boundary='+boundary,expected=(302,303))
|
|
return next(d for d in props(s,'/management/portal-services')['documents'] if d['file_name']==name)
|
|
def resource(s,doc,title):
|
|
payload={'document_id':doc['id'],'title':title,'description':'Conteúdo sintético para formação em QA.','category':'formacao-qa','topic':'editorial-qa','document_type':'guide','issuer':'Entidade sintética QA','source_url':'https://example.invalid/editorial-qa','language':'pt','territorial_scope':'unknown','source_confirmation':'identified','legal_status':'not_applicable','rights_status':'authorized','data_classification':'public','source_reference':'Conteúdo sintético criado para demonstração editorial; sem efeito jurídico.','independent_review':False,'legislation':False,'essential':False,'associations':[]}
|
|
call(s,'/management/portal-services/resources',payload,expected=(302,303))
|
|
r=next(r for r in props(s,'/management/portal-services')['resources'] if r['document_id']==doc['id'])
|
|
return r,payload
|
|
def current(s,id):return next(r for r in props(s,'/management/portal-services')['resources'] if r['id']==id)
|
|
try:
|
|
a=login('authorized');u=login('unprivileged');v=session()
|
|
call(v,'/management/sectors',expected=401);call(u,'/management/sectors',expected=403)
|
|
ck('Sessão normal com MFA e gestão; anónimo/sem permissão recusados',True)
|
|
doc=upload(a,'formacao-editorial-qa.txt',b'Documento sintetico QA para formacao editorial. Sem dados reais.\n')
|
|
# Run the normal existing worker against this isolated queue only.
|
|
php='C:/Users/macbook/.config/investmoz/php-8.5.11/php.exe';source=p/'source'
|
|
subprocess.run([php,str(source/'artisan'),'queue:work','--stop-when-empty','--tries=1','--max-time=100'],check=True,capture_output=True)
|
|
doc=next(d for d in props(a,'/management/portal-services')['documents'] if d['id']==doc['id'])
|
|
ck('Carregamento e análise real do sintético',doc['malware_scan_status']=='clean',{'id':doc['id'],'scan':doc['malware_scan_status']})
|
|
r,data=resource(a,doc,'Documento sintético editorial QA');id=r['id']
|
|
call(v,'/documentos/'+str(id),expected=404)
|
|
data.update({'title':'Documento sintético editorial QA — editado','metadata_version':r['metadata_version']})
|
|
call(a,'/management/portal-services/resources/'+str(id),data,method='PUT',expected=(302,303))
|
|
call(a,'/management/portal-services/resources/'+str(id),data,method='PUT',expected=409)
|
|
r=current(a,id);ck('Edição e concorrência documental',r['title']==data['title'] and len(r['revisions'])>=2)
|
|
call(a,'/management/portal-services/resources/'+str(id),{'published':True},expected=(302,303))
|
|
shown=props(v,'/documentos/'+str(id));ck('Visitante consulta documento publicado',shown['resource']['title']==data['title'])
|
|
binary=call(v,'/documentos/'+str(id)+'/download');ck('Download original íntegro',hashlib.sha256(binary).hexdigest()==doc['sha256'])
|
|
call(a,'/management/portal-services/resources/'+str(id),{'published':False},expected=(302,303));call(v,'/documentos/'+str(id),expected=404);call(v,'/documentos/'+str(id)+'/download',expected=404)
|
|
ck('Retirada recusa consulta e download; histórico preservado',len(current(a,id)['revisions'])>=4)
|
|
# Legislacao uses a plainly synthetic specimen; official status is not fabricated.
|
|
law=upload(a,'legislacao-sintetica-qa.txt',b'EXEMPLAR SINTETICO QA. Nao e diploma oficial. Apenas formacao.\n')
|
|
subprocess.run([php,str(source/'artisan'),'queue:work','--stop-when-empty','--tries=1','--max-time=100'],check=True,capture_output=True)
|
|
lr,ld=resource(a,law,'Legislação sintética QA — sem validade');lid=lr['id'];ld.update({'document_type':'legislation','legislation':True,'legal_status':'unknown','metadata_version':lr['metadata_version'],'description':'Exemplar sintético QA; não é fonte oficial nem diploma aplicável.'})
|
|
call(a,'/management/portal-services/resources/'+str(lid),ld,method='PUT',expected=(302,303))
|
|
call(a,'/management/portal-services/resources/'+str(lid),{'published':True},expected=(302,303))
|
|
laws=props(v,'/legislacao?q=Legisla%C3%A7%C3%A3o%20sint%C3%A9tica')['resources']['data'];ck('Legislação sintética consultável sem simular origem oficial',any(x['id']==lid for x in laws))
|
|
call(a,'/management/portal-services/resources/'+str(lid),{'published':False},expected=(302,303));call(v,'/documentos/'+str(lid),expected=404)
|
|
ck('Retirada da legislação sintética',True)
|
|
# Sector draft -> explicit publish -> public consumers -> withdrawal.
|
|
sd={'name':'Sector sintético editorial QA','slug':'sector-editorial-qa','short_description':'Apenas formação QA','description':'Conteúdo sintético','sort_order':200,'is_active':True,'editorial_published':False}
|
|
call(a,'/management/sectors',sd,expected=(302,303));records=props(a,'/management/sectors?q=sector-editorial-qa')['records']['data'];sector=next(x for x in records if x['slug']==sd['slug']);sid=sector['id']
|
|
ck('Activo sem publicar mantém sector fora do catálogo',sector['published_at'] is None)
|
|
call(a,'/management/sectors/'+str(sid),{**sd,'editorial_published':True},method='PUT',expected=(302,303))
|
|
public=props(v,'/sectores');(o/'SECTORES-PUBLICOS.json').write_text(json.dumps(public,ensure_ascii=False,default=str),encoding='utf8')
|
|
ck('Novo sector publicado aparece na navegação pública',sd['name'] in json.dumps(public,ensure_ascii=False))
|
|
# Filters use Sector::choices; publication must constrain this consumer too.
|
|
catalogue=props(v,'/oportunidades');ck('Novo sector aparece nos filtros públicos',sd['name'] in json.dumps(catalogue,ensure_ascii=False))
|
|
call(a,'/management/sectors/'+str(sid),sd,method='PUT',expected=(302,303))
|
|
ck('Retirada do catálogo público',sd['name'] not in json.dumps(props(v,'/sectores'),ensure_ascii=False))
|
|
# Article body on same resource, original unchanged; publication and withdrawal via existing commands.
|
|
r=current(a,id);edit='/management/portal-services/resources/'+str(id)+'/article'
|
|
call(v,edit,expected=401);call(u,edit,expected=403);call(u,edit,{'body':'intrusão','metadata_version':r['metadata_version']},method='PUT',expected=403)
|
|
ad={'body':'Artigo sintético QA. Primeira versão.\n\nSegundo parágrafo para formação.','metadata_version':r['metadata_version'],'image_resource_id':None}
|
|
call(a,edit,ad,method='PUT',expected=(302,303));call(a,edit,ad,method='PUT',expected=409);call(v,'/artigos/'+str(id),expected=404)
|
|
a2=login('authorized');recovered=props(a2,edit);ck('Artigo recuperado noutra sessão no mesmo registo',recovered['content']['body']==ad['body'] and recovered['resource']['id']==id)
|
|
call(a2,'/management/portal-services/resources/'+str(id),{'published':True},expected=(302,303));ap=props(v,'/artigos/'+str(id));ck('Artigo publicado consultável pelo visitante',ap['article']['body']==ad['body'])
|
|
r=current(a2,id);ad2={**ad,'body':'Artigo sintético QA. Segunda versão recuperada.\n\nOriginal preservado.','metadata_version':r['metadata_version']}
|
|
call(a2,edit,ad2,method='PUT',expected=(302,303));call(v,'/artigos/'+str(id),expected=404);call(a2,'/management/portal-services/resources/'+str(id),{'published':True},expected=(302,303));ck('Edição exige republicação expressa',props(v,'/artigos/'+str(id))['article']['body']==ad2['body'])
|
|
call(a2,'/management/portal-services/resources/'+str(id),{'published':False},expected=(302,303));call(v,'/artigos/'+str(id),expected=404)
|
|
r=current(a2,id);ck('Histórico e original preservados após duas edições e retirada',len(r['revisions'])>=9 and r['document_id']==doc['id'],{'revisions':len(r['revisions']),'same_document_id':True})
|
|
(o/'SINTETICOS.json').write_text(json.dumps({'document_resource':id,'law_resource':lid,'sector_id':sid,'article_resource':id,'original_sha256':doc['sha256']},indent=2),'utf8')
|
|
except Exception as e:
|
|
checks.append({'criterio':'Execução focada','resultado':'falhou','evidencia':str(e)})
|
|
finally:
|
|
(o/'PROVAS-HTTP-QA.json').write_text(json.dumps({'target':'editorial_20261018_test:55441','checks':checks,'events':events,'active_changes':0,'accepted_tests_repeated':False},ensure_ascii=False,indent=2),'utf8')
|
|
print(json.dumps({'checks':len(checks),'failed':[c for c in checks if c['resultado']=='falhou']},ensure_ascii=True))
|