Files
dtf-system/tests/smoke_test.py
Cauê Faleiros bb6fb14b1a
Some checks failed
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Publish images (push) Has been cancelled
Build and deploy / Secret scan and release gate (push) Has been cancelled
Build and deploy / Integration suite on a real stack (push) Has been cancelled
fix: the server refuses stacked pieces and files laid out at other proportions, and never cuts a strip with ink
The price came from the layout the browser sent, checked only in part:
- Pieces on top of each other passed: 100 copies stacked in one place bill
  10 cm and print over each other. The layout validator now refuses any
  overlap.
- A file laid out at proportions it does not have (a 5 m sheet sent as
  10 cm) was found only by the print file, after payment. The quote now
  checks each raster file's proportions from the bytes it already reads.
- The empty strips the Site cuts from a ready sheet were cut on its word.
  The print file now reads them: a strip with ink sends the item to hand
  preparation with the reason, instead of printing the art cut off.

Test fixtures that laid real images out at impossible proportions now keep
the image's own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:56:00 -03:00

394 lines
26 KiB
Python

"""Local stack integration checks; creates and retains clearly named test orders.
Run: python3 -m tests.smoke_test. Standard library only. Honors .env/environment.
"""
from concurrent.futures import ThreadPoolExecutor
import hashlib
import http.cookiejar
import json
import os
import struct
import zlib
from pathlib import Path
import time
from urllib.error import HTTPError
from urllib.request import build_opener, HTTPCookieProcessor, Request, urlopen
from uuid import uuid4
def final_png_bytes(label='final'):
"""A tiny real RGBA PNG tagged 300 DPI for operator final-file tests."""
def chunk(kind, body):
return struct.pack('>I', len(body)) + kind + body + struct.pack('>I', zlib.crc32(kind + body) & 0xffffffff)
red = hashlib.sha256(label.encode()).digest()[0]
row = b'\x00' + bytes((red, 30, 60, 255, 0, 0, 0, 0))
return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 2, 1, 8, 6, 0, 0, 0)) +
chunk(b'pHYs', struct.pack('>IIB', 11811, 11811, 1)) +
chunk(b'IDAT', zlib.compress(row)) + chunk(b'IEND', b''))
if Path('.env').exists():
for line in Path('.env').read_text().splitlines():
if line.strip() and not line.startswith('#') and '=' in line:
key,value=line.split('=',1)
os.environ.setdefault(key,value)
# CI runs these from a container on the stack's own network, because a runner
# container cannot reach ports published on the host's loopback. SITE_BASE_URL
# points at the gateway by service name; SITE_HOST_HEADER keeps the Host the
# gateway and TrustedHostMiddleware expect, so the security configuration under
# test stays identical to a developer's localhost run.
BASE=os.environ.get('SITE_BASE_URL') or 'http://localhost:'+os.environ.get('SITE_PORT','8080')
HOST_HEADER=os.environ.get('SITE_HOST_HEADER')
def with_host(headers=None):
headers=dict(headers or {})
if HOST_HEADER and not any(k.lower()=='host' for k in headers):
headers['Host']=HOST_HEADER
return headers
class Client:
def __init__(self):
self.jar=http.cookiejar.CookieJar()
self.opener=build_opener(HTTPCookieProcessor(self.jar))
self.operator_client=None
def call(self,path,body=None,operator=False,expected=200,method=None):
headers=with_host({'Content-Type':'application/json'})
if operator:
if self.operator_client is None:
self.operator_client=Client()
self.operator_client.call('/operator/login',{'email':os.environ.get('OPERATOR_EMAIL','operator@example.test'),'password':os.environ.get('OPERATOR_PASSWORD','local-operator-only')})
return self.operator_client.call(path,body,expected=expected,method=method)
reset=False
for attempt in range(20):
request=Request(BASE+'/api'+path,data=None if body is None else json.dumps(body).encode(),
headers=headers,method=method)
try:
with self.opener.open(request,timeout=30) as response:
assert response.status==expected,(path,response.status,expected)
return json.load(response)
except HTTPError as exc:
if exc.code==expected:return json.load(exc)
text=exc.read().decode()
# The gateway's own limit (nginx, 20 r/s per address, burst 100) is
# an HTML page, not the API's JSON: a fast suite waits for it.
if exc.code==429 and text.lstrip().startswith('<html') and attempt<19:
time.sleep(1);continue
# The API allows 60 sign-ins per address in 15 min (app/core/auth.py
# throttle), and the whole suite signs in from one address: a test
# that did not ask for the limit starts the count again.
if exc.code==429 and path=='/operator/login' and not reset:
from app.core import db
with db.connect() as c:
c.execute('DELETE FROM dtf_local.login_attempts')
reset=True;continue
raise AssertionError((path,exc.code,text)) from exc
def register(client, customer, password):
"""Create an account as the Site does: with e-mail on, the code sent to the
address (kept readable on the local stack) confirms it."""
started=client.call('/account/register',{'customer':customer,'password':password})
if 'verify' not in started:
return started
from app.core import db
with db.connect() as c:
body=c.execute("SELECT body FROM dtf_local.mail_queue WHERE kind='code' AND to_addr=%s ORDER BY id DESC LIMIT 1",
(customer['mail'].strip().lower(),)).fetchone()['body']
code=next(word for word in body.split() if word.isdigit() and len(word)==6)
return client.call('/account/register/verify',{'signup':started['verify'],'code':code})
def wait_scan(client, uid, operator=False, expected='clean'):
prefix='/operator/uploads' if operator else '/uploads'
deadline=time.monotonic()+150
while time.monotonic()<deadline:
state=client.call(prefix+'/'+uid,operator=operator)
if state['scan_state'] in ('clean','rejected','error'):
assert state['scan_state']==expected,state
return state
time.sleep(0.5)
raise AssertionError('Malware scan did not finish')
def upload_bytes(client, content, name='LOCAL-TEST.cdr', order_id=None, expected_scan='clean'):
operator=order_id is not None
prefix='/operator/uploads' if operator else '/uploads'
start='/operator/orders/'+order_id+'/uploads' if operator else prefix
data=client.call(start,{'name':name,'size':len(content)},operator=operator)
uid=data['id'];size=data['part_bytes']
for offset in range(0,len(content),size):
url=client.call(prefix+'/'+uid+'/parts/'+str(offset//size+1),{},operator=operator)['url']
with urlopen(Request(url,data=content[offset:offset+size],method='PUT'),timeout=30) as response:
assert response.status==200
client.call(prefix+'/'+uid+'/complete',{},operator=operator)
wait_scan(client,uid,operator,expected_scan)
return uid
def review_photo(client, order_id):
"""A 2000x1500 JPEG attached as the order's review photo, in Revisão.
The same transport site_video_test uses: start the operator upload, PUT the
single part, complete it, wait for the scan, then POST the review."""
from io import BytesIO
from PIL import Image
out=BytesIO()
Image.new('RGB',(2000,1500),(200,80,40)).save(out,'JPEG',quality=85)
content=out.getvalue()
start=client.call('/operator/orders/'+order_id+'/reviews/uploads',
{'name':'revisao.jpg','size':len(content)},operator=True)
uid=start['id']
url=client.call('/operator/uploads/'+uid+'/parts/1',{},operator=True)['url']
with urlopen(Request(url,data=content,method='PUT'),timeout=30) as response:
assert response.status==200
client.call('/operator/uploads/'+uid+'/complete',{},operator=True)
wait_scan(client,uid,operator=True)
return client.call('/operator/orders/'+order_id+'/reviews',{'upload_id':uid},operator=True)
def item_spec(mode, metres, grade, uid, aspect=None):
"""One file across the film, `metres` long. `aspect` (width / length) for
a real image: the piece then keeps the file's proportions, as the server
checks, inside the same billed length."""
film_width=27 if mode in ('uvfile','uv') else 57
height_cm=float(metres)*100
length_cm=round(film_width/aspect,4) if aspect else height_cm
return {'mode':mode,'metres':str(metres),'grade':grade,'uploads':[uid],
'production':{'version':2,'film_width_cm':film_width,'height_cm':height_cm,
'sources':[{'upload_id':uid,
'kind':'sheet' if mode in ('file','uvfile','premium') else 'artwork',
'width_cm':film_width,'length_cm':length_cm,'copies':1,
'rotation_degrees':0,'mirrored':False,'measurement':'customer'}],
'placements':[{'source_index':0,'copy_index':0,'x_cm':0,'y_cm':0,
'width_cm':film_width,'length_cm':length_cm,
'rotation_degrees':0,'mirrored':False}]},
'quality_status':'unverified' if grade==0 else 'ok',
'quality_acknowledged':False}
def approved_quote(client, quote, items):
"""The approval a customer pays against: automatic, or by the operator."""
if quote['status']=='approved':
return client.call('/quotes/'+quote['id'])['approved']
return client.call('/operator/quotes/'+quote['id']+'/approve',{'items':items},operator=True)
def run():
client=Client();other=Client()
config=client.call('/session');other.call('/session')
assert client.call('/health')['integrations']=='fake'
# 4 GB per file (Dropstar, 2026-10-28).
assert config['max_upload_bytes'] == 4 * 1024 ** 3
client.call('/uploads',{'name':'too-large.cdr',
'size':config['max_upload_bytes']+1},expected=413)
cancelled=client.call('/uploads',{'name':'CANCELLED-PART.cdr','size':3})['id']
other.call('/uploads/'+cancelled,expected=404,method='DELETE')
assert client.call('/uploads/'+cancelled,method='DELETE')['cancelled']
client.call('/uploads/'+cancelled,expected=410)
client.call('/operator/board',expected=401)
block=config['part_bytes'];content=b'DTF local multipart test\n'+b'x'*block
uid=client.call('/uploads',{'name':'LOCAL-SMOKE-ONLY.cdr','size':len(content)})['id']
other.call('/uploads/'+uid,expected=404)
other.call('/uploads/'+uid+'/parts/1',{},expected=404)
signed=client.call('/uploads/'+uid+'/parts/1',{})['url']
with urlopen(Request(signed,data=content[:block],method='PUT'),timeout=30) as response:assert response.status==200
assert client.call('/uploads/'+uid)['parts']==[1]
client.call('/uploads/'+uid+'/complete',{},expected=409)
signed=client.call('/uploads/'+uid+'/parts/2',{})['url']
with urlopen(Request(signed,data=content[block:],method='PUT'),timeout=30) as response:assert response.status==200
client.call('/uploads/'+uid+'/complete',{})
client.call('/uploads/'+uid+'/complete',{})
wait_scan(client,uid)
client.call('/uploads/'+uid+'/parts/1',{},expected=409)
download=client.call('/operator/uploads/'+uid+'/download',operator=True)
with urlopen(download['url'],timeout=30) as response:assert hashlib.sha256(response.read()).digest()==hashlib.sha256(content).digest()
unsigned=download['url'].split('?')[0]
try:urlopen(unsigned,timeout=10);raise AssertionError('Bucket must be private')
except HTTPError as exc:assert exc.code==403
print('PASS: multipart resume, incomplete rejection, immutable completion, ownership, private/downloaded bytes')
# Above QUOTE_AUTO_MAX_METRES (50 m by default), so a person reviews it.
# One order, one machine (Marcus, 2026-11-26): the two textile products;
# UV goes in an order of its own.
items=[item_spec(m,'26',90,uid) for m in ('file','avulsa')]
draft={'request_key':str(uuid4()),'customer':{'cnpj':'11222333000181','zap':'11999999999','mail':'local-smoke@example.test'},
'items':items,'freight':{'service':'mock-standard','postal_code':'14400000'},
'destination':{'recipient':'Local Smoke Ltda','street':'Rua de Teste','number':'100',
'district':'Centro','city':'Franca','state':'SP','postal_code':'14400000'}}
client.call('/quotes',{**draft,'total_cents':1},expected=422)
mixed_cart=client.call('/quotes',{**draft,'items':[items[0],item_spec('uvfile','13',90,uid)]},expected=422)['detail']
assert any('outra máquina' in str(e.get('msg','')) for e in mixed_cart), mixed_cart
# Freight quoted by CEP alone cannot ship: the address is required, must be
# the quoted CEP, and a pickup order takes none.
client.call('/quotes',{**draft,'destination':None},expected=422)
client.call('/quotes',{**draft,'destination':{**draft['destination'],'postal_code':'01001000'}},expected=422)
client.call('/quotes',{**draft,'destination':{**draft['destination'],'state':'XX'}},expected=422)
client.call('/quotes',{**draft,'freight':{'service':'pickup'}},expected=422)
client.call('/quotes',{**draft,'items':[{k:v for k,v in items[0].items() if k!='production'}]},expected=422)
outside={**items[0],'production':{**items[0]['production'],
'placements':[{**items[0]['production']['placements'][0],'x_cm':1}]}}
client.call('/quotes',{**draft,'items':[outside]},expected=422)
client.call('/quotes',{**draft,'items':[{**items[0],'metres':'1.00'}]},expected=422)
client.call('/quotes',{**draft,'customer':{**draft['customer'],'cnpj':'11111111111111'}},expected=422)
# A person buys with a CPF: its check digits count as a CNPJ's do.
client.call('/quotes',{**draft,'customer':{**draft['customer'],'cnpj':'529.982.247-24'}},expected=422)
client.call('/quotes',{**draft,'request_key':str(uuid4()),'customer':{**draft['customer'],'cnpj':'529.982.247-25'}})
quote=client.call('/quotes',draft)
assert quote['status']=='pending_review'
assert client.call('/quotes/'+quote['id'])['review_reason']=='Pedido acima de 50 m'
assert client.call('/quotes',draft)['id']==quote['id']
client.call('/quotes',{**draft,'freight':{'service':'pickup'},'destination':None},expected=409)
qid=quote['id']
other.call('/quotes/'+qid,expected=404)
client.call('/orders/dev-paid',{'quote_id':qid},expected=409)
client.call('/operator/quotes/'+qid+'/approve',{'items':items},expected=401)
altered={**items[0],'production':{**items[0]['production'],
'sources':[{**items[0]['production']['sources'][0],'measurement':'file'}]}}
client.call('/operator/quotes/'+qid+'/approve',{'items':[altered,*items[1:]]},operator=True,expected=422)
# Nor does the review change the residue the customer accepted (Dropstar, 2026-10-29).
client.call('/operator/quotes/'+qid+'/approve',{'items':[{**items[0],'residue_accepted':2},*items[1:]]},
operator=True,expected=422)
# Reviewer corrects a browser-supplied grade and length. Browser values are proposals.
# One price per product (2026-10-23): the grade is kept, the price ignores it.
corrected=[{**items[0],'metres':'1.01','grade':0},*items[1:]]
approved=client.call('/operator/quotes/'+qid+'/approve',{'items':corrected},operator=True)
assert approved['items'][0]['total_cents']==2189 and approved['items'][0]['grade']==0
assert [i['unit_cents'] for i in approved['items'][1:]]==[2190]
assert approved['total_cents']==2189+56940+int(os.environ.get('MOCK_FREIGHT_CENTS','1500'))
assert approved['destination']=={**draft['destination'],'complement':''}
client.call('/operator/quotes/'+qid+'/approve',{'items':items},operator=True,expected=409)
assert not client.call('/quotes/'+qid)['auto_approved']
# A cart the Site priced is approved at once and can be paid straight away,
# at the server's own prices; no operator can then change it.
# The server works the grade out from the file: this PNG is 6059 px across
# 57 cm, 270 DPI, which is grade 100 under the 200 DPI clean threshold;
# 29232 px long, the 275 cm it is laid out at (the server checks it).
png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(6059).to_bytes(4,'big')+(29232).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
graded=upload_bytes(client,png,name='arte-270dpi.png')
low_png=b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(3366).to_bytes(4,'big')+(16240).to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
low=upload_bytes(client,low_png,name='arte-150dpi.png')
small={**draft,'request_key':str(uuid4()),'items':[item_spec('avulsa','2.75',90,graded)]}
auto=client.call('/quotes',small)
assert auto['status']=='approved'
seen=client.call('/quotes/'+auto['id'])
assert seen['auto_approved'] and seen['review_reason'] is None
assert isinstance(seen.get('prumo'), list) and seen['prumo'], seen.get('prumo')
assert seen['approved']['total_cents']==6132+int(os.environ.get('MOCK_FREIGHT_CENTS','1500'))
assert client.call('/quotes',small)['status']=='approved'
client.call('/operator/quotes/'+auto['id']+'/approve',{'items':small['items']},operator=True,expected=409)
# The residue dots the customer accepted printing stay with the item.
accepted={**small,'request_key':str(uuid4()),'items':[{**item_spec('avulsa','2.75',90,graded),'residue_accepted':3}]}
client.call('/quotes',{**accepted,'items':[{**accepted['items'][0],'residue_accepted':-1}]},expected=422)
kept=client.call('/quotes',accepted)
assert kept['status']=='approved'
assert client.call('/quotes/'+kept['id'])['approved']['items'][0]['residue_accepted']==3
# The thinnest stroke and its contraction class (item 9) stay with the item too.
stroked={**small,'request_key':str(uuid4()),'items':[{**item_spec('avulsa','2.75',90,graded),'stroke_px':6,'stroke_class':'C2'}]}
client.call('/quotes',{**stroked,'items':[{**stroked['items'][0],'stroke_class':'C4'}]},expected=422)
held_stroke=client.call('/quotes',stroked)
assert held_stroke['status']=='approved'
stroke_item=client.call('/quotes/'+held_stroke['id'])['approved']['items'][0]
assert (stroke_item['stroke_px'],stroke_item['stroke_class'])==(6,'C2'), stroke_item
# A sheet with fine lines and solid areas (item 16) keeps the customer's choice.
mixed={**stroked,'request_key':str(uuid4()),'items':[{**stroked['items'][0],'stroke_choice':'client_c3'}]}
client.call('/quotes',{**mixed,'items':[{**mixed['items'][0],'stroke_choice':'both'}]},expected=422)
mixed_item=client.call('/quotes/'+client.call('/quotes',mixed)['id'])['approved']['items'][0]
assert mixed_item['stroke_choice']=='client_c3', mixed_item
# Loose art split by stroke (item 17): each sheet is an item, and the pair
# has one 1 m minimum, on its first sheet.
# Each sheet's own file, 6059 px across 57 cm, as long as the sheet.
header=lambda rows:b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR'+(6059).to_bytes(4,'big')+rows.to_bytes(4,'big')+b'\x08\x06\x00\x00\x00'+b'\x00'*4
sheet_files={'0.3':upload_bytes(client,header(3189),name='folha-30.png'),
'0.15':upload_bytes(client,header(1594),name='folha-15.png')}
part=lambda metres,n,mode='avulsa':{**item_spec(mode,metres,90,sheet_files[metres]),'split':{'group':'f0','part':n,'of':2}}
split={**small,'request_key':str(uuid4()),'items':[part('0.3',1),part('0.15',2)]}
client.call('/quotes',{**split,'items':split['items'][:1]},expected=422)
client.call('/quotes',{**split,'items':[part('0.3',1),part('0.15',1)]},expected=422)
client.call('/quotes',{**split,'items':[part('0.3',1,'file'),part('0.15',2,'file')]},expected=422)
held_split=client.call('/quotes',split)
assert held_split['status']=='approved', held_split
sheets=client.call('/quotes/'+held_split['id'])['approved']['items']
assert [(i['billed_metres'],i['total_cents'],i['split']['part']) for i in sheets]==[('0.8',1752,1),('0.2',438,2)], sheets
# The Site grades only art it analysed. A grade on art it did not analyse
# is checked against the file like any other, and this one cannot be.
claimed={**item_spec('avulsa','2.75',0,uid),'grade':90}
held=client.call('/quotes',{**small,'request_key':str(uuid4()),'items':[claimed]})
assert held['status']=='pending_review'
assert client.call('/quotes/'+held['id'])['review_reason']=='Nota não conferida no servidor'
# A better grade than the file supports, or one the server cannot check, waits too:
# the price ignores the grade, but the order shows it.
low_item={**item_spec('avulsa','2.75',100,low),'quality_status':'warning','quality_acknowledged':True}
inflated=client.call('/quotes',{**small,'request_key':str(uuid4()),'items':[low_item]})
assert inflated['status']=='pending_review'
assert client.call('/quotes/'+inflated['id'])['review_reason']=='Nota 100 maior que a do arquivo (75)'
unchecked=client.call('/quotes',{**small,'request_key':str(uuid4()),'items':[item_spec('avulsa','2.75',90,uid)]})
assert client.call('/quotes/'+unchecked['id'])['review_reason']=='Nota não conferida no servidor'
print('PASS: priced carts are approved at checkout; large or inconsistent ones wait for review')
client.call('/orders/dev-paid',{'quote_id':qid,'total_cents':1},expected=422)
other.call('/orders/dev-paid',{'quote_id':qid},expected=404)
# Concurrent retries must produce precisely one payment/order/outbox pair.
with ThreadPoolExecutor(max_workers=4) as executor:
paid=list(executor.map(lambda _:client.call('/orders/dev-paid',{'quote_id':qid}),range(4)))
assert len({p['id'] for p in paid})==1
order=paid[0];oid=order['id']
assert order['payment']['status']=='paid' and order['snapshot']==approved
board=client.call('/operator/board',operator=True)
assert len([o for o in board['orders'] if o['quote_id']==qid])==1
client.call('/operator/orders/'+oid+'/move',{'state':'fin','version':0},operator=True,expected=409)
# Above 10 m the proof comes first: the parent cannot move at all until
# Prova OK on its proof card in Revisão (item 0.1).
held=client.call('/operator/orders/'+oid+'/move',{'state':'cor','version':0},operator=True,expected=409)
assert 'Aguardando prova' in held['detail'], held
card=next(o for o in board['orders'] if o['id']==oid)['proof_card']
from app.core import db
with db.connect() as c:
c.execute("UPDATE dtf_local.orders SET state='rev' WHERE id=%s",(card['id'],))
client.call('/operator/orders/'+card['id']+'/proof-answer',{'result':'ok'},operator=True)
version=next(o for o in client.call('/operator/board',operator=True)['orders'] if o['id']==oid)['version']
client.call('/operator/orders/'+oid+'/move',{'state':'cor','version':version},operator=True,expected=422)
# Dropstar's flow (2026-10-23): Arte conferida is the queue, Revisão comes before Finalizado.
machine=None
for state in ('cor','rec','tra','imp','rev','fin'):
if state=='tra':
# The queue takes approved final files only.
client.call('/operator/orders/'+oid+'/move',{'state':'tra','version':version},operator=True,expected=409)
files=[{'item_index':i,'upload_id':upload_bytes(client,final_png_bytes(str(i)),name=f'LOCAL-FINAL-{i}.png',order_id=oid)} for i in range(len(items))]
result=client.call('/operator/orders/'+oid+'/final-files',{'version':version,'files':files,'note':'Local test manual final-file approval'},operator=True)
version=result['version']
body={'state':state,'version':version,'reason':'Local test correction' if state=='cor' else ''}
if state=='imp':
if machine is None:
machine=client.call('/operator/machines',{'name':'Smoke '+uuid4().hex[:6],'products':['textil']},operator=True)['id']
body['machine_id']=machine
# Above 1 m Finalizado needs the review photo (app/reviews.py).
if state=='fin':review_photo(client,oid)
moved=client.call('/operator/orders/'+oid+'/move',body,operator=True)
version+=1;assert moved['version']==version
client.call('/operator/orders/'+oid+'/move',{'state':'rec','version':0},operator=True,expected=409)
assert len(client.call('/operator/orders/'+oid+'/history',operator=True))==6
# A mistaken move can be undone one stage at a time, with an internal
# reason. The customer is not told again: going back and forward once more
# adds no messages (the outbox count below stays 4).
client.call('/operator/orders/'+oid+'/move',{'state':'rev','version':version},operator=True,expected=422)
client.call('/operator/orders/'+oid+'/move',{'state':'imp','version':version},operator=True,expected=409)
back=client.call('/operator/orders/'+oid+'/move',{'state':'rev','version':version,'reason':'Movido por engano'},operator=True)
assert back['state']=='rev';version+=1
review_photo(client,oid)
client.call('/operator/orders/'+oid+'/move',{'state':'fin','version':version},operator=True);version+=1
history=client.call('/operator/orders/'+oid+'/history',operator=True)
assert len(history)==8 and history[-2]['back'] and history[-2]['reason']=='Movido por engano' and not history[-1]['back']
# The customer sees the stages and the correction's reason, never the
# internal reason for going back.
seen=client.call('/customer/orders/'+oid)['history']
assert len(seen)==7 and all(h['reason']=='' or h['to_state']=='cor' for h in seen)
assert any(h['to_state']=='cor' and h['reason']=='Local test correction' for h in seen)
print('PASS: a mistaken move is undone one stage back with a reason, without messaging the customer again')
print('PASS: all modes, authoritative review/prices/freight, tamper rejection, concurrent payment idempotency, transitions and history')
deadline=time.monotonic()+30
while time.monotonic()<deadline:
events=[e for e in client.call('/operator/events?order='+str(order['number']),operator=True)['events'] if e['payload']['order_id']==oid]
if len(events)==4 and all(e['delivered_at'] and e['receipt'] for e in events):break
time.sleep(1)
else:raise AssertionError('Mock outbox did not drain')
assert len({e['event_key'] for e in events})==4 and {e['provider'] for e in events}=={'tiny'}
# Tiny sets the pickup situação from the order it is sent; the fake sale
# has no Tiny id, so the real adapter would search for it.
ready={e['provider']:e['payload'] for e in events if e['payload']['event']=='ready'}
assert ready['tiny']['order']['freight']==order['snapshot']['freight'] and 'tiny_id' in ready['tiny']
print(f"PASS: 4 durable fake receipts. Local test order #{order['number']} retained in Finalizado.")
return oid
if __name__=='__main__':run()