Files
dtf-system/tests/test_tiny.py
Cauê Faleiros b3ecba590b
All checks were successful
Build and deploy / Validate source (push) Successful in 7s
Build and deploy / Integration suite on a real stack (push) Successful in 7m45s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Successful in 1m25s
fix: customer credit reaches Tiny as CREDITO PRE-PAGO, with its own marcador beside SITE DTF (#42)
Marcus, 2026-11-18: "Pago fora do site › Crédito do cliente" maps to the
forma de recebimento CREDITO PRE-PAGO (987762591), and the order also
gets the marcador CREDITO PRE-PAGO. CORREÇÃO DTF, refused by Tiny for
#42, is for correction orders only. A retry adds only the marcadores
the order is missing.

The outbox computes the forma when it delivers, so #42's queued sale
goes through on its next retry after the deploy.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-18 12:24:21 -03:00

894 lines
52 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""The Tiny v3 adapter against a fake HTTP transport: payload and idempotency.
This proves the documented contract only; the client's account must still
confirm products, contacts and order fields. Runs where httpx is installed.
The OAuth connection against the real database is tests/tiny_oauth_test.py.
"""
import json
import os
import unittest
from datetime import date
from unittest import mock
import httpx
from app import tiny as tiny_module
from app.tiny import TinyError, TinyOrders, contact_payload, order_payload
PAID = {'order_id': 'b6f1c0de-0000-4000-8000-000000000001', 'number': 42, 'event': 'payment_approved',
'order': {'customer': {'cnpj': '11222333000181', 'zap': '16999999999', 'mail': 'loja@example.test'},
'items': [{'mode': 'avulsa', 'grade': 90, 'billed_metres': '2.8', 'unit_cents': 2490}],
'freight': {'service': 'mock-standard', 'total_cents': 1500},
'destination': {'recipient': 'Loja Teste', 'street': 'Rua A', 'number': '10',
'complement': '', 'district': 'Centro', 'city': 'Franca',
'state': 'SP', 'postal_code': '14400000'},
'total_cents': 8472}}
PRODUCTS = {'TINY_PRODUCT_TEXTIL_FOLHA': '101', 'TINY_PRODUCT_TEXTIL_AVULSA': '102',
'TINY_PRODUCT_UV_FOLHA': '103', 'TINY_PRODUCT_UV_AVULSA': '104',
'TINY_PRODUCT_TEXTIL_PREMIUM': '105', 'TINY_FORMA_ENVIO_RETIRADA': '77'}
PICKUP = {**PAID, 'order': {**PAID['order'], 'destination': None, 'freight': {'service': 'pickup', 'total_cents': 0}}}
READY = {'order_id': PAID['order_id'], 'number': 42, 'event': 'ready', 'reason': '', 'order': PICKUP['order']}
def product_ids(cls):
"""These tests sell by product id: without Dropstar's SKU defaults."""
for name in ('SKU_DEFAULTS', 'STEP_DEFAULTS', 'METRE_DEFAULTS'):
cls = mock.patch.dict(f'app.tiny.{name}', {}, clear=True)(cls)
return cls
class FakeAuth:
def access_token(self):
return 'access-1'
class FakeTinyCase(unittest.TestCase):
"""A Tiny account in memory: contacts, orders, products and formas de envio."""
def setUp(self):
self.contacts = []
self.orders = []
self.calls = []
self.refuse_status = 0
self.refuse_tag = 0
self.tags = {}
self.methods = {'77': {'id': 77, 'nome': 'Retirar pessoalmente', 'tipo': '6',
'formasFrete': [{'id': 771, 'nome': 'Retirar em loja'}]},
'78': {'id': 78, 'nome': 'Correios', 'tipo': '1',
'formasFrete': [{'id': 782, 'nome': 'SEDEX CONTRATO AG (03220)', 'codigo': '03220'},
{'id': 781, 'nome': 'PAC CONTRATO AG (03298)', 'codigo': '03298'}]},
'80': {'id': 80, 'nome': 'Jadlog', 'tipo': '7',
'formasFrete': [{'id': 801, 'nome': '.PACKAGE', 'codigo': '3'}]}}
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()}
# Ajuste Fino, per art: the SKU Marcus registered (2026-11-12).
self.products['106'] = {'id': 106, 'sku': 'DTFIMP.AJF.UN', 'descricao': 'Ajuste Fino',
'situacao': 'A', 'precos': {'preco': 6.9}}
def handler(request):
path = request.url.path.removeprefix('/public-api/v3')
self.calls.append((request.method, path))
assert request.headers['authorization'] == 'Bearer access-1'
# Like Tiny: cpfCnpj matches the text the contact was saved with, punctuation and all.
if request.method == 'GET' and path == '/contatos':
cnpj = request.url.params.get('cpfCnpj')
return httpx.Response(200, json={'itens': [c for c in self.contacts if cnpj in (None, c['cpfCnpj'])]})
if request.method == 'POST' and path == '/contatos':
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.startswith('/formas-envio/'):
wanted = path.rsplit('/', 1)[-1]
if wanted not in self.methods:
return httpx.Response(404, json={'mensagem': 'não encontrado'})
return httpx.Response(200, json=self.methods[wanted])
if request.method == 'GET' and path == '/formas-envio':
return httpx.Response(200, json={'itens': list(self.methods.values())})
if request.method == 'PUT' and path.startswith('/pedidos/') and path.endswith('/situacao'):
if self.refuse_status:
self.refuse_status -= 1
return httpx.Response(503, text='indisponível')
wanted = int(path.split('/')[2])
next(o for o in self.orders if o['id'] == wanted)['situacao'] = json.loads(request.content)['situacao']
return httpx.Response(204)
if request.method == 'GET' and path == '/pedidos':
cnpj = request.url.params.get('cpfCnpj')
owners = {c['id'] for c in self.contacts if cnpj in (None, c['cpfCnpj'])}
return httpx.Response(200, json={'itens': [{'id': o['id'], 'numeroPedido': o['numeroPedido']}
for o in self.orders
if cnpj is None or o.get('idContato') in owners]})
if path.startswith('/pedidos/') and path.endswith('/marcadores'):
wanted = int(path.split('/')[2])
if request.method == 'GET':
return httpx.Response(200, json=self.tags.get(wanted, []))
if self.refuse_tag:
self.refuse_tag -= 1
return httpx.Response(503, text='indisponível')
self.tags.setdefault(wanted, []).extend(json.loads(request.content))
return httpx.Response(204)
if request.method == 'GET' and path.startswith('/pedidos/'):
wanted = int(path.rsplit('/', 1)[-1])
return httpx.Response(200, json=next(o for o in self.orders if o['id'] == wanted))
if request.method == 'POST' and path == '/pedidos':
order = {'situacao': 0, **json.loads(request.content), 'id': 9000 + len(self.orders),
'numeroPedido': str(100 + len(self.orders))}
self.orders.append(order)
return httpx.Response(200, json={'id': order['id'], 'numeroPedido': order['numeroPedido']})
return httpx.Response(404)
self.handler = handler
self.tiny = TinyOrders(auth=FakeAuth(), transport=httpx.MockTransport(handler),
today=date(2026, 9, 24))
@product_ids
@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']),
(777, 'DTF-42', '2026-09-24'))
# The DTF number is also the e-commerce order number; no channel unless one is set.
self.assertEqual(pedido['ecommerce'], {'numeroPedidoEcommerce': 'DTF-42'})
with mock.patch.dict(os.environ, {'TINY_ECOMMERCE_ID': '555'}):
self.assertEqual(order_payload(PAID, 777)['ecommerce'], {'numeroPedidoEcommerce': 'DTF-42', 'id': 555})
item = pedido['itens'][0]
self.assertEqual((item['produto'], item['quantidade'], item['valorUnitario']),
({'id': 102}, 2.8, 24.9))
self.assertEqual(pedido['valorFrete'], 15.0)
self.assertEqual((pedido['enderecoEntrega']['cep'], pedido['enderecoEntrega']['enderecoNro'],
pedido['enderecoEntrega']['nomeDestinatario']), ('14400000', '10', 'Loja Teste'))
contact = contact_payload(PAID['order'])
self.assertEqual((contact['tipoPessoa'], contact['cpfCnpj'], contact['endereco']['uf']),
('J', '11.222.333/0001-81', 'SP'))
def test_only_a_montador_venda_names_its_seller(self):
# No seller: Tiny's channel sets it (Dropstar, 2026-10-23).
self.assertNotIn('vendedor', order_payload(PAID, 777, date(2026, 9, 24)))
# A Venda carries who assembled it (Marcus, 2026-11-17).
venda = {**PAID, 'order': {**PAID['order'], 'seller': {'id': 2001, 'name': 'Lais'}}}
self.assertEqual(order_payload(venda, 777, date(2026, 9, 24))['vendedor'], {'id': 2001})
pickup = order_payload({**PAID, 'order': {**PAID['order'], 'destination': None,
'freight': {'service': 'pickup', 'total_cents': 0}}}, 1)
self.assertNotIn('enderecoEntrega', pickup)
self.assertIn('retirada', pickup['observacoes'])
def test_treatment_is_a_line_and_one_more_day(self):
base = {**PAID['order'],
'freight': {'service': 'mock-standard', 'total_cents': 1500, 'days': 3}}
plain = {'order': base, **{k: v for k, v in PAID.items() if k != 'order'}}
treatment = {'order': {**base, 'treatment': {'cents': 990, 'hours': 24},
'total_cents': base['total_cents'] + 990},
**{k: v for k, v in PAID.items() if k != 'order'}}
# Ajuste Fino is sold by the SKU Marcus registered, found in the
# catalogue: the arts are its quantity and the band its unit price.
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '', 'TINY_SKU_TREATMENT': ''}):
pedido = order_payload(treatment, 777, date(2026, 9, 24), product_id=self.tiny.product_id)
self.assertIn({'produto': {'id': 106}, 'quantidade': 1, 'valorUnitario': 9.9,
'infoAdicional': 'Ajuste Fino · 1 arte · +24 h'}, pedido['itens'])
self.assertNotEqual(pedido['dataPrevista'], order_payload(plain, 777, date(2026, 9, 24))['dataPrevista'])
# Per art: the quantity is the number of arts and the unit is the band price.
per_art = {'order': {**base, 'treatment': {'cents': 2070, 'hours': 24, 'arts': 3,
'unit_cents': 690},
'total_cents': base['total_cents'] + 2070},
**{k: v for k, v in PAID.items() if k != 'order'}}
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '', 'TINY_SKU_TREATMENT': ''}):
pedido = order_payload(per_art, 777, date(2026, 9, 24), product_id=self.tiny.product_id)
self.assertIn({'produto': {'id': 106}, 'quantidade': 3, 'valorUnitario': 6.9,
'infoAdicional': 'Ajuste Fino · 3 artes · +24 h'}, pedido['itens'])
# The numeric id, when the client gives one, still wins.
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '105'}):
pedido = order_payload(per_art, 777, date(2026, 9, 24))
self.assertIn({'produto': {'id': 105}, 'quantidade': 3, 'valorUnitario': 6.9,
'infoAdicional': 'Ajuste Fino · 3 artes · +24 h'}, pedido['itens'])
# Without the numeric id, the catalogue lookup is required before sending.
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '', 'TINY_SKU_TREATMENT': ''}):
with self.assertRaisesRegex(TinyError, 'TINY_SKU_TREATMENT'):
order_payload(treatment, 777, date(2026, 9, 24))
def test_faturado_boleto_carries_its_bank_account_on_the_installment(self):
boleto = {'TINY_RECEIPT_BOLETO': '919478947'}
with mock.patch.dict(os.environ, {**boleto, 'TINY_BOLETO_ACCOUNT': '977344551'}), \
mock.patch.dict(tiny_module.RECEIPT_METHODS, {'faturado': 919478947}):
pedido = order_payload({**PAID, 'payment': {'method': 'faturado'}}, 777, date(2026, 9, 24))
self.assertEqual(pedido['pagamento']['formaRecebimento'], {'id': 919478947})
# Every installment names the account: Tiny must not choose its preferred one.
self.assertEqual(pedido['pagamento']['parcelas'], [{
'dias': 0, 'data': '2026-09-24', 'valor': 84.72,
'formaRecebimento': {'id': 919478947}, 'meioPagamento': {'id': 977344551}}])
self.assertIn('faturado (Boleto)', pedido['observacoesInternas'])
# Without the account setting, no account is sent at all.
with mock.patch.dict(os.environ, {**boleto, 'TINY_BOLETO_ACCOUNT': ''}), \
mock.patch.dict(tiny_module.RECEIPT_METHODS, {'faturado': 919478947}):
pedido = order_payload({**PAID, 'payment': {'method': 'faturado'}}, 777, date(2026, 9, 24))
self.assertNotIn('meioPagamento', pedido['pagamento']['parcelas'][0])
# A pix order never gets the boleto account.
with mock.patch.dict(os.environ, {'TINY_BOLETO_ACCOUNT': '977344551'}):
pedido = order_payload({**PAID, 'payment': {'method': 'pix'}}, 777, date(2026, 9, 24))
self.assertNotIn('meioPagamento', pedido['pagamento']['parcelas'][0])
def test_the_check_lists_ajuste_fino_by_its_sku(self):
from app.tiny import check
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '', 'TINY_SKU_TREATMENT': ''}):
self.assertEqual(check(orders=self.tiny)['Ajuste Fino'], 'ok')
self.products['106']['situacao'] = 'I'
self.tiny.skus.clear()
self.assertIn('DTFIMP.AJF.UN', check(orders=self.tiny)['Ajuste Fino'])
def test_second_delivery_finds_the_first_order(self):
first = self.tiny.deliver('k1', PAID)
second = self.tiny.deliver('k1', PAID)
self.assertEqual((first['status'], second['status']), ('created', 'already-created'))
self.assertEqual(first['tiny_id'], second['tiny_id'])
self.assertEqual(self.calls.count(('POST', '/pedidos')), 1)
self.assertEqual(self.calls.count(('POST', '/contatos')), 1)
def test_existing_contact_is_reused(self):
# As Tiny keeps it: found only by the punctuated CNPJ.
self.contacts.append({'id': 321, 'cpfCnpj': '11.222.333/0001-81'})
self.tiny.deliver('k1', PAID)
self.assertNotIn(('POST', '/contatos'), self.calls)
self.assertEqual(self.orders[0]['idContato'], 321)
# The order is found again by the same contact: a resend creates nothing.
self.assertEqual(self.tiny.deliver('k1', PAID)['status'], 'already-created')
self.assertEqual(len(self.orders), 1)
def test_a_contact_typed_without_punctuation_is_found_too(self):
self.contacts.append({'id': 322, 'cpfCnpj': '11222333000181'})
self.tiny.deliver('k1', PAID)
self.assertNotIn(('POST', '/contatos'), self.calls)
self.assertEqual(self.orders[0]['idContato'], 322)
self.assertEqual(self.tiny.deliver('k1', PAID)['status'], 'already-created')
self.assertEqual(len(self.orders), 1)
def test_an_existing_cpf_contact_is_found_by_its_punctuated_cpf(self):
self.contacts.append({'id': 760799765, 'cpfCnpj': '130.323.978-71', 'nome': 'Teste Fernandes'})
person = {**PAID, 'order': {**PAID['order'], 'customer': {**PAID['order']['customer'], 'cnpj': '13032397871'}}}
self.tiny.deliver('k-cpf', person)
self.assertNotIn(('POST', '/contatos'), self.calls)
self.assertEqual(self.orders[0]['idContato'], 760799765)
def test_a_cpf_customer_is_a_person_and_not_looked_up_in_the_company_registry(self):
looked_up = []
self.tiny.names = lambda document: looked_up.append(document)
person = {**PAID, 'order': {**PAID['order'], 'customer': {**PAID['order']['customer'], 'cnpj': '52998224725'}}}
self.tiny.deliver('k-cpf', person)
self.assertEqual((self.contacts[0]['tipoPessoa'], self.contacts[0]['cpfCnpj'], self.contacts[0]['nome']),
('F', '529.982.247-25', 'Loja Teste'))
# With the name the Site now asks for, the contact is the person's.
named = {**person['order'], 'customer': {**person['order']['customer'], 'name': 'Maria da Silva'}}
self.assertEqual(contact_payload(named)['nome'], 'Maria da Silva')
self.assertEqual(looked_up, [])
def test_production_events_are_not_sent(self):
self.assertEqual(self.tiny.deliver('k2', {**PAID, 'event': 'ready'})['status'], 'not-applicable')
self.assertEqual(self.calls, [])
def test_missing_product_mapping_fails_rather_than_guessing(self):
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TEXTIL_AVULSA': ''}):
with self.assertRaises(TinyError):
self.tiny.deliver('k3', PAID)
self.assertNotIn(('POST', '/pedidos'), self.calls)
def test_connection_check_only_reads(self):
from app.tiny import check
results = check(auth=FakeAuth(), transport=httpx.MockTransport(self.handler))
self.assertEqual(set(results.values()), {'ok'})
self.assertEqual(len(results), 9)
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 27 cm · folha montada'])
self.assertEqual(results['DTF UV 27 cm · artes avulsas'], 'TINY_PRODUCT_UV_AVULSA sem id')
self.assertEqual(results['pedidos'], 'ok')
# The order list is asked by date: unfiltered, Tiny times out on a large account.
asked = []
def timing_out(request):
if request.url.path.endswith('/pedidos'):
asked.append(dict(request.url.params))
if 'dataInicial' not in request.url.params:
return httpx.Response(400, json={'mensagem': 'Sua consulta levou muito tempo.'})
return self.handler(request)
self.assertEqual(check(auth=FakeAuth(), transport=httpx.MockTransport(timing_out))['pedidos'], 'ok')
self.assertEqual(asked[-1]['limit'], '1')
denied = check(auth=FakeAuth(), transport=httpx.MockTransport(lambda r: httpx.Response(403, text='forbidden')))
self.assertTrue(denied['pedidos'].startswith('GET /pedidos: 403'))
def test_rate_limit_is_a_retryable_failure(self):
tiny = TinyOrders(auth=FakeAuth(), transport=httpx.MockTransport(lambda r: httpx.Response(429)))
with self.assertRaisesRegex(TinyError, 'rate limit'):
tiny.deliver('k4', PAID)
@product_ids
@mock.patch.dict(os.environ, PRODUCTS)
class TinyStatusTests(FakeTinyCase):
"""Situações that the client's Tiny -> n8n notices turn into WhatsApp messages."""
def puts(self):
return [call for call in self.calls if call[0] == 'PUT']
def test_nothing_changes_while_status_updates_are_off(self):
self.assertEqual(self.tiny.deliver('k1', PICKUP)['status'], 'created')
self.assertEqual(self.orders[0]['situacao'], 0)
self.assertEqual(self.tiny.deliver('k2', READY)['status'], 'not-applicable')
self.assertEqual(self.puts(), [])
@mock.patch.dict(os.environ, {'TINY_STATUS_UPDATES': 'true'})
def test_paid_order_is_approved_once(self):
first = self.tiny.deliver('k1', PICKUP)
self.assertEqual((first['status'], first['situacao']), ('created', 'Aprovada'))
self.assertEqual(self.orders[0]['situacao'], 3)
second = self.tiny.deliver('k1', PICKUP)
self.assertEqual(second['status'], 'already-created')
self.assertNotIn('situacao', second)
self.assertEqual(len(self.puts()), 1)
@mock.patch.dict(os.environ, {'TINY_STATUS_UPDATES': 'true'})
def test_retry_after_a_failed_approval_finishes_it(self):
self.refuse_status = 1
with self.assertRaises(TinyError):
self.tiny.deliver('k1', PICKUP)
self.assertEqual((len(self.orders), self.orders[0]['situacao']), (1, 0))
retry = self.tiny.deliver('k1', PICKUP)
self.assertEqual((retry['status'], retry['situacao']), ('already-created', 'Aprovada'))
self.assertEqual(self.calls.count(('POST', '/pedidos')), 1)
@mock.patch.dict(os.environ, {'TINY_STATUS_UPDATES': 'true'})
def test_an_order_already_moved_on_is_not_approved_again(self):
self.tiny.deliver('k1', PICKUP)
self.orders[0]['situacao'] = 7
self.tiny.deliver('k1', PICKUP)
self.assertEqual(self.orders[0]['situacao'], 7)
@mock.patch.dict(os.environ, {'TINY_STATUS_UPDATES': 'true'})
def test_ready_pickup_order_is_set_ready_once_by_its_known_id(self):
sale = self.tiny.deliver('k1', PICKUP)
self.calls.clear()
ready = self.tiny.deliver('k2', {**READY, 'tiny_id': sale['tiny_id']})
self.assertEqual((ready['status'], ready['situacao'], ready['tiny_number']),
('status-updated', 'Pronto para envio', sale['tiny_number']))
self.assertEqual(self.orders[0]['situacao'], 7)
self.assertNotIn(('GET', '/pedidos'), self.calls, 'a known id needs no search')
again = self.tiny.deliver('k2', {**READY, 'tiny_id': sale['tiny_id']})
self.assertEqual(again['status'], 'status-unchanged')
self.assertEqual(len(self.puts()), 1)
@mock.patch.dict(os.environ, {'TINY_STATUS_UPDATES': 'true'})
def test_ready_without_an_id_finds_the_order(self):
self.tiny.deliver('k1', PICKUP)
self.assertEqual(self.tiny.deliver('k2', READY)['status'], 'status-updated')
self.assertEqual(self.orders[0]['situacao'], 7)
@mock.patch.dict(os.environ, {'TINY_STATUS_UPDATES': 'true'})
def test_ready_before_the_sale_reached_tiny_is_retried(self):
with self.assertRaisesRegex(TinyError, 'not in Tiny yet'):
self.tiny.deliver('k2', READY)
self.assertEqual(self.puts(), [])
@mock.patch.dict(os.environ, {'TINY_STATUS_UPDATES': 'true'})
def test_a_finished_delivery_order_is_ready_too(self):
# Dropstar's flow, 2026-10-23: Finalizado is "Pronto para envio" for every order.
sale = self.tiny.deliver('k1', PAID)
ready = self.tiny.deliver('k2', {**READY, 'order': PAID['order'], 'tiny_id': sale['tiny_id']})
self.assertEqual((ready['status'], ready['situacao']), ('status-updated', 'Pronto para envio'))
self.assertEqual(self.orders[0]['situacao'], 7)
@mock.patch.dict(os.environ, {'TINY_STATUS_UPDATES': 'true'})
def test_the_queue_is_preparando_envio_but_never_moves_an_invoiced_order_back(self):
sale = self.tiny.deliver('k1', PAID)
started = {**READY, 'event': 'production_started', 'order': PAID['order'], 'tiny_id': sale['tiny_id']}
moved = self.tiny.deliver('k2', started)
self.assertEqual((moved['status'], moved['situacao'], self.orders[0]['situacao']),
('status-updated', 'Preparando envio', 4))
self.orders[0]['situacao'] = 1 # the team invoiced it
self.assertEqual(self.tiny.deliver('k2', started)['status'], 'status-unchanged')
self.assertEqual(self.orders[0]['situacao'], 1)
@mock.patch.dict(os.environ, {'TINY_STATUS_UPDATES': 'true'})
def test_a_cancelled_order_is_cancelled_in_tiny_unless_invoiced(self):
self.tiny.deliver('k1', PAID)
cancelled = {**READY, 'event': 'cancelled', 'order': PAID['order']}
done = self.tiny.deliver('k3', cancelled)
self.assertEqual((done['status'], done['situacao'], self.orders[0]['situacao']),
('status-updated', 'Cancelada', 2))
self.orders[0]['situacao'] = 1
kept = self.tiny.deliver('k3', cancelled)
self.assertEqual((kept['status'], kept['situacao'], self.orders[0]['situacao']),
('status-unchanged', 'Faturada', 1))
def test_printing_and_cancelling_change_nothing_while_status_updates_are_off(self):
self.tiny.deliver('k1', PAID)
self.calls.clear()
for event in ('production_started', 'cancelled'):
self.assertEqual(self.tiny.deliver('k', {**READY, 'event': event, 'order': PAID['order']})['status'],
'not-applicable')
self.assertEqual(self.calls, [])
def test_orders_are_filled_in_as_the_store_s_own(self):
from datetime import date
from app.tiny import CATEGORY, PICKUP_CARRIER, RECEIPT_METHODS
self.assertEqual(CATEGORY, 986932924) # DTF SITE, Dropstar 2026-10-26
thursday = date(2026, 9, 24)
with mock.patch.dict(os.environ, {'FREIGHT_PRODUCTION_DAYS': '1'}):
pickup = order_payload({**PICKUP, 'payment': {'method': 'pix'}}, 1, thursday, shipping=self.tiny.shipping)
# Pickup: the DropStar carrier, "Retirar pessoalmente" and "Retirar em loja", ready after production.
self.assertEqual(pickup['transportador'], {'fretePorConta': 'R', 'id': PICKUP_CARRIER,
'formaEnvio': {'id': 77}, 'formaFrete': {'id': 771}})
self.assertEqual(pickup['dataPrevista'], '2026-09-25')
self.assertEqual(pickup['pagamento'], {'categoria': {'id': CATEGORY}, 'formaRecebimento': {'id': RECEIPT_METHODS['pix']},
'parcelas': [{'dias': 0, 'data': '2026-09-24', 'valor': 84.72, 'formaRecebimento': {'id': RECEIPT_METHODS['pix']}}]})
# Delivery: the Correios contract's PAC or SEDEX, or Jadlog; the date in working days.
for service, method, frete in (('pac', 78, 781), ('sedex', 78, 782), ('jadlog', 80, 801)):
order = {**PAID['order'], 'freight': {'service': service, 'total_cents': 1500, 'days': 6}}
sent = order_payload({**PAID, 'order': order, 'payment': {'method': 'card'}}, 1, thursday,
shipping=self.tiny.shipping)
self.assertEqual(sent['transportador'], {'fretePorConta': 'R', 'formaEnvio': {'id': method},
'formaFrete': {'id': frete}}, service)
self.assertEqual(sent['dataPrevista'], '2026-10-02')
self.assertEqual(sent['pagamento']['formaRecebimento'], {'id': RECEIPT_METHODS['card']})
# Looked up once per service.
self.assertEqual(self.calls.count(('GET', '/formas-envio/78')), 2)
# A test order, or a carrier Tiny does not have: the order still goes, without them,
# in the store's category all the same, and with no seller: the team links one in Tiny.
plain = order_payload(PAID, 1, thursday, shipping=self.tiny.shipping)
self.assertNotIn('transportador', plain)
self.assertEqual(plain['pagamento'], {'categoria': {'id': CATEGORY}})
self.assertNotIn('vendedor', plain)
self.assertTrue(plain['observacoesInternas'].startswith('Site DTF · pago · '))
# An order the team registered (D-35): its origin, and how it was paid
# outside the site, each way named as Tiny's forma de recebimento.
counter = order_payload({**PAID, 'origin': 'atendimento', 'payment': {'method': 'cash', 'outside': True}},
1, thursday, shipping=self.tiny.shipping)
self.assertTrue(counter['observacoesInternas'].startswith('Atendimento DTF · pago fora do site (dinheiro) · '))
self.assertEqual(counter['pagamento']['categoria'], {'id': CATEGORY})
self.assertEqual(counter['pagamento']['formaRecebimento'], {'id': RECEIPT_METHODS['cash']})
pix = order_payload({**PAID, 'origin': 'atendimento', 'payment': {'method': 'pix', 'outside': True}},
1, thursday, shipping=self.tiny.shipping)
self.assertEqual(pix['pagamento']['formaRecebimento'], {'id': RECEIPT_METHODS['pix']})
self.assertEqual(pix['pagamento']['categoria'], {'id': CATEGORY})
# Dinheiro (Marcus, 2026-10-27) and the customer's credit, CREDITO
# PRE-PAGO (Marcus, 2026-11-18; no longer CORREÇÃO DTF).
self.assertEqual((RECEIPT_METHODS['cash'], RECEIPT_METHODS['credit']), (919478944, 987762591))
# A Dropflow order goes in DTF DROPFLOW, not DTF SITE (D-21).
batch = order_payload({**PAID, 'origin': 'dropflow', 'payment': {'method': 'credit', 'outside': True}},
1, thursday, shipping=self.tiny.shipping)
self.assertEqual(batch['pagamento']['categoria'], {'id': 987032506})
self.assertEqual(batch['pagamento']['formaRecebimento'], {'id': 987762591})
self.assertTrue(batch['observacoesInternas'].startswith('Dropflow DTF · pago fora do site (crédito do cliente) · '))
def test_the_order_is_tagged_kanbandtf_once(self):
first = self.tiny.deliver('k1', PAID)
self.assertEqual(first['marcador'], 'SITE DTF')
tiny_id = self.orders[0]['id']
self.assertEqual(self.tags[tiny_id], [{'descricao': 'SITE DTF'}])
# A second delivery finds the order and its tag, and adds nothing.
self.tiny.deliver('k1', PAID)
self.assertEqual(len(self.orders), 1)
self.assertEqual(self.tags[tiny_id], [{'descricao': 'SITE DTF'}])
def test_customer_credit_also_carries_the_credito_pre_pago_marcador(self):
credit = {**PAID, 'payment': {'method': 'credit', 'outside': True}}
first = self.tiny.deliver('k1', credit)
self.assertEqual(first['marcador'], 'SITE DTF, CREDITO PRE-PAGO')
tiny_id = self.orders[0]['id']
self.assertEqual(self.orders[0]['pagamento']['formaRecebimento'], {'id': 987762591})
self.assertEqual(self.tags[tiny_id], [{'descricao': 'SITE DTF'}, {'descricao': 'CREDITO PRE-PAGO'}])
# A retry adds only what is missing.
self.tags[tiny_id] = [{'descricao': 'SITE DTF'}]
self.tiny.deliver('k1', credit)
self.assertEqual(self.tags[tiny_id], [{'descricao': 'SITE DTF'}, {'descricao': 'CREDITO PRE-PAGO'}])
def test_a_failed_tag_is_retried_without_a_second_order(self):
self.refuse_tag = 1
with self.assertRaises(TinyError):
self.tiny.deliver('k1', PAID)
self.assertEqual(len(self.orders), 1)
retry = self.tiny.deliver('k1', PAID)
self.assertEqual((retry['status'], retry['marcador']), ('already-created', 'SITE DTF'))
self.assertEqual(len(self.orders), 1)
self.assertEqual(self.tags[self.orders[0]['id']], [{'descricao': 'SITE DTF'}])
def test_pickup_forma_de_envio_is_found_by_name(self):
from app.tiny import check, find_pickup
with mock.patch.dict(os.environ, {'TINY_FORMA_ENVIO_RETIRADA': ''}):
self.tiny.deliver('k1', PICKUP)
self.assertEqual(self.orders[0]['transportador']['formaEnvio'], {'id': 77})
self.assertEqual(check(orders=self.tiny)['forma de envio de retirada'], 'ok')
# Dropstar's account also has "Retirar na loja": the exact name wins.
self.methods['79'] = {'id': 79, 'nome': 'Retirar na loja', 'tipo': '6'}
self.assertEqual(check(orders=self.tiny)['forma de envio de retirada'], 'ok')
self.assertEqual(find_pickup(self.tiny)[0]['id'], 77)
self.methods['77']['nome'] = 'Retirar no balcão'
self.assertIn('mais de uma', check(orders=self.tiny)['forma de envio de retirada'])
del self.methods['77'], self.methods['79']
self.assertIn('nenhuma', check(orders=self.tiny)['forma de envio de retirada'])
TEXTIL = {**PAID, 'order': {**PAID['order'], 'items': [
{'mode': 'file', 'grade': 100, 'billed_metres': '2.8', 'unit_cents': 1490, 'total_cents': 4172}]}}
@product_ids
@mock.patch.dict(os.environ, {**PRODUCTS, 'TINY_SKU_TEXTIL_FOLHA': 'DTFIMP.TX'})
class TinySkuTests(FakeTinyCase):
"""Têxtil folha sold as the client's SKUs: 1 metro plus 10 to 90 cm."""
def setUp(self):
super().setUp()
skus = {'DTFIMP.TX.100CM': 200, **{f'DTFIMP.TX.{cm:04d}CM': 200 + cm // 10 for cm in range(10, 100, 10)},
# Same family, different product: must never be taken for 10 cm.
'DTFIMP.TX.010CM': 299}
for code, pid in skus.items():
self.products[str(pid)] = {'id': pid, 'sku': code, 'descricao': code, 'situacao': 'A'}
def test_metres_become_metre_skus_plus_one_centimetre_sku_at_the_price_paid(self):
self.tiny.deliver('k1', TEXTIL)
lines = [(i['produto']['id'], i['quantidade'], i['valorUnitario']) for i in self.orders[0]['itens']]
# 2,80 m at R$ 14,90: 2 × "1 metro" + 1 × "80 cm", adding up to R$ 41,72.
self.assertEqual(lines, [(200, 2, 14.9), (208, 1, 11.92)])
self.assertAlmostEqual(sum(q * v for _, q, v in lines), 41.72)
self.assertIn('2.8 m', self.orders[0]['itens'][0]['infoAdicional'])
# Each code is looked up once, then remembered.
self.tiny.deliver('k2', {**TEXTIL, 'number': 43})
self.assertEqual(self.calls.count(('GET', '/produtos')), 2)
def test_whole_metres_and_small_rests(self):
from app.tiny import sku_lines
item = lambda metres: {'billed_metres': metres, 'unit_cents': 1990}
self.assertEqual(sku_lines(item('1'), 'P'), [('P.100CM', 1, 1990)])
self.assertEqual(sku_lines(item('1.3'), 'P'), [('P.100CM', 1, 1990), ('P.0030CM', 1, 597)])
self.assertEqual(sku_lines(item('12.4'), 'P'), [('P.100CM', 12, 1990), ('P.0040CM', 1, 796)])
with self.assertRaises(TinyError):
sku_lines(item('1.25'), 'P')
def test_a_missing_sku_fails_before_the_order_is_created(self):
del self.products['208']
with self.assertRaisesRegex(TinyError, 'DTFIMP.TX.0080CM'):
self.tiny.deliver('k3', TEXTIL)
self.assertNotIn(('POST', '/pedidos'), self.calls)
def test_other_modes_keep_their_product_id(self):
self.tiny.deliver('k4', PAID)
self.assertEqual(self.orders[0]['itens'][0]['produto'], {'id': 102})
def test_settings_check_and_probe_report_the_skus(self):
from app.tiny import check, required_settings
self.assertNotIn('TINY_PRODUCT_TEXTIL_FOLHA', required_settings())
self.assertIn('TINY_PRODUCT_TEXTIL_AVULSA', required_settings())
self.assertEqual(check(orders=self.tiny)['DTF Têxtil 57 cm · folha montada'], 'ok')
self.products['205']['situacao'] = 'I'
self.tiny.skus.clear()
self.assertIn('DTFIMP.TX.0050CM', check(orders=self.tiny)['DTF Têxtil 57 cm · folha montada'])
from app import tiny_probe
lines = []
tiny_probe.main(['pedido', '--cnpj', '11222333000181', '--email', 'a@example.test',
'--celular', '16999999999', '--metros', '1,3'], orders=self.tiny, out=lines.append)
text = '\n'.join(lines)
# 1,30 m at the single price, R$ 19,90: one "1 metro" and three "10 cm".
self.assertIn('"quantidade": 1', text)
self.assertIn('"valorUnitario": 19.9', text)
self.assertIn('"valorUnitario": 5.97', text)
# A new contact is previewed with the name it will get.
self.assertIn('será criado como "a@example.test"', text)
self.tiny.names = lambda cnpj: {'legal': 'EMPRESA TESTE LTDA', 'trade': 'Teste'}
lines.clear()
tiny_probe.main(['pedido', '--cnpj', '11222333000182', '--email', 'a@example.test',
'--celular', '16999999999'], orders=self.tiny, out=lines.append)
self.assertIn('será criado como "EMPRESA TESTE LTDA"', '\n'.join(lines))
self.assertEqual(self.orders, [])
UV = {**PAID, 'order': {**PAID['order'], 'items': [
{'mode': 'uvfile', 'grade': 100, 'billed_metres': '2.3', 'unit_cents': 6990, 'total_cents': 16077}]}}
@product_ids
@mock.patch.dict(os.environ, {**PRODUCTS, 'TINY_SKU10_UV_FOLHA': 'DTFIMP.UV.010CM'})
class TinyStepSkuTests(FakeTinyCase):
"""UV sold as one SKU per 10 cm, the only UV SKU the client has."""
def setUp(self):
super().setUp()
self.products['300'] = {'id': 300, 'sku': 'DTFIMP.UV.010CM', 'descricao': 'UV 10 cm', 'situacao': 'A'}
def test_the_length_in_ten_centimetre_steps_at_the_price_paid(self):
self.tiny.deliver('k1', UV)
lines = [(i['produto']['id'], i['quantidade'], i['valorUnitario']) for i in self.orders[0]['itens']]
self.assertEqual(lines, [(300, 23, 6.99)]) # 2,30 m at R$ 69,90 = R$ 160,77
def test_a_rest_that_does_not_divide_gets_its_own_line(self):
from app.tiny import step_lines
lines = step_lines({'billed_metres': '1.3', 'unit_cents': 1495}, 'C')
self.assertEqual(lines, [('C', 12, 149), ('C', 1, 155)])
self.assertEqual(sum(q * c for _, q, c in lines), 1943)
def test_settings_and_check_know_the_step_sku(self):
from app.tiny import check, required_settings
self.assertNotIn('TINY_PRODUCT_UV_FOLHA', required_settings())
self.assertEqual(check(orders=self.tiny)['DTF UV 27 cm · folha montada'], 'ok')
del self.products['300']
self.tiny.skus.clear()
self.assertIn('DTFIMP.UV.010CM', check(orders=self.tiny)['DTF UV 27 cm · folha montada'])
@product_ids
@mock.patch.dict(os.environ, {**PRODUCTS, 'TINY_SKU10_UV_FOLHA': 'DTFIMP.UV.010CM',
'TINY_SKU_METRO_UV_FOLHA': 'DTFIMP.UV.1MT'})
class TinyMetreAndStepSkuTests(FakeTinyCase):
"""UV as the client registered it: DTFIMP.UV.1MT per metre and DTFIMP.UV.010CM per 10 cm."""
def setUp(self):
super().setUp()
self.products['300'] = {'id': 300, 'sku': 'DTFIMP.UV.010CM', 'descricao': 'UV 10 cm', 'situacao': 'A'}
self.products['301'] = {'id': 301, 'sku': 'DTFIMP.UV.1MT', 'descricao': 'UV 1 metro', 'situacao': 'A'}
def test_whole_metres_then_ten_centimetre_steps(self):
self.tiny.deliver('k1', UV)
lines = [(i['produto']['id'], i['quantidade'], i['valorUnitario']) for i in self.orders[0]['itens']]
# 2,30 m at R$ 69,90: 2 × "1 metro" + 3 × "10 cm", R$ 160,77 in all.
self.assertEqual(lines, [(301, 2, 69.9), (300, 3, 6.99)])
self.assertAlmostEqual(sum(q * v for _, q, v in lines), 160.77)
def test_whole_metres_alone_and_the_check(self):
from app.tiny import check, step_lines
self.assertEqual(step_lines({'billed_metres': '2', 'unit_cents': 6990}, 'C', 'M'), [('M', 2, 6990)])
self.assertEqual(check(orders=self.tiny)['DTF UV 27 cm · folha montada'], 'ok')
del self.products['301']
self.tiny.skus.clear()
self.assertIn('DTFIMP.UV.1MT', check(orders=self.tiny)['DTF UV 27 cm · folha montada'])
@product_ids
@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 27 cm · artes avulsas): ok DTF-104', text)
self.assertIn('TINY_SKU_TREATMENT (Ajuste Fino): ok DTFIMP.AJF.UN', text)
self.assertIn('TINY_FORMA_ENVIO_RETIRADA (retirada): ok Retirar pessoalmente', text)
code, text = self.probe('formas-envio')
self.assertIn('77\t6\tRetirar pessoalmente', text)
self.assertTrue(all(method == 'GET' for method, _ in self.calls))
def test_usuarios_lists_the_types_and_marks_the_integration_user(self):
import base64 as b64
handler = self.handler
allowed = {'on': True}
def account(request):
if request.url.path.endswith('/usuarios'):
if not allowed['on']:
return httpx.Response(403, text='')
return httpx.Response(200, json={'itens': [
{'id': 1, 'nome': 'Marcus', 'email': 'marcus@example.test', 'tipo': 'administrador'},
{'id': 2, 'nome': 'Integração', 'email': 'dev@example.test', 'tipo': 'usuario'}]})
return handler(request)
self.tiny.http = httpx.Client(base_url=tiny_module.API, transport=httpx.MockTransport(account))
claims = b64.urlsafe_b64encode(json.dumps({'name': 'Integração', 'email': 'dev@example.test'}).encode()).decode().rstrip('=')
with mock.patch.object(self.tiny.auth, 'access_token', return_value=f'h.{claims}.s'):
code, text = self.probe('usuarios')
self.assertEqual(code, 0, text)
self.assertIn('Integração conectada como: Integração · dev@example.test', text)
self.assertIn('2\tusuario\tIntegração\tdev@example.test\t<- integração', text)
self.assertIn('1\tadministrador\tMarcus\tmarcus@example.test', text)
self.assertNotIn(claims, text)
# Without the app's Usuários permission: says what to tick.
allowed['on'] = False
code, text = self.probe('usuarios')
self.assertEqual(code, 1)
self.assertIn('Marque Usuários (Leitura)', text)
def test_diagnostico_finds_the_part_tiny_refuses(self):
handler = self.handler
def refusing(request):
path = request.url.path.removeprefix('/public-api/v3')
if request.method == 'POST' and path == '/pedidos' and 'ecommerce' in json.loads(request.content):
self.calls.append((request.method, path))
return httpx.Response(403, text='')
return handler(request)
self.tiny.http = httpx.Client(base_url=tiny_module.API, transport=httpx.MockTransport(refusing))
args = ('diagnostico', '--cpf', '130.323.978-71', '--email', 'a@example.test', '--celular', '16999999999')
# Never creates a contact: one that exists is required.
code, text = self.probe(*args)
self.assertEqual(code, 1)
self.assertIn('não existe no Tiny', text)
self.assertNotIn(('POST', '/contatos'), self.calls)
self.assertNotIn(('POST', '/pedidos'), self.calls)
self.contacts.append({'id': 600, 'cpfCnpj': '130.323.978-71', 'nome': 'Teste Fernandes'})
code, text = self.probe(*args)
self.assertEqual(code, 0, text)
self.assertIn('completo: recusado', text)
self.assertIn('sem ecommerce: ACEITO', text)
# The one order Tiny accepted is cancelled at once, and nothing after it is sent.
self.assertEqual(len(self.orders), 1)
self.assertEqual(self.orders[0]['situacao'], tiny_module.CANCELADA)
self.assertIn('cancelado no Tiny', text)
self.assertNotIn(('POST', '/contatos'), self.calls)
def test_diagnostico_blames_the_permission_when_all_are_refused(self):
handler = self.handler
def refusing(request):
if request.method == 'POST' and request.url.path.endswith('/pedidos'):
return httpx.Response(403, text='')
return handler(request)
self.tiny.http = httpx.Client(base_url=tiny_module.API, transport=httpx.MockTransport(refusing))
self.contacts.append({'id': 600, 'cpfCnpj': '130.323.978-71', 'nome': 'Teste Fernandes'})
code, text = self.probe('diagnostico', '--cpf', '13032397871', '--email', 'a@example.test',
'--celular', '16999999999')
self.assertEqual(code, 1)
self.assertIn('só o essencial', text)
self.assertIn('permissão do usuário do Tiny', text)
self.assertEqual(self.orders, [])
def test_campos_says_which_lookup_needs_a_permission(self):
handler = self.handler
def account(request):
path = request.url.path.removeprefix('/public-api/v3')
if path == '/formas-recebimento':
return httpx.Response(200, json={'itens': [{'id': 1, 'nome': 'Pix'}]})
if path == '/categorias-receita-despesa':
return httpx.Response(403, json={'mensagem': 'sem permissão'})
if path in ('/vendedores', '/intermediadores'):
return httpx.Response(200, json={'itens': []})
return handler(request)
self.tiny.http = httpx.Client(base_url=tiny_module.API, transport=httpx.MockTransport(account))
code, text = self.probe('campos')
self.assertEqual(code, 1)
self.assertIn('Formas de recebimento: 1', text)
self.assertIn('"nome": "Pix"', text)
self.assertIn('Libere "Contas Receber (Leitura)"', text)
self.assertIn('Forma de envio 78 · tipo 1 · Correios', text)
def test_exemplo_shows_an_order_without_the_customer(self):
self.tiny.deliver('k1', PAID)
self.orders[0].update(cliente={'nome': 'Fulano', 'cpfCnpj': '1'}, pagamento={'formaRecebimento': {'id': 1}})
code, text = self.probe('exemplo', self.orders[0]['numeroPedido'])
self.assertEqual(code, 0)
self.assertIn('"formaRecebimento"', text)
self.assertNotIn('Fulano', text)
self.assertIn('cliente', text.splitlines()[-1])
self.assertTrue(all(method == 'GET' for method, _ in self.calls[-3:]))
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.assertIn('"categoria": {', text)
self.assertIn('Marcador: SITE DTF', text)
self.assertEqual(self.orders, [])
self.assertTrue(all(method == 'GET' for method, _ in self.calls))
def test_an_existing_contact_is_shown_as_reused(self):
self.contacts.append({'id': 760799765, 'cpfCnpj': '130.323.978-71'})
code, text = self.probe('pedido', '--cpf', '13032397871', '--email', 'a@example.test',
'--celular', '16999999999')
self.assertEqual(code, 0)
self.assertIn('Contato 130.323.978-71: já existe no Tiny (id 760799765)', text)
self.assertIn('"idContato": 760799765', text)
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)
self.assertIn('E-commerce no Tiny: numeroPedidoEcommerce DTF-TESTE-', 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': 'SITE DTF'}])
def test_a_number_tiny_did_not_keep_fails_the_supervised_order(self):
# Tiny may drop the e-commerce block of an order with no channel.
def dropping(request):
if request.method == 'POST' and request.url.path.endswith('/pedidos'):
body = {k: v for k, v in json.loads(request.content).items() if k != 'ecommerce'}
request = httpx.Request(request.method, request.url, headers=request.headers, content=json.dumps(body))
return self.handler(request)
self.tiny = TinyOrders(auth=FakeAuth(), transport=httpx.MockTransport(dropping), today=date(2026, 9, 24))
code, text = self.probe('pedido', '--cnpj', '11222333000181', '--email', 'a@example.test',
'--celular', '16999999999', '--confirmar')
self.assertEqual(code, 1, text)
self.assertIn('numeroPedidoEcommerce (vazio) · sem canal', text)
self.assertIn('FALHA: o Tiny não guardou DTF-TESTE-', text)
self.assertEqual(self.orders[0]['situacao'], 2)
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
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[-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):
"""Dropstar's catalogue needs no settings; a setting replaces a default."""
def test_defaults_and_overrides(self):
from app import tiny
empty = {name: '' for name in [*tiny.SKU_SETTINGS.values(), *tiny.STEP_SETTINGS.values(),
*tiny.METRE_SETTINGS.values(), *tiny.PRODUCT_SETTINGS.values()]}
with mock.patch.dict(os.environ, empty):
self.assertEqual(tiny.mode_codes('file'), tiny.sku_codes('DTFIMP.TX'))
self.assertEqual(tiny.mode_codes('avulsa'), tiny.sku_codes('DTFIMP.TX'))
self.assertEqual(tiny.mode_codes('uv'), ['DTFIMP.UV.1MT', 'DTFIMP.UV.010CM'])
# Premium's own catalogue: DTFIMP.TXP.100CM per metre and DTFIMP.TXP.0010CM to 0090CM (Marcus, 2026-11-11).
self.assertEqual(tiny.mode_codes('premium'), tiny.sku_codes('DTFIMP.TXP'))
self.assertIn('DTFIMP.TXP.0010CM', tiny.mode_codes('premium'))
self.assertEqual(tiny.required_settings(), ['TINY_CLIENT_ID', 'TINY_CLIENT_SECRET', 'TINY_REDIRECT_URI'])
with mock.patch.dict(os.environ, {'TINY_SKU10_UV_FOLHA': 'UV.X'}):
self.assertEqual(tiny.mode_codes('uvfile'), ['UV.X'])
with mock.patch.dict(os.environ, {'TINY_SKU_UV_FOLHA': 'UV.P'}):
self.assertEqual(tiny.mode_codes('uvfile'), tiny.sku_codes('UV.P'))
class TreatmentSettingTests(unittest.TestCase):
"""Ajuste Fino is sold by its SKU, so no product id is required any more."""
def test_the_treatment_id_is_never_required(self):
from app.tiny import required_settings
with mock.patch.dict(os.environ, {'TINY_PRODUCT_TREATMENT': '', 'TINY_SKU_TREATMENT': ''}):
self.assertNotIn('TINY_PRODUCT_TREATMENT', required_settings())
with mock.patch.dict(os.environ, {'TINY_SKU_TREATMENT': 'DTFIMP.AJF.LOTE'}):
self.assertNotIn('TINY_PRODUCT_TREATMENT', required_settings())
if __name__ == '__main__':
unittest.main()