# Testing the flow with scripted steps

## What you want to do

You want to check the shop's flow: that a declined card is rescued, that a parcel over the limit is given up after its first attempt, and that a charge ending in an error is never rescued. Each test should say how the steps end, without setting up a bank or a parcel that makes them end that way.

## The code

The program is [chapter 25](https://itinera-dev.org/book/java/25-reading-the-result.md)'s shop, with its tests in a file beside it, as in [chapter 27](https://itinera-dev.org/book/java/27-testing-a-step-alone.md). The shop's log prints a line for every event, and JUnit's console launcher shows all a test prints. So before each test, the method marked `@BeforeEach` sends what the program prints to nowhere, with `System.setOut`, and after it, the one marked `@AfterEach` gives the console back:

Java, from the program [`ch29_testing_the_flow_with_scripted_steps.test`](https://github.com/itinera-dev/book/blob/main/java/tested/ch29_testing_the_flow_with_scripted_steps.test.java)

```java
private final PrintStream console = System.out;

@BeforeEach
void quiet() {
  System.setOut(new PrintStream(OutputStream.nullOutputStream()));
}

@AfterEach
void speak() {
  System.setOut(console);
}

```

Each test makes an instance of the workflow for one of Ann's orders, a `WorkflowInstance<Sync>`, what `create()` gives for a synchronous workflow, from `org.itineradev.itinera.instance` and `org.itineradev.itinera.workflow`. `NewOrder` is as [chapter 25](https://itinera-dev.org/book/java/25-reading-the-result.md) shows it, and `Parcel` as [chapter 21](https://itinera-dev.org/book/java/21-deciding-where-a-steps-data-comes-from.md) does. The workflow, `Orders`, is declared as [chapter 23](https://itinera-dev.org/book/java/23-undoing-a-charge-when-the-shipping-fails.md) shows it, and its steps, policies and reporters are where that page says they are shown:

Java, from the program [`ch29_testing_the_flow_with_scripted_steps.test`](https://github.com/itinera-dev/book/blob/main/java/tested/ch29_testing_the_flow_with_scripted_steps.test.java)

```java
/** An instance of the shop's workflow for an order of 30, with this card and this parcel. */
private static WorkflowInstance<Sync> order(String order, String card, long weight) {
  var parcel = new Parcel(weight, List.of(20L, 15L, 5L));
  return new Orders("email")
      .instance()
      .initialData(new NewOrder(order, "Ann", 30, parcel, card))
      .create();
}

```

The first test runs the instance with a script. `Scripted.scripted(instance)`, from `org.itineradev.itinera.executor.testing`, starts it. `step` names a step, and what follows says what its attempts do in place of running it: what they contribute, and how they end. `onAttempt` moves on to another attempt of the same step, `andStep` to another step, and `run` runs the journey, throwing a `Refusal` as an executor's `run` does:

Java, from the program [`ch29_testing_the_flow_with_scripted_steps.test`](https://github.com/itinera-dev/book/blob/main/java/tested/ch29_testing_the_flow_with_scripted_steps.test.java)

```java
@Test
void a_declined_card_is_renewed_and_the_charge_tried_again_with_it() throws Refusal {
  var run =
      Scripted.scripted(order("A-1", "ann-2024", 1))
          .step("charge")
          .willFail("card-expired")
          .onAttempt(2)
          .willContribute("receipt", "R-A-1")
          .willSucceed()
          .andStep("charge_rescue")
          .willContribute("card", "ann-2029")
          .willSucceed()
          .andStep("ship")
          .willContribute("tracking", "T-A-1")
          .willSucceed()
          .run();
  assertTrue(run.getResult().isSucceeded());
  var retried = run.step("charge").attempt(2);
  assertEquals("ann-2029", retried.input("card", TypeToken.of(String.class)).orNull());
}

```

The next three run one script, in which the shipping's first attempt fails with the reason each test chooses, and the last of them reads what the shipping was built with:

Java, from the program [`ch29_testing_the_flow_with_scripted_steps.test`](https://github.com/itinera-dev/book/blob/main/java/tested/ch29_testing_the_flow_with_scripted_steps.test.java)

```java
/** The reason a policy failed the journey with, if one did. */
private static Optional<String> failedByAPolicy(JourneyResult result) {
  Failure failure = result.failure();
  if (failure == null || failure.cause() != FailureCause.FAIL_WORKFLOW) return Optional.empty();
  return Optional.of(failure.reason().code());
}

/**
 * Runs an order of 60 kg whose shipping fails on attempt 1 with this reason, and would succeed on
 * attempt 2.
 */
private static ScriptedRun shippingThatFailsWith(String reason) throws Refusal {
  return Scripted.scripted(order("A-2", "ann-2028", 60))
      .step("charge")
      .willContribute("receipt", "R-A-2")
      .willSucceed()
      .andStep("ship")
      .willFail(reason)
      .onAttempt(2)
      .willContribute("tracking", "B-A-2")
      .willSucceed()
      .run();
}

@Test
void a_shipping_that_fails_with_too_heavy_is_tried_again() throws Refusal {
  var run = shippingThatFailsWith("too-heavy");
  assertEquals(2, run.step("ship").getAttempts().size());
  assertTrue(run.getResult().isSucceeded());
}

@Test
void a_shipping_that_fails_with_over_parcel_limit_is_given_up_after_attempt_1() throws Refusal {
  var run = shippingThatFailsWith("over-parcel-limit");
  assertEquals(1, run.step("ship").getAttempts().size());
  assertEquals(Optional.of("no-carrier-can-take-it"), failedByAPolicy(run.getResult()));
}

@Test
void a_scripted_shipping_is_still_built_with_the_weight_the_adapter_supplies() throws Refusal {
  var run = shippingThatFailsWith("too-heavy");
  var first = run.step("ship").attempt(1);
  assertEquals(60L, first.input("weight", TypeToken.of(Long.class)).orNull());
}

```

The next ends the charge's first attempt in an error, as the bank's would:

Java, from the program [`ch29_testing_the_flow_with_scripted_steps.test`](https://github.com/itinera-dev/book/blob/main/java/tested/ch29_testing_the_flow_with_scripted_steps.test.java)

```java
@Test
void a_charge_that_ends_in_an_error_is_given_up_and_never_rescued() throws Refusal {
  var run =
      Scripted.scripted(order("A-3", "ann-2028", 1))
          .step("charge")
          .willTerminateAbnormally("the payment network is down")
          .onAttempt(2)
          .willContribute("receipt", "R-A-3")
          .willSucceed()
          .andStep("charge_rescue")
          .willSucceed()
          .run();
  assertTrue(run.step("charge_rescue").getAttempts().isEmpty());
  assertEquals(Optional.of("payment-network-down"), failedByAPolicy(run.getResult()));
}

```

The last test leaves out the shipping's attempt 2, and checks that `run` rejects the script by throwing a `TestMistake`, from `org.itineradev.itinera.testing`, whose `getProblems()` holds a `Mistake.AttemptLeftOut`, from the same package, naming the attempt left out:

Java, from the program [`ch29_testing_the_flow_with_scripted_steps.test`](https://github.com/itinera-dev/book/blob/main/java/tested/ch29_testing_the_flow_with_scripted_steps.test.java)

```java
@Test
void a_script_that_leaves_out_the_shipping_attempt_2_is_refused() {
  var script = Scripted.scripted(order("A-4", "ann-2028", 1)).step("ship").willFail("too-heavy");
  var mistake = assertThrows(TestMistake.class, script::run);
  assertEquals(List.of(new Mistake.AttemptLeftOut("ship", 2)), mistake.getProblems());
}
```

The console launcher prints:

What running the tests of `ch29_testing_the_flow_with_scripted_steps` prints, recorded in [`ch29_testing_the_flow_with_scripted_steps.txt`](https://github.com/itinera-dev/book/blob/main/java/tested/ch29_testing_the_flow_with_scripted_steps.txt)

```text
JUnit Jupiter > FlowTest > a charge that ends in an error is given up and never rescued :: STARTED
JUnit Jupiter > FlowTest > a charge that ends in an error is given up and never rescued :: SUCCESSFUL
JUnit Jupiter > FlowTest > a declined card is renewed and the charge tried again with it :: STARTED
JUnit Jupiter > FlowTest > a declined card is renewed and the charge tried again with it :: SUCCESSFUL
JUnit Jupiter > FlowTest > a script that leaves out the shipping attempt 2 is refused :: STARTED
JUnit Jupiter > FlowTest > a script that leaves out the shipping attempt 2 is refused :: SUCCESSFUL
JUnit Jupiter > FlowTest > a scripted shipping is still built with the weight the adapter supplies :: STARTED
JUnit Jupiter > FlowTest > a scripted shipping is still built with the weight the adapter supplies :: SUCCESSFUL
JUnit Jupiter > FlowTest > a shipping that fails with over parcel limit is given up after attempt 1 :: STARTED
JUnit Jupiter > FlowTest > a shipping that fails with over parcel limit is given up after attempt 1 :: SUCCESSFUL
JUnit Jupiter > FlowTest > a shipping that fails with too heavy is tried again :: STARTED
JUnit Jupiter > FlowTest > a shipping that fails with too heavy is tried again :: SUCCESSFUL

Test run finished after 309 ms
[         2 containers found      ]
[         0 containers skipped    ]
[         2 containers started    ]
[         0 containers aborted    ]
[         2 containers successful ]
[         0 containers failed     ]
[         6 tests found           ]
[         0 tests skipped         ]
[         6 tests started         ]
[         0 tests aborted         ]
[         6 tests successful      ]
[         0 tests failed          ]
```

## How it works

1. **The script replaces only a step's `run`.** Every step is still built for real, with its inputs and services: the shipping's first attempt was built with the weight the adapter supplied, 60. A step the script doesn't name runs for real, as the lookup and the pricing do here. Everything else is the executor's, as in any journey: the hooks, the decisions, the events and the result.
2. **A script names steps by their names in the workflow.** A rescue step is named by its own name, `charge_rescue`. `willFail`, `willTerminateAbnormally` and `willSucceed` end an attempt, and `willContribute` adds a contribution before it ends, which the executor commits only if the attempt succeeds. An attempt `onAttempt` doesn't name is attempt 1.
3. **The script must cover what can happen.** `run` checks it before the journey starts, and throws a `TestMistake` if a scripted step leaves out an attempt it can have, after a retry or a rescue, or can fail on attempt 1 while its rescue step has no script. So some of the other tests script attempts the workflow never reaches, such as the shipping's attempt 2 after `over-parcel-limit`.
4. **The run says what each step went through.** `run` returns a `ScriptedRun`: its `getResult()` is the result an executor would have given, whose `isSucceeded()` says whether the journey succeeded, as in [chapter 5](https://itinera-dev.org/book/java/05-a-first-journey.md), and `step` gives a step's record. Its `getAttempts()` lists the attempts it had, and `attempt(2)` gives attempt 2, or `null` when there was none. An attempt's `input` reads what its step was built with, as `Contributions`'s `read` does in [chapter 27](https://itinera-dev.org/book/java/27-testing-a-step-alone.md): for the charge's attempt 2, the card the rescue step contributed. Attempts that never ran aren't there, so the rescue step of the charge that ended in an error has none.
5. **The same script tests one decision of the flow.** Two tests run the shipping's script with only the reason its first attempt gives changed. With `too-heavy`, the shipping is retried and the order succeeds. With `over-parcel-limit`, `failedShipping` gives it up, and `failedByAPolicy` reads the result's `failure()`, [chapter 25](https://itinera-dev.org/book/java/25-reading-the-result.md)'s `Failure`, or `null` for a journey that didn't fail: its cause is `FAIL_WORKFLOW`, with the policy's reason.

So the flow is tested apart from the steps' rules: a change to the charge's rules never breaks these tests, and a change to the workflow is caught by them. But neither kind of test runs one real journey from start to end, with the shop's real steps and its services faked.

## Outcomes

We have shown how to test a workflow's flow with scripted steps, checked before the journey runs.

| The usual way                                                                                                         | With Itinera                                                                                              |
| --------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| Testing what happens after a failure often means making a real dependency fail, or mocking every call the code makes. | A script says how each attempt of a step ends, and the executor runs the rest of the journey as it would. |
| A test of the flow often breaks when a business rule changes.                                                         | Scripted steps never run their rules, so a change to those rules never changes what these tests see.      |
