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's shop, with its tests in a file beside it, as in chapter 27. 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 Java's System.setOut, and after it, the one marked @AfterEach gives the console back:
private val console = System.out
@BeforeEach
fun quiet() {
System.setOut(PrintStream(OutputStream.nullOutputStream()))
}
@AfterEach
fun 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 shows it, and Parcel as chapter 21 does. The workflow, Orders, is declared as chapter 23 shows it, and its steps, policies and reporters are where that page says they are shown:
/** An instance of the shop's workflow for an order of 30, with this card and this parcel. */
private fun order(order: String, card: String, weight: Long): WorkflowInstance<Sync> =
Orders(channel = "email")
.instance()
.initialData(
NewOrder(
order,
"Ann",
price = 30,
parcel = Parcel(weight, size = listOf(20, 15, 5)),
card = card,
)
)
.create()
/** An instance of the shop's workflow for an order of 30, with this card and this parcel. */
private fun order(order: String, card: String, weight: Long): WorkflowInstance<Async> =
Orders(channel = "email")
.instance()
.initialData(
NewOrder(
order,
"Ann",
price = 30,
parcel = Parcel(weight, size = listOf(20, 15, 5)),
card = card,
)
)
.create()
The first test runs the instance with a script. 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:
@Test
fun `a declined card is renewed and the charge tried again with it`() {
val run =
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.result.isSucceeded)
val retried = run.step("charge").attempt(2)
assertEquals("ann-2029", retried?.input("card", typeToken<String>())?.orNull())
}
@Test
fun `a declined card is renewed and the charge tried again with it`() =
runBlocking<Unit> {
val run =
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.result.isSucceeded)
val retried = run.step("charge").attempt(2)
assertEquals("ann-2029", retried?.input("card", typeToken<String>())?.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:
/** The reason a policy failed the journey with, if one did. */
private fun failedByAPolicy(result: JourneyResult): String? =
result.failure?.takeIf { it.cause == FailureCause.FAIL_WORKFLOW }?.reason?.code
/**
* Runs an order of 60 kg whose shipping fails on attempt 1 with this reason, and would succeed
* on attempt 2.
*/
private fun shippingThatFailsWith(reason: String): ScriptedRun =
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
fun `a shipping that fails with too-heavy is tried again`() {
val run = shippingThatFailsWith("too-heavy")
assertEquals(2, run.step("ship").attempts.size)
assertTrue(run.result.isSucceeded)
}
@Test
fun `a shipping that fails with over-parcel-limit is given up after attempt 1`() {
val run = shippingThatFailsWith("over-parcel-limit")
assertEquals(1, run.step("ship").attempts.size)
assertEquals("no-carrier-can-take-it", failedByAPolicy(run.result))
}
@Test
fun `a scripted shipping is still built with the weight the adapter supplies`() {
val run = shippingThatFailsWith("too-heavy")
val first = run.step("ship").attempt(1)
assertEquals(60L, first?.input("weight", typeToken<Long>())?.orNull())
}
/** The reason a policy failed the journey with, if one did. */
private fun failedByAPolicy(result: JourneyResult): String? =
result.failure?.takeIf { it.cause == FailureCause.FAIL_WORKFLOW }?.reason?.code
/**
* Runs an order of 60 kg whose shipping fails on attempt 1 with this reason, and would succeed
* on attempt 2.
*/
private suspend fun shippingThatFailsWith(reason: String): ScriptedRun =
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
fun `a shipping that fails with too-heavy is tried again`() =
runBlocking<Unit> {
val run = shippingThatFailsWith("too-heavy")
assertEquals(2, run.step("ship").attempts.size)
assertTrue(run.result.isSucceeded)
}
@Test
fun `a shipping that fails with over-parcel-limit is given up after attempt 1`() =
runBlocking<Unit> {
val run = shippingThatFailsWith("over-parcel-limit")
assertEquals(1, run.step("ship").attempts.size)
assertEquals("no-carrier-can-take-it", failedByAPolicy(run.result))
}
@Test
fun `a scripted shipping is still built with the weight the adapter supplies`() =
runBlocking<Unit> {
val run = shippingThatFailsWith("too-heavy")
val first = run.step("ship").attempt(1)
assertEquals(60L, first?.input("weight", typeToken<Long>())?.orNull())
}
The next ends the charge's first attempt in an error, as the bank's would:
@Test
fun `a charge that ends in an error is given up and never rescued`() {
val run =
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").attempts.isEmpty())
assertEquals("payment-network-down", failedByAPolicy(run.result))
}
@Test
fun `a charge that ends in an error is given up and never rescued`() =
runBlocking<Unit> {
val run =
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").attempts.isEmpty())
assertEquals("payment-network-down", failedByAPolicy(run.result))
}
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 problems hold a Mistake.AttemptLeftOut, from the same package, naming the attempt left out:
@Test
fun `a script that leaves out the shipping's attempt 2 is refused`() {
val script = scripted(order("A-4", "ann-2028", 1)).step("ship").willFail("too-heavy")
val mistake = assertThrows<TestMistake> { script.run() }
assertEquals(listOf(Mistake.AttemptLeftOut("ship", 2)), mistake.problems)
}@Test
fun `a script that leaves out the shipping's attempt 2 is refused`() =
runBlocking<Unit> {
val script = scripted(order("A-4", "ann-2028", 1)).step("ship").willFail("too-heavy")
val mistake = assertThrows<TestMistake> { script.run() }
assertEquals(listOf(Mistake.AttemptLeftOut("ship", 2)), mistake.problems)
}In the asynchronous form, which tests chapter 26's shop, the instance is a WorkflowInstance<Async>, run is a suspend function, and each test runs its body in runBlocking, writing its script the same way.
The console launcher prints the same for both forms:
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's attempt 2 is refused() :: STARTED
JUnit Jupiter > FlowTest > a script that leaves out the shipping's 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 731 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 ]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's attempt 2 is refused() :: STARTED
JUnit Jupiter > FlowTest > a script that leaves out the shipping's 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 756 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
- 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. - A script names steps by their names in the workflow. A rescue step is named by its own name,
charge_rescue.willFail,willTerminateAbnormallyandwillSucceedend an attempt, andwillContributeadds a contribution before it ends, which the executor commits only if the attempt succeeds. An attemptonAttemptdoesn't name is attempt 1. - The script must cover what can happen.
runchecks it before the journey starts, and throws aTestMistakeif 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 afterover-parcel-limit. - The run says what each step went through.
runreturns aScriptedRun: itsresultis the result an executor would have given, whoseisSucceededsays whether the journey succeeded, as in chapter 5, andstepgives a step's record. Itsattemptslists the attempts it had, andattempt(2)gives attempt 2, ornullwhen there was none. An attempt'sinputreads what its step was built with, asContributions'sreaddoes in chapter 27: 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. - 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. Withover-parcel-limit,failedShippinggives it up, andfailedByAPolicyreads the result'sfailure, chapter 25'sFailure, ornullfor a journey that didn't fail: its cause isFAIL_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. |