---
title: "14.8 Exercises"
url: https://una-lang.org/en/learn/testing/exercises/
release: v0.4.0
edition: "0.2"
---

# 14.8 Exercises

Each exercise starts from `exercises/N/start`, a package of the chapter's download: for exercises 1 to 3, the day-to-day program, and for exercises 4 and 5, the order intake of [section 14.3](https://una-lang.org/en/learn/testing/fakes-given-expect-performed-and-expect-not-performed/#an-order-line-that-never-reaches-the-inventory), each with the exercise's examples added at the end. `una test .` fails there until the exercise is done. Work in the start package: run `una test .` first and read which example fails and why, edit the code, run `una fmt .` to put it in canonical form, since the check requires it, then `una test .` again.

## 14.8.1 Exercise 1: a card that refuses everything

::::exercise
The start package has an example that needs a fake card processor which refuses every charge, whatever the amount:

```una include="exercises/1/start/src/checkout.una#L176-L182" title="exercises/1/start/src/checkout.una"
example "a card that refuses every charge is Declined"
  given @inventory = shelf(empty_map().with(key: "LAMP-01", value: 4))
  given @payments = refusing()
  given @mailer = outbox()
  do checkout([Line(sku: "LAMP-01", quantity: 1, unit_cents: 1990)], email: "ana@example.invalid")
  expect fails Declined
  expect performed @inventory.release
```

`una test .` stops at the check, since no handler is called `refusing`:

```text include="exercises/1/start/expected/diagnostics.txt"
error U1001 at src/checkout.una:178:21: cannot find handler `refusing` in this module, its imports or the prelude
```

:::hint
*Hint:* a handler implements every operation of its capability ([How to write a fake and install it](https://una-lang.org/en/learn/testing/fakes-given-expect-performed-and-expect-not-performed/#how-to-write-a-fake-and-install-it)). `Payments` has one operation, `charge`, and it fails with `PaymentError`. Copy `processor_down`, rename it, and fail with the other variant.
:::

Check your answer with `una test .`.

:::answer Answer (*check, run, test*; `exercises/1/answer`).
Add the handler next to the other fakes:

```diff include="exercises/1/start..exercises/1/answer:src/checkout.una" context="1" title="src/checkout.una"
--- a/src/checkout.una
+++ b/src/checkout.una
@@ -108,2 +108,6 @@
 
+--- A fake card processor that refuses every charge.
+handler refusing() for Payments
+  op charge(cents) = fail Refused
+
 --- A fake card processor that never answers.
```
:::
::::

## 14.8.2 Exercise 2: tell the customer

::::exercise
When the card is declined, the store wants to mail the customer, so that they can try another card. The start package has this example:

```una include="exercises/2/start/src/checkout.una#L176-L182" title="exercises/2/start/src/checkout.una"
example "a declined card mails the customer"
  given @inventory = shelf(empty_map().with(key: "LAMP-01", value: 4))
  given @payments = card(limit: 1000)
  given @mailer = outbox()
  do checkout([Line(sku: "LAMP-01", quantity: 2, unit_cents: 1990)], email: "ana@example.invalid")
  expect fails Declined
  expect performed @mailer.send
```

:::hint
*Hint:* the `Refused` arm of `checkout` becomes a block: send the mail, then fail. The arm then needs two lines, each indented under `is Refused ->`. Then run `una test .` again, and read which example fails now.
:::

If you change only the code, `una test .` reports another example:

```text include="exercises/2/code-only/expected/commands/test.txt#L6-L8"
example checkout "a declined card releases the stock and mails nothing" ... FAILED
  src/checkout.una:168: expect not performed @mailer.send
  the trace has `@mailer.send` at event 4
```

That example states the old behavior. A change of behavior changes the examples that describe it, in the same edit.

Check your answer with `una test .`.

:::answer Answer (*check, run, test*; `exercises/2/answer`).
Mail the customer in the `Refused` arm, and update the example that said no mail goes out:

```diff include="exercises/2/start..exercises/2/answer:src/checkout.una" context="1" title="src/checkout.una"
--- a/src/checkout.una
+++ b/src/checkout.una
@@ -81,3 +81,5 @@
         when problem
-          is Refused -> fail Declined(cents)
+          is Refused ->
+            @mailer.send(email, body: "Your card was declined for {cents} cents. Nothing was charged.")
+            fail Declined(cents)
           is Unreachable -> fail PaymentDown
@@ -158,3 +160,3 @@
 
-example "a declined card releases the stock and mails nothing"
+example "a declined card releases the stock"
   given @inventory = shelf(empty_map().with(key: "DESK-02", value: 1))
@@ -165,3 +167,2 @@
   expect performed @inventory.release
-  expect not performed @mailer.send
 
```
:::
::::

## 14.8.3 Exercise 3: put back what was reserved

::::exercise
Fix the gap named in [section 14.5](https://una-lang.org/en/learn/testing/day-to-day-checkout/#running-it). The start package has two examples. The first fails: a cart whose second line is out of stock must release the first. The second passes, and must keep passing: a cart whose first line is out of stock has nothing to release.

```una include="exercises/3/start/src/checkout.una#L176-L190" title="exercises/3/start/src/checkout.una"
example "a line out of stock releases the lines reserved before it"
  given @inventory = shelf(empty_map().with(key: "LAMP-01", value: 4))
  given @payments = card(limit: 100000)
  given @mailer = outbox()
  do checkout([Line(sku: "LAMP-01", quantity: 2, unit_cents: 1990), Line(sku: "DESK-02", quantity: 1, unit_cents: 24900)], email: "ana@example.invalid")
  expect fails OutOfStock
  expect performed @inventory.release

example "a first line out of stock releases nothing"
  given @inventory = shelf(empty_map().with(key: "LAMP-01", value: 4))
  given @payments = card(limit: 100000)
  given @mailer = outbox()
  do checkout([Line(sku: "DESK-02", quantity: 1, unit_cents: 24900), Line(sku: "LAMP-01", quantity: 2, unit_cents: 1990)], email: "ana@example.invalid")
  expect fails OutOfStock
  expect not performed @inventory.release
```

```text include="exercises/3/start/expected/commands/test.txt#L8-L13"
example checkout "a line out of stock releases the lines reserved before it" ... FAILED
  src/checkout.una:182: expect performed @inventory.release
  the trace has no `@inventory.release`
example checkout "a first line out of stock releases nothing" ... ok

8 examples: 7 passed, 1 failed
```

:::hint
*Hint:* in `reserve_all`, keep a `let edit` list of the lines reserved so far ([section 9.2](https://una-lang.org/en/learn/loops/names-that-change-let-edit/#s9-2)), and hand them to `release_all` before you fail. `reserve_all` then needs `release` in its `uses` too. Releasing every line of the cart passes the first example, but not the second.
:::

Check your answer with `una test .`.

:::answer Answer (*check, run, test*; `exercises/3/answer`).
Track the reserved lines, and release them at the first line that cannot be held:

```diff include="exercises/3/start..exercises/3/answer:src/checkout.una" context="1" title="src/checkout.una"
--- a/src/checkout.una
+++ b/src/checkout.una
@@ -43,7 +43,9 @@
 
---- Reserves the units of every line, and fails at the first line the warehouse cannot hold.
+--- Reserves the units of every line. At the first line the warehouse cannot hold, it releases
+--- the lines it reserved before it, and fails.
 reserve_all(lines: List[Line]) -> Unit
-  uses @inventory: Inventory[reserve]
+  uses @inventory: Inventory[reserve, release]
   fails CheckoutError
 =
+  let edit reserved: List[Line] = []
   for line in lines
@@ -51,3 +53,5 @@
     if not held
+      release_all(reserved)
       fail OutOfStock(sku: line.sku)
+    reserved = reserved.append(item: line)
 
```
:::
::::

## 14.8.4 Exercise 4: units shipped

::::exercise
This exercise works on the order intake of [An order line that never reaches the inventory](https://una-lang.org/en/learn/testing/fakes-given-expect-performed-and-expect-not-performed/#an-order-line-that-never-reaches-the-inventory). Write `shipped(results)`, the total of the units of the accepted lines of a batch. The start package has it with a body of `0`, and this example:

```una include="exercises/4/start/src/orders.una#L134-L140" title="exercises/4/start/src/orders.una"
--- How many units a batch ships in all. Exercise 4: replace the 0.
pub shipped(results: List[Result[Order, OrderError]]) -> Int = 0

example "a batch ships only its accepted units"
  given @inventory = warehouse(empty_map().with(key: "LAMP-01", value: 4))
  do shipped(process(["LAMP-01, 2", "LAMP-01, 9", "LAMP-01, 1"]))
  expect result == 3
```

The `do` line nests two calls. `process` asks the inventory, which the `given` line fakes, and `shipped` adds up what `process` gave back. `shipped` itself performs no operation.

:::hint
*Hint:* first write a private function from one outcome to its units: a `when` over the `Result` ([section 7.4](https://una-lang.org/en/learn/failure/failures-as-values-attempt-and-result/#s7-4)) whose `Ok` arm gives the order's quantity and whose `Err` arm gives 0. Then `shipped` is one line: `map` that function over the results, and `sum` the list ([section 10.3](https://una-lang.org/en/learn/collections/functions-over-lists-map-filter-and-fold/#s10-3)).
:::

Check your answer with `una test .`. On the start package it reports:

```text include="exercises/4/start/expected/commands/test.txt#L8-L12"
example orders "a batch ships only its accepted units" ... FAILED
  src/orders.una:140: expect result == 3
  it is false, with `result` = `0`

7 examples: 6 passed, 1 failed
```

:::answer Answer (*check, run, test*; `exercises/4/answer`).
Add `units`, and give `shipped` its body:

```diff include="exercises/4/start..exercises/4/answer:src/orders.una" context="1" title="src/orders.una"
--- a/src/orders.una
+++ b/src/orders.una
@@ -133,4 +133,11 @@
 
---- How many units a batch ships in all. Exercise 4: replace the 0.
-pub shipped(results: List[Result[Order, OrderError]]) -> Int = 0
+--- The units an outcome ships: its quantity when accepted, 0 when rejected.
+units(outcome: Result[Order, OrderError]) -> Int
+=
+  when outcome
+    is Ok(value) -> value.quantity
+    is Err -> 0
+
+--- How many units a batch ships in all.
+pub shipped(results: List[Result[Order, OrderError]]) -> Int = results.map(each: units).sum()
 
```
:::
::::

## 14.8.5 Exercise 5: fall back to the backup

::::exercise
This exercise works on the order intake of [An order line that never reaches the inventory](https://una-lang.org/en/learn/testing/fakes-given-expect-performed-and-expect-not-performed/#an-order-line-that-never-reaches-the-inventory). The store keeps a backup copy of its inventory. When the inventory does not answer, ask the backup once before giving up. The start package has `on_hand_or_backup`, which asks only the inventory, and three examples:

```una include="exercises/5/start/src/orders.una#on_hand_or_backup" title="exercises/5/start/src/orders.una"
--- The units of `sku` on hand: asks the inventory, and asks the backup copy once when the
--- inventory does not answer.
pub on_hand_or_backup(sku: Text) -> Option[Int]
  uses @inventory: Inventory[on_hand]
  uses @backup: Inventory[on_hand]
  fails StoreError
=
  -- Exercise 5: ask @backup when this call fails.
  @inventory.on_hand(sku)
    if error pass
```

```una include="exercises/5/start/src/orders.una#L145-L162" title="exercises/5/start/src/orders.una"
example "when the inventory does not answer, the backup does"
  given @inventory = offline()
  given @backup = warehouse(empty_map().with(key: "LAMP-01", value: 4))
  do on_hand_or_backup("LAMP-01")
  expect result == Some(4)

example "the backup is not asked when the inventory answers"
  given @inventory = warehouse(empty_map().with(key: "LAMP-01", value: 4))
  given @backup = offline()
  do on_hand_or_backup("LAMP-01")
  expect result == Some(4)
  expect not performed @backup.on_hand

example "when neither answers, the failure is Timeout"
  given @inventory = offline()
  given @backup = offline()
  do on_hand_or_backup("LAMP-01")
  expect fails Timeout
```

A handler holds no state, so no example can make one inventory fail once and then answer. With two bindings of `Inventory`, `@inventory` and `@backup`, each case is one an example can set up: one fake fails and the other answers.

:::hint
*Hint:* `attempt` works on a capability operation too. Keep the outcome of `@inventory.on_hand(sku)` with `let first = attempt …`, then take it apart with a `when`. The `Ok` arm gives the value as it is. The `Err` arm asks `@backup.on_hand(sku)`, on a line of its own, indented under the arm. The backup fails with `StoreError` too, the kind of `on_hand_or_backup`, so a plain `if error pass` under that call hands on its failure.
:::

Check your answer with `una test .`. The first example fails on the start package, and the second fails on an answer that always asks the backup.

:::answer Answer (*check, run, test*; `exercises/5/answer`).
Replace the body:

```diff include="exercises/5/start..exercises/5/answer:src/orders.una" context="1" title="src/orders.una"
--- a/src/orders.una
+++ b/src/orders.una
@@ -140,5 +140,8 @@
 =
-  -- Exercise 5: ask @backup when this call fails.
-  @inventory.on_hand(sku)
-    if error pass
+  let first = attempt @inventory.on_hand(sku)
+  when first
+    is Ok(value) -> value
+    is Err ->
+      @backup.on_hand(sku)
+        if error pass
 
```

To use it in the program, call it from `check_stock` in place of `@inventory.on_hand`. Then `check_stock`, `accept` and `process` also declare `uses @backup: Inventory[on_hand]`, `main` installs a handler for `@backup` in the same `with`, and every example that calls them gives `@backup` a `given` line.
:::
::::
