feat: the Tiny test order cancels itself, and a guarded cancel for test orders left open
All checks were successful
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Successful in 3m19s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m7s

Tiny has no delete, and the team's users cannot cancel by hand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-21 15:42:18 -03:00
parent c266bea684
commit a2382f4834
2 changed files with 80 additions and 19 deletions

View File

@@ -10,14 +10,16 @@ Tiny has no sandbox, so this is how the adapter is proven on the real account.
python -m app.tiny_probe exemplo NUMERO the structure of an existing order, without the
customer's details, to copy in Site orders (read-only)
python -m app.tiny_probe pedido --cnpj ... --email ... --celular ... [--modo file] [--metros 1.3]
show the test order; --confirmar creates it
show the test order; --confirmar creates it, then cancels it
python -m app.tiny_probe cancelar TINY_ID cancel a test order (DTF-TESTE-...) left open; nothing else
The test order goes through TinyOrders.deliver, exactly as the worker sends a
paid order. The duplicate guard is then proven read-only first (the order must
be found by its purchase-order number) and only then by a second delivery,
which must return the existing order. If the search cannot find the order, the
second delivery is not attempted: it would create a duplicate. Cancel the test
order in Olist afterwards.
second delivery is not attempted: it would create a duplicate. Either way the
test order is then cancelled through the API (Tiny has no delete, and the
team's users may not cancel by hand), and read back to show it is.
"""
import argparse
import json
@@ -185,22 +187,49 @@ def pedido(orders, payload, confirm, out, wait=time.sleep):
return None
first = orders.deliver('teste-integracao', payload)
out(f"1º envio: {first['status']} · Tiny id {first['tiny_id']} · nº {first['tiny_number']}")
for attempt in range(FIND_ATTEMPTS):
found = orders.find(payload)
if found:
break
if attempt < FIND_ATTEMPTS - 1:
wait(FIND_WAIT_SECONDS)
else:
out(f'FALHA: a busca por {tiny.purchase_order(payload["number"])} não encontrou o pedido. '
'Um reenvio criaria um duplicado; o 2º envio não foi feito. Cancele o pedido no Olist.')
try:
for attempt in range(FIND_ATTEMPTS):
found = orders.find(payload)
if found:
break
if attempt < FIND_ATTEMPTS - 1:
wait(FIND_WAIT_SECONDS)
else:
out(f'FALHA: a busca por {tiny.purchase_order(payload["number"])} não encontrou o pedido. '
'Um reenvio criaria um duplicado; o 2º envio não foi feito.')
return False
second = orders.deliver('teste-integracao', payload)
out(f"2º envio: {second['status']} · Tiny id {second['tiny_id']}")
passed = second['status'] == 'already-created' and second['tiny_id'] == first['tiny_id']
out('OK: o reenvio encontrou o mesmo pedido.' if passed else 'FALHA: o reenvio não devolveu o mesmo pedido.')
return passed
finally:
# Whatever happened above, the test order does not stay open.
cancelar(orders, first['tiny_id'], out)
def cancelar(orders, tiny_id, out):
"""Cancel a test order through the API and read it back. Only orders
this probe made (purchase order DTF-TESTE-...) are touched."""
try:
detail = orders.request('GET', f'/pedidos/{tiny_id}')
number = detail.get('numeroPedido')
if not str(detail.get('numeroOrdemCompra') or '').startswith(tiny.purchase_order('TESTE-')):
out(f'Recusado: o pedido {tiny_id} não é um pedido de teste (DTF-TESTE-...); nada foi alterado.')
return False
if detail.get('situacao') != tiny.CANCELADA:
orders.set_situacao(tiny_id, tiny.CANCELADA)
detail = orders.request('GET', f'/pedidos/{tiny_id}')
except tiny.TinyError as exc:
out(f'FALHA ao cancelar o pedido {tiny_id}: {exc}. Rode: python -m app.tiny_probe cancelar {tiny_id}')
return False
second = orders.deliver('teste-integracao', payload)
out(f"2º envio: {second['status']} · Tiny id {second['tiny_id']}")
passed = second['status'] == 'already-created' and second['tiny_id'] == first['tiny_id']
out(('OK: o reenvio encontrou o mesmo pedido.' if passed else 'FALHA: o reenvio não devolveu o mesmo pedido.')
+ f" Cancele o pedido nº {first['tiny_number']} no Olist.")
return passed
situacao = detail.get('situacao')
if situacao == tiny.CANCELADA:
out(f'Pedido nº {number} cancelado no Tiny.')
return True
out(f'FALHA: o pedido nº {number} ficou em {tiny.SITUACOES.get(situacao, situacao)}. '
f'Rode: python -m app.tiny_probe cancelar {tiny_id}')
return False
def main(argv=None, orders=None, out=print):
@@ -214,6 +243,8 @@ def main(argv=None, orders=None, out=print):
commands.add_parser('campos')
example = commands.add_parser('exemplo')
example.add_argument('numero')
cancel = commands.add_parser('cancelar')
cancel.add_argument('tiny_id', type=int)
order = commands.add_parser('pedido')
order.add_argument('--cnpj', '--cpf', dest='cnpj', required=True, help='CNPJ ou CPF do cliente')
order.add_argument('--email', required=True)
@@ -240,6 +271,8 @@ def main(argv=None, orders=None, out=print):
return 0 if campos(orders, out) else 1
if args.command == 'exemplo':
return 0 if exemplo(orders, args.numero, out) else 1
if args.command == 'cancelar':
return 0 if cancelar(orders, args.tiny_id, out) else 1
cnpj = ''.join(ch for ch in args.cnpj if ch.isdigit())
if len(cnpj) not in (11, 14):
out('Informe um CPF (11 dígitos) ou um CNPJ (14 dígitos).')

View File

@@ -613,6 +613,26 @@ class TinyProbeTests(FakeTinyCase):
self.assertEqual(len(self.orders), 1)
self.assertEqual(self.orders[0]['itens'][0]['produto'], {'id': 104})
self.assertIn('2º envio: already-created', text)
# Then cancelled through the API, and read back: it does not stay open.
self.assertEqual(self.orders[0]['situacao'], 2)
self.assertIn(f"Pedido nº {self.orders[0]['numeroPedido']} cancelado no Tiny.", text)
self.assertEqual(self.tags[self.orders[0]['id']], [{'descricao': 'KANBANDTF'}])
def test_cancelar_touches_only_test_orders(self):
self.tiny.deliver('k1', PAID)
real = self.orders[0]
code, text = self.probe('cancelar', str(real['id']))
self.assertEqual(code, 1)
self.assertIn('não é um pedido de teste', text)
self.assertEqual(real['situacao'], 0)
self.assertNotIn('PUT', [method for method, _ in self.calls])
# A test order left open is cancelled; asked again, it is already.
test = tiny_probe_payload()
self.tiny.deliver('k2', test)
left = self.orders[-1]
self.assertEqual(self.probe('cancelar', str(left['id']))[0], 0)
self.assertEqual(left['situacao'], 2)
self.assertEqual(self.probe('cancelar', str(left['id']))[0], 0)
def test_resend_is_skipped_when_the_search_cannot_find_the_order(self):
from app import tiny_probe
@@ -624,7 +644,15 @@ class TinyProbeTests(FakeTinyCase):
lines = []
self.assertFalse(tiny_probe.pedido(self.tiny, payload, True, lines.append, wait=lambda s: None))
self.assertEqual(len(self.orders), 1)
self.assertIn('o 2º envio não foi feito', lines[-1])
self.assertIn('o 2º envio não foi feito', lines[-2])
# Not left open all the same.
self.assertEqual(self.orders[0]['situacao'], 2)
self.assertIn('cancelado no Tiny', lines[-1])
def tiny_probe_payload():
from app import tiny_probe
return tiny_probe.test_order('11222333000181', 'a@example.test', '16999999999', 'file')
class DefaultSkuTests(unittest.TestCase):