feat: check Tiny products and add a supervised order test
All checks were successful
Build and deploy / Validate source (push) Successful in 11s
Build and deploy / Integration suite on a real stack (push) Successful in 2m39s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m43s

"Testar conexão" now also reads the four configured Tiny products and
requires each to be active. app/tiny_probe.py runs from the worker console
to list products, confirm the configured ids, and create one marked test
order through the worker's own delivery path, proving the duplicate guard
by search before a second delivery. Nothing is sent without --confirmar.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-09-25 10:23:07 -03:00
parent 56021d8451
commit 988b252f9d
5 changed files with 241 additions and 11 deletions

View File

@@ -31,12 +31,15 @@ class FakeAuth:
return 'access-1'
@mock.patch.dict(os.environ, PRODUCTS)
class TinyTests(unittest.TestCase):
class FakeTinyCase(unittest.TestCase):
"""A Tiny account in memory: contacts, orders and the four products."""
def setUp(self):
self.contacts = []
self.orders = []
self.calls = []
self.products = {value: {'id': int(value), 'sku': f'DTF-{value}', 'descricao': f'Produto {value}',
'situacao': 'A', 'precos': {'preco': 14.9}} for value in PRODUCTS.values()}
def handler(request):
path = request.url.path.removeprefix('/public-api/v3')
@@ -49,6 +52,13 @@ class TinyTests(unittest.TestCase):
contact = {**json.loads(request.content), 'id': 500 + len(self.contacts)}
self.contacts.append(contact)
return httpx.Response(200, json={'id': contact['id']})
if request.method == 'GET' and path.startswith('/produtos/'):
wanted = path.rsplit('/', 1)[-1]
if wanted not in self.products:
return httpx.Response(404, json={'mensagem': 'não encontrado'})
return httpx.Response(200, json=self.products[wanted])
if request.method == 'GET' and path == '/produtos':
return httpx.Response(200, json={'itens': list(self.products.values())})
if request.method == 'GET' and path == '/pedidos':
return httpx.Response(200, json={'itens': [{'id': o['id']} for o in self.orders]})
if request.method == 'GET' and path.startswith('/pedidos/'):
@@ -65,6 +75,9 @@ class TinyTests(unittest.TestCase):
self.tiny = TinyOrders(auth=FakeAuth(), transport=httpx.MockTransport(handler),
today=date(2026, 9, 24))
@mock.patch.dict(os.environ, PRODUCTS)
class TinyTests(FakeTinyCase):
def test_payload_carries_contact_products_address_and_freight(self):
pedido = order_payload(PAID, 777, date(2026, 9, 24))
self.assertEqual((pedido['idContato'], pedido['numeroOrdemCompra'], pedido['data']),
@@ -110,8 +123,15 @@ class TinyTests(unittest.TestCase):
def test_connection_check_only_reads(self):
from app.tiny import check
results = check(auth=FakeAuth(), transport=httpx.MockTransport(self.handler))
self.assertEqual(results, {'pedidos': 'ok', 'contatos': 'ok'})
self.assertEqual(set(results.values()), {'ok'})
self.assertEqual(len(results), 6)
self.assertTrue(all(method == 'GET' for method, _ in self.calls))
self.products['103']['situacao'] = 'I'
with mock.patch.dict(os.environ, {'TINY_PRODUCT_UV_AVULSA': ''}):
results = check(auth=FakeAuth(), transport=httpx.MockTransport(self.handler))
self.assertIn('não está ativo', results['DTF UV 28,5 cm · folha montada'])
self.assertEqual(results['DTF UV 28,5 cm · artes avulsas'], 'TINY_PRODUCT_UV_AVULSA sem id')
self.assertEqual(results['pedidos'], 'ok')
denied = check(auth=FakeAuth(), transport=httpx.MockTransport(lambda r: httpx.Response(403, text='forbidden')))
self.assertTrue(denied['pedidos'].startswith('GET /pedidos: 403'))
@@ -121,5 +141,54 @@ class TinyTests(unittest.TestCase):
tiny.deliver('k4', PAID)
@mock.patch.dict(os.environ, PRODUCTS)
class TinyProbeTests(FakeTinyCase):
"""The supervised console tool run against the fake Tiny."""
def probe(self, *argv):
from app import tiny_probe
lines = []
code = tiny_probe.main(list(argv), orders=self.tiny, out=lines.append)
return code, '\n'.join(lines)
def test_products_and_settings_are_listed_without_writing(self):
code, text = self.probe('produtos', 'DTF')
self.assertEqual(code, 0)
self.assertIn('101\tDTF-101\tProduto 101', text)
code, text = self.probe('conferir')
self.assertEqual(code, 0)
self.assertIn('TINY_PRODUCT_UV_AVULSA (DTF UV 28,5 cm · artes avulsas): ok DTF-104', text)
self.assertTrue(all(method == 'GET' for method, _ in self.calls))
def test_order_is_shown_and_not_created_without_confirmation(self):
code, text = self.probe('pedido', '--cnpj', '11.222.333/0001-81', '--email', 'a@example.test',
'--celular', '16999999999')
self.assertEqual(code, 0)
self.assertIn('"numeroOrdemCompra": "DTF-TESTE-', text)
self.assertIn('Nada foi criado', text)
self.assertEqual(self.orders, [])
self.assertTrue(all(method == 'GET' for method, _ in self.calls))
def test_confirmed_order_is_created_once_and_found_on_resend(self):
code, text = self.probe('pedido', '--cnpj', '11222333000181', '--email', 'a@example.test',
'--celular', '16999999999', '--modo', 'uv', '--confirmar')
self.assertEqual(code, 0, text)
self.assertEqual(len(self.orders), 1)
self.assertEqual(self.orders[0]['itens'][0]['produto'], {'id': 104})
self.assertIn('2º envio: already-created', text)
def test_resend_is_skipped_when_the_search_cannot_find_the_order(self):
from app import tiny_probe
blind = lambda request: (httpx.Response(200, json={'itens': []})
if request.method == 'GET' and request.url.path.endswith('/pedidos')
else self.handler(request))
self.tiny = TinyOrders(auth=FakeAuth(), transport=httpx.MockTransport(blind), today=date(2026, 9, 24))
payload = tiny_probe.test_order('11222333000181', 'a@example.test', '16999999999', 'file')
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])
if __name__ == '__main__':
unittest.main()