Unit tests and property tests are great when you have access to the code and can test from the inside, but what about when you want to test something from the outside? What about when you want to test an external system? This is typically integration / end-to-end testing. For example: you might want to test a webapp from a user’s point-of-view, automating interactions. Or you might want to test a live backend web service attached to a database.
In this article I’ll posit that testing stateful things from the outside is a special category deserving of special treatment. We’ll discuss goals and ideals, sketch a solution idea, then talk about an existing solution.
What makes integration testing different?
Unit and property tests are typically small, and only test a little functionality at a time. Integration tests are typically large, in that each test is comprised of many actions and assertions.
In unit tests it’s cheap to set up state before you test against it, whereas when testing an external system you have to manipulate the state through expensive actions, and the state is persistent. Each action requires the system to be in a certain state, and so most actions become dependent on previous actions in the same test.
In unit tests calling a function is immediate. In integration tests there’s often a delay between an action completing and the state settling — for example, DOM updates take time, new resources might need to be fetched, or state might have to trickle through to other microservices.
When a unit test fails you can easily re-run it and add debugging. When an integration test fails, especially on a nightly QA run or in CI, you often can’t step through it, and the environment may have already moved on or been torn down, making it hard to debug failures.
Integration tests effectively automate what human testers do. Human testers typically have tens of tests, with tens or even hundreds of steps in each. As such, writing automated integration tests is effectively like writing large test scripts.
An ideal solution
Let’s talk about what an ideal solution would look like.
Comprehensibility
My first goal is comprehensibility. There are two sides to this: comprehensibility of the code and comprehensibility of the results.
Starting with the results,
most test frameworks will throw an exception on the first failure.
When we’re writing large test scripts it isn’t helpful to get a single failure such as
AssertionFailed: Got 2, expected 1.
I want to know:
- Got 2 what? Expected 1 what?
- Was there more than a single failure?
- Whereabouts in the test script did the failure occur?
- What was the state of the system leading up to the failure?
As for comprehensibility of the code,
I want a non-programming human tester to be able to understand the code.
That means a separation of concerns so that actions and assertions are stated
in such a way that the what is separated from the how.
For example if we were testing a website, I want to see something like clickLoginButton() rather than
driver.find("form.login button")(2).click()
I want to see something like assertUserCount.increasedBy(1) rather than
val userCountBefore = driver.find("#users span")(4).text.toInt
login()
val userCountAfter = driver.find("#users span")(4).text.toInt
assertEquals(userCountAfter - userCountBefore, 1)
Separation of concerns & DRY
Going further with a separation of concerns, I want actions, assertions, internal state, external state observation, and test definitions to all be separate concepts. Not only does this help with comprehensibility and maintainability, it also keeps your code DRY.
And I want my code to be DRY. Inspecting the state of an external system is often brittle because there are no compile-time relationships enforced. A change in the external system can often result in changes to the integration tests to keep them in sync. Having precisely one place to change per external system change is efficient and maintainable.
Robustness
I want my tests to be robust. I don’t want them to be flaky. That means I want things like automatic retries, for example when we’re waiting for a state change to appear. An assertion that fails now might not fail in a second or two.
I also want my observations of the external state to be resilient — sometimes that means being more specific in your inspection so that you fail early rather than make a false observation and have tests fail for confusing reasons.
Functional programming
As a functional programmer, I want an FP solution.
I don’t just want to chuck everything in an IO monad so I can tick a box that makes me feel warm and fuzzy.
No, I want the benefits of common FP practices:
composability and reasonability via concepts like immutability, referential transparency, and parametricity.
Invariants, state, and property testing
I want to be able to encode invariants. I want to be able to specify things like “the count of users in the user panel list should always match the number of users displayed in the summary”. Invariants should always hold true, they should be specified once, and they should be automatically checked at every step of the test.
Having invariants allows us to have property testing too, almost for free, so long as we can encode dynamic actions. A simple example of this could be for all actions we can take, the target system should never crash: generate 1000 random (smart) actions and test it out.
Ideally our solution should be able to keep track of its own internal state too. That would allow us to write invariants like “the number of users on the screen should always match the number of users in our internal state”, and then we simply update our internal state on certain actions, allowing us to avoid manually testing the same condition everywhere.
Finally, we should allow state-machine based testing for domains in which the target system’s state changes in complex ways.
Sketching an API
Let’s dream up our ideal solution. First we’ll start off with some concepts.
Observation
The main concept in our solution that differentiates it from other solutions, is observation. Whereas the external system is a stateful, moving target, we want to take a snapshot of its state at given points in time.
We’ll take an observation of the external system and record everything we care about in a single value. This can be a product for multiple values, a sum type for a choice of values, or any combination of both. We should be able to declare the means of observation once and allow our shiny new test framework to fetch new observations whenever it deems necessary, like between actions, and on retry. So basically:
type Observer[Obs] = () => Obs
But we’ll need some extra features.
- It should support various execution models; we might want it to be async and have to wrap it in a
Future, or maybe use a ZIO or Cats Effect monad. It should also support direct synchronous usage too (which we can support viatype Id[A] = A). We’ll call this abstractionF[_]. - Observation should be able to fail.
- Observation often requires a driver/handle to the external system, for example: a database connection.
We’ll call this a
Reffor “reference”. Put it all together and we end up with:
type Observer[F[_], Ref, Obs, Err] = Ref => F[Err Or Obs]
An example observation could look like this:
class Obs(db: SqlConnection) {
val userCount: Int =
db.execute("select count(1) from users")
val tags: Set[String] =
db.executeList("select name from tags").toSet
val tagCount: Int =
tags.size
}
If you need multiple references, simply create your own composite, example:
case class Ref(http: HttpClient, db: SqlConnection)
Having a single observation type and handing over the means to make the observations to the test framework is a very different paradigm than the status quo — the status quo is to make micro-observations on demand, manually interleaved between actions and assertions. Our approach allows us to be DRY, separate concerns, have automatic retries, and support invariant testing.
Note that Obs doesn’t have to observe your entire system on every step — you scope it to what a given test suite
actually cares about. For a multi-page webapp, for instance, Obs is often a sum type representing whichever screen
or view is currently active, so each observation only inspects what’s actually visible.
Next we’ll create a DSL:
class Dsl[F[_], Ref, Obs, State, Err] {
// our API will go in here
}
We’ve added a new abstract type, State, to denote internal state tracking that we mentioned in the previous section.
These 5 types give us everything we need.
Reports
Next, let’s say that we have a Report that is generated after each test executes.
It should be capable of outputting a String that we can show to users.
It should be configurable too, such that if a test passes we can show a concise tree of all actions/steps taken,
and if a test fails we should be able to show more info so that the user can trace through it and understand the context.
It should also include an Option[Err].
An example could be this on success:
✓ Main test
✓ Login
✓ Search for item
✓ Add to cart
✓ Logout
✓ All pass.
Performed 23 actions, 19 checks.
And this on failure:
✘ Main test
✘ Login
✓ Set username to test123
✓ Set password to ThisIsATestAccount123456!
✘ Click Login
✘ Post-conditions
✘ Logged in user should be Some(test123), got None.
✘ Login form should be hidden.
- Search for item
- Add to cart
- Logout
Performed 3 actions, 3 checks.
Ideally it would be nice and colourful too.
Actions
Now let’s move on to our most basic building block: actions.
- Each action should have a name, and a function that acts.
- It should be able to fail.
- It should be able to update the internal state on success.
- The acting function should have access to the most recent
Ref,Obs, andState. - The action name should (optionally) be a function that also takes the most recent
Ref,Obs, andState. This allows for more specific info in the report. For example “test123” in the above report might not have been hardcoded but rather fetched dynamically from the DB. - Actions should have pre-conditions.
- Actions should have post-conditions.
- Actions should be horizontally composable in that they can be sequenced together to run in order.
- Actions should be vertically composable in that they can be nested, and grouped into a single composite action.
- Actions should be conditional, for example we might want to skip the login action if we’re already logged in.
Okay that was a fun set of features to dream up. Just for fun, this is what a subset of the API would look like:
case class ROS[R, O, S](ref: R, obs: O, state: S)
case class SingleAction[F[_], R, O, S, E](
name: Option[ROS[R,O,S]] => String,
act : ROS[R,O,S] => Option[() => F[E Or (O => E Or S)]])
Hairy! The types tell a story:
the Option is there to indicate an action can be skipped if its conditions aren’t met;
the () => F is there so that when we’re in synchronous mode and not using effect monads,
we have control over when the action executes;
the result of F allows for failure or a state update;
and the state update function O => E Or S also allows for failure.
Good thing we can hide it all behind a nice DSL so that usage looks like this:
val clickLoginButton =
dsl.action("Click Login")(_.obs.loginButton.click) // simple name, simple action
.updateState(_.login) // update state on success
.unless(_.state.isLoggedIn) // conditionality
When we’re doing web testing, in addition to being an immutable snapshot of data,
it’s natural for observations to also track elements on the page, as you can see from obs.loginButton.click above.
That way, all the CSS and page inspection is in one place.
As for composition, let’s use >> for sequencing, and .group to group multiple into a single.
val login = (enterUsername >> enterPassword >> clickLoginButton).group("Login")
Assertions
Now what about assertions? There are two kinds:
- “point” assertions: run at a single point in time.
(Obs, State) => Option[Err] - “around” assertions: gather data before an action, and assert after an action.
For example: “assert the user count increases by 1”.
(before: (Obs, State) => A, test: (Obs, State, A) => Option[Err])
Assertions should have names, and like actions, their names should be functions so that live information can be presented in the report. Ideally there should be a nice DSL. Remember we talked about a separation of concerns — here it’s wise to separate the subject of an assertion (which we’ll call a focus) from the assertion logic itself. This allows both for nicely reusable code and a clear API:
// Focus on a single value
val balance = dsl.focus("User's account balance").value(_.obs.balance)
// Single value assertion usage
balance.assert(0)
balance.assert.increaseBy(100)
balance.assert.noChange
// Focus on a collection
val names = dsl.focus("User names").collection(_.obs.userNames)
// Collection assertion usage
names.assert.distinct
names.assert.contains("Bob")
names.assert.equalIgnoringOrder("Bob", "Jane")
names.size.assert.decreaseBy(1)
Composition & invariants
Next we need a means of composing assertions together, and composing assertions with actions. I’m going to introduce 2 more symbolic operators and then we’ll stop at a grand total of 3, lest it become too confusing:
&for composing assertions together.balance.assert(0) & names.assert.contains("Bob")+>for composing actions and assertions. Here we’ll allowpreCondition +> actionandaction +> postConditionso that the+indicates we’re adding an assertion into an action, and the>continues to denote the order of events. Therefore, we can do this:balance.assert(0) +> deposit(100) +> balance.assert(100) >> withdraw(10) +> balance.assert(90)
Invariants are simply either kind of assertion but instead of being composed directly into actions, they are stored separately. Let’s imagine a test plan as follows, and trust that the test framework will interweave all the invariants before and after all the actions.
case class TestPlan(invariants: Assertions, actions: Actions)
We now have most of what we need. Let’s add dynamic assertions and actions to our DSL:
case class OS(obs: O, state: S)
case class ROS(ref: R, obs: O, state: S)
def choosePoint (n: Name)(f: OS => Points) : Point
def chooseAround (n: Name)(f: OS => Arounds) : Around
def chooseAction (n: Name)(f: ROS => Actions) : Action
def choosePointAttempt (n: Name)(f: OS => E Or Points) : Point
def chooseAroundAttempt(n: Name)(f: OS => E Or Arounds) : Around
def chooseActionAttempt(n: Name)(f: ROS => E Or Actions): Action
Now we have enough for property testing.
Retries
Next we need retries. We’re just sketching an API so it’s enough to say that our engine should support retries when anything fails: actions, state updates, assertions. There should be a user-specifiable retry policy. It should also be smart enough to only retry the bits that are needed. For example if an action succeeds but its post-conditions fail, then only the observations and post-conditions should be retried, not the action.
State machines
Seeing as we mentioned it earlier, we’ll just briefly cover state machine testing. We don’t need much more than we already have. All we need is a super-action supporting a dynamic number of dynamic sub-actions.
def loop(n: Name)(l: ROS => LoopResult): Action
where LoopResult can be:
- actions (including doing nothing)
- exit the loop (
break) - sleep for a specified duration
- any of the above plus a state update
- failure
And that’s about it. We’ve now dreamed up and explored what an ideal test framework for integration testing would look like, and discussed why its needs are different from that of an ordinary unit testing framework.
An existing solution
This topic is near and dear to my heart as I’ve spent many years doing extensive webapp testing using this approach. It’s a topic that brings me joy and I don’t know of any other libraries quite like it.
Patterns like the Page Object Model help separate the what from the how, and tools like ScalaCheck’s Commands
or Hypothesis handle stateful property testing,
but nothing (that I’m aware of) brings together all the features we sketched:
first-class observations, invariants, retries, rich reports, a composable (optionally-FP) API,
and the ability to write test scripts like a human tester would write.
I’ve created such a library called Scala Test State. It’s available for Scala and Scala.js, and has extension modules for ZIO and Cats Effect. It includes all the features we’ve discussed, plus more.
In one case at $WORK, I used it to rewrite a Selenium-based test suite, cutting runtime from 24 hours down to 20 minutes. It’s quietly been around for years at this point, and is battle-tested by real-world usage.
(I’ll talk more about using it for webapp testing in another blog post.)
A REST server example
Let’s look at a simple example of testing a JSON REST service. You might want to have this run against production after every deployment as a smoke test. Or you might run it on a schedule against your QA environment.
For the sake of brevity, I’ll omit some details like imports from the code snippets, but you can find the full code on GitHub: endpoints and tests.
We’ll use Cats Effect for our execution model, Tapir for our HTTP endpoint specification, and sttp as our HTTP client.
We’ll test a simple service with three endpoints:
GET /users/{id}
POST /users
DELETE /users/{id}
Let’s start by defining our user model:
case class User(id: UUID, name: String, createdAt: Instant)
Next let’s define our HTTP endpoints:
object Endpoints {
val userGet = endpoint
.get
.in("users" / path[UUID]("id"))
.errorOut(statusCode(StatusCode.NotFound).and(stringBody))
.out(jsonBody[User])
val userPost = endpoint
.post
.in("users")
.in(jsonBody[User])
.errorOut(statusCode(StatusCode.Conflict).and(stringBody))
.out(statusCode(StatusCode.Created).and(jsonBody[User]))
.out(header[String]("Location"))
val userDelete = endpoint
.delete
.in("users" / path[UUID]("id"))
.errorOut(statusCode(StatusCode.NotFound).and(stringBody))
.out(jsonBody[User])
}
Okay now let’s get to using Test State. We’ll aim to create a simple test script that does the following:
- Assert a test user doesn’t exist yet
- Create a test user
- Assert the test user exists and has the right name
- Delete the test user
- Assert the test user doesn’t exist anymore
Firstly, I don’t want to write the assertions 3 times so let’s track our expected state and use an invariant. For our observation we’ll make a GET request to query the user in the database. Finally, our invariant will assert that our observed user name matches our expected one.
case class Obs(user: Option[User])
case class State(userName: Option[String])
val dsl = Dsl.io[Ref, Obs, State] // F[_] = cats.effect.IO, Err = String
val userName = dsl.focus("User name").obsAndState(_.user.map(_.name), _.userName)
val invariant = userName.assert.equal
Let’s allocate a UUID for the test user once outside our test. We’ll store it in the ref. We’ll also need to know the URL and have access to a HTTP client so those go in the ref too.
case class Ref(testUserId: UUID, baseUri: Uri, http: WebSocketBackend[IO])
While we’re here let’s add a convenience method to make HTTP calls.
This takes an endpoint definition and an input, and returns an IO that, when executed, returns a response with either
an error or successful output.
case class Ref(testUserId: UUID, baseUri: Uri, http: WebSocketBackend[IO]) {
def call[I, E, O](endpoint: PublicEndpoint[I, E, O, Any])
(input: I): IO[Response[Either[E, O]]] =
SttpClientInterpreter()
.toRequestThrowDecodeFailures(endpoint, Some(baseUri))
.apply(input)
.send(http)
}
Next we’ll create an observer to make that GET call and use our new call method:
val observer = dsl.observer(ref =>
for {
response <- ref.call(Endpoints.userGet)(ref.testUserId)
} yield Obs(response.body.toOption)
)
Now we’re ready to think about actions. Firstly we’ll create action definitions:
def createUser(name: String) = dsl.action(s"Create user: $name").attempt { ros =>
for {
now <- IO.delay(Instant.now())
user = User(ros.ref.testUserId, name, now)
resp <- ros.ref.call(Endpoints.userPost)(user)
} yield resp.body.left.toOption
}.updateState(_.copy(userName = Some(name)))
def deleteUser = dsl.action("Delete user").attempt { ros =>
for {
resp <- ros.ref.call(Endpoints.userDelete)(ros.ref.testUserId)
} yield resp.body.left.toOption
}.updateState(_.copy(userName = None))
We’re using .attempt so that we can return an Option[Err] (which in our case is an Option[String])
in the case of failure,
which is exactly what our response body.left.toOption gives us.
Now we’re ready to write our test script. It is a simple thing:
val actions = createUser("Alice") >> deleteUser
Finally, we put everything together to be able to run this test:
def test(ref: Ref): IO[Report[String]] =
Plan(actions, invariant)
.withInitialState(State(None))
.withObserver(observer)
.withRef(ref)
.run()
And voilà, we’re done.
We simply create our Ref outside our test and call this method.
If we call .assert() on our Report we see this:
✓ Initial state.
✓ Create user: Alice
✓ Delete user
✓ All pass.
Performed 2 actions, 3 checks in 463 ms.
The implicit assertion settings use different formatting for success and failure.
Rather than customise these,
we can ask for more detail simply by calling .assert(useFailSettingsOnPass = true),
which results in this:
✓ Initial state.
✓ User name should be None.
✓ Create user: Alice
✓ Action
✓ Invariants
✓ User name should be Some("Alice").
✓ Delete user
✓ Action
✓ Invariants
✓ User name should be None.
✓ All pass.
Performed 2 actions, 3 checks in 394 ms.
We’ve made it to the end. Thank you for reading this far. I hope this has been as much fun to read as it was to write.
Stay tuned for a follow-up post on testing webapps. If you can’t wait, there are examples available here that you can read through.