All checks were successful
Build and deploy / Validate source (push) Successful in 1m38s
Build and deploy / Integration suite on a real stack (push) Successful in 4m57s
Build and deploy / Secret scan and release gate (push) Successful in 13s
Build and deploy / Publish images (push) Successful in 2m1s
The cart and the account signup take either document, each with its own mask and check digits. Tiny gets a person (F) for a CPF, Mercado Pago the matching identification type, and only CNPJs go to the company registry. The Kanban, the account page and the alerts show which one it is. Also pins the Correios test's clock: its fake token expired today, so the suite failed from Oct 16 on. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
168 lines
7.8 KiB
Python
168 lines
7.8 KiB
Python
"""The Correios client against a fake HTTP transport: token, price, time, boxes.
|
|
|
|
This proves the manuals' contract only; app.correios_probe must still confirm
|
|
it on Dropstar's contract. Runs where httpx is installed.
|
|
"""
|
|
import base64
|
|
import json
|
|
import os
|
|
import unittest
|
|
from datetime import datetime, timezone
|
|
from decimal import Decimal
|
|
from unittest import mock
|
|
|
|
import httpx
|
|
|
|
from app.correios import CorreiosFreight, CorreiosQuotes, cents
|
|
from app.freight import FreightOptions
|
|
|
|
BOX = [Decimal('63'), Decimal('15.5'), Decimal('15.5')]
|
|
PACKAGE = {'JADLOG_PESO_BASE_KG': '0.3', 'JADLOG_PESO_POR_METRO_KG': '0.075', 'FREIGHT_PRODUCTION_DAYS': '1',
|
|
'JADLOG_CAIXA_CM': '63x15.5x15.5', 'JADLOG_CUBAGEM_KG_M3': '300', 'JADLOG_METROS_POR_CAIXA': '60'}
|
|
|
|
|
|
class FakeCorreios:
|
|
"""Answers as the Token, Preço and Prazo manuals describe."""
|
|
|
|
def __init__(self, prices=None, token_status=201, expires='2026-10-16T10:00:00'):
|
|
self.calls = []
|
|
self.tokens = 0
|
|
self.prices = prices or {'03298': '23,50', '03220': '41,10'}
|
|
self.token_status = token_status
|
|
self.expires = expires
|
|
self.refuse_next = False
|
|
|
|
def __call__(self, request):
|
|
self.calls.append(request)
|
|
path = request.url.path
|
|
if path == '/token/v1/autentica/cartaopostagem':
|
|
self.tokens += 1
|
|
if self.token_status != 201:
|
|
return httpx.Response(self.token_status, json={'msgs': ['Usuário ou senha inválidos']})
|
|
return httpx.Response(201, json={'token': f'tok-{self.tokens}', 'expiraEm': self.expires,
|
|
'cartaoPostagem': {'numero': '0076691373', 'contrato': '9912551407',
|
|
'dr': 72}})
|
|
if self.refuse_next:
|
|
self.refuse_next = False
|
|
return httpx.Response(401, json={'msgs': ['Token expirado']})
|
|
code = path.rsplit('/', 1)[-1]
|
|
if path.startswith('/preco/v1/nacional/'):
|
|
if request.url.params['cepDestino'] == '00000000':
|
|
return httpx.Response(400, json={'txErro': 'ERP-006: CEP de destino inválido.'})
|
|
return httpx.Response(200, json={'coProduto': code, 'pcFinal': self.prices[code]})
|
|
if path.startswith('/prazo/v1/nacional/'):
|
|
return httpx.Response(200, json={'coProduto': code, 'prazoEntrega': 3 if code == '03298' else 1})
|
|
return httpx.Response(404)
|
|
|
|
|
|
def quotes(fake, **kwargs):
|
|
# A fixed day before the fake token's expiry, so the test never ages.
|
|
kwargs.setdefault('clock', lambda: datetime(2026, 10, 15, 12, tzinfo=timezone.utc))
|
|
return CorreiosQuotes(user='8825364223', access_code='codigo-1', card='0076691373',
|
|
transport=httpx.MockTransport(fake), **kwargs)
|
|
|
|
|
|
class CorreiosQuotesTest(unittest.TestCase):
|
|
def test_token_from_the_posting_card_then_contract_prices(self):
|
|
fake = FakeCorreios()
|
|
q = quotes(fake)
|
|
self.assertEqual(q.price('03298', '01310100', 1500, BOX), 2350)
|
|
token, price = fake.calls
|
|
self.assertEqual(token.headers['authorization'],
|
|
'Basic ' + base64.b64encode(b'8825364223:codigo-1').decode())
|
|
self.assertEqual(json.loads(token.content), {'numero': '0076691373'})
|
|
params = dict(price.url.params)
|
|
self.assertEqual(price.headers['authorization'], 'Bearer tok-1')
|
|
# Grams, a package with whole centimetres, and the contract's own rates.
|
|
self.assertEqual(params, {'cepOrigem': '14402310', 'cepDestino': '01310100', 'psObjeto': '1500',
|
|
'tpObjeto': '2', 'comprimento': '63', 'largura': '16', 'altura': '16',
|
|
'nuContrato': '9912551407', 'nuDR': '72'})
|
|
|
|
def test_the_token_is_reused_until_it_expires_and_renewed_when_refused(self):
|
|
now = [datetime(2026, 10, 15, 12, tzinfo=timezone.utc)]
|
|
fake = FakeCorreios(expires='2026-10-16T10:00:00')
|
|
q = quotes(fake, clock=lambda: now[0])
|
|
q.days('03298', '01310100')
|
|
q.days('03220', '01310100')
|
|
self.assertEqual(fake.tokens, 1)
|
|
# Close to its end (10:00 in Brasília is 13:00 UTC), a new one.
|
|
fake.expires = '2026-10-17T10:00:00'
|
|
now[0] = datetime(2026, 10, 16, 12, 55, tzinfo=timezone.utc)
|
|
q.days('03298', '01310100')
|
|
self.assertEqual(fake.tokens, 2)
|
|
# Refused before its time: renewed once and asked again.
|
|
fake.refuse_next = True
|
|
self.assertEqual(q.days('03298', '01310100'), 3)
|
|
self.assertEqual(fake.tokens, 3)
|
|
|
|
def test_refusals_say_what_the_correios_said(self):
|
|
q = quotes(FakeCorreios(token_status=401))
|
|
with self.assertRaisesRegex(Exception, 'Usuário ou senha inválidos'):
|
|
q.bearer()
|
|
with self.assertRaisesRegex(Exception, 'ERP-006'):
|
|
quotes(FakeCorreios()).price('03298', '00000000', 500, BOX)
|
|
|
|
def test_prices_in_brazilian_format_become_centavos(self):
|
|
self.assertEqual([cents('23,50'), cents('1.234,56'), cents('7'), cents(11.64)], [2350, 123456, 700, 1164])
|
|
|
|
|
|
class CorreiosFreightTest(unittest.TestCase):
|
|
def freight(self, fake, **env):
|
|
with mock.patch.dict(os.environ, {**PACKAGE, **env}):
|
|
return CorreiosFreight(quotes(fake))
|
|
|
|
def test_pac_and_sedex_for_the_package(self):
|
|
fake = FakeCorreios()
|
|
freight = self.freight(fake)
|
|
pac = freight.quote('pac', '01310100', '2.8')
|
|
self.assertEqual((pac['total_cents'], pac['days'], pac['description']), (2350, 4, 'Correios PAC'))
|
|
sedex = freight.quote('sedex', '01310100', '2.8')
|
|
self.assertEqual((sedex['total_cents'], sedex['days']), (4110, 2))
|
|
# 0.3 kg of box plus 0.075 kg for each of the 2.8 metres, in grams.
|
|
grams = [c.url.params['psObjeto'] for c in fake.calls if c.url.path.startswith('/preco')]
|
|
self.assertEqual(grams, ['510', '510'])
|
|
|
|
def test_a_long_order_is_one_object_per_box(self):
|
|
fake = FakeCorreios()
|
|
quote = self.freight(fake).quote('pac', '01310100', '130')
|
|
# 60 + 60 + 10 metres: two full boxes at one price, the last at its own.
|
|
grams = sorted(c.url.params['psObjeto'] for c in fake.calls if c.url.path.startswith('/preco'))
|
|
self.assertEqual(grams, ['1050', '4800'])
|
|
self.assertEqual((quote['boxes'], quote['total_cents']), (3, 3 * 2350))
|
|
|
|
def test_a_setting_overrides_a_service_code(self):
|
|
fake = FakeCorreios(prices={'03298': '23,50', '03220': '41,10', '04669': '19,90'})
|
|
quote = self.freight(fake, CORREIOS_COD_PAC='04669').quote('pac', '01310100', '1')
|
|
self.assertEqual(quote['total_cents'], 1990)
|
|
|
|
def test_no_box_no_correios(self):
|
|
with mock.patch.dict(os.environ, {**PACKAGE, 'JADLOG_CAIXA_CM': '', 'JADLOG_CUBAGEM_KG_M3': ''}):
|
|
with self.assertRaises(RuntimeError):
|
|
CorreiosFreight(quotes(FakeCorreios()))
|
|
|
|
|
|
class FreightOptionsTest(unittest.TestCase):
|
|
def test_every_option_cheapest_first_and_a_failing_carrier_left_out(self):
|
|
with mock.patch.dict(os.environ, PACKAGE):
|
|
correios = CorreiosFreight(quotes(FakeCorreios()))
|
|
|
|
class Broken:
|
|
name = 'jadlog'
|
|
services = {'jadlog': 'Jadlog'}
|
|
|
|
def quote(self, *args):
|
|
raise ValueError('Não foi possível cotar o frete na Jadlog agora: HTTP 500')
|
|
|
|
options = FreightOptions([Broken(), correios])
|
|
found = options.options('01310100', '2.8', 5000)
|
|
self.assertEqual([o['service'] for o in found['options']], ['pac', 'sedex'])
|
|
self.assertEqual(found['unavailable'][0]['service'], 'jadlog')
|
|
self.assertEqual(options.quote('sedex', '01310100', '2.8')['total_cents'], 4110)
|
|
self.assertEqual(options.quote('pickup', '')['total_cents'], 0)
|
|
with self.assertRaises(ValueError):
|
|
options.quote('motoboy', '01310100', '2.8')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|