test_roundtrip.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import random
  2. import warnings
  3. import pytest
  4. from app import app, SERVICES, URL_PREFIX
  5. TOLERANCE = 0.02
  6. @pytest.fixture
  7. def client():
  8. app.config['TESTING'] = True
  9. with app.test_client() as c:
  10. yield c
  11. def _call(client, endpoint, service, amount):
  12. resp = client.post(f'{URL_PREFIX}/{endpoint}', json={'service': service, 'amount': amount})
  13. assert resp.status_code == 200, resp.get_json()
  14. return resp.get_json()
  15. def _near(a, b):
  16. return abs(float(a) - float(b)) <= TOLERANCE
  17. def _check(label, a, b):
  18. diff = abs(float(a) - float(b))
  19. if diff > TOLERANCE:
  20. warnings.warn(f"{label}: {float(a):.4f} vs {float(b):.4f} (diff={diff:.4f})", stacklevel=2)
  21. def test_net_retail_roundtrip(client):
  22. net = random.uniform(58, 258)
  23. for service_key in SERVICES:
  24. r1 = _call(client, 'net_to_retail', service_key, net)
  25. retail = float(r1['retail'])
  26. r2 = _call(client, 'retail_to_net', service_key, retail)
  27. _check(f'[{service_key}] list', r1['list'], r2['list'])
  28. _check(f'[{service_key}] net', net, r2['net'])
  29. shared_keys = set(r1.get('details', {})) & set(r2.get('details', {}))
  30. for k in shared_keys:
  31. _check(f'[{service_key}] details.{k}', r1['details'][k], r2['details'][k])