Home / Learn / 14 Testing

Release v0.4.0Edition 0.2

14.5 Day-to-day: checkout

Page 6 of 10

14.5.1 What the checkout must do

Now the program from the start of the chapter. A checkout takes a cart and an email address. It reserves the units of every line in the warehouse, charges the card for the total, and mails a receipt. Three services, each a capability, and each step can fail. Each part below says what it is for, and how the examples of section 14.6 reach it.

14.5.2 The kinds and the services

day-to-day/src/checkout.unathe kinds and the servicesuna
module checkout

--- One line of a cart: a SKU, how many units, and the price of one unit in cents.
pub kind Line
  sku: Text
  quantity: Int
  unit_cents: Int

--- Why a checkout did not go through.
pub kind CheckoutError = EmptyCart | OutOfStock(sku: Text) | Declined(cents: Int) | PaymentDown

--- How the card processor can fail.
pub kind PaymentError = Refused | Unreachable

--- The warehouse. `reserve` holds units for an order and says whether it could.
pub capability Inventory
  op reserve(sku: Text, quantity: Int) -> Bool
  op release(sku: Text, quantity: Int) -> Unit

--- The card processor. A charge gives the processor's reference for the payment.
pub capability Payments
  op charge(cents: Int) -> Text
    fails PaymentError

--- The store's mail service.
pub capability Mailer
  op send(to: Text, body: Text) -> Unit

CheckoutError is what the caller sees. PaymentError is what the card processor says, and the checkout translates it: a refused card becomes Declined, with the amount, and a processor that does not answer becomes PaymentDown.

reserve returns a Bool instead of failing. A warehouse that says "not enough units" has answered the question, and the checkout decides what that means for the order. A failure is kept for the case where a service cannot answer at all, as Unreachable is for the card processor. Each service is its own capability, so each example can fake one of them without touching the others, and a header shows which of them a function needs.

14.5.3 The total, a pure step

shipping_fee is the function of section 14.4, with its contract and without the requirement. total adds the lines and the fee. It performs no operation, so its examples need no fakes.

day-to-day/src/checkout.unauna
--- The shipping fee in cents: 4.90, and nothing from 50.00 on.
pub shipping_fee(subtotal: Int) -> Int
  ensures result >= 0 and result <= 490
  ensures subtotal >= 5000 implies result == 0
=
  if subtotal >= 5000 then 0 else 490

--- What the customer pays for a cart, shipping included.
pub total(lines: List[Line]) -> Int
=
  let edit subtotal = 0
  for line in lines
    subtotal = subtotal + line.quantity * line.unit_cents
  subtotal + shipping_fee(subtotal)

14.5.4 Reserving and releasing

Two private helpers, one for each direction. reserve_all fails at the first line the warehouse cannot hold. Private functions may leave their uses and fails to inference, but these two declare them, so each helper's effects can be read where it is defined.

day-to-day/src/checkout.unauna
--- Reserves the units of every line, and fails at the first line the warehouse cannot hold.
reserve_all(lines: List[Line]) -> Unit
  uses @inventory: Inventory[reserve]
  fails CheckoutError
=
  for line in lines
    let held = @inventory.reserve(line.sku, quantity: line.quantity)
    if not held
      fail OutOfStock(sku: line.sku)

--- Hands the units of every line back to the warehouse.
release_all(lines: List[Line]) -> Unit
  uses @inventory: Inventory[release]
=
  for line in lines
    @inventory.release(line.sku, quantity: line.quantity)

14.5.5 The checkout

An empty cart fails before any service is asked. Then the stock is reserved, and attempt keeps the outcome of the charge as a value, a Result that is Ok or Err (chapter 7), so the checkout can clean up before it fails: when the card is refused or the processor does not answer, the units go back to the warehouse.

day-to-day/src/checkout.unauna
--- Reserves the cart, charges the card, and mails a receipt. Gives the payment's reference.
pub checkout(lines: List[Line], email: Text) -> Text
  uses @inventory: Inventory[reserve, release]
  uses @payments: Payments[charge]
  uses @mailer: Mailer[send]
  fails CheckoutError
=
  if lines.len == 0
    fail EmptyCart
  else
    reserve_all(lines)
      if error pass
    let cents = total(lines)
    let charged = attempt @payments.charge(cents)
    when charged
      is Ok(reference) ->
        @mailer.send(email, body: "Paid {cents} cents. Reference {reference}.")
        reference
      is Err(problem) ->
        release_all(lines)
        when problem
          is Refused -> fail Declined(cents)
          is Unreachable -> fail PaymentDown

Step by step:

The order of the statements is the order of the effects: reserve, charge, then mail. The examples in section 14.6 pin that order down.

14.5.6 The log

describe turns an outcome into a line of the store's log, and reason gives each failure its words. Neither performs an operation.

day-to-day/src/checkout.unauna
--- What the store's log says about a checkout.
pub describe(outcome: Result[Text, CheckoutError]) -> Text
=
  when outcome
    is Ok(reference) -> "paid, reference {reference}"
    is Err(problem) -> reason(problem)

reason(problem: CheckoutError) -> Text
=
  when problem
    is EmptyCart -> "the cart is empty"
    is OutOfStock(sku) -> "not enough {sku} in stock"
    is Declined(cents) -> "the card was declined for {cents} cents"
    is PaymentDown -> "the card processor did not answer"

14.5.7 The fakes

One handler per behavior a test needs, as in Which fake to write: a warehouse with a given stock, a card processor with a limit, one that never answers, and a mail service that accepts everything. Each fits on a line or two. The parameters choose the case: card(limit: 10000) approves a cart of 44.70 and refuses one of 249.00, so one handler covers both outcomes, and each example shows its limit next to its cart.

day-to-day/src/checkout.unauna
--- A fake warehouse that holds the units in `stock`.
handler shelf(stock: Map[Text, Int]) for Inventory
  op reserve(sku, quantity) = stock.get(key: sku).or_else(default: 0) >= quantity
  op release(sku, quantity) = unit

--- A fake card processor that accepts every charge up to `limit` cents.
handler card(limit: Int) for Payments
  op charge(cents) = if cents <= limit then "PAY-{cents}" else fail Refused

--- A fake card processor that never answers.
handler processor_down() for Payments
  op charge(cents) = fail Unreachable

--- A fake mail service: it accepts every message and delivers none.
handler outbox() for Mailer
  op send(to, body) = unit

14.5.8 Running it

main installs the same fakes with with, and runs four carts: two lamps, two desks when one is in stock, one desk over the card's limit, and an empty cart. In a real store, the handlers would call the warehouse, the card processor and the mail server; the checkout itself would not change.

day-to-day/src/checkout.unauna
pub main() -> Unit
  uses @console: Console[print]
=
  let stock = empty_map().with(key: "LAMP-01", value: 4).with(key: "DESK-02", value: 1)
  let lamps = [Line(sku: "LAMP-01", quantity: 2, unit_cents: 1990)]
  let two_desks = [Line(sku: "DESK-02", quantity: 2, unit_cents: 24900)]
  let one_desk = [Line(sku: "DESK-02", quantity: 1, unit_cents: 24900)]
  let empty: List[Line] = []
  for cart in [lamps, two_desks, one_desk, empty]
    let outcome = attempt checkout(cart, email: "ana@example.invalid") with @inventory = shelf(stock), @payments = card(limit: 10000), @mailer = outbox()
    @console.print(describe(outcome))

One with clause binds the three services, separated by commas, for the call it ends. main itself holds only @console, so the checkout can reach no other service than the ones installed there.

una run . prints the log shown in What you'll build.

Warning

One path is still wrong. When the first line of a cart is reserved and the second is out of stock, the checkout fails without releasing the first. No example covers that case yet, so una test . passes. Exercise 3 writes the example that exposes it, then fixes the code.

14.5.9 The whole program

The whole file, to read in one piece or to copy:

day-to-day/src/checkout.unathe whole programcheckruntestuna
module checkout

--- One line of a cart: a SKU, how many units, and the price of one unit in cents.
pub kind Line
  sku: Text
  quantity: Int
  unit_cents: Int

--- Why a checkout did not go through.
pub kind CheckoutError = EmptyCart | OutOfStock(sku: Text) | Declined(cents: Int) | PaymentDown

--- How the card processor can fail.
pub kind PaymentError = Refused | Unreachable

--- The warehouse. `reserve` holds units for an order and says whether it could.
pub capability Inventory
  op reserve(sku: Text, quantity: Int) -> Bool
  op release(sku: Text, quantity: Int) -> Unit

--- The card processor. A charge gives the processor's reference for the payment.
pub capability Payments
  op charge(cents: Int) -> Text
    fails PaymentError

--- The store's mail service.
pub capability Mailer
  op send(to: Text, body: Text) -> Unit

--- The shipping fee in cents: 4.90, and nothing from 50.00 on.
pub shipping_fee(subtotal: Int) -> Int
  ensures result >= 0 and result <= 490
  ensures subtotal >= 5000 implies result == 0
=
  if subtotal >= 5000 then 0 else 490

--- What the customer pays for a cart, shipping included.
pub total(lines: List[Line]) -> Int
=
  let edit subtotal = 0
  for line in lines
    subtotal = subtotal + line.quantity * line.unit_cents
  subtotal + shipping_fee(subtotal)

--- Reserves the units of every line, and fails at the first line the warehouse cannot hold.
reserve_all(lines: List[Line]) -> Unit
  uses @inventory: Inventory[reserve]
  fails CheckoutError
=
  for line in lines
    let held = @inventory.reserve(line.sku, quantity: line.quantity)
    if not held
      fail OutOfStock(sku: line.sku)

--- Hands the units of every line back to the warehouse.
release_all(lines: List[Line]) -> Unit
  uses @inventory: Inventory[release]
=
  for line in lines
    @inventory.release(line.sku, quantity: line.quantity)

--- Reserves the cart, charges the card, and mails a receipt. Gives the payment's reference.
pub checkout(lines: List[Line], email: Text) -> Text
  uses @inventory: Inventory[reserve, release]
  uses @payments: Payments[charge]
  uses @mailer: Mailer[send]
  fails CheckoutError
=
  if lines.len == 0
    fail EmptyCart
  else
    reserve_all(lines)
      if error pass
    let cents = total(lines)
    let charged = attempt @payments.charge(cents)
    when charged
      is Ok(reference) ->
        @mailer.send(email, body: "Paid {cents} cents. Reference {reference}.")
        reference
      is Err(problem) ->
        release_all(lines)
        when problem
          is Refused -> fail Declined(cents)
          is Unreachable -> fail PaymentDown

--- What the store's log says about a checkout.
pub describe(outcome: Result[Text, CheckoutError]) -> Text
=
  when outcome
    is Ok(reference) -> "paid, reference {reference}"
    is Err(problem) -> reason(problem)

reason(problem: CheckoutError) -> Text
=
  when problem
    is EmptyCart -> "the cart is empty"
    is OutOfStock(sku) -> "not enough {sku} in stock"
    is Declined(cents) -> "the card was declined for {cents} cents"
    is PaymentDown -> "the card processor did not answer"

--- A fake warehouse that holds the units in `stock`.
handler shelf(stock: Map[Text, Int]) for Inventory
  op reserve(sku, quantity) = stock.get(key: sku).or_else(default: 0) >= quantity
  op release(sku, quantity) = unit

--- A fake card processor that accepts every charge up to `limit` cents.
handler card(limit: Int) for Payments
  op charge(cents) = if cents <= limit then "PAY-{cents}" else fail Refused

--- A fake card processor that never answers.
handler processor_down() for Payments
  op charge(cents) = fail Unreachable

--- A fake mail service: it accepts every message and delivers none.
handler outbox() for Mailer
  op send(to, body) = unit

pub main() -> Unit
  uses @console: Console[print]
=
  let stock = empty_map().with(key: "LAMP-01", value: 4).with(key: "DESK-02", value: 1)
  let lamps = [Line(sku: "LAMP-01", quantity: 2, unit_cents: 1990)]
  let two_desks = [Line(sku: "DESK-02", quantity: 2, unit_cents: 24900)]
  let one_desk = [Line(sku: "DESK-02", quantity: 1, unit_cents: 24900)]
  let empty: List[Line] = []
  for cart in [lamps, two_desks, one_desk, empty]
    let outcome = attempt checkout(cart, email: "ana@example.invalid") with @inventory = shelf(stock), @payments = card(limit: 10000), @mailer = outbox()
    @console.print(describe(outcome))

example "a cart under 50.00 pays shipping"
  do total([Line(sku: "MUG-03", quantity: 1, unit_cents: 4999)])
  expect result == 5489

example "a cart of two lamps is charged and mailed"
  given @inventory = shelf(empty_map().with(key: "LAMP-01", value: 4))
  given @payments = card(limit: 10000)
  given @mailer = outbox()
  do checkout([Line(sku: "LAMP-01", quantity: 2, unit_cents: 1990)], email: "ana@example.invalid")
  expect result == "PAY-4470"
  expect performed @mailer.send

example "an empty cart asks nobody anything"
  given @inventory = shelf(empty_map())
  given @payments = processor_down()
  given @mailer = outbox()
  do checkout([], email: "ana@example.invalid")
  expect fails EmptyCart
  expect not performed @inventory.reserve
  expect not performed @payments.charge
  expect not performed @mailer.send

example "a cart the warehouse cannot hold is never charged"
  given @inventory = shelf(empty_map().with(key: "DESK-02", value: 1))
  given @payments = card(limit: 100000)
  given @mailer = outbox()
  do checkout([Line(sku: "DESK-02", quantity: 2, unit_cents: 24900)], email: "ana@example.invalid")
  expect fails OutOfStock
  expect not performed @payments.charge

example "a declined card releases the stock and mails nothing"
  given @inventory = shelf(empty_map().with(key: "DESK-02", value: 1))
  given @payments = card(limit: 10000)
  given @mailer = outbox()
  do checkout([Line(sku: "DESK-02", quantity: 1, unit_cents: 24900)], email: "ana@example.invalid")
  expect fails Declined
  expect performed @inventory.release
  expect not performed @mailer.send

example "a card processor that does not answer is PaymentDown"
  given @inventory = shelf(empty_map().with(key: "LAMP-01", value: 4))
  given @payments = processor_down()
  given @mailer = outbox()
  do checkout([Line(sku: "LAMP-01", quantity: 2, unit_cents: 1990)], email: "ana@example.invalid")
  expect fails PaymentDown
  expect performed @inventory.release

Next:14.6 Testing it