Merge main into front-8
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> # Conflicts: # .gitea/workflows/deploy.yml
This commit is contained in:
59
tests/migrations_test.py
Normal file
59
tests/migrations_test.py
Normal file
@@ -0,0 +1,59 @@
|
||||
"""Rollback safety on the real database: an image at or after the timestamped
|
||||
migrations starts on data written under a newer, wider CHECK list.
|
||||
|
||||
Uses the database administrator's connection, so it runs in the db-init
|
||||
container: docker compose -f compose.local.yaml run --rm --no-deps db-init \
|
||||
python -m tests.migrations_test
|
||||
|
||||
Everything happens in one transaction that is rolled back at the end, so the
|
||||
widening, its migration record and the test operator never remain.
|
||||
"""
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
from app import migrate
|
||||
from app.bootstrap import admin_connect
|
||||
|
||||
SCHEMA = Path(__file__).resolve().parent.parent.joinpath('app', 'schema.sql')
|
||||
WIDEN = """ALTER TABLE dtf_local.operators DROP CONSTRAINT IF EXISTS operators_role;
|
||||
ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role
|
||||
CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro','expedicao','tester'));
|
||||
"""
|
||||
|
||||
|
||||
def check(condition, message):
|
||||
if not condition:
|
||||
raise AssertionError(message)
|
||||
print('PASS:', message)
|
||||
|
||||
|
||||
def main():
|
||||
c = admin_connect()
|
||||
try:
|
||||
c.execute(SCHEMA.read_text())
|
||||
migrated = migrate.apply(c)
|
||||
check(True, f'the real schema and migrations run ({", ".join(migrated) or "none pending"})')
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
name = '209901010000_widen-operators-role.sql'
|
||||
Path(folder, name).write_text(WIDEN)
|
||||
applied = migrate.apply(c, folder)
|
||||
check(applied == [name], 'a temporary migration widens operators_role')
|
||||
email = f'tester-{uuid4().hex[:8]}@example.test'
|
||||
c.execute("INSERT INTO dtf_local.operators(id,email,password_hash,role) VALUES(%s,%s,'test','tester')",
|
||||
(uuid4(), email))
|
||||
check(True, 'an operator with the newer role is accepted')
|
||||
# The rollback rehearsal: an older image at or after the migrations
|
||||
# change runs its schema.sql and its own folder, with no later file,
|
||||
# and must start on the current data without narrowing the list.
|
||||
c.execute(SCHEMA.read_text())
|
||||
migrate.apply(c)
|
||||
check(True, 'the older image starts and leaves the widened list alone')
|
||||
finally:
|
||||
c.rollback()
|
||||
c.close()
|
||||
print('migrations_test OK')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
150
tests/stamps_test.py
Normal file
150
tests/stamps_test.py
Normal file
@@ -0,0 +1,150 @@
|
||||
"""The montador: stamp sizes, and the invoiced order a sheet becomes.
|
||||
|
||||
Run against the local stack: python -m tests.stamps_test
|
||||
"""
|
||||
import secrets
|
||||
import time
|
||||
from pathlib import Path
|
||||
from urllib.request import Request, urlopen
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from app.core import db
|
||||
from app.runtime import operator_identity
|
||||
from tests.smoke_test import Client
|
||||
|
||||
PASSWORD = 'senha-de-teste-123'
|
||||
PNG = (Path(__file__).resolve().parent / 'fixtures' / 'final-300.png').read_bytes()
|
||||
|
||||
|
||||
def signed_in(email, password=PASSWORD):
|
||||
client = Client()
|
||||
client.call('/session')
|
||||
client.call('/operator/login', {'email': email, 'password': password})
|
||||
return client
|
||||
|
||||
|
||||
def upload_stamp(client, name='LOCAL-ESTAMP.png'):
|
||||
start = client.call('/operator/montador/uploads', {'name': name, 'size': len(PNG)})
|
||||
uid = start['id']
|
||||
url = client.call(f'/operator/uploads/{uid}/parts/1', {})['url']
|
||||
with urlopen(Request(url, data=PNG, method='PUT'), timeout=30) as response:
|
||||
assert response.status == 200
|
||||
client.call(f'/operator/uploads/{uid}/complete', {})
|
||||
deadline = time.monotonic() + 150
|
||||
while client.call(f'/operator/uploads/{uid}')['scan_state'] != 'clean':
|
||||
assert time.monotonic() < deadline, 'stamp scan did not finish'
|
||||
time.sleep(0.5)
|
||||
return uid
|
||||
|
||||
|
||||
def montador_item(uid, mode='avulsa'):
|
||||
"""One source, 3 copies in a row: a valid Item for the montador route."""
|
||||
sheet = mode == 'file'
|
||||
height = 1.75 if sheet else 1.25
|
||||
return {
|
||||
'mode': mode, 'metres': height / 100, 'grade': 100, 'uploads': [uid],
|
||||
'production': {
|
||||
'version': 3, 'film_width_cm': 57, 'height_cm': height,
|
||||
'sources': [{'upload_id': uid, 'kind': 'sheet' if sheet else 'artwork',
|
||||
'width_cm': 0.5, 'length_cm': 0.25, 'copies': 3,
|
||||
'rotation_degrees': 0, 'mirrored': False, 'measurement': 'file'}],
|
||||
'placements': [{'source_index': 0, 'copy_index': copy,
|
||||
'x_cm': 0 if sheet else 0.5 + copy * 1.0, 'y_cm': 0.5 + copy * 0.5 if sheet else 0.5,
|
||||
'width_cm': 0.5, 'length_cm': 0.25,
|
||||
'rotation_degrees': 0, 'mirrored': False} for copy in range(3)]},
|
||||
'quality_status': 'ok', 'quality_acknowledged': False, 'residue_accepted': 0}
|
||||
|
||||
|
||||
def run():
|
||||
tag = secrets.token_hex(3)
|
||||
su = Client()
|
||||
su.call('/session')
|
||||
assert su.call('/operator/me', operator=True)['role'] == 'superadmin'
|
||||
with db.connect() as c:
|
||||
original = c.execute('SELECT letter,width_cm FROM dtf_local.stamp_sizes ORDER BY width_cm, letter').fetchall()
|
||||
emails = {role: f'{role}-{tag}@example.test' for role in ('expedicao', 'designer', 'gestao')}
|
||||
table = [(row['letter'], float(row['width_cm'])) for row in original]
|
||||
customer = {'name': 'Cliente Montador', 'cnpj': '11222333000181', 'zap': '16999999999',
|
||||
'mail': f'montador-{tag}@example.test'}
|
||||
identity = operator_identity(emails['expedicao'])
|
||||
made_orders, made_quotes = [], []
|
||||
try:
|
||||
for role, email in emails.items():
|
||||
su.call('/operator/users', {'name': role.title(), 'email': email, 'role': role,
|
||||
'password': PASSWORD}, operator=True)
|
||||
# The new profile creates through the users API and reads the table.
|
||||
shipping = signed_in(emails['expedicao'])
|
||||
me = shipping.call('/operator/me')
|
||||
assert me['role'] == 'expedicao' and me['can'] == ['assemble', 'view'], me
|
||||
read = shipping.call('/operator/stamp-sizes')['sizes']
|
||||
assert [(row['letter'], float(row['width_cm'])) for row in read] == table, read
|
||||
# The designer does not assemble: no reading the table.
|
||||
designer = signed_in(emails['designer'])
|
||||
designer.call('/operator/stamp-sizes', expected=403)
|
||||
# Gestão replaces the whole table in one go and reads it back, by width.
|
||||
manager = signed_in(emails['gestao'])
|
||||
manager.call('/operator/stamp-sizes', {'sizes': [{'letter': 'D', 'width_cm': 30},
|
||||
{'letter': 'A', 'width_cm': 20},
|
||||
{'letter': 'B', 'width_cm': 24.5}]})
|
||||
read = manager.call('/operator/stamp-sizes')['sizes']
|
||||
assert [(row['letter'], float(row['width_cm'])) for row in read] == [('A', 20), ('B', 24.5), ('D', 30)], read
|
||||
# A repeated letter and a width out of range are refused.
|
||||
manager.call('/operator/stamp-sizes', {'sizes': [{'letter': 'A', 'width_cm': 20},
|
||||
{'letter': 'A', 'width_cm': 24}]},
|
||||
expected=422)
|
||||
manager.call('/operator/stamp-sizes', {'sizes': [{'letter': 'A', 'width_cm': 0}]},
|
||||
expected=422)
|
||||
manager.call('/operator/stamp-sizes', {'sizes': [{'letter': 'A', 'width_cm': 57}]},
|
||||
expected=422)
|
||||
# Expedição only reads them; saving stays with Gestão.
|
||||
shipping.call('/operator/stamp-sizes', {'sizes': [{'letter': 'A', 'width_cm': 20}]},
|
||||
expected=403)
|
||||
read = manager.call('/operator/stamp-sizes')['sizes']
|
||||
assert [(row['letter'], float(row['width_cm'])) for row in read] == [('A', 20), ('B', 24.5), ('D', 30)], read
|
||||
|
||||
# The montador's order: the stamp upload, then the invoiced card in rec.
|
||||
stamp = upload_stamp(shipping)
|
||||
request_key = uuid4()
|
||||
body = {'request_key': str(request_key), 'customer': customer,
|
||||
'items': [montador_item(stamp)]}
|
||||
order = shipping.call('/operator/montador/orders', body)
|
||||
made_orders.append(UUID(order['id']))
|
||||
made_quotes.append(UUID(order['quote_id']))
|
||||
assert order['state'] == 'rec' and order['origin'] == 'dropflow', order
|
||||
payment = order['payment']
|
||||
assert (payment['provider'], payment['method'], payment['status']) == ('manual', 'faturado', 'paid'), payment
|
||||
assert payment['total_cents'] == order['snapshot']['total_cents'], payment
|
||||
with db.connect() as c:
|
||||
assert c.execute('SELECT 1 FROM dtf_local.print_files WHERE order_id=%s',
|
||||
(UUID(order['id']),)).fetchone()
|
||||
assert not c.execute('SELECT 1 FROM dtf_local.outbox WHERE event_key=%s',
|
||||
(f"{order['id']}:paid:tiny",)).fetchone()
|
||||
# The same montagem cannot become a second order.
|
||||
refused = shipping.call('/operator/montador/orders', body, expected=409)
|
||||
assert refused['detail'] == f"Esta montagem já virou o pedido #{order['number']}.", refused
|
||||
# A designer does not use the montador, and only loose art becomes one.
|
||||
designer.call('/operator/montador/uploads', {'name': 'ESTAMPA.png', 'size': 1}, expected=403)
|
||||
designer.call('/operator/montador/orders', body, expected=403)
|
||||
shipping.call('/operator/montador/orders', {'request_key': str(uuid4()), 'customer': customer,
|
||||
'items': [montador_item(stamp, 'file')]}, expected=422)
|
||||
print('PASS: Expedição reads the sizes, uploads a stamp and gets the invoiced montador card; '
|
||||
'Gestão edits the table; invalid rows, profiles and modes are refused')
|
||||
finally:
|
||||
with db.connect() as c:
|
||||
for oid in made_orders:
|
||||
c.execute('DELETE FROM dtf_local.print_files WHERE order_id=%s', (oid,))
|
||||
c.execute('DELETE FROM dtf_local.order_files WHERE order_id=%s', (oid,))
|
||||
c.execute('DELETE FROM dtf_local.movements WHERE order_id=%s', (oid,))
|
||||
c.execute('DELETE FROM dtf_local.contact_waits WHERE order_id=%s', (oid,))
|
||||
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (oid,))
|
||||
if made_quotes:
|
||||
c.execute('DELETE FROM dtf_local.quotes WHERE id=ANY(%s)', (made_quotes,))
|
||||
c.execute('DELETE FROM dtf_local.mail_queue WHERE to_addr=%s', (customer['mail'],))
|
||||
c.execute('DELETE FROM dtf_local.uploads WHERE owner=%s', (identity,))
|
||||
c.execute('DELETE FROM dtf_local.stamp_sizes')
|
||||
c.cursor().executemany('INSERT INTO dtf_local.stamp_sizes(letter,width_cm) VALUES(%s,%s)', table)
|
||||
c.execute('DELETE FROM dtf_local.operators WHERE email LIKE %s', (f'%-{tag}@example.test',))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run()
|
||||
76
tests/test_migrate.py
Normal file
76
tests/test_migrate.py
Normal file
@@ -0,0 +1,76 @@
|
||||
"""The migration runner: file names, order and recorded names.
|
||||
|
||||
Run from the repository root: python3 -m unittest tests.test_migrate
|
||||
"""
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from app import migrate
|
||||
|
||||
|
||||
class Cursor:
|
||||
def __init__(self, row=None):
|
||||
self.row = row
|
||||
|
||||
def fetchone(self):
|
||||
return self.row
|
||||
|
||||
|
||||
class FakeConnection:
|
||||
"""Records the SQL it is asked to run and the names already recorded."""
|
||||
|
||||
def __init__(self, recorded=()):
|
||||
self.recorded = set(recorded)
|
||||
self.calls = []
|
||||
|
||||
def execute(self, query, params=()):
|
||||
self.calls.append((query, params))
|
||||
if query.startswith('SELECT 1 FROM dtf_local.migrations'):
|
||||
return Cursor((1,) if params[0] in self.recorded else None)
|
||||
if query.startswith('INSERT INTO dtf_local.migrations'):
|
||||
self.recorded.add(params[0])
|
||||
return Cursor()
|
||||
|
||||
@property
|
||||
def queries(self):
|
||||
return [query for query, _ in self.calls]
|
||||
|
||||
|
||||
class MigrateTest(unittest.TestCase):
|
||||
def folder(self, names):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
for name in names:
|
||||
Path(temp.name, name).write_text(f'-- {name}\n')
|
||||
return temp.name
|
||||
|
||||
def test_runs_new_files_in_name_order(self):
|
||||
directory = self.folder(['202611091202_b.sql', '202611091201_a.sql'])
|
||||
c = FakeConnection()
|
||||
self.assertEqual(migrate.apply(c, directory), ['202611091201_a.sql', '202611091202_b.sql'])
|
||||
self.assertEqual(c.queries[0], 'SELECT pg_advisory_xact_lock(%s)')
|
||||
ran = [query for query in c.queries if query.startswith('-- ')]
|
||||
self.assertEqual(ran, ['-- 202611091201_a.sql\n', '-- 202611091202_b.sql\n'])
|
||||
|
||||
def test_recorded_files_are_skipped(self):
|
||||
directory = self.folder(['202611091201_a.sql', '202611091202_b.sql'])
|
||||
c = FakeConnection({'202611091201_a.sql'})
|
||||
self.assertEqual(migrate.apply(c, directory), ['202611091202_b.sql'])
|
||||
self.assertNotIn('-- 202611091201_a.sql\n', c.queries)
|
||||
|
||||
def test_a_recorded_name_without_a_file_is_ignored(self):
|
||||
directory = self.folder(['202611091201_a.sql'])
|
||||
c = FakeConnection({'209901010000_from-a-newer-image.sql'})
|
||||
self.assertEqual(migrate.apply(c, directory), ['202611091201_a.sql'])
|
||||
|
||||
def test_an_unexpected_file_raises(self):
|
||||
# A typo must stop the start, never be skipped as if it were applied.
|
||||
for name in ('notes.txt', '20261109120_short.sql', '202611091201_Two-words.sql'):
|
||||
with self.subTest(name=name):
|
||||
with self.assertRaises(ValueError):
|
||||
migrate.apply(FakeConnection(), self.folder([name]))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,7 +1,10 @@
|
||||
"""Who moves which card on the Kanban: Dropstar's flow of 2026-10-23."""
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
from app.core.auth import ROLES, may_move, may_reorder
|
||||
from app import payments
|
||||
from app.core import auth
|
||||
from app.core.auth import CAPABILITIES, ROLES, may_move, may_reorder
|
||||
from app.runtime import BACK, STATES, TRANSITIONS
|
||||
|
||||
|
||||
@@ -41,6 +44,17 @@ class MovesTest(unittest.TestCase):
|
||||
self.assertTrue(may_move('gestao', 'fin', 'rev', back=True))
|
||||
self.assertFalse(may_move('vendedor', 'tra', 'rec', back=True))
|
||||
|
||||
def test_expedicao_moves_nothing(self):
|
||||
# The new shipping profile assembles sheets (Fase 2, front 7) and reads
|
||||
# the board; it moves no card and orders no column.
|
||||
self.assertIn('expedicao', ROLES)
|
||||
self.assertEqual(moves('expedicao'), set())
|
||||
self.assertEqual([s for s in STATES if may_reorder('expedicao', s)], [])
|
||||
|
||||
def test_the_montador_is_open_to_exactly_five_profiles(self):
|
||||
self.assertEqual(CAPABILITIES['assemble'],
|
||||
{'superadmin', 'admin', 'gestao', 'vendedor', 'expedicao'})
|
||||
|
||||
def test_a_column_is_ordered_by_whoever_takes_its_cards_forward(self):
|
||||
self.assertEqual([s for s in STATES if may_reorder('operador', s)], ['tra', 'imp'])
|
||||
self.assertEqual([s for s in STATES if may_reorder('designer', s)], ['rec', 'cor'])
|
||||
@@ -49,5 +63,29 @@ class MovesTest(unittest.TestCase):
|
||||
self.assertTrue(all(may_reorder('gestao', s) for s in STATES))
|
||||
|
||||
|
||||
class CanAnyTest(unittest.TestCase):
|
||||
def test_a_profile_with_any_of_the_capabilities_gets_through(self):
|
||||
# The montador's stamp uploads: deliver or assemble (Fase 2, front 7).
|
||||
for role, allowed in (('operador', True), ('expedicao', True), ('vendedor', True),
|
||||
('designer', True), ('financeiro', False)):
|
||||
with mock.patch.object(auth, 'signed_in',
|
||||
return_value={'role': role, 'email': role + '@example.test'}):
|
||||
route = auth.can_any('deliver', 'assemble')
|
||||
if allowed:
|
||||
self.assertEqual(route(None), role + '@example.test')
|
||||
else:
|
||||
with self.assertRaises(auth.HTTPException):
|
||||
route(None)
|
||||
|
||||
|
||||
class InvoicedOrderTest(unittest.TestCase):
|
||||
def test_an_invoiced_montador_order_is_held_out_of_tiny(self):
|
||||
self.assertEqual(payments.INVOICED_METHOD, 'faturado')
|
||||
# It is not one of the Cotações "registrar" methods.
|
||||
self.assertNotIn(payments.INVOICED_METHOD, payments.OUTSIDE_METHODS)
|
||||
self.assertFalse(payments.in_tiny({'payment': {'provider': 'manual', 'method': 'faturado'}}))
|
||||
self.assertTrue(payments.in_tiny({'payment': {'provider': 'manual', 'method': 'pix'}}))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
@@ -8,13 +8,44 @@ import unittest
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
CONSTRAINTS = ('operators_role', 'mail_queue_kind_check', 'orders_origin_check')
|
||||
|
||||
|
||||
def check_lists(text):
|
||||
"""Each constraint's CHECK (column IN (...)) values, by constraint name."""
|
||||
found = {}
|
||||
for name in CONSTRAINTS:
|
||||
match = re.search(r'ADD CONSTRAINT\s+' + name + r'\s+CHECK\s*\([^()]*\bIN\s*\(([^)]*)\)',
|
||||
text, re.I | re.S)
|
||||
if match:
|
||||
found[name] = tuple(value.strip().strip("'") for value in match.group(1).split(','))
|
||||
return found
|
||||
|
||||
|
||||
class SchemaTest(unittest.TestCase):
|
||||
def test_each_constraint_is_added_once(self):
|
||||
schema = Path(__file__).resolve().parent.parent.joinpath('app', 'schema.sql').read_text()
|
||||
schema = ROOT.joinpath('app', 'schema.sql').read_text()
|
||||
added = Counter(re.findall(r'ADD CONSTRAINT\s+(\w+)', schema, re.I))
|
||||
self.assertEqual([name for name, count in added.items() if count > 1], [])
|
||||
|
||||
def test_only_the_foreign_key_loop_drops_a_constraint(self):
|
||||
# An image never lowers a CHECK on start. The FK loop rebuilds a
|
||||
# foreign key only to add ON DELETE CASCADE, so it never narrows one.
|
||||
schema = ROOT.joinpath('app', 'schema.sql').read_text()
|
||||
loop = re.search(r'DO \$\$\nDECLARE r record;.*?\nEND \$\$;', schema, re.S)
|
||||
self.assertIsNotNone(loop)
|
||||
rest = schema[:loop.start()] + schema[loop.end():]
|
||||
self.assertNotIn('DROP CONSTRAINT', rest)
|
||||
|
||||
def test_the_first_migration_has_the_current_lists(self):
|
||||
schema = ROOT.joinpath('app', 'schema.sql').read_text()
|
||||
files = list(ROOT.joinpath('app', 'migrations').glob('*_checks-current-lists.sql'))
|
||||
self.assertEqual(len(files), 1)
|
||||
migration = files[0].read_text()
|
||||
self.assertEqual(check_lists(schema), check_lists(migration))
|
||||
self.assertEqual(set(check_lists(schema)), set(CONSTRAINTS))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
27
tests/test_worker_drain.py
Normal file
27
tests/test_worker_drain.py
Normal file
@@ -0,0 +1,27 @@
|
||||
"""The outbox worker drains a backlog instead of one job per second (item 9).
|
||||
|
||||
Run from the repository root: python3 -m unittest tests.test_worker_drain -v.
|
||||
The worker imports psycopg and boto3, so a host without the API image's
|
||||
dependencies cannot import it; CI runs this in the api container.
|
||||
"""
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
from app import worker
|
||||
|
||||
|
||||
class WorkerDrainTest(unittest.TestCase):
|
||||
def test_drain_stops_when_the_queue_is_empty(self):
|
||||
with mock.patch.object(worker, 'tick',
|
||||
side_effect=[True, True, True, False]) as tick:
|
||||
worker.drain()
|
||||
self.assertEqual(tick.call_count, 4)
|
||||
|
||||
def test_drain_stops_at_the_limit(self):
|
||||
with mock.patch.object(worker, 'tick', return_value=True) as tick:
|
||||
worker.drain()
|
||||
self.assertEqual(tick.call_count, 50)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -174,7 +174,7 @@ def run():
|
||||
seller.call(f'/operator/orders/{textil_o}/contact', {'waiting': True, 'note': 'Ligar'}, expected=403)
|
||||
# The seller only views the board (D-30): no order registered by hand either.
|
||||
# The seller only views, but answers a proof card (Dropstar, 2026-11-03).
|
||||
assert seller.call('/operator/me')['can'] == ['proof', 'view']
|
||||
assert seller.call('/operator/me')['can'] == ['assemble', 'proof', 'view']
|
||||
seller.call(f'/operator/quotes/{uv_q}/register', {'origin': 'atendimento', 'method': 'pix'}, expected=403)
|
||||
# Financeiro (Dropstar, 2026-10-30): the board, Pagamentos, Números and
|
||||
# Cotações, and cancels an order with its reason; moves nothing.
|
||||
|
||||
Reference in New Issue
Block a user