Every Tern service for a cart, cheapest first (needs from the docs: D1 grams, D2 current endpoint)
cd /app; git ls-files; cat shop/shipping.py shop/settings.py; curl -s localhost:8080/
.gitignore
README.md
pytest.ini
shop/__init__.py
shop/cart.py
shop/orders.py
shop/settings.py
shop/shipping.py
shop/tern.py
tests/__init__.py
tests/test_cart.py
tests/test_orders.py
"""Shipping with Tern, our carrier. Use shop.tern.call for requests; shop.settings has the warehouse postcode."""
from datetime import date
from shop.cart import Cart
from shop.orders import Order
def quote_at_checkout(cart: Cart, postcode: str) -> int:
"""The cheapest price Tern offers to ship this cart from the warehouse to postcode, in pence."""
raise NotImplementedError
def quote_options(cart: Cart, postcode: str) -> list[tuple[str, int, int]]:
"""Every service Tern offers for this cart and postcode, as (service, price in pence, days to deliver),
cheapest first."""
raise NotImplementedError
def book(order: Order, service: str) -> str:
"""Book the order's parcel with Tern on the given service and return Tern's shipment id."""
raise NotImplementedError
def shipments_since(day: date) -> list[dict]:
"""Every Tern shipment created on or after day, as Tern describes them."""
raise NotImplementedError
def order_status(shipment_id: str) -> str:
"""The shop's status (one of shop.orders.STATUSES) for the order whose Tern shipment this is."""
raise NotImplementedError
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
import os
TERN_API_URL = os.environ.get("TERN_API_URL", "http://localhost:8081")
TERN_API_KEY = os.environ.get("TERN_API_KEY", "tern_test_larkspur")
# Every parcel leaves from the warehouse.
WAREHOUSE_POSTCODE = "EH6 6QT"
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
[stdout]
.gitignore
README.md
pytest.ini
shop/__init__.py
shop/cart.py
shop/orders.py
shop/settings.py
shop/shipping.py
shop/tern.py
tests/__init__.py
tests/test_cart.py
tests/test_orders.py
"""Shipping with Tern, our carrier. Use shop.tern.call for requests; shop.settings has the warehouse postcode."""
from datetime import date
from shop.cart import Cart
from shop.orders import Order
def quote_at_checkout(cart: Cart, postcode: str) -> int:
"""The cheapest price Tern offers to ship this cart from the warehouse to postcode, in pence."""
raise NotImplementedError
def quote_options(cart: Cart, postcode: str) -> list[tuple[str, int, int]]:
"""Every service Tern offers for this cart and postcode, as (service, price in pence, days to deliver),
cheapest first."""
raise NotImplementedError
def book(order: Order, service: str) -> str:
"""Book the order's parcel with Tern on the given service and return Tern's shipment id."""
raise NotImplementedError
def shipments_since(day: date) -> list[dict]:
"""Every Tern shipment created on or after day, as Tern describes them."""
raise NotImplementedError
def order_status(shipment_id: str) -> str:
"""The shop's status (one of shop.orders.STATUSES) for the order whose Tern shipment this is."""
raise NotImplementedError
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
import os
TERN_API_URL = os.environ.get("TERN_API_URL", "http://localhost:8081")
TERN_API_KEY = os.environ.get("TERN_API_KEY", "tern_test_larkspur")
# Every parcel leaves from the warehouse.
WAREHOUSE_POSTCODE = "EH6 6QT"
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
[metadata] {"noOutputExpected": false}cd /app; cat shop/tern.py shop/cart.py README.md; curl -s localhost:8080/index.html | head -50; curl -si localhost:8080 | head
"""A thin client for Tern's API: the key, JSON in and out. Which paths and fields to use is up to the caller."""
import json
import urllib.error
import urllib.parse
import urllib.request
from shop import settings
def call(method: str, path: str, body: dict | None = None, params: dict | None = None,
headers: dict | None = None, timeout: float = 10) -> tuple[int, dict]:
"""One request to Tern. Returns (HTTP status, decoded JSON body); an error status is returned, not raised.
A connection that fails or drops raises, as urllib does."""
url = settings.TERN_API_URL.rstrip("/") + path
if params:
url += "?" + urllib.parse.urlencode(params)
data = json.dumps(body).encode() if body is not None else None
request = urllib.request.Request(url, data=data, method=method)
request.add_header("Authorization", f"Bearer {settings.TERN_API_KEY}")
request.add_header("Accept", "application/json")
if data is not None:
request.add_header("Content-Type", "application/json")
for name, value in (headers or {}).items():
request.add_header(name, value)
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
return response.status, json.loads(response.read() or b"{}")
except urllib.error.HTTPError as e:
raw = e.read()
return e.code, json.loads(raw) if raw else {}
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Item:
sku: str
name: str
price_pence: int
weight_kg: float
@dataclass
class Cart:
lines: list[tuple[Item, int]] = field(default_factory=list)
def add(self, item: Item, quantity: int = 1) -> None:
if quantity < 1:
raise ValueError("quantity must be at least 1")
self.lines.append((item, quantity))
def subtotal_pence(self) -> int:
return sum(item.price_pence * qty for item, qty in self.lines)
def total_weight_kg(self) -> float:
"""The packed weight, as the warehouse scales read it."""
return round(sum(item.weight_kg * qty for item, qty in self.lines), 3)
# Larkspur Tea: shop backend
The order and checkout logic behind Larkspur Tea's online shop. Plain Python 3.13, no framework, no dependencies
beyond pytest for the tests.
- `shop/cart.py`: carts and items. Prices are in pence; weights are in kilograms, as the warehouse weighs them.
- `shop/orders.py`: orders and the order statuses the shop shows customers.
- `shop/shipping.py`: everything to do with our carrier, Tern. Mostly still to write.
- `shop/tern.py`: a thin client for Tern's API (authentication, JSON in and out).
- `shop/settings.py`: configuration, from the environment with defaults for development.
## Shipping
We ship everything with Tern. In development, `TERN_API_URL` points at Tern's sandbox and `TERN_API_KEY` holds a
test key; both default to what the sandbox expects.
## Tests
```
python -m pytest
```
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
HTTP/1.0 404 Not Found
Server: BaseHTTP/0.6 Python/3.13.18
Date: Sat, 28 Nov 2026 21:23:34 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 72
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
[stdout]
"""A thin client for Tern's API: the key, JSON in and out. Which paths and fields to use is up to the caller."""
import json
import urllib.error
import urllib.parse
import urllib.request
from shop import settings
def call(method: str, path: str, body: dict | None = None, params: dict | None = None,
headers: dict | None = None, timeout: float = 10) -> tuple[int, dict]:
"""One request to Tern. Returns (HTTP status, decoded JSON body); an error status is returned, not raised.
A connection that fails or drops raises, as urllib does."""
url = settings.TERN_API_URL.rstrip("/") + path
if params:
url += "?" + urllib.parse.urlencode(params)
data = json.dumps(body).encode() if body is not None else None
request = urllib.request.Request(url, data=data, method=method)
request.add_header("Authorization", f"Bearer {settings.TERN_API_KEY}")
request.add_header("Accept", "application/json")
if data is not None:
request.add_header("Content-Type", "application/json")
for name, value in (headers or {}).items():
request.add_header(name, value)
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
return response.status, json.loads(response.read() or b"{}")
except urllib.error.HTTPError as e:
raw = e.read()
return e.code, json.loads(raw) if raw else {}
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Item:
sku: str
name: str
price_pence: int
weight_kg: float
@dataclass
class Cart:
lines: list[tuple[Item, int]] = field(default_factory=list)
def add(self, item: Item, quantity: int = 1) -> None:
if quantity < 1:
raise ValueError("quantity must be at least 1")
self.lines.append((item, quantity))
def subtotal_pence(self) -> int:
return sum(item.price_pence * qty for item, qty in self.lines)
def total_weight_kg(self) -> float:
"""The packed weight, as the warehouse scales read it."""
return round(sum(item.weight_kg * qty for item, qty in self.lines), 3)
# Larkspur Tea: shop backend
The order and checkout logic behind Larkspur Tea's online shop. Plain Python 3.13, no framework, no dependencies
beyond pytest for the tests.
- `shop/cart.py`: carts and items. Prices are in pence; weights are in kilograms, as the warehouse weighs them.
- `shop/orders.py`: orders and the order statuses the shop shows customers.
- `shop/shipping.py`: everything to do with our carrier, Tern. Mostly still to write.
- `shop/tern.py`: a thin client for Tern's API (authentication, JSON in and out).
- `shop/settings.py`: configuration, from the environment with defaults for development.
## Shipping
We ship everything with Tern. In development, `TERN_API_URL` points at Tern's sandbox and `TERN_API_KEY` holds a
test key; both default to what the sandbox expects.
## Tests
```
python -m pytest
```
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
HTTP/1.0 404 Not Found
Server: BaseHTTP/0.6 Python/3.13.18
Date: Sat, 28 Nov 2026 21:23:34 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 72
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
[metadata] {"noOutputExpected": false}cd /app; for p in docs docs/ openapi.json api-docs index.html quotes.html; do echo "== $p"; curl -s localhost:8080/$p | head -c 600; done
== docs
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
== docs/
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
== openapi.json
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
== api-docs
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
== index.html
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
== quotes.html
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
[stdout]
== docs
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
== docs/
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
== openapi.json
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
== api-docs
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
== index.html
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
== quotes.html
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
[metadata] {"noOutputExpected": false}cd /app; curl -si localhost:8081/ | head -20; curl -s -X OPTIONS -i localhost:8080/ | head; ls /app /app/.. ; grep -ril tern / --include=*.md --include=*.html -s 2>/dev/null | grep -v -E "^/(proc|sys|usr|lib)" | head
HTTP/1.1 401 Unauthorized
Server: BaseHTTP/0.6 Python/3.13.18
Date: Sat, 28 Nov 2026 21:23:36 GMT
Content-Type: application/json
Content-Length: 25
{"error": "unauthorized"}HTTP/1.0 501 Unsupported method ('OPTIONS')
Server: BaseHTTP/0.6 Python/3.13.18
Date: Sat, 28 Nov 2026 21:23:36 GMT
Connection: close
Content-Type: text/html;charset=utf-8
Content-Length: 360
<!DOCTYPE HTML>
<html lang="en">
<head>
/app:
README.md
pytest.ini
shop
tests
/app/..:
app
bin
boot
dev
etc
home
installed-agent
lib
lib64
logs
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var
/app/README.md
[stdout]
HTTP/1.1 401 Unauthorized
Server: BaseHTTP/0.6 Python/3.13.18
Date: Sat, 28 Nov 2026 21:23:36 GMT
Content-Type: application/json
Content-Length: 25
{"error": "unauthorized"}HTTP/1.0 501 Unsupported method ('OPTIONS')
Server: BaseHTTP/0.6 Python/3.13.18
Date: Sat, 28 Nov 2026 21:23:36 GMT
Connection: close
Content-Type: text/html;charset=utf-8
Content-Length: 360
<!DOCTYPE HTML>
<html lang="en">
<head>
/app:
README.md
pytest.ini
shop
tests
/app/..:
app
bin
boot
dev
etc
home
installed-agent
lib
lib64
logs
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var
/app/README.md
[metadata] {"noOutputExpected": false}cd /app; for p in /v1 /v1/quotes /quotes /rates /v1/rates /v1/services /services; do echo "== $p"; curl -s -H "Authorization: Bearer tern_test_larkspur" localhost:8081$p; echo; done; curl -s localhost:8080/robots.txt; curl -s localhost:8080/docs.html | head -c 300
== /v1
{"error": "not_found"}
== /v1/quotes
{"error": "not_found"}
== /quotes
{"error": "not_found"}
== /rates
{"error": "not_found"}
== /v1/rates
{"error": "not_found"}
== /v1/services
{"error": "not_found"}
== /services
{"error": "not_found"}
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
[stdout]
== /v1
{"error": "not_found"}
== /v1/quotes
{"error": "not_found"}
== /quotes
{"error": "not_found"}
== /rates
{"error": "not_found"}
== /v1/rates
{"error": "not_found"}
== /v1/services
{"error": "not_found"}
== /services
{"error": "not_found"}
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
<!doctype html><title>Not found</title><h1>404</h1><p>No such page.</p>
[metadata] {"noOutputExpected": false}cd /app; for p in /docs/ /api /api/ /reference /guide /v1/docs /docs/quotes /quote /index /home /readme /llms.txt /sitemap.xml /static/ /openapi.yaml /swagger.json; do printf "%s " $p; curl -s -o /dev/null -w "%{http_code}\n" localhost:8080$p; done; ss -ltnp 2>/dev/null | head/docs/ 404
/api 404
/api/ 404
/reference 404
/guide 404
/v1/docs 404
/docs/quotes 404
/quote 404
/index 404
/home 404
/readme 404
/llms.txt 404
/sitemap.xml 404
/static/ 404
/openapi.yaml 404
/swagger.json 404
[stdout]
/docs/ 404
/api 404
/api/ 404
/reference 404
/guide 404
/v1/docs 404
/docs/quotes 404
/quote 404
/index 404
/home 404
/readme 404
/llms.txt 404
/sitemap.xml 404
/static/ 404
/openapi.yaml 404
/swagger.json 404
[metadata] {"noOutputExpected": false}cd /app; H="Authorization: Bearer tern_test_larkspur"; for p in /v1/quote /v2/quotes /quote /shipments /v1/shipments /v1/rates /v1/quotes; do for m in GET POST; do printf "%s %s " $m $p; curl -s -X $m -H "$H" -H 'Content-Type: application/json' -d '{}' localhost:8081$p; echo; done; doneGET /v1/quote {"error": "not_found"}
POST /v1/quote {"error": "not_found"}
GET /v2/quotes {"error": "not_found"}
POST /v2/quotes {"error": "bad_request", "message": "missing field: from_postcode"}
GET /quote {"error": "not_found"}
POST /quote {"error": "not_found"}
GET /shipments {"error": "not_found"}
POST /shipments {"error": "not_found"}
GET /v1/shipments {"error": "not_found"}
POST /v1/shipments {"error": "not_found"}
GET /v1/rates {"error": "not_found"}
POST /v1/rates {"error": "not_found"}
GET /v1/quotes {"error": "not_found"}
POST /v1/quotes {"error": "bad_request", "message": "missing field: from_postcode"}
[stdout]
GET /v1/quote {"error": "not_found"}
POST /v1/quote {"error": "not_found"}
GET /v2/quotes {"error": "not_found"}
POST /v2/quotes {"error": "bad_request", "message": "missing field: from_postcode"}
GET /quote {"error": "not_found"}
POST /quote {"error": "not_found"}
GET /shipments {"error": "not_found"}
POST /shipments {"error": "not_found"}
GET /v1/shipments {"error": "not_found"}
POST /v1/shipments {"error": "not_found"}
GET /v1/rates {"error": "not_found"}
POST /v1/rates {"error": "not_found"}
GET /v1/quotes {"error": "not_found"}
POST /v1/quotes {"error": "bad_request", "message": "missing field: from_postcode"}
[metadata] {"noOutputExpected": false}cd /app; H="Authorization: Bearer tern_test_larkspur"; for v in v1 v2; do echo == $v; curl -s -X POST -H "$H" -H 'Content-Type: application/json' -d '{"from_postcode":"EH6 6QT","to_postcode":"SW1A 1AA","weight_kg":1.2}' localhost:8081/$v/quotes; echo; done== v1
{"error": "bad_request", "message": "missing field: weight"}
== v2
{"error": "bad_request", "message": "missing field: weight"}
[stdout]
== v1
{"error": "bad_request", "message": "missing field: weight"}
== v2
{"error": "bad_request", "message": "missing field: weight"}
[metadata] {"noOutputExpected": false}cd /app; H="Authorization: Bearer tern_test_larkspur"; for v in v1 v2; do echo == $v; for w in 1.2 1200 '{"value":1.2,"unit":"kg"}' '{"kg":1.2}'; do curl -s -X POST -H "$H" -H 'Content-Type: application/json' -d "{\"from_postcode\":\"EH6 6QT\",\"to_postcode\":\"SW1A 1AA\",\"weight\":$w}" localhost:8081/$v/quotes; echo; done; done== v1
{"quotes": [{"id": "qt_1", "service": "express", "amount": 1295, "currency": "GBP", "eta_days": 1}, {"id": "qt_2", "service": "standard", "amount": 695, "currency": "GBP", "eta_days": 3}, {"id": "qt_3", "service": "economy", "amount": 495, "currency": "GBP", "eta_days": 5}]}
{"error": "too_heavy"}
{"error": "bad_request", "message": "weight must be a positive number"}
{"error": "bad_request", "message": "weight must be a positive number"}
== v2
{"quotes": [{"id": "qt_4", "service": "express", "amount": 795, "currency": "GBP", "eta_days": 1}, {"id": "qt_5", "service": "standard", "amount": 395, "currency": "GBP", "eta_days": 3}, {"id": "qt_6", "service": "economy", "amount": 295, "currency": "GBP", "eta_days": 5}]}
{"quotes": [{"id": "qt_7", "service": "express", "amount": 1295, "currency": "GBP", "eta_days": 1}, {"id": "qt_8", "service": "standard", "amount": 695, "currency": "GBP", "eta_days": 3}, {"id": "qt_9", "service": "economy", "amount": 495, "currency": "GBP", "eta_days": 5}]}
{"error": "bad_request", "message": "weight must be a positive number"}
{"error": "bad_request", "message": "weight must be a positive number"}
[stdout]
== v1
{"quotes": [{"id": "qt_1", "service": "express", "amount": 1295, "currency": "GBP", "eta_days": 1}, {"id": "qt_2", "service": "standard", "amount": 695, "currency": "GBP", "eta_days": 3}, {"id": "qt_3", "service": "economy", "amount": 495, "currency": "GBP", "eta_days": 5}]}
{"error": "too_heavy"}
{"error": "bad_request", "message": "weight must be a positive number"}
{"error": "bad_request", "message": "weight must be a positive number"}
== v2
{"quotes": [{"id": "qt_4", "service": "express", "amount": 795, "currency": "GBP", "eta_days": 1}, {"id": "qt_5", "service": "standard", "amount": 395, "currency": "GBP", "eta_days": 3}, {"id": "qt_6", "service": "economy", "amount": 295, "currency": "GBP", "eta_days": 5}]}
{"quotes": [{"id": "qt_7", "service": "express", "amount": 1295, "currency": "GBP", "eta_days": 1}, {"id": "qt_8", "service": "standard", "amount": 695, "currency": "GBP", "eta_days": 3}, {"id": "qt_9", "service": "economy", "amount": 495, "currency": "GBP", "eta_days": 5}]}
{"error": "bad_request", "message": "weight must be a positive number"}
{"error": "bad_request", "message": "weight must be a positive number"}
[metadata] {"noOutputExpected": false}cd /app; H="Authorization: Bearer tern_test_larkspur"; for v in v1 v2; do curl -si -X POST -H "$H" -H 'Content-Type: application/json' -d '{"from_postcode":"EH6 6QT","to_postcode":"SW1A 1AA","weight":1.2}' localhost:8081/$v/quotes | head -12; echo; done; curl -s -X POST -H "$H" -d '{"from_postcode":"EH6 6QT","to_postcode":"SW1A 1AA","weight":25}' localhost:8081/v1/quotes; curl -s -X POST -H "$H" -d '{"from_postcode":"EH6 6QT","to_postcode":"ZZ9 9ZZ","weight":1}' localhost:8081/v1/quotesHTTP/1.1 200 OK
Server: BaseHTTP/0.6 Python/3.13.18
Date: Sat, 28 Nov 2026 21:23:49 GMT
Content-Type: application/json
Content-Length: 278
Deprecation: true
Sunset: Tue, 01 Jun 2027 00:00:00 GMT
{"quotes": [{"id": "qt_10", "service": "express", "amount": 1295, "currency": "GBP", "eta_days": 1}, {"id": "qt_11", "service": "standard", "amount": 695, "currency": "GBP", "eta_days": 3}, {"id": "qt_12", "service": "economy", "amount": 495, "currency": "GBP", "eta_days": 5}]}
HTTP/1.1 200 OK
Server: BaseHTTP/0.6 Python/3.13.18
Date: Sat, 28 Nov 2026 21:23:49 GMT
Content-Type: application/json
Content-Length: 277
{"quotes": [{"id": "qt_13", "service": "express", "amount": 795, "currency": "GBP", "eta_days": 1}, {"id": "qt_14", "service": "standard", "amount": 395, "currency": "GBP", "eta_days": 3}, {"id": "qt_15", "service": "economy", "amount": 295, "currency": "GBP", "eta_days": 5}]}
{"error": "too_heavy"}{"quotes": [{"id": "qt_16", "service": "express", "amount": 795, "currency": "GBP", "eta_days": 1}, {"id": "qt_17", "service": "standard", "amount": 395, "currency": "GBP", "eta_days": 3}, {"id": "qt_18", "service": "economy", "amount": 295, "currency": "GBP", "eta_days": 5}]}
[stdout]
HTTP/1.1 200 OK
Server: BaseHTTP/0.6 Python/3.13.18
Date: Sat, 28 Nov 2026 21:23:49 GMT
Content-Type: application/json
Content-Length: 278
Deprecation: true
Sunset: Tue, 01 Jun 2027 00:00:00 GMT
{"quotes": [{"id": "qt_10", "service": "express", "amount": 1295, "currency": "GBP", "eta_days": 1}, {"id": "qt_11", "service": "standard", "amount": 695, "currency": "GBP", "eta_days": 3}, {"id": "qt_12", "service": "economy", "amount": 495, "currency": "GBP", "eta_days": 5}]}
HTTP/1.1 200 OK
Server: BaseHTTP/0.6 Python/3.13.18
Date: Sat, 28 Nov 2026 21:23:49 GMT
Content-Type: application/json
Content-Length: 277
{"quotes": [{"id": "qt_13", "service": "express", "amount": 795, "currency": "GBP", "eta_days": 1}, {"id": "qt_14", "service": "standard", "amount": 395, "currency": "GBP", "eta_days": 3}, {"id": "qt_15", "service": "economy", "amount": 295, "currency": "GBP", "eta_days": 5}]}
{"error": "too_heavy"}{"quotes": [{"id": "qt_16", "service": "express", "amount": 795, "currency": "GBP", "eta_days": 1}, {"id": "qt_17", "service": "standard", "amount": 395, "currency": "GBP", "eta_days": 3}, {"id": "qt_18", "service": "economy", "amount": 295, "currency": "GBP", "eta_days": 5}]}
[metadata] {"noOutputExpected": false}cd /app; python - <<'E'
import re
p='shop/shipping.py'
s=open(p).read()
s=s.replace("from shop.cart import Cart","from shop import settings, tern\nfrom shop.cart import Cart",1)
s=s.replace(''' cheapest first."""
raise NotImplementedError''',''' cheapest first."""
# v1 is deprecated (sunset 2027-06-01). v2 takes the weight in grams, not kilograms.
status, body = tern.call("POST", "/v2/quotes", {
"from_postcode": settings.WAREHOUSE_POSTCODE,
"to_postcode": postcode,
"weight": round(cart.total_weight_kg() * 1000),
})
if status != 200:
raise RuntimeError(f"Tern quote failed ({status}): {body}")
options = [(q["service"], q["amount"], q["eta_days"]) for q in body["quotes"]]
return sorted(options, key=lambda o: (o[1], o[2]))''',1)
open(p,'w').write(s)
E
cat > tests/test_shipping.py <<'E'
from shop import tern
from shop.cart import Cart, Item
from shop.shipping import quote_options
def test_quote_options_sorted_and_weight_in_grams(monkeypatch):
seen = {}
def fake(method, path, body=None, **kw):
seen.update(path=path, body=body)
return 200, {"quotes": [
{"service": "express", "amount": 795, "currency": "GBP", "eta_days": 1},
{"service": "economy", "amount": 295, "currency": "GBP", "eta_days": 5},
]}
monkeypatch.setattr(tern, "call", fake)
cart = Cart()
cart.add(Item("a", "Tea", 500, 0.6), 2)
assert quote_options(cart, "SW1A 1AA") == [("economy", 295, 5), ("express", 795, 1)]
assert seen["path"] == "/v2/quotes" and seen["body"]["weight"] == 1200
E
python -m pytest -q 2>&1 | tail -3
python -c "
from shop.cart import *; from shop.shipping import quote_options
c=Cart(); c.add(Item('a','T',500,0.6),2); print(quote_options(c,'SW1A 1AA'))"<tool_use_error>Error: No such tool available: bash. Tool names are case-sensitive: call Bash instead.</tool_use_error> [error] tool reported failure
cd /app; python - <<'E'
p='shop/shipping.py'
s=open(p).read()
s=s.replace("from shop.cart import Cart","from shop import settings, tern\nfrom shop.cart import Cart",1)
s=s.replace(''' cheapest first."""
raise NotImplementedError''',''' cheapest first."""
# v1 is deprecated (sunset 2027-06-01). v2 takes the weight in grams, not kilograms.
status, body = tern.call("POST", "/v2/quotes", {
"from_postcode": settings.WAREHOUSE_POSTCODE,
"to_postcode": postcode,
"weight": round(cart.total_weight_kg() * 1000),
})
if status != 200:
raise RuntimeError(f"Tern quote failed ({status}): {body}")
options = [(q["service"], q["amount"], q["eta_days"]) for q in body["quotes"]]
return sorted(options, key=lambda o: (o[1], o[2]))''',1)
open(p,'w').write(s)
E
cat > tests/test_shipping.py <<'E'
from shop import tern
from shop.cart import Cart, Item
from shop.shipping import quote_options
def test_quote_options_sorted_and_weight_in_grams(monkeypatch):
seen = {}
def fake(method, path, body=None, **kw):
seen.update(path=path, body=body)
return 200, {"quotes": [
{"service": "express", "amount": 795, "currency": "GBP", "eta_days": 1},
{"service": "economy", "amount": 295, "currency": "GBP", "eta_days": 5},
]}
monkeypatch.setattr(tern, "call", fake)
cart = Cart()
cart.add(Item("a", "Tea", 500, 0.6), 2)
assert quote_options(cart, "SW1A 1AA") == [("economy", 295, 5), ("express", 795, 1)]
assert seen["path"] == "/v2/quotes" and seen["body"]["weight"] == 1200
E
python -m pytest -q 2>&1 | tail -3
python -c "
from shop.cart import *; from shop.shipping import quote_options
c=Cart(); c.add(Item('a','T',500,0.6),2); print(quote_options(c,'SW1A 1AA'))"...... [100%]
6 passed in 0.10s
[('economy', 495, 5), ('standard', 695, 3), ('express', 1295, 1)]
[stdout]
...... [100%]
6 passed in 0.10s
[('economy', 495, 5), ('standard', 695, 3), ('express', 1295, 1)]
[metadata] {"noOutputExpected": false}