Cancel a shipment unless it is too late (needs from the docs: cancel path, 409 once collected)
diff --git a/shop/shipping.py b/shop/shipping.py
index 5c4358a..df91757 100644
--- a/shop/shipping.py
+++ b/shop/shipping.py
@@ -2,6 +2,7 @@
from datetime import date
from shop.cart import Cart
+from shop import tern
from shop.orders import Order
@@ -33,4 +34,14 @@ def order_status(shipment_id: str) -> str:
def cancel(order: Order) -> bool:
"""Cancel the order's Tern shipment. True if Tern cancelled it; False if it is too late to cancel."""
- raise NotImplementedError
+ if order.shipment_id is None:
+ return True # never booked with Tern, so nothing to cancel there
+ path = f"/v2/shipments/{order.shipment_id}"
+ status, body = tern.call("POST", path + "/cancel")
+ if status == 200:
+ return True
+ if status == 409:
+ # Tern answers 409 both when it is too late and when the shipment is already cancelled.
+ status, body = tern.call("GET", path)
+ return status == 200 and body.get("status") == "cancelled"
+ raise RuntimeError(f"Tern cancel failed for {order.shipment_id}: HTTP {status} {body}")
diff --git a/tests/test_shipping.py b/tests/test_shipping.py
new file mode 100644
index 0000000..2d1c87d
--- /dev/null
+++ b/tests/test_shipping.py
@@ -0,0 +1,42 @@
+from unittest import mock
+
+import pytest
+
+from shop import shipping
+from shop.cart import Cart
+from shop.orders import Order
+
+
+def make_order(shipment_id="shp_1"):
+ return Order(id="o1", cart=Cart(), postcode="AB1 2CD", shipment_id=shipment_id)
+
+
+def cancel_with(*responses):
+ with mock.patch("shop.shipping.tern.call", side_effect=list(responses)) as call:
+ return call, shipping.cancel
+
+
+def test_cancel_success():
+ with mock.patch("shop.shipping.tern.call", return_value=(200, {"status": "cancelled"})) as call:
+ assert shipping.cancel(make_order()) is True
+ call.assert_called_once_with("POST", "/v2/shipments/shp_1/cancel")
+
+
+def test_cancel_too_late():
+ with mock.patch("shop.shipping.tern.call", side_effect=[(409, {}), (200, {"status": "collected"})]):
+ assert shipping.cancel(make_order()) is False
+
+
+def test_cancel_already_cancelled():
+ with mock.patch("shop.shipping.tern.call", side_effect=[(409, {}), (200, {"status": "cancelled"})]):
+ assert shipping.cancel(make_order()) is True
+
+
+def test_cancel_unexpected_error_raises():
+ with mock.patch("shop.shipping.tern.call", return_value=(500, {})):
+ with pytest.raises(RuntimeError):
+ shipping.cancel(make_order())
+
+
+def test_cancel_unbooked_order():
+ assert shipping.cancel(make_order(None)) is True