In this chapter you will learn

  • how to test pure functions by providing examples
  • how to test pure functions by providing properties
  • how to test side effects without using any mocking libraries
  • how to develop new functionalities in a test-driven way

“ Beware of bugs in the above code; I have only proved it correct, not tried it. ”

—Donald Knuth

Do you have tests for that?

This last chapter of the book is devoted to one of the most important software engineering activities: testing . Tests are one of the major methods of writing maintainable software. They can be used to make sure the program behaves according to the requirements, it doesn’t have bugs we discovered earlier, and that it integrates with external APIs, services, or databases properly.

Having an application that consists mostly of pure functions that operate on immutable values makes writing tests a very enjoyable endeavor. The tests in this chapter are small and readable, and they cover a lot of production code.

On top of all that, we can also use tests to document the application: to help clarify the responsibilities and inner working to other team members. This is the best kind of documentation because it can’t get outdated as easily as normal text-based documentation usually does—assuming that the test itself is easy to understand. That all makes tests a very important element of well-developed, readable, and maintainable software.

We have dropped a few testing techniques and hints earlier in the book, but now it’s time to bring all we learned together and show how easy our testing job becomes once we choose the functional paradigm. We will first try to add tests to the existing pop culture travel guide application from the previous chapter. We will show you how to approach writing tests for our existing pure functions, including the IO-based ones. Unsurprisingly, we will discover some not-so-obvious bugs in our original implementations!

Did you catch any bugs in the previous chapter? If not, don’t worry. Tests have got your back, too!

We will then show you how easy it is to use tests as a documentation of features that are not yet implemented and use them to guide the implementation process. We will write tests first, then fill the implementation, following a very popular test-driven development practice. This will become a very important tool in your functional testing inventory. We will also learn some new pure functions and recap material from previous chapters along the way. Let’s start!

Tests are just functions

The main takeaway from this chapter is that we don’t introduce any new concepts that are useful only in the testing code. We reuse exactly the same mechanisms : pure functions and immutable values. We don’t need any mocking libraries because what we learned previously is enough to write any kind of tests!

You can find all the code we discuss in this chapter in the src/test/scala directory in the books’ companion code repository. Open the ch12_BasicTest file and try to write tests there! You should also remove other test files if you want to run only your tests!

The only additional tool we will need is the testing framework itself: we will run our tests using the scalatest library. One of the most basic options is calling the provided test function.

scalatest is the most popular Scala testing tool, and it provides a lot of different options and testing flavors. Here, we just focus on the most basic ones that are available in other tools and languages.

The signature above is a simplified version of what’s available in scalatest , but it’s enough to get accustomed to functional testing . We don’t want to go into scalatest library details. We will use it only to showcase functional programming testing techniques, which are also possible to achieve (and very popular) in other functional languages.

So what can we do with the test function? We can call it inside a testing class, passing the two required parameters: a String ( testName ) and a parameterless function ( testFun ), like this:

import org.scalatest.funsuite.AnyFunSuite    ①
class ch12_BasicTest extends AnyFunSuite {
  test("2 times 2 should always be 4")({     ②
    assert(2 * 2 == 4)                       ②
  })
}

① scalatest requires us to define all the function calls inside a class that extends from one of the built-in traits. In this case we use AnyFunSuite .

② We call the test function with the test case name and with a parameterless function (a block of code that will be executed lazily by the testing framework) that returns an Assertion . Here, we use a helper assert function that takes a Boolean condition and returns an Assertion value.

When we execute such a test in the terminal, we will get the following answer:

>

sbt test  ch12_BasicTest:
- 2 times 2 should always be 4
Run completed in 95 milliseconds.
Total number of tests run: 1
All tests passed.
In this chapter we will work from the IDE and terminal—not the REPL. Look at the book’s source code to see all the tests in action. Call `sbt test` and see the output of more than twenty tests we are going to implement in this chapter! Now that you know how all this works, let’s see some real test cases! ## Choosing functions to test The most convenient functions to test are pure functions that use simple types. Our testing adventure should start with trying to write tests for pure functions that don’t take or return `IO` values. There are two main reasons for choosing this particular strategy: - Such non- **`IO`** functions usually represent an important business logic. We can be pretty sure that they are part of the functional core. Yes, I know `IO` s are also immutable values! Testing functions that take and return them are also quite easy to write, but we’d like to focus on such tests separately, later in the chapter. - Tests for such functions are very easy to write. Looks like a win-win, right? We are writing tests for the most important functionality, and at the same time, these tests are the easiest to write. If we have a small, pure function that takes some immutable values and returns an immutable value back, the only job—and sometimes a very difficult one—is choosing the right immutable values. That’s when we are doing **testing by providing examples** . Usually, the better the requirements and the more the design of our application resembles those requirements, the easier the job of choosing the right examples becomes. One of the pure functions that doesn’t use `IO` values is `guideScore` . Sure enough, it’s one of the most important functions in the travel guide application. Here it is, along with the requirements: ```java def guideScore(guide: TravelGuide): Int = { val descriptionScore = guide.attraction.description.map(_ => 30).getOrElse(0) val quantityScore = Math.min(40, guide.subjects.size * 10) val totalFollowers = guide.subjects .map(_ match { case Artist(_, followers) => followers case _ => 0 }).sum val totalBoxOffice = guide.subjects .map(_ match { case Movie(_, boxOffice) => boxOffice case _ => 0 }).sum val followersScore = Math.min(15, totalFollowers / 100_000) val boxOfficeScore = Math.min(15, totalBoxOffice / 10_000_000) descriptionScore + quantityScore + followersScore + boxOfficeScore } ``` We wrote and discussed this function in chapter 11. The guide _score_ consists of - 30 points for a description - 10 points for each artist or movie (max. 40 points) - 1 point for each 100,000 followers (all artists combined; max. 15 points) - 1 point for each $10,000,000 in box office earnings (all movies combined; max. 15 points)                                                    ![](/images/book/grokking-functional-programming/2acfbe11-ff00-4bfc-aeba-65ace9481884.png) Let’s think about it first. How would you approach making sure that this implementation satisfies the requirements? ## Testing by providing examples The `guideScore` function can easily be tested by providing examples (input parameters), calling the function and asserting on its output. Pure functions always return the same outputs for the same inputs, so there shouldn’t be any nondeterminism or flakiness in such a test. **Important:** Open `ch12_TravelGuideTest` in your editor and remove all the test functions from there if you want to code along.

The difficult job here, however, is to come up with the right examples and right assertions. It’s very important to double-check—probably on a piece of paper or maybe in the code comment—that the asserted output is correct. Remember, your test is your last resort . It needs to be correct!

The best approach is to look at the function’s signature: ``` def guideScore(guide: TravelGuide): Int ``` We can immediately see that we need to come up with an example—a `TravelGuide` value—call the function passing that value, and then assert on an `Int` value we get back. That’s all we need. ``` test("score of a guide with a description, 0 artists, and 2 popular movies should be 65") { ① val guide = TravelGuide( Attraction( "Yellowstone National Park", Some("first national park in the world"), Location(LocationId("Q1214"), "Wyoming", 586107) ), List(Movie("The Hateful Eight", 155760117), Movie("Heaven’s Gate", 3484331)) ) // 30 (description) + 0 (0 artists) + 20 (2 movies) + 15 (159 million box office) assert(guideScore(guide) == 65) } ``` ① In Scala, we can omit the round brackets if we pass a function as a parameter. Here, it is passed using only curly brackets. Here, the `guide` value is the **example** we generated and provided. We then use it, referring to the requirements, to **manually calculate** what the result should be. Finally, we call the function and **assert** that the return value is correct. Our test suite consists of one test. Let’s run it.

>

sbt test  ch12_TravelGuideTest:
- score of a guide with a description, 0 artists, 
  and 2 popular movies should be 65
All tests passed.
THIS IS BIG! FP tests are just calling functions and asserting on their outputs. Great news! Our implementation is not that bad—it works correctly in at least one case. Let’s generate more examples in the same spirit. ## Practicing testing by example ![](/images/book/grokking-functional-programming/22898c8d-7cc6-4778-9976-130f00d11b0c.png) It’s your turn to write some tests and provide more examples that cover more combinations. Remember that the most important activity is to make sure your example is valid and the expected value you use in the assertion is correct according to the requirements. Here is the function-under-test signature: ``` def guideScore(guide: TravelGuide): Int ``` **Your task is to create a** **`TravelGuide`** **value, calculate manually the correct answer and write the following two tests** . 1. Score of a guide with no description, 0 artists, and 0 movies should be ... \* 2. Score of a guide with no description, 0 artists, and 2 movies with no box office earnings should be ... \* Remember to finish both sentences, providing the manually calculated expected value! Answers ```rust test("score of a guide with no description, 0 artists, and 0 movies should be 0") { val guide = TravelGuide( Attraction( "Yellowstone National Park", None, Location(LocationId("Q1214"), "Wyoming", 586107) ), List.empty ) // 0 (description) + 0 (0 artists) + 0 (0 movies) assert(guideScore(guide) == 0) } test("score of a guide with no description, 0 artists, and 2 movies with no box office earnings should be 20") { val guide = TravelGuide( Attraction( "Yellowstone National Park", None, Location(LocationId("Q1214"), "Wyoming", 586107) ), List(Movie("The Hateful Eight", 0), Movie("Heaven's Gate", 0)) ) // 0 (description) + 0 (0 artists) + 20 (2 movies) + 0 (0 million box office) assert(guideScore(guide) == 20) } ``` The guide _score_ consists of - 30 points for a description - 10 points for each artist or movie (max. 40 points) - 1 point for each 100,000 followers (all artists combined; max. 15 points) - 1 point for each $10,000,000 in box office earnings (all movies combined; max. 15 points) ## Generating good examples I hope you appreciate how concise and understandable the tests are when we fully embrace the functional programming paradigm. Note that this characteristic— **great testability** —comes with every pure function—no matter what language and testing library you choose. Testing in FP Testing in FP is testing pure functions by providing parameters and asserting on expected output values. We now have three test cases that cover quite different scenarios. Let’s execute the whole test suite. As a word of caution, remember to always double-check that you are testing the right thing. If you write some tests and they pass immediately, try changing the implementation of the function-under-test randomly and see whether tests start failing.

>

sbt test  ch12_TravelGuideTest:
- score of a guide with a description, 0 artists,
  and 2 popular movies should be 65
- score of a guide with no description, 0 artists, 
  and 0 movies should be 0
- score of a guide with no description, 0 artists, and 2 movies 
  with no box office earnings should be 20
All tests passed.
As you’ve just seen, we wrote three tests by providing three examples, and it looks like the function works correctly! However, while writing tests for pure functions is pretty straightforward, generating examples and **looking for potential corner cases can be very challenging** . This and the fact that we are the authors of the implementation (which makes the function ultimately bug-free, right?) tempts us to consider `guideScore` as a properly implemented function. Many programmers would agree that this is enough and safely move on, even though many various different examples are still missing.

Now, the worst thing is that—spoiler alert!— guideScore has at least one bug, which we haven’t found yet—neither in the previous chapter, where we implemented it nor here after writing a few example-based test cases. Can you spot it? Can you think of any examples that would expose this or another bug? If not, don’t worry. Testing is such a popular and powerful programming practice, specifically because finding bugs just by looking at the implementation is hard. And again, it’s even harder if you are the author of the implementation!

There are programmers who excel at finding bugs just by looking at the implementation; however, they too are using tests to confirm and prove what they found!

Some programmers would find the problem with the implementation quickly, and some would not. We can’t leave that much to chance! Too much is at stake. That’s why we need more techniques that help maximize the chance of finding the right examples and, as a consequence, the majority of bugs in our pure functions. FP gives us such techniques!

## Generating properties If you think that the function you implemented is correct and you can’t come up with any examples that prove otherwise, it’s best to add a few **property-based tests for your pure function** —especially if it belongs to the functional core and represents an essential concern.

What are those mysterious properties? They are more general descriptions of your function’s desired behavior. They require you to stop thinking about specific examples and focus on more high-level properties instead. This change of focus helps you look at the functionality from a different perspective, enhancing your chances of finding bugs. Let’s see this in practice and ask ourselves this: what are high-level requirement-like constraints of the guide scoring functionality ?

Separation of concerns

Separation of concerns was heavily discussed in chapter 8.

![](/images/book/grokking-functional-programming/89063a50-119c-40cd-9f03-46f77d058f33.png) The guide _score_ consists of - 30 points for a description - 10 points for each artist or movie (max. 40 points) - 1 point for each 100,000 followers (all artists combined; max. 15 points) - 1 point for each $10,000,000 in box office earnings (all movies combined; max. 15 points) We came up with three properties. The process of generating them is similar to generating specific examples: you look at the requirements and try to figure out how some values should impact (or not) the end result. For example, given all other values are the same, how much does the different number of movies affect the output value? You need to encode that in the test code. That’s where property-based tests come in. ## Property-based testing Generating properties is the hardest part of defining the property-based test. Once we have them, we can very conveniently transform them into test code. Let’s see the first property-based test in action. ```javascript import org.scalacheck._, Arbitrary._, org.scalatestplus.scalacheck._ ① test("guide score should not depend on its attraction's name and description strings") { forAll((name: String, description: String) => { val guide = TravelGuide( Attraction( name, Some(description), Location(LocationId("Q1214"), "Wyoming", 586107) ), List(Movie("The Hateful Eight", 155760117), Movie("Heaven's Gate", 3484331)) ) // 30 (description) + 0 (0 artists) + 20 (2 movies) + 15 (159 million box office) assert(guideScore(guide) == 65) }) } ``` ① We use the `scalacheck` library (it’s already installed if you use the book’s sbt console) to write property-based tests. We get a successful execution, but internally, the testing framework executed the function we passed to `forAll` multiple times and confirmed that no matter what `String` values are passed as name and description, the guide score will always be `65` . Isn’t it nice? We, as humans, came up with general properties of the system and delegated the hard work of generating examples to the computer. The behavior of the `forAll` and `test` functions are fully configurable. You can, for example, set the number of successfully executed assertions that are required to mark the whole test as successful. We will use default values in this book, which should be enough in most cases.

>

sbt test  ...
- guide score should not depend on its 
  attraction's name and description strings
All tests passed.
It looks pretty similar to what we previously had, right? The only difference is this new `forAll` helper function that takes a function, which—in this case—takes two `String` values and generates an `Assertion` . It turns out this function internally generates the two `String` values for us and calls our function multiple times with different `String` s! So the test above is executed many times with a different name and a different description! When we run this test, we get a familiar message: Property-based testing Property-based testing is testing applications by providing high-level requirement-like constraints and letting the testing framework generate and run the example-based test cases. ## Testing by providing properties Before implementing the remaining three property-based tests, let’s look at them from yet another perspective. If we look closely, these properties can be treated as examples but with some additional “wiggle points.” ![](/images/book/grokking-functional-programming/ac618f70-9ef0-44a2-a34a-e61a696bc115.png) These are exactly the same properties we listed earlier but now in a tabular form. Looking at this, we can quickly understand that the assertions also need to be more relaxed. Most of the time we are looking at asserting on ranges of possible output values, not specific ones. We asserted on the exact guide score for property #1 because the value of the attraction’s name and description shouldn’t have any impact on the score. For the remaining two properties we need ranges. Let’s implement one of them. We will write more properties in this chapter (you will too!). However, we will only show details, tables, and descriptions of the creation process for the first three properties. Explanations of properties in this table can be found in the “Generating properties” section two pages back. ``` test("guide score should always be between 30 and 70 if it has a description and some bad movies") { forAll((amountOfMovies: Byte) => { val guide = TravelGuide( Attraction( "Yellowstone National Park", Some("first national park in the world"), Location(LocationId("Q1214"), "Wyoming", 586107) ), if (amountOfMovies > 0) List.fill(amountOfMovies)(Movie("Random Movie", 0)) else List.empty ) val score = guideScore(guide) // min. 30 (description) and no more than 70 (upper limit with no artists and 0 box office) assert(score >= 30 && score <= 70) }) } ``` The second test makes sure that the functionality behaves correctly for any number of movies. The framework automatically picks different values of the expected type. In this case, it’s `Byte` , which may represent negative values; thus, we should make sure to not use them in the test. There is a better way of achieving that, which we’ll show very soon. ## Delegating the work by passing functions                                                    ![](/images/book/grokking-functional-programming/ff15092e-db72-459b-a495-fee73a647f0b.png) Q So we are just giving a function to the `forAll` function, and when the test runner runs the test, `forAll` automatically generates different parameters and then calls our function using them? A Yes! Note we can pass any function we want. In the first test we passed a two-parameter function that took `String` values. Then, we passed a function with a single `Byte` parameter. The values were generated automatically based on the types, so, in a sense, we delegated some work by passing a function. Now, let’s try to implement the third property-based test, passing a different function to the **`forAll`** function . We can do that by looking at the description and its tabular version. ❸ **The guide score should always be between 20 and 50 if there is an artist and a movie but no description** . If an attraction has no description, and its travel guide has a single artist and a single movie, its score will always be between 20 and 50 (inclusive), **no matter how much** the movie earned and how many followers the artist has. ![](/images/book/grokking-functional-programming/782f37f9-bad4-4e58-b750-e4c1cd7b38f8.png) ```php test("guide score should always be between 20 and 50 if there is an artist and a movie but no description") { forAll((followers: Int, boxOffice: Int) => { ① val guide = TravelGuide( Attraction( "Yellowstone National Park", None, Location(LocationId("Q1214"), "Wyoming", 586107) ), List(Artist("Chris LeDoux", followers), Movie("The Hateful Eight", boxOffice)) ) val score = guideScore(guide) // the score needs to be at least: 20 = 0 (no description) + 10 (1 artist) + 10 (10 movie) // but maximum of 50 in a case when there are lots of followers and high box office earnings assert(score >= 20 && score <= 50) }) } ``` ① This time we pass a function that takes two `Int` s. That means the test runner will run it with different `Int` values. The assertion below needs to hold for any combination. ## Understanding failures of property-based tests We have written three example-based tests and three property-based tests. Let’s run the whole test suite and see what happens.

>

sbt test  ch12_TravelGuideTest:
  - score of a guide with a description, 0 artists,      ①
    and 2 popular movies should be 65
  - score of a guide with no description, 0 artists,     ①
    and 0 movies should be 0
  - score of a guide with no description, 0 artists,     ①
    and 2 movies with no box office earnings should be 20
  - guide score should not depend on its a               ②
    attraction's name and description strings
  - guide score should always be between 30 and 70       ②
    if it has a description and some bad movies
  - guide score should always be between 20 and 50
    if there is an artist and a movie but no description *** FAILED ***

TestFailedException was thrown during property evaluation.
  Message: 19 was not greater than or equal to 20
  Occurred when passed generated values (
    arg0 = 0, // 63 shrinks
    arg1 = -11438470 // 39 shrinks
  )
  
Run completed in 1 second, 55 milliseconds.
Tests: succeeded 5, failed 1
*** 1 TEST FAILED ***

① Three example-based tests passed.

② Two property-based tests passed.

The last property-based test failed! The test executor gives us a lot of helpful details. It turns out that it generated 0 followers and -11438470 box ofice. The guide score was 19 while we were asserting that no matter what, it will be equal to or larger than 20. What are shrinks? As you can see, the error message we got is pretty detailed and understandable, except for two pieces of information: 63 and 39 **shrinks** . Let’s try to understand them. Here’s how the process looks from the start: 1. The test runner randomly chooses some parameters and executes our test multiple times with different combinations of parameters. 2. If all the generated combinations succeed, the test runner stops and reports test success. 3. Otherwise, when it encounters an error case, it is usually an “unreadable” combination like **`-1103249821`** and **`1567253213`** . It could report them, but it likes us humans and wants to be nicer. 4. The test runner tries to simplify the error-case parameters. It “guesses” a simpler parameter value (e.g., closer to 0) that may still fail and runs the test again. If the test still fails, the test runner has just performed a single shrink. This process continues until it cannot find a simpler value that still fails the test. So, in our example, 63 shrinks indicates that the test runner tried 63 times to simplify the first parameter, and it decided that “0" is the simplest one that still causes the failure. ## Wrong test or a bug? The test runner executed our property-based test and found a failing combination of parameters, simplified them (shrinking), and reported them. Now it’s our turn to interpret this result. Adding tests after the implementation carries more risk than adding them before the implementation. We always need to double-check whether we test the right thing—for example, by changing the implementation detail that should fail the test. We will explore adding tests before the implementation (test-driven development) at the end of this chapter. THIS IS BIG! Property-based tests help us look at our functions more critically.

The problem of making sure we test the right thing is present in the example-based tests, but it’s even more visible in the property-based ones because of the sheer number of different combinations. However, in both cases, when we write a new test and it fails, we first need to determine where the problem lies: is it the test that is wrong, or did we just find a bug in the implementation? Then, we’ll act accordingly.

The property-based test we wrote fails with the following exception: ``` TestFailedException was thrown during property evaluation. Message: 19 was not greater than or equal to 20 Occurred when passed generated values ( arg0 = 0, // 63 shrinks arg1 = -11438470 // 39 shrinks ) ``` `arg0` is the first argument of the function we passed to `forAll` ( `followers` ), and `arg1` is the second one ( `boxOffice` ). Here, based on the business case we have at hand, we can safely assume that the test is wrong. While `0` followers seems like a perfectly fine value, –11 million box office earnings is probably not something we need to support. If it was, then it’d be an implementation bug, and we’d need to change the implementation to support negative box office earnings. Let’s assume that, for our case, we only want to support and test nonnegative box office earnings. \* That means we need to make sure our property-based test generates only nonnegative `boxOffice` values. And while we are at it, the same should apply to followers. **We need to change the test** . + \* We use “nonnegative" numbers because 0 is a completely acceptable box office score, contrary to what Hollywood executives say. + That doesn’t mean our function is bug-free, though! No celebration yet. There is still a bug hiding there, waiting to be discovered. We will catch it with one of the next property-based tests we will write. Previously, we showed a snippet that partially solved such an issue: ``` if (amountOfMovies > 0) List.fill(...) else List.empty ``` `amountOfMovies` was a generated `Byte` value. When the test runner generated a negative `Byte` , we just replaced it with 0. However, this is not a perfect solution, and we can do a lot better. ## Custom generators Using an `if` expression in the test case to cut out half of the possibly generated values (e.g., all `Int` values smaller than 0) and replacing it with a constant value makes the test runner unaware of what’s going on inside. It may execute a lot of test cases with different negative values, but internally, it will always be the same test. What a waste!                                                    ![](/images/book/grokking-functional-programming/ff15092e-db72-459b-a495-fee73a647f0b.png) Q How, exactly, does the `forAll` function choose the parameters? A Let’s look at what’s going on internally when we pass a function with a single `Byte` parameter to `forAll` . The `forAll` function may call our test case (a function) against the following values: `–34` , `–5` , `29` , `57` , `0` , `–128` , `–59` , `1` , `127` , `–7` . Every time you execute such a test, you may get a different set of values with a different nu mber of entries, depending on the results. What’s important here is that “corner case" values have higher chances of being picked (e.g., `0` , the largest possible value \[ `127` for `Byte` \], the smallest one \[ `–128` \], and so on) and they are given extra weights in the generation process. Again, every execution is different, but if you include such a test in your continuous integration (CI) environment, your functions will get a lot of exposure to different parameter values! Going back to our original problem with negative values: if we replace all the negative values in the test with zeros, we will “get rid” of around half of our tests. This happens because all the generated negative values become zeros when we pass them to our pure function—and since it’s a pure function, we know we will always get the same result. Why do we bother calling it over and over again? We need to use the underlying resources more thoughtfully and pass as many different parameters on each execution as possible. We want to constrain the set of possible generated values. We want to customize how the parameters are generated. We need **custom generators** . To be able to generate only nonnegative integers, we need the following : THIS IS BIG! In FP, even generating random test values can be described by a single immutable value. ``` val nonNegativeInt: Gen[Int] = Gen.chooseNum(0, Int.MaxValue) ① ``` ① `chooseNum` is a built-in pure function that creates `Gen` values. It’s one of many such helper functions. You can discover and explore them by going to the `scalacheck` library documentation. `nonNegativeInt` is an **immutable value describing a process of generating** `Int` **values** . Again, note that it only describes the process, but this should no longer be a surprise for you because everything in functional programming is designed using this mindset. ## Using custom generators Using a custom `Gen` value is very straightforward because there is a special, curried version of the `forAll` function. It takes generators on its first parameter list, leaving the second parameter list to the function that executes our test case. Hence, not much changes in the new version. ```kotlin val nonNegativeInt: Gen[Int] = Gen.chooseNum(0, Int.MaxValue) ① forAll(nonNegativeInt, nonNegativeInt)((followers: Int, boxOffice: Int) => { val guide = TravelGuide( Attraction("Yellowstone National Park", None, Location(LocationId("Q1214"), "Wyoming", 586107)), List(Artist("Chris LeDoux", followers), Movie("The Hateful Eight", boxOffice)) ) val score = guideScore(guide) assert(score >= 20 && score <= 50) }) ``` ① `nonNegativeInt` is just an immutable value, and it can be reused by many tests, so let’s define it in the outer scope.

A cool thing about Gen values is that they can easily be reused and composed together. We can build more complicated, bigger generators from smaller ones. We already know how to do it because Gen has the flatMap function defined on itself ! Since we have a lot of intuition about using flatMap s—it’s our bread and butter now—we should be able to figure out how to compose smaller generators into a bigger one.

```javascript val randomArtist: Gen[Artist] = for { ① name <- Gen.identifier ① followers <- nonNegativeInt ① } yield Artist(name, followers) ① test("guide score should always be between 10 and 25 if there is just a single artist") { forAll(randomArtist)((artist: Artist) => { val guide = TravelGuide( Attraction("Yellowstone National Park", None, Location(LocationId("Q1214"), "Wyoming", 586107)), ② List(artist) ) val score = guideScore(guide) // no description (0), just a single artist (10) with random number of followers (0-15) assert(score >= 10 && score <= 25) }) } ``` ① Here, we create a custom generator of `Artist` values, which is built from two smaller generators. `identifier` is a built-in one that generates alphanumeric strings, and `nonNegativeInt` is the one we created earlier. It’s building big things from smaller ones all over again! ② Our new property-based test gets randomly generated artists, which have random alphanumerical names and nonnegative followers. We have just fixed one test and written a new one. Let’s run them.

>

sbt test  ...
All tests passed.
## Testing more complicated scenarios in a readable way Building generators is a great way to write many good and readable property-based tests—and do it quickly. The fact that we can easily combine smaller generators into bigger, more complicated ones means that we are able to test more sophisticated properties without sacrificing the readability. For example, let’s write a generator of lists of `Artist` s. ``` val randomArtists: Gen[List[Artist]] = for { numberOfArtists <- Gen.chooseNum(0, 100) ① artists <- Gen.listOfN(numberOfArtists, randomArtist) ② } yield artists ``` ① We first generate a number of elements in the output list. ② Then, we use another built-in helper function that generates a list of `numberOfArtists` elements, and each element is a value generated by the `randomArtist` generator we implemented earlier.

See? We have just created a Gen[List[Artist]] value that describes the process of generating random lists of a maximum of 100 Artist values (each with an alphanumeric name and nonnegative followers). It’s still just an immutable value created using the flatMap function. The randomArtists generator uses the randomArtist generator, which, in turn, uses the nonNegativeInt generator. randomArtists could easily be reused to create even more complicated generators (e.g., Gen[List[PopCultureSubject]] ), which we’ll ask you to implement yourself very soon. This process of creating more generators and properties should continue until we find a bug or exhaust our possibilities of writing new, good test cases.

Sequential programs

flatMap as a way of sequentially building bigger values from smaller ones was introduced in chapter 5, and we’ve used it in every chapter since.

Having a new `randomArtists` generator, we can now create a few more **property-based tests that are still very concise and readable** . Let’s see one of them. ``` test("guide score should always be between 0 and 55 if there is no description and no movies") { forAll(randomArtists)((artists: List[Artist]) => { val guide = TravelGuide( Attraction("Yellowstone National Park", None, Location(LocationId("Q1214"), "Wyoming", 586107)), artists ) // 40 points if 4 artists or more + 15 if 1_500_000 followers or more val score = guideScore(guide) assert(score >= 0 && score <= 55) }) } ``` Nothing unusual, right? However, it turns out this test finally finds a bug! ## Finding and fixing bugs in the implementation When we run our new test, we get the following test failure: ``` - guide score should always be between 0 and 55 if there is no description and no movies *** FAILED *** ① TestFailedException was thrown during property evaluation. Message: -19196 was not greater than or equal to 0 Occurred when passed generated values ( arg0 = List(Artist(l,225818040), Artist(q,2147483647)) // 6 shrinks ② ) ``` ① Remember that your failure details may be different, but you should get a failure when running this test! ② Note that the test runner performed six shrinks. That means that it first encountered a failure for a much more complicated list of artists, but it then worked its way through to simplify it, and it got us a perfectly small and self-contained failing example. Isn’t it helpful? It’s exactly what we needed! A real implementation bug—not a test problem. How can we know it’s an implementation bug just by looking at the failure message? Because the test runner provided us with a small, concise example of a list, which, when included in the travel guide, caused the `guideScore` function to return a negative score! Negative scores weren’t part of any of the requirements we listed earlier! The score should always be 0–100. The two generated artists look OK, too. Yes, they are called “ `l` ” and “ `q` ,” so they are not your usual celebrity names. But they have these big, 2-billion+ followings, which is not impossible, even now. I’d like to think they are some big artists from the future, maybe even extraterrestrial ones? Their names wouldn’t look so strange then, would they? All jokes aside—the implementation problem we found is a pretty common and dangerous one: **integer overflow** . This problem appears when an arithmetic operation creates a value that is outside of the given type’s range. In the case of Scala’s `Int` , the range is from `-2147483648` to `2147483647` . When we add two 2-billion+ values, we get a negative value. Note that in some cases you may need to work with larger numbers and will hit the `Long` -overflow problem. You can generate this problem by using `Gen[Long]` instead of `Gen[Int]` in the tests. You’d need to use the `BigInt` type to solve this safely. One of the possible solutions can be found in the book’s companion code. Fixing this problem is very straightforward. Inside the `guideScore` function, we need to use a type with a wider range, such as `Long` , to perform the internal additions. ``` val totalFollowers: Long = guide.subjects .map(_ match { case Artist(_, followers) => followers.toLong ① case _ => 0 }).sum ``` ① Here, we use the `.toLong` function to transform the followers `Int` to a `Long` value. This way adding two 2-billion+ values will not overflow. We need to do the same for `totalBoxOffice` and then transform `Long` s back to `Int` s when we deal with small scores. ``` val followersScore = Math.min(15, totalFollowers / 100_000).toInt ① ``` ① We can safely use `.toInt` here because we know it can’t be bigger than `15` . ## Coffee break: Property-based tests ![](/images/book/grokking-functional-programming/22fc00fa-ad5a-4637-bcfb-04ac1854bb1f.png) It’s time you develop our final property-based test. We’d like to check how the `guideScore` function behaves when it gets guides with different lists of `PopCultureSubject` s ( `Artist` s or `Movie` s). Hopefully it’s going to be successful and we will finally be able to move on! **Your task is t** . 1. Write new properties that will allow generating lists of random **`PopCultureSubject`** values 2. Write the new test that ensures that **`guideScore`** will always return a score of 0 to 70 if it gets a guide with pop culture subjects only (without a description, which is “worth” 30 points). When in doubt, remember that all we need is immutable values and pure functions. We use exactly the same ideas but applied to generating values for testing purposes. This new test can be described using the tabular view we introduced earlier: ![](/images/book/grokking-functional-programming/7a3dff15-8682-435b-8b3f-0f87f6d76cda.png) As you can see, the generator should be able to generate different combinations of random movies and artists. Here are the generators that we have already implemented. They may be used as an inspiration (and maybe even more?). ``` val nonNegativeInt: Gen[Int] = Gen.chooseNum(0, Int.MaxValue) val randomArtist: Gen[Artist] = for { name <- Gen.identifier followers <- nonNegativeInt } yield Artist(name, followers) val randomArtists: Gen[List[Artist]] = for { numberOfArtists <- Gen.chooseNum(0, 100) artists <- Gen.listOfN(numberOfArtists, randomArtist) } yield artists ``` You will probably need to use `Gen.identifier` , `Gen.chooseNum` , and `Gen.listOfN` in your generators, too! Hints - Make sure to reuse the generators above in your new generators. - The main generator should be a value of type `Gen[List[PopCultureSubject]]` . - When you have a `List[Movie]` and you append all the elements from the `List[Artist]` to it, the compiler will be able to infer the resulting type automatically. It’s going to be `List[PopCultureSubject]` . ## Coffee break explained: Property-based tests ![](/images/book/grokking-functional-programming/22fc00fa-ad5a-4637-bcfb-04ac1854bb1f.png) As with many other property-based tests, the most difficult work is to come up with the property itself, taking into consideration all domain-related caveats. Once that’s done, the rest of the process becomes easier. We first need to develop the generators. ``` val randomMovie: Gen[Movie] = for { ① name <- Gen.identifier ① boxOffice <- nonNegativeInt ① } yield Movie(name, boxOffice) ① val randomMovies: Gen[List[Movie]] = for { ② numberOfMovies <- Gen.chooseNum(0, 100) ② movies <- Gen.listOfN(numberOfMovies, randomMovie) ② } yield movies ② val randomPopCultureSubjects: Gen[List[PopCultureSubject]] = for { ③ movies <- randomMovies ③ artists <- randomArtists ③ } yield movies.appendedAll(artists) ③ ``` ① A `randomMovie` generator uses the built-in `Gen.identifier` generator to generate a random alphanumerical name and our own `nonNegativeInt` to generate the `boxOffice` value. ② We can use the `randomMovie` generator to generate a list of 0 to 100 random movies. ③ Then, we can build the final generator by using the new `randomMovies` generator and `randomArtists` we implemented earlier. We use `appendedAll` and get the list of pop culture subjects back. Once we have generators, we can write this very small, readable, and concise test case: ```rust test("guide score should always be between 0 and 70 if it only contains pop culture subjects") { forAll(randomPopCultureSubjects)((popCultureSubjects: List[PopCultureSubject]) => { ① val guide = TravelGuide( Attraction("Yellowstone National Park", None, Location(LocationId("Q1214"), "Wyoming", 586107)), popCultureSubjects ) // min. 0 if the list of pop culture subjects is empty (there is never any description) // max. 70 if there are more than four subjects with big followings val score = guideScore(guide) assert(score >= 0 && score <= 70) }) } ``` ① We pass the generator to `forAll` and use the generated value directly. When we run it, the test runner will generate a lot of lists and make sure that no matter how big or small a list is or how big or small the followers and `boxOffice` values are, the `guideScore` will always be between `0` and `70` . Additionally, all of this is achieved using **standard functional tools, which makes the tests easy to read and comprehend** . THIS IS BIG! We use exactly the same techniques in tests as in production code. ## Properties and examples As you can see , property-based tests can be pretty helpful and not very hard to write. This is, however, dependent on the application design: the more small, pure functions you have in your codebase, the better this form of tests will serve you. Remember that it’s usually hard for us humans to assume a function doesn’t behave correctly after writing a couple of passing example-based tests. When we can’t come up with any examples, it’s usually a good strategy to turn to property-based tests, just to be sure.                                                    ![](/images/book/grokking-functional-programming/ff15092e-db72-459b-a495-fee73a647f0b.png) Q What about unit tests, integration tests, and the testing pyramid? Can we use this categorization in functional program tests as well? A All the intuitions you have developed while testing imperative programs will definitely help you write better tests for your functional programs. However, there is an important difference that we need to highlight now to get this out of the way. Functional tests are about testing that a function returns an expected output value once we pass it a given set of parameters. That can mean that all functional tests are just unit tests, and we need to cover integration and end-to-end tests in an imperative way. However, as you shall see, the reality is that if we approach the design of the whole program in a functional way, we can cover a huge majority of functionalities (and code) just by writing those functional “unit" tests! And that’s great news, taking into account that writing unit tests is much easier than writing other types of tests: they are usually smaller, faster, and more stable. ![](/images/book/grokking-functional-programming/8291ffc3-33f7-4e9d-b989-0dd51af33d11.png) The next section of this chapter does exactly that. **We will write integration tests using examples and properties** . ## Requirements coverage

Let’s get one important issue out of the way. We should not write tests for the sake of writing tests. The ultimate goal is to ensure that our implementation works correctly according to the requirements . Tests are one way of achieving that—and the most popular one for sure, but we need to always remember that they are just a means to an end. Moreover, there are other ways of ensuring the code implements the requirements correctly, especially when we start using functional programming.

We have focused on testing `guideScore` using example-based and property-based tests, but there are more requirements that need to be covered, and it’s always a good idea to plan our testing strategy based on requirements. Here’s a summary of how confident we can be that each requirement is implemented correctly. Requirements: Pop culture travel guide 1. The application should take a single **`String`** value: a search term for the tourist attraction that the user wants to visit and needs a travel guide for. 2. The application needs to search for a given attraction, its description (if it exists), and its geographical location. It should prefer locations with larger populations. 3. The application should use a location to - Find artists originating from this location, sorted by the number of social media followers - Find movies that take place in this location, sorted by the box office earnings 4. For a given tourist attraction, artists and movies form its “pop culture travel guide” that should be returned to the user. If there are more possible guides, the application needs to return the one with the highest score, which is calculated as follows: - 30 points for a description - 10 points for each artist or movie (max. 40 points) - 1 point for each 100,000 followers (all artists combined; max. 15 points) - 1 point for each $10,000,000 in box office earnings (all movies combined; max. 15 points) 5. We will add support for more pop culture subjects in the future (e.g., video games). Requirement #1 is already covered because we encoded it as a function signature. The only requirements we still need to test are #2 and #3, and that’s where we will focus our attention next. We have covered requirement #4 by testing a single pure function, using examples and properties. That’s why we can be sure that this does what’s required. Requirement #5 is also covered because we encoded it as a type. This is yet another functional technique we can use, together with function signatures and different forms of tests. Note that there are different functional programmers that prefer one style over others. For example, type-level programming tries to put as many requirements in the types as possible and not write too many tests. We will not cover this in the book, but it’s important to understand different preferences. ## Testing side-effectful requirements The remaining requirements need some sort of external service to be implemented. In our case, we need a SPARQL endpoint that feeds our application with data. Parts of these requirements are already covered by types, but a majority of them aren’t. That’s why we still need tests for them. Remember that what we discuss here can be easily reused in other contexts such as SQL databases. The problems and solutions we show in the book would look very similar. Side-effectful requirements The application needs to search for a given attraction, its description (if it exists), and its geographical location. **It should prefer locations with larger populations.** This requirement is partially covered by types. We modeled `Attraction` exactly after this. The application should prefer locations to - Find artists originating from this location, sorted by the number of social media followers - Find movies that take place in this location, sorted by the box office earnings We are entering one of the most difficult territories: **testing side-effectful requirements** (i.e., requirements that need external data sources and read/write IO actions). If your application needs an external service of any kind to do its job, you are going to face integration problems. These include low-level things, such as proper request formats, parsing responses, API limits, performance; and high-level ones like synchronizing business data requirements with the way data is represented in the external service and transforming it correctly. And that’s just the tip of the iceberg because we also need to keep security issues, version upgrades, schema evolution, and more in mind. These problems can be verified using **integration testing** strategies. To cover these requirements, we will need two different kinds of tests: one for covering the request/response side (whether our read/write IO actions integrate correctly with the external data source) and one for covering the usage side (whether the data from responses is used correctly). Fortunately, the functional design paradigm we have embraced will help us write both kinds of tests without changing anything in the production code and without any need for specialized mocking libraries. Functional tools, the fact that everything is an immutable value, and your preexisting intuitions from testing imperative programs would be enough to write concise and helpful tests. Imperative programming embraced mocking and mocking libraries to write tests that focus on a single aspect of an integration. To achieve that, one needs to imitate other aspects or fix them. This is where mocks and stubs are helpful. ## Identifying the right test for the job Identifying requirements for a particular type of test is not a trivial task, and it gets substantially harder when we deal with side-effectful functionalities. The best approach is to ask a question about responsibilities: “Is this particular requirement handled mostly by the application or the external service itself?” The application needs to search for a given attraction, its description (if it exists), and its geographical location. **It should prefer locations with larger populations** .                             ↓ This is an **external service concern,** because our application only **specifies** how the date in the response should be ordered—the ordering itself needs to be handled by the service. The same applies to SQL queries: we don’t usually want to query all the rows of a table and then sort them—that would be wasteful and not always possible. That’s why “how to sort the results” and “prefer locations with larger populations” are both mostly the external service’s internal concerns, and we don’t need to test them directly. There is no point in stubbing a response that is already sorted and claim that we tested it. If our functionality depends completely on a concern that is internal to the external service, we can only test it properly by using the real service. Otherwise, if we deal with a concern internal to our application, we can “imitate” the external service by using mocks or **stubs** (simple versions of the external service that always return the same responses). To stub or not to stub? We can use this information to identify the two different types of tests we need to write to verify side-effectful functionalities against requirements: - _Service data usage tests_ —How the application uses data after it’s fetched or prepares data before it’s stored, including the way it’s transformed from and to business values (the external service data can be stubbed here because it’s not the concern we test). - _Service integration tests_ —Whether the application formats requests and fetches responses from the real service correctly (the data can’t be stubbed—we need to use the real service to test it). Note that both types of tests test only our application’s concerns. The first tests high-level ones, while the second tests more low-level ones, including proper API message formatting. ## Data usage tests Let’s start by adding tests that make sure the application we’ve written uses the external data according to the requirements. Remember that it’s always a good idea to try to infer test cases directly from the requirements. ![](/images/book/grokking-functional-programming/f2e4c18e-d63f-47fb-8691-0024a7035603.png) As you can see, we are able to produce test cases based only on the requirements without touching or analyzing the production code! The only assumption here is that artists and movies need to be fetched from the external data source and used in the application (i.e., included in the travel guide returned by the application’s main function). Note that we don’t discuss anything about the requests, servers, APIs, or even the response’s format. In these tests we want to make sure our application uses the external data according to the requirements. We will make sure the data is correctly fetched and parsed using a different form of tests with real servers running in the background! Let’s write our first test that “assumes” there is a specific location and artist available in the external data source.

❶

Let’s start with the test "scaffold." Let’s describe what we’d like the test to look like from a birds-eye perspective. We will use a given–when–then template and write comments.

```javascript test("travel guide should include artists originating from the attraction's location") { ① // given an external data source with an attraction named "Tower Bridge" ② // at a location that brought us "Queen" ... // when we want to get a travel guide for this attraction ② ... // then we get a travel guide with "Queen" ② ... } ``` ① Using such a template helps to understand what we’d like to test in detail without writing any code. Note that `scalatest` and other test libraries have a better way of writing a given–when–then template, but we decided to keep tests in this book as simple as possible and leave all possible improvements and decorations to you and your team. ② Note that the **given** section will be the one that prepares the data that we will then “stub” in the **when** section, which will execute the _function under test_ . Finally, the **then** section will contain the assertion.

❷

Next, let’s fill the given section, which should contain all the data we’d like to have available for our test. It’s up to us to pick the right examples: some real ones may give test readers some additional context. Here, we want our stubbed external service to have information about Tower Bridge in London and be able to return a single artist (”Queen”) originating from London.

```php test("travel guide should include artists originating from the attraction's location") { // given an external data source with an attraction named "Tower Bridge" // at a location that brought us "Queen" val attractionName = "Tower Bridge" val london = Location(LocationId("Q84"), "London", 8_908_081) val queen = Artist("Queen", 2_050_559) val dataAccess = new DataAccess { def findAttractions(name: String, ordering: AttractionOrdering, limit: Int): IO[List[Attraction]] = IO.pure(List(Attraction(attractionName, None, london))) def findArtistsFromLocation(locationId: LocationId, limit: Int): IO[List[Artist]] = if (locationId == london.id) IO.pure(List(queen)) else IO.pure(List.empty) def findMoviesAboutLocation(locationId: LocationId, limit: Int): IO[List[Movie]] = IO.pure(List.empty) ① } // when we want to get a travel guide for this attraction ... // then we get a travel guide with "Queen" ... } ``` ① The `dataAccess` value contains three functions that represent our stubbed external service. It always returns a single attraction, never return any movies, and returns “Queen” only if somebody wants to fetch artists from London.

❸

Note that our job is very straightforward now. We have a single dataAccess value that contains three pure functions (which are also values!) that return specific, hardcoded information without any failures (this is how we “stubbed” the external service). We now need to call the function under test ( travelGuide ) and see whether it correctly read the data and included it in the resulting guide.

```php test("travel guide should include artists originating from the attraction's location") { // given an external data source with an attraction named "Tower Bridge" // at a location that brought us "Queen" val attractionName = "Tower Bridge" val london = Location(LocationId("Q84"), "London", 8_908_081) val queen = Artist("Queen", 2_050_559) val dataAccess = new DataAccess { def findAttractions(name: String, ordering: AttractionOrdering, limit: Int): IO[List[Attraction]] = IO.pure(List(Attraction(attractionName, None, london))) def findArtistsFromLocation(locationId: LocationId, limit: Int): IO[List[Artist]] = if (locationId == london.id) IO.pure(List(queen)) else IO.pure(List.empty) def findMoviesAboutLocation(locationId: LocationId, limit: Int): IO[List[Movie]] = IO.pure(List.empty) ① } // when we want to get a travel guide for this attraction val guide: Option[TravelGuide] = travelGuide(dataAccess, attractionName).unsafeRunSync() ② // then we get a travel guide with "Queen" assert(guide.exists(_.subjects == List(queen))) } ``` ① We pass the `dataAccess` value representing the stubbed external service to the `travelGuide` function. Then, we `unsafeRunSync` the `IO` value to “run” the program. ② Finally, in the `then` section, we assert that the resulting travel guide contains the artist, which confirms that the function read and used the value from an external service correctly. And that’s all! We have just tested `travelGuide` and confirmed that it **uses the data from the external service properly** ! The test is small, concise, and there is no magic in it: just values and functions. Such tests are even more powerful when we have more external services. ## Practicing stubbing external services using `IO` ![](/images/book/grokking-functional-programming/22898c8d-7cc6-4778-9976-130f00d11b0c.png) To practice what we learned, let’s try to write a similar test that confirms that our implementation correctly uses movie-related data coming from an external service. You will be testing the `travelGuide` function: ``` def travelGuide( data: DataAccess, attractionName: String ): IO[Option[TravelGuide]] ``` **Your task is to create the test of “travel guide should include movies set in the attraction’s location”** that uses the following template:

Given an external data source with an attraction named “ Golden Gate Bridge ” at a location where “ Inside Out ” was taking place,

when we want to get a travel guide for this attraction,

then we get a travel guide that includes the “ Inside Out ” movie.

“Inside Out" (box office 857611174 ) was taking place in San Francisco (population 883963 ), which has id "Q62" in Wikidata (all these may not be important, but you need to put some values there, and it’s usually better to use values that improve comprehension and act as documentation, which we’ll discuss later).

Answer ```php test("travel guide should include movies set in the attraction's location") { // given an external data source with an attraction named "Golden Gate Bridge" // at a location where "Inside Out" was taking place in val attractionName = "Golden Gate Bridge" val sanFrancisco = Location(LocationId("Q62"), "San Francisco", 883_963) val insideOut = Movie("Inside Out", 857_611_174) val dataAccess = new DataAccess { def findAttractions(name: String, ordering: AttractionOrdering, limit: Int): IO[List[Attraction]] = IO.pure(List(Attraction(attractionName, None, sanFrancisco))) def findArtistsFromLocation(locationId: LocationId, limit: Int): IO[List[Artist]] = IO.pure(List.empty) def findMoviesAboutLocation(locationId: LocationId, limit: Int): IO[List[Movie]] = if (locationId == sanFrancisco.id) IO.pure(List(insideOut)) else IO.pure(List.empty) } // when we want to get a travel guide for this attraction val guide: Option[TravelGuide] = travelGuide(dataAccess, attractionName).unsafeRunSync() // then we get a travel guide that includes the "Inside Out" movie assert(guide.exists(_.subjects == List(insideOut))) } ``` ## Testing and design In the last two tests we made use of the fact that `travelGuide` takes a `DataAccess` value as a parameter. \* This way we could pass a `DataAccess` value that had hardcoded responses. (We wrote that this was a “stubbed” external service, but we don’t really do anything out of the ordinary here. It’s still just a value holding references to three pure functions—nothing more). \* We can use this technique in many more testing scenarios, including “semi-end-to-end" tests, which we will briefly discuss later.                                                    ![](/images/book/grokking-functional-programming/ff15092e-db72-459b-a495-fee73a647f0b.png) Q What if I need to stub something that is not exposed as a function parameter? A That is a very good question that doesn’t have a definitive answer. However, just asking such question should make us aware that there might be a problem in the design of the application. If we generated test cases directly from requirements and our code didn’t support providing some of the things we wanted to “stub" (assume they are always the same), it would usually mean that there are some entangled concerns that we need to separate. In FP, it usually means exposing something as a parameter: either a pure function or a different immutable value. That’s how merely thinking about tests may improve the overall design. Note that we will design using TDD later in the chapter. Separation of concerns Separation of concerns was heavily discussed in chapter 8. ![](/images/book/grokking-functional-programming/94769ff0-d85a-4c4b-afca-4fb3af0986c8.png) A well-designed function exposes only the right amount of parameters that represent essential concerns. Tests help us find this balance. Moreover, remember that the function itself should be responsible for doing a single thing only. All that is usually difficult to pull off, but designing immutable values and writing pure functions with tests for them iteratively helps a lot in making it happen.                                                    ![](/images/book/grokking-functional-programming/ff15092e-db72-459b-a495-fee73a647f0b.png) Q OK, another question. Why do we treat functions that use `IO` values differently? They are just values like everything else, right? And the tests look like normal example-based tests we wrote earlier. A They look the same because they use the same FP tooling! However, the rule of thumb is that the majority of our code should consist of pure functions that don’t take or return `IO` values because they mean that there is going to be some external, impure world involved, and that’s important for testing. We need to verify a lot more about such functions: how they use the data from the external source is just one of them. If you additionally feel that our `IO` -based tests had too much duplicated code, especially in the test setup phase, don’t worry because we will address these concerns later. ## Service integration tests The second aspect we need to test to make sure our application works correctly in the presence of side effects is its integration with the real service that is used in production. In our case, we need to make sure the application integrates correctly with real SPARQL endpoints. There are several different approaches we can use here, and they are usually paradigm-agnostic, meaning that in these tests it doesn’t matter whether we use imperative or functional programming that much. However, FP does give us a little bit more flexibility, as we will show later in the chapter, even in this case. Again, remember that the same rules apply to SQL integration or any other external service or data source, for that matter. Testing low-level integration with external APIs The important thing here is that we want to test only the integration with a SPARQL endpoint, and that means we don’t really need to write any business-related tests, which are covered by the tests where we stubbed the `IO` values (data usage tests). We are going to test on a lower level now. We only need to “prove” that all three `DataAccess` functions used in production are correctly integrating with a real SPARQL endpoint—no matter how they are later used by the `travelGuide` and other functions. Different aspects of the application may need different testing approaches, and we need to choose carefully. Here, we will use a _Fuseki SPARQL_ _server_ that is part of the Apache Jena library we’ve used so far (see the `FusekiServer` type in Jena’s documentation). It exposes real SPARQL endpoints. Depending on the external service you use and would like to test against, you need to find a server that is as close to the original as possible. Sometimes you can get exactly the same server, to the version, by using Docker. For example, the `testcontainers` library uses Docker to provide those real servers in a test-friendly manner. Remember that we’d like to avoid using an internet connection in tests because of query limits, network problems, state-related issues, and so on! Such tests are usually very flaky and not very useful. The best way to achieve great tests is to test each case in isolation, preferably using it’s own fresh server instance. ``` val model = RDFDataMgr.loadModel(getClass.getResource("testdata.ttl").toString) val ds = DatasetFactory.create(model) val server = FusekiServer.create.add("/test", ds).build server.start() ``` The server starts serving data from the `testdata.ttl` file (see `src/test/resources` ) we prepared. This data includes an attraction in Venice, some US national parks, their locations, artists from those locations, and movies taking place in those locations. We downloaded this data from Wikidata, using a script available in the book’s repository. Note that this data is stable and won’t change between tests!                                                    ![](/images/book/grokking-functional-programming/2acfbe11-ff00-4bfc-aeba-65ace9481884.png) **Let’s think about it first.** The snippet above uses imperative programming. Do you know any technique we could use here to make it functional? ## Local servers as `Resource` s in integration tests

The library we use to read from the Wikidata SPARQL server and to run a local server instance is an imperative Java library. There are many caveats when using this library—one of the most important caveats is a possible resource leak we learned about earlier. This problem applies to our test server as well. When we call start , we trigger a lot of side effects like running a server, opening a port, and waiting for incoming connections. These are all finite resources. Multiply that by the number of tests we’d like to run, each one having its own instance, and you get the idea. We need to clean up all the resources when we no longer need them, even when a test fails! That’s why we need the Resource type again.

Handling resources

Resource leaks were handled using Resource in chapter 11.

``` def localSparqlServer: Resource[IO, FusekiServer] = { ① val start: IO[FusekiServer] = IO.blocking { ② val model = RDFDataMgr.loadModel( ② getClass.getResource("testdata.ttl").toString ② ) ② val ds = DatasetFactory.create(model) ② val server = FusekiServer.create.add("/test", ds).build ② server.start() ② server ② } ② Resource.make(start)(server => IO.blocking(server.stop())) ③ } ``` ① Apache Jena's local SPARQL server implementation ② An `IO` value that describes a program that starts a server and returns a handle to it ( `FusekiServer` ) ③ An `IO` value that describes a program that needs to be executed when the resource is no longer needed (regardless of anything else) We now have a value representing a closeable resource that we can `use` without worrying about potential resource leaks. As you remember, `Resource` has the **`flatMap`** function defined, which allows us to compose different small `Resource` values into more powerful ones. Let’s create a `Resource` that represents an existing connection to the local server. ``` val testServerConnection: Resource[IO, RDFConnection] = for { localServer <- localSparqlServer connection <- connectionResource(localServer.serverURL(), "test") ① } yield connection ``` ① `connectionResource` was a value we developed in the previous chapter. It represented a connection to the real server. We needed to parametrize it with a URL and endpoint name to be able to use a different server. Note that it’s production code that becomes part of our test suite! It is another value representing a closeable resource. When it’s `use` d, it returns an `IO` value describing a program that creates a local server and opens a connection to it (another finite resource). Both the connection and the server are closed automatically, even after failure. ## Writing isolated integration tests We now have a single value, `testServerConnection` , that we can reuse in all our integration tests. It’s going to create and close a server and a connection for us! Note that, once again, we’ve reused a technique we learned previously when writing production code. This time we used it in tests. I hope you appreciate how versatile these tools are and how learning one of them applies to more than a single scenario. THIS IS BIG! `Resource` and `IO` types help write proper readable and maintainable integration tests. Enough introductions! Let’s see our first real integration test now. ```javascript test("data access layer should fetch attractions from a real SPARQL server") { val result: List[Attraction] = testServerConnection .use(connection => { // given a real external data source with attractions in Venice val dataAccess = getSparqlDataAccess(execQuery(connection)) // when we use it to find attractions named "Bridge of Sighs" dataAccess.findAttractions("Bridge of Sighs", ByLocationPopulation, 5) }) .unsafeRunSync() // then we get a list of results with Bridge of Sighs in it assert(result.exists(_.name == "Bridge of Sighs") && result.size <= 5) } ``` And that’s all! This small test creates a server that opens a local port, and creates a connection to it using production code: - `connectionResource` is production code that is reused internally by `testServerConnection` . - `getSparqlDataAccess` is production code used to create a `DataAccess` value that executes real SPARQL queries. Then, it calls the `findAttractions` function, which returns an `IO` value describing a side-effectful execution of a SPARQL query on our local server that was populated by some test data, including an attraction in Venice. That’s why we can assert that at least “Bridge of Sighs” is returned from the server. Finally, the connection is safely disposed of and the server is closed, releasing all the resources. This happens because we used the `Resource` value, which disposes of the connection automatically after the function we pass to the use function finished its execution.

That means we have just written a small, isolated integration test . It doesn’t depend on any preexisting setup, and it cleans up after itself. It focuses on testing only the small “data layer” represented by one of the three DataAccess functions without any additional context that we tested in previous tests. In this and the following tests, we only want to know whether SPARQL queries are correct and the input and output values are properly transformed to and from our data model values.

## Integration with a service is a single responsibility If writing integration tests is so easy, why don’t we add more of them? There are lots of details to focus on from the integration perspective: Does `DataAccess` pass the ordering parameters correctly? Does it conform to the provided results-set limit? Does it return proper artists and movies? We have already tested a simple attractions fetching, and here’s an example of how we would approach testing the ordering. ```javascript test("data access layer should fetch attractions sorted by location population") { val locations: List[Location] = testServerConnection .use(connection => { // given a real external data source with national parks in the US val dataAccess = getSparqlDataAccess(execQuery(connection)) // when we use it to find three locations of the attraction named "Yellowstone" dataAccess.findAttractions("Yellowstone", ByLocationPopulation, 3) ① }) .unsafeRunSync() .map(_.location) // then we get a list of three locations sorted properly by their population assert(locations.size == 3 && locations == locations.sortBy(_.population).reverse) } ``` ① Our test data includes three locations for the Yellowstone National Park: Wyoming, Montana, and Idaho. We should test every useful combination of parameters, each combination in its own test. This should not be problematic because our **data access implementation is business agnostic** . It only knows about the SPARQL data service, the queries, and the immutable values it takes and returns. It’s a small layer consisting of single-responsibility functions. We can test them in isolation to ensure that when used in a bigger program, they will do what’s required. We don’t test the integration from the perspective of `travelGuide` or any other function. `DataAccess` **has a single responsibility** , which is integration with an external SPARQL endpoint! ![](/images/book/grokking-functional-programming/526079fd-da59-4abf-9beb-ace11041c67c.png) Yes, you see it right! We can also write property-based integration tests. We will show one very soon, but first, let’s confirm we are on the same page regarding example-based integration tests. ## Coffee break: Writing integration tests ![](/images/book/grokking-functional-programming/22fc00fa-ad5a-4637-bcfb-04ac1854bb1f.png) We now know how to write isolated integration tests that use real services. In this exercise, we will develop three more such integration tests that verify our `DataAccess` component. **Your task is to write the following three tests** . ```rust test("data access layer should fetch attractions sorted by name") { // given a real external data source with national parks in the US // when we use it to find five attractions named "National Park" // then we get a list of five attractions sorted properly by their name } test("data access layer should fetch artists from a real SPARQL server") { // given a real external data source with attractions in Venice // when we use it to find an artist from Venice // then we get a list of a single artist named "Talco" } test("data access layer should fetch movies from a real SPARQL server") { // given a real external data source with attractions in Venice // when we use it to find max two movies set in Venice // then we get a list of a two movies: // "Spider-Man: Far from Home" and "Casino Royale" } ``` We provided the templates for you. Not much more code is needed. Remember that our integration tests are very concise! Remember that you have the `testServerConnection` value at your disposal: ``` val testServerConnection: Resource[IO, RDFConnection] ```

It describes a server that loads the testdata.ttl file from test resources. It includes all the data you need, such as attractions, movies, artists from Venice, and two US national parks. All the information you need is included in the given-when-then templates above. One more thing that you will need is the following value that represents Wikidata identifier for Venice. You can use it directly in the two last tests:

Remember that you can explore the Wikidata database yourself at https://query.wikidata.org . You can download any entities and put them in the testdata.ttl file, using the script provided in the book’s companion source code.

``` val veniceId: LocationId = LocationId("Q641") ``` Hints - Use the `map` function to assert only on artist and movie names. - Remember that we also provide limit parameters in each test. They are included in the given–when–then templates. - Remember to run the `IO` values to execute the side effects! ## Coffee break explained: Writing integration tests ![](/images/book/grokking-functional-programming/22fc00fa-ad5a-4637-bcfb-04ac1854bb1f.png) Writing integration tests is not that exciting anymore, is it? After creating the `testServerConnection` value, we could safely reuse it and test different aspects of our application’s data layer. And that’s how it’s supposed to be! Integration tests (and tests in general) should not be exciting; they should be boring, both when reading and when writing them. ```javascript test("data access layer should fetch attractions sorted by name") { val attractions: List[Attraction] = testServerConnection .use(connection => { // given a real external data source with national parks in the US val dataAccess = ① // when we use it to find five attractions named "National Park" dataAccess.findAttractions("National Park", ByName, 5) }) .unsafeRunSync() // then we get a list of five attractions sorted properly by their name assert(attractions.size == 5 && attractions.map(_.name) == attractions.sortBy(_.name).map(_.name)) ② } test("data access layer should fetch artists from a real SPARQL server") { val artists: List[Artist] = testServerConnection .use(connection => { // given a real external data source with attractions in Venice val dataAccess = getSparqlDataAccess(execQuery(connection)) ③ // when we use it to find an artist from Venice dataAccess.findArtistsFromLocation(veniceId, 1) }) .unsafeRunSync() // then we get a list of a single artist named "Talco" assert(artists.map(_.name) == List("Talco")) ④ } test("data access layer should fetch movies from a real SPARQL server") { val movies: List[Movie] = testServerConnection .use(connection => { // given a real external data source with attractions in Venice val dataAccess = getSparqlDataAccess(execQuery(connection)) // when we use it to find max two movies set in Venice dataAccess.findMoviesAboutLocation(veniceId, 2) ⑤ }) .unsafeRunSync() // then we get a list of a two movies: "Spider-Man: Far from Home" and "Casino Royale" assert(movies.map(_.name) == List("Spider-Man: Far from Home", "Casino Royale")) } ``` ① `getSparqlDataAccess` is the function we test. It returns the implementation of `DataAccess` functions that perform real SPARQL queries on production. (Of course, we don’t use a production database here. The connection we pass is the local test instance.) ② We use `sortBy` to verify the order without assuming anything about specific values. ③ If you feel that there is too much duplication between tests, maybe a good idea would be to introduce a reusable `Resource[IO, DataAccess]` value. ④ When we set the limit to `1` , we expect only a single artist, always. ⑤ We could also add more cases—for example, testing whether the box office is returned correctly. ## Integration tests take more time The integration tests we have written are pretty small and understandable. They test the real integration with a real server! Have you tried introducing a bug into one of the queries in the production code? If not, go do it now because our new integration tests should fail when somebody does something like that!

There is a drawback to using too many of such isolated integration tests. They may slow down our testing pipeline considerably . If we use real servers, we need to wait more to start the process, open ports, wait and handle incoming connections, and so on. It’s far more work than just calling a function and asserting on its result. We need to think about that when designing our test suites.

Starting and stopping a server takes time, so it may sometimes be tempting to use a single instance for all tests. This, however, comes with another trade-off. Your tests are no longer isolated, and you need to ensure the isolation through a different mechanism (e.g., by creating randomly named tables in an SQL database). This is especially important if your tests change data in the external service. This discussion is about a more general topic, which is software testing disconnected from any specific paradigm, but rest assured that functional programming gives you all the tools you need to implement any of the known testing strategies. For example, you could use a Resource value once and add all the integration tests there. This would be a preferred solution in our case because in this application, we only have input actions (we only read from the external service/data source).

Concurrent IO s

Concurrent IO programs were discussed in chapter 10.

Another approach would be to use a concurrent execution of integration tests. This would require using a `parSequence` on our `IO` s. Since we are dealing with opening ports, which are a shared resource, we need to make sure our server-starting implementation is able to look for an available port (resources like CPU or memory play a role, too).

As you can see, there are some very important decisions we need to make, especially when writing integration tests. All the tools we’ve used in the production code can be reused in testing, which is very reassuring. Fortunately, we only need to test single-responsibility DataAccess functions this way because we extracted as much functionality as possible into pure non-IO functions—their tests are always quick!

Functional core

Design principles of integrating pure and impure code in a program were discussed in chapter 8.

## Property-based integration tests                                                    ![](/images/book/grokking-functional-programming/ff15092e-db72-459b-a495-fee73a647f0b.png) Q Are we still using pure functional programming in these integration tests? I noticed that we need to call `unsafeRunSync` in each of them, which definitely is not pure, because it executes the side effects encoded in a given `IO` value. A The integration tests we have written are not completely pure because they can’t be. We are testing the side-effectful functionalities. However, note that ④ majority of the tests are still pure functions. The impurity is introduced when we call `unsafeRunSync` directly. If calling this impure function is not OK for you or your team, you could create a helper `test` function , which takes an `IO[Assertion]` and runs it internally. Then, all your tests would just be `IO` s and completely pure, and the impure calls would be hidden, just like in the production application when we call `unsafeRunSync` once, outside of the functional core. You can also go all in and create tests using for comprehensions: using `Ref` for local servers and `parSequence` to run tests concurrently. The great thing about having everything modeled as pure functions and immutable values is that we can use any tool that works with pure functions and immutable values! In the case of testing, we can use property-based tests even for testing functionalities that require side effects! For example, here is a test that checks whether our implementation of the SPARQL client uses the `limit` parameter properly. No matter how big or small the `limit` parameter is, we should always get maximum `limit` results. ``` test("data access layer should accept and relay limit values to a real SPARQL server") { forAll(nonNegativeInt)((limit: Int) => { ① val movies: List[Movie] = testServerConnection .use(connection => { val dataAccess = getSparqlDataAccess(execQuery(connection)) dataAccess.findMoviesAboutLocation(veniceId, limit) }) .unsafeRunSync() assert(movies.size <= limit) ② }) } ``` ① This test shows that we can use property-based checks in integration tests as well. This test would fail with an internal SPARQL server error if we used a default generator (that generates negative integers) because negative limits are not supported. That’s why we use the custom `nonNegativeInt` generator. ② Note that each tests creates and stops a SPARQL server. This can happen dozens of times in a property-based test! This tests makes sure the `limit` parameter is relayed properly. This test may take some time, but we get a lot of confidence back. ## Choosing the right testing approach We can choose the testing tool, depending on how confident we are about an implementation. There are quite a few options to choose from, so let’s do a quick recap. ![](/images/book/grokking-functional-programming/975e3f3c-c11d-4af3-9a49-c8fb31f2d3a4.png) Additionally, remember what your function–under–test is. For example, when we wanted to test the logic inside the `travelGuide` function, we didn’t want to test whether an external data source sorts results properly. That seems obvious in hindsight, but it’s often the main reason behind bloated and not very useful test suites. We need to be aware of all the options and choose the right tool that ensures the software is tested and documented in an understandable way. We need to keep tests small and useful. We also need to make sure the tests cover all the requirements. It’s important to understand that there are some different approaches out there, even in the FP world. For example, type-level programming (not covered in the book) tries to put as many things in the types as possible. ![](/images/book/grokking-functional-programming/632e751f-7944-4dbe-a5a6-711f798093f5.png) ## Test-driven development So far we have been adding tests only to existing functions. Before we wrap up this chapter (and the book!), I’d like to show you that all these techniques can be used for **test-driven development** (i.e., adding new features by writing a failing test first and only then implementing it properly). Let’s see an example of that—here’s a new big requirement. ![](/images/book/grokking-functional-programming/58b990a9-38ac-4c72-9a90-6c8eea4734e4.png) Let’s try to approach this problem as we did with previous ones: by trying to figure out how to model this new requirement. What we have so far is a function with the following signature: Now, the new requirement says that we should return only a guide that has a score higher than `55` . That’s still possible using the signature above (returning `Some` when there is a good guide with a high score and `None` otherwise). However, in case we can’t find a good guide, we need to return a search report that shows what guides were generated and considered and what kinds of problems we have encountered. What problems can there be? Aren’t we using pure functions? What kinds of problems can we expect? Note that we use a lot of IO actions in our current implementation. Some of those actions may fail with a network error or timeout. Currently, the whole `IO` program will fail if something like that happens. However, when we analyze this closely, we are able to recover from such situations. If there are three locations that we need artists and movies for and fetching one of them fails, we still have the remaining two locations that may produce a good guide. That’s why we need a new signature that models both scenarios. ``` def travelGuide(data: DataAccess, attractionName: String): IO[Option[TravelGuide]] case class SearchReport(badGuides: List[TravelGuide], problems: List[String]) def travelGuide(dataAccess: DataAccess, attractionName: String): IO[Either[SearchReport, TravelGuide]] ``` ## Writing a test for a feature that doesn’t exist

Changing the signature of the travelGuide function means we first need to adjust the current implementation to the new signature. That shouldn’t be too difficult because we can change Some(guide) to Right(guide) and None to Left(SearchReport(List.empty, List.empty)) without changing anything else (they are semantically the same). The same should be done for tests. That should make the code compile again, but it doesn’t really implement any new feature—specifically, we don’t return bad guides or any problems (the lists are always empty). That’s the cue for our first failing test. Let’s employ the TDD approach and write a test for one of the new functionalities.

Since we are testing a function that uses IO values, but is not acting as the direct integration layer, we will use tests with stubbed IO values (we called them data usage tests : they verify how the data from an external service is used in the function under test ).

Either

Option , Either, and error handling were discussed in chapter 6. We mentioned there that Either can be used in more scenarios, and here’s an example of that.

We are testing both business logic and some data source concerns at once, so it’s more of an “end-to-end” test. ```php test("travelGuide should return a search report if it can't find a good-enough guide") { // given an external data source with a single attraction, // no movies, no artists and no IO failures val dataAccess = dataAccessStub( IO.pure(List(yellowstone)), IO.pure(List.empty), IO.pure(List.empty) ) // when we want to get a travel guide val result: Either[SearchReport, TravelGuide] = travelGuide(dataAccess, "").unsafeRunSync() ① // then we get a search report with bad guides (0 artists, 0 movies means the score is < 55) assert(result == Left( SearchReport(List(TravelGuide(yellowstone, List.empty)), problems = List.empty) )) } ``` ① We pass an empty string here because all the data is stubbed to always return the same. Note that we used two additional helpers: one is `dataAccessStub` function, which takes three `IO` values and returns a `DataAccess` with three functions that return given values, and the second is `yellowstone` : ```php def dataAccessStub( ①② attractions: IO[List[Attraction]], artists: IO[List[Artist]], movies: IO[List[Movie]] ): DataAccess = new DataAccess { def findAttractions(name: String, ordering: AttractionOrdering, limit: Int): IO[List[Attraction]] = attractions def findArtistsFromLocation(locationId: LocationId, limit: Int): IO[List[Artist]] = artists def findMoviesAboutLocation(locationId: LocationId, limit: Int): IO[List[Movie]] = movies } val yellowstone: Attraction = Attraction("Yellowstone National Park", Some("first national park in the world"), Location(LocationId("Q1214"), "Wyoming", 586107)) ``` ① We pass an empty string here because all the data is stubbed to always return the same. ② Having these helpers makes the test above and the following tests much easier to read. ## Red-green-refactor We have our first test, and it fails because our function returns a `SearchReport` that doesn’t contain any bad guides, even though we know that at least one should be fetched (Yellowstone with no pop culture subjects). We could now implement this functionality in the simplest possible way and then create another test, which should be failing. Then, we would change the implementation in the simplest possible way that satisfies both test cases, refactor the code if we feel there’s a better way, and move on to creating the third test case. This iterative process, which is called _red-green-refactor_ , continues until we satisfy all the requirements. We could also speed up this process and do it in batches. So let’s write two more failing tests before writing our first implementation. THIS IS BIG! Mocking and stubbing are just passing values to functions. ```php val hatefulEight: Movie = Movie("The Hateful Eight", 155760117) ① val heavensGate: Movie = Movie("Heaven's Gate", 3484331) ① test("travelGuide should return a travel guide if two movies are available") { // given an external data source with a single attraction, // two movies, no artists and no IO failures val dataAccess = dataAccessStub( IO.pure(List(yellowstone)), IO.pure(List.empty), IO.pure(List(hatefulEight, heavensGate)) ② ) // when we want to get a travel guide val result: Either[SearchReport, TravelGuide] = travelGuide(dataAccess, "").unsafeRunSync() // then we get a proper travel guide because it has a high score (> 55 points) assert(result == Right(TravelGuide(yellowstone, List(hatefulEight, heavensGate)))) } test("travelGuide should return a search report with problems when fetching attractions fails") { // given an external data source that fails when trying to fetch attractions val dataAccess = dataAccessStub( IO.delay(throw new Exception("fetching failed")), IO.pure(List.empty), IO.pure(List.empty) ③ ) // when we want to get a travel guide val result: Either[SearchReport, TravelGuide] = travelGuide(dataAccess, "").unsafeRunSync() // then we get a search report with a list of problems assert(result == Left( SearchReport(badGuides = List.empty, problems = List("fetching failed")) ④ )) } ``` ① We add a few more helper immutable values that make our tests more understandable. ② This is a test that tests the successful path. When there are always some big movies, we can be sure that the travel guide has a high score. ③ Here, we simulate a failure by stubbing an `IO` value that describes a failing program. ④ The list of problems is a list of strings. We decided these strings should be messages extracted from all the exceptions we encounter. Now we have three failing tests (we are _red_ ), so let’s implement a function that satisfies them all ( _green_ ). ## Making tests green Our new implementation needs to find attractions with a given name (a maximum of three) and then fetch artists and movies for each location. If fetching attractions fails, we need to return a `SearchReport` with the exception message inside. That’s what our tests are testing for, and this is what we need to implement. The first step, not shown here, is to create a single `travelGuide` function that satisfies the test without worrying about the design. Then, we refactor it by extracting two functions and naming everything properly. Here’s the _green_ (and _refactored_ ) implementation. Again, we show a version after some refactoring. The first green version was not book material. ```php def travelGuideForAttraction( ① dataAccess: DataAccess, attraction: Attraction ): IO[TravelGuide] = { List( dataAccess.findArtistsFromLocation(attraction.location.id, 2), dataAccess.findMoviesAboutLocation(attraction.location.id, 2) ).parSequence.map(_.flatten).map(subjects => TravelGuide(attraction, subjects)) } def findGoodGuide(guides: List[TravelGuide]): Either[SearchReport, TravelGuide] = { guides.sortBy(guideScore).reverse.headOption match { case Some(bestGuide) => if (guideScore(bestGuide) > 55) Right(bestGuide) else Left(SearchReport(guides, List.empty)) case None => Left(SearchReport(List.empty, List.empty)) } } def travelGuide( ② dataAccess: DataAccess, attractionName: String ): IO[Either[SearchReport, TravelGuide]] = { dataAccess .findAttractions(attractionName, ByLocationPopulation, 3) .attempt .flatMap(_ match { case Left(exception) => IO.pure(Left(SearchReport(List.empty, List(exception.getMessage)))) case Right(attractions) => attractions .map(attraction => travelGuideForAttraction(dataAccess, attraction)) .parSequence .map(findGoodGuide) }) } ``` ① This function concurrently fetches artists and movies for a location of a given attraction and returns a program that, if successfully executed, returns a TravelGuide. ② This function gets a list and returns Right(TravelGuide) if there is a guide with a high score or Left(SearchReport) otherwise. Note that we can add some additional tests for this function as well! Look at the new **`attempt`** function we called on the `IO` . That’s how we can get any exception that would be thrown by the program described in that `IO` . We use its message in the result. ![](/images/book/grokking-functional-programming/6aa1edff-6b9f-4671-8482-7ddab99dcdd7.png) ## Adding more red tests As described earlier, after our tests have become green and we have refactored the code so that it looks _good enough_ , we face this question: is this enough, or are there any features still missing? If there are missing functionalities, we should add another test that _highlights_ one of them by failing (being _red_ ). In our case, the requirements were that we should not fail if fetching anything fails, but we should gather the exception messages as a list and return them inside a `SearchReport` value. So far, we have just implemented gathering the exceptions thrown by the `findAttractions` function (by calling `attempt` on the `IO` value it returns), but there are two more data layer functions we still call without protecting against their possible exceptions by calling `attempt` . Here’s the test that shows that. Remember that when you `flatMap` ten `IO` values together to create a sequence, if only one of them describes a program that will fail when executed, the whole `IO` value describes a program that will fail when executed. A program returned by `attempt` protects us against that. ```sql val yosemite = Attraction("Yosemite National Park", ① Some("national park in California, United States"), Location(LocationId("Q109661"), "Madera County", 157327)) test("travelGuide should return a search report with some guides if it can't fetch artists due to IO failures") { // given a data source that fails when trying to fetch artists for "Yosemite" val dataAccess = new DataAccess { def findAttractions(name: String, ordering: AttractionOrdering, limit: Int) = IO.pure(List(yosemite, yellowstone)) def findArtistsFromLocation(locationId: LocationId, limit: Int) = if (locationId == yosemite.location.id) IO.delay(throw new Exception("Yosemite artists fetching failed")) else IO.pure(List.empty) def findMoviesAboutLocation(locationId: LocationId, limit: Int) = IO.pure(List.empty) } // when we want to get a travel guide val result: Either[SearchReport, TravelGuide] = travelGuide(dataAccess, "").unsafeRunSync() // then we get a search report with one bad guide (< 55) and list of errors assert( result == Left( SearchReport( badGuides = List(TravelGuide(yellowstone, List.empty)), problems = List("Yosemite artists fetching failed") ) ) ) } ``` ① We create yet another immutable value, which holds a small descriptive name and can be used to improve the tests readability. It’s definitely a more complicated test, but it’s still a small one! Here our `DataAccess` stub is defined directly, without any helper, because it does more than just return the same value every time. It returns a failing `IO` when asked about artists from the location of Yosemite. It doesn’t fail when getting artists from the location of Yellowstone. And since there are no artists and movies at all in our stubbed data layer, there is no good guide here to return. That’s why we expect a `SearchReport` back. It needs to contain a guide for Yellowstone and a problem description it encountered when trying to find artists from Yosemite’s location. Our current `travelGuide` function fails when this test runs. Isn’t it a nice API? And remember that it’s still just a function returning an immutable value! ## The last TDD iteration To make the test green (without failing any previous tests), we need to change the production code and `attempt` every `IO` value in our program, gather all the exceptions, and return them as a part of a `SearchReport` value. ![](/images/book/grokking-functional-programming/958a67db-d895-4505-a61f-c573b677f321.png) As you see, test-driven development can be a good technique to use when dealing with new requirements. We have been able to completely overhaul our previous version and add new, more complicated features step by step while still keeping a somewhat concise implementation. We also have a pretty good test suite that covers the new requirements. We could also use property-based tests for TDD, especially when developing non- `IO` -based pure functions (like `findGoodGuide` ). Note that we have introduced `collect` and `attempt` without much explanation in the final pages of the book. This was done on purpose. **You now know everything you need to start learning new functions and exploring the world of functional APIs on your own** . **And that’s all!** As you probably expect, there are a few more cases that we haven’t covered here and a few great possible improvements to our pop culture travel guide. We will ask you to implement these things very soon. Make sure you play with the code and try to expand our tests and solutions. The material in chapters 11 and 12 is advanced—grokking it requires practice! Take your time and never stop coding (functionally!) ## Summary In this chapter we used all the familiar functional programming tools to develop tests that helped us discover some bugs and understand the requirements. CODE: `CH12_*` Explore this chapter’s source code by looking at `ch12_*` files in the book’s repository.        ⤷ Make sure to look in the `test` directory, too! Test pure functions by providing examples We added some quick and small tests by providing examples of inputs and asserting on expected outputs. We learned that testing in functional programming is mainly about coming up with function input parameters and verifying a function’s output value. Test pure functions by providing properties We then learned about property-based tests, which helped us find an integer-overflow bug in our chapter 11 `guideScore` implementation. They are developed by providing specifically generated values and testing whether a function returns output from an expected range. We learned how to provide our own generators ( `Gen` values) and that they also have the `flatMap` function, which makes them easy to compose. We also learned that coming up with properties is not an easy job, and it’s good to base them on requirements. Test side effects without using any mocking libraries We then moved over to testing functions that use `IO` values. There are two approaches to testing such functions: stubbing `IO` values when a given function just uses the external data or running real servers when its main responsibility is the integration. In our case we used stubbed `IO` values to test the `travelGuide` function and a real server to test the `DataAccess` implementation returned by the `getSparqlDataAccess` function in the production code. We used a `Resource` value to make sure our locally run SPARQL server instances are always closed and released properly. We showed that we can use property-based tests in such integration tests as well. By stubbing we mean hardcoding `DataAccess` functions to always return the same values. Develop new functionalities in a test-driven way Finally, we got a new requirement and decided to implement it using the test-driven development approach (TDD). We first created three failing tests ( _red_ ), then we implemented a new version of `travelGuide` that satisfied those tests ( _green_ ), extracted smaller helper functions from it ( _refactor_ ), and repeated the process to end up with the final version. We didn’t show the version before the refactoring, but you may imagine it wasn’t very pretty! Explore the book’s code repository for more! ## The last dance Thank you for reading _Grokking Functional Programming_ ! I am sure that the knowledge and skills you’ve obtained here will help you grow as a programmer and achieve massive success in your career. I hope you’ve had a lot of fun reading all 12 chapters and analyzing their examples. The good news is that all of them can be further expanded to include even more advanced topics. If you strive for more functional programming goodies taught in the spirit of this book, please make sure to visit my web page at [https://michalplachta.com](https://michalplachta.com) . You can get in touch with me there as well! And finally, if you’ve enjoyed all these hard exercises in the book, and you can’t get over the fact that it’s all over now, I have a surprise for you! Farewell exercises                 ![](/images/book/grokking-functional-programming/c604de1c-cf69-4091-abb4-ae58088ea394.png) 1. **API rate limiter** —Wikidata servers have API limits. Our solution from chapters 11 and 12 doesn’t keep track of all the requests it makes. Your task is to use your knowledge about functional concurrency to implement a configurable request rate limiter for the whole application (e.g., make no more than five requests a second). 2. **Console user interface** —The application we’ve implemented in chapters 11 and 12 doesn’t have any user interface! Implement a console-based interface that asks for the name of an attraction and returns a travel guide. For example: ``` Enter attraction name: ① > Bridge of Sighs Thanks! Preparing your guide... Bridge of Sighs is a bridge over a canal in Venice. Before visiting, you may want to listen to Talco and watch some movies that take place in Venice: "Spider-Man: Far from Home" and "Casino Royale". ``` ① What if one of our users tries to pull a “SPARQL injection” trick on us? 3. **Stream-based asynchronous interface** —Can you expand your implementation of the console-based user interface above and allow the user to search for multiple attractions at once? ``` Enter attraction name: ① > Bridge of Sighs Thanks! Preparing your guide... Want to search for another one in the meantime? > Yosemite Thanks! Preparing 2 guides for you... ``` ① What if one of our users tries to pull a “SPARQL injection” trick on us? 4. **Testing** —Did you add proper tests for all the functionalities you’ve implemented above? 5. **Functional design** —Expand the model we developed for the application in chapter 9 (currency exchange). Can you introduce a better model that doesn’t use **`BigDecimal`** s directly?