Files
Investidor-V2/outputs/investmoz-audit-current-20261012/business-country-http.py
T
nala 287e991486
tests / ci (push) Waiting to run
oportunidades 7
2026-10-13 11:40:29 +02:00

59 lines
6.2 KiB
Python

"""Business-interest consumer only; new sessions and explicit QA headers, never a browser demonstration."""
from pathlib import Path
from datetime import datetime,timezone
import json,sys,uuid,time
OUT=Path(__file__).resolve().parent
exec((OUT/'audit-http.py').read_text(encoding='utf-8').split("proof={'at'")[0],globals())
class CriterionSession(Session):
def request(self,method,path,data=None,accept='text/html',check_target=True,extra_headers=None):
previous=self.client.addheaders
try:
if extra_headers:self.client.addheaders=previous+list(extra_headers.items())
return super().request(method,path,data,accept,check_target)
finally:self.client.addheaders=previous
Session=CriterionSession
fixture=json.loads((OUT/'business-country-fixture.json').read_text(encoding='utf-8'));assert fixture['target']=={'database':'stability_consumers_20261011_084534_test','port':55441}
label=sys.argv[2] if len(sys.argv)>2 else 'before';assert label in ['before','after'];receiptPath=OUT/'business-country-attempt-data.json'
if receiptPath.exists():attempt=json.loads(receiptPath.read_text(encoding='utf-8'))
else:
attempt={'key':str(uuid.uuid4()),'payload':{'fullName':'QA países negócio legado','email':'investmoz-business-audit@example.com','phone':'+258840000019','investorType':'empresa','country':'Moçambique','declared_origin_country_code':'BR','sectorInterest':'Agronegócio QA','existingBusinessId':fixture['business_id'],'modality':'company_sale','message':'Mensagem exclusivamente sintética para auditar países, origem e estatísticas em QA.','privacyConsent':True,'shareWithProponent':False}}
receiptPath.write_text(json.dumps(attempt,ensure_ascii=False,indent=2),encoding='utf-8')
proof={'at':datetime.now(timezone.utc).isoformat(),'base':BASE,'target':TARGET,'active_writes':0,'browser_observed':False,'fixture_is_synthetic':True,'published_fixture_not_a_workflow_proof':True,'criteria':{}};stage='isolation';s=Session()
used_mfa_bucket=None
def manager_login(client):
global used_mfa_bucket
a=actors['manager'];assert client.request('GET','/login')[0]==200
assert client.request('POST','/login',{'email':a['email'],'password':a['password']},'application/json')[0]in [200,204,302]
assert client.request('GET','/two-factor-challenge')[0]==200
if used_mfa_bucket==int(time.time())//30:time.sleep(31-time.time()%30)
elif time.time()%30>26:time.sleep(4)
used_mfa_bucket=int(time.time())//30
st,_,body=client.request('POST','/two-factor-challenge',{'code':otp(a.get('totp_secret',a.get('secret')))},'application/json')
if st not in [200,204,302]:proof['MFA_error']={'status':st,'fields':list(json.loads(body).get('errors',{}))}
assert st in [200,204,302]
def managed(client,path):
st,headers,body=client.request('GET',path)
if st!=200:proof['unexpected_response']={'status':st,'path':path.split('?',1)[0],'redirect_path':urlparse(headers.get('Location','')).path}
assert st==200;return page(body)['props']
try:
st,_,body=s.request('GET','/_qa/runtime',check_target=False);assert st==200 and json.loads(body)['target']['database']==fixture['target']['database']
stage='public_form';st,_,body=s.request('GET','/negocios/'+fixture['slug']+'/manifestar-interesse');assert st==200
p=page(body);assert p['component']=='investment/business-interest' and p['props']['record']['id']==fixture['business_id'];codes={x['code']for x in p['props']['countries']};assert {'MZ','BR','PT'}<=codes
proof['criteria']['public_form_and_catalogue']={'HTTP':200,'country_codes':len(codes),'component':p['component']}
manager=Session();manager_login(manager);before=managed(manager,'/management/interests?origin=BR');countBefore=sum(x['count']for x in before['originStatistics']['interests'])
stage='submission';st,_,body=s.request('POST','/api/v1/interest-requests',attempt['payload'],'application/json',extra_headers={'Idempotency-Key':attempt['key']});proof['submission_response']={'status':st,'error_fields':list(json.loads(body).get('errors',{}))};assert st==201
ref=json.loads(body)['data']['reference'];proof['reference']=ref
stage='repeat';st,_,body=s.request('POST','/api/v1/interest-requests',attempt['payload'],'application/json',extra_headers={'Idempotency-Key':attempt['key']});assert st==201 and json.loads(body)['data']['reference']==ref
proof['criteria']['same_key_reuses_reference']=True
stage='origin_filter';origin=managed(manager,'/management/interests?origin=BR&q='+ref);rows=origin['requests']['data'];proof['criteria']['origin_filter_diagnostic']={'matches':len(rows),'countries':[r['country']for r in rows],'origins':[r['declaredOrigin']['code']for r in rows]};assert len(rows)==1 and rows[0]['reference']==ref and rows[0]['declaredOrigin']['code']=='BR';id_=rows[0]['id'];assert rows[0]['country']=='Moçambique'
countAfter=sum(x['count']for x in origin['originStatistics']['interests']);proof['criteria']['origin_statistics_after_replay']={'before':countBefore,'after':countAfter,'reference_occurrences':len(rows)}
stage='new_manager_session';manager.request('POST','/logout',{},'application/json');manager=Session();manager_login(manager)
detail=managed(manager,f'/management/interests/{id_}');assert detail['interest']['country']=='Moçambique' and detail['declaredOrigin']['code']=='BR' and detail['interest']['existing_business_id']==fixture['business_id']
proof['criteria']['recovered_new_manager_session_country_origin_and_business']=True
stage='country_filter';filtered=managed(manager,'/management/interests?country=MZ&origin=BR&q='+ref);matches=filtered['requests']['data'];proof['criteria']['ISO_filter_covers_preserved_legacy_country']={'country':'MZ','stored_country':'Moçambique','matching_records':len(matches)}
assert len(matches)==1,'ISO filter excludes the accepted legacy country value'
other=managed(manager,'/management/interests?country=PT&origin=BR&q='+ref);assert other['requests']['data']==[];proof['criteria']['different_country_excludes_record']=True
manager.request('POST','/logout',{},'application/json');proof['result']='passed'
except Exception as e:proof.update(result='stopped',stage=stage,error_type=type(e).__name__)
(OUT/f'business-country-{label}.json').write_text(json.dumps(proof,ensure_ascii=False,indent=2),encoding='utf-8');print(json.dumps(proof,ensure_ascii=True));sys.exit(0 if proof['result']=='passed'else 1)