<h2 id="intro">Intro</h2>
<p>I have liked writing automated tests for a long time, so it’s not a surprise that I end up writing them in Haskell too. This is very broad topic, so this episode only scratches the surface.</p>
<h2 id="hspec">HSpec</h2>
<p>HSpec is testing framework that automatically detects tests, like most of the modern systems. It supports hierarchies, so one can organize tests by feature for example.</p>
<pre><code>spec :: Spec
spec = do
    describe &quot;Very important feature&quot; $ do
        it &quot;Execution should be error free&quot; $ do
            ...

        it &quot;Flux capacitors can be charged&quot; $ do
            ...

    describe &quot;Somewhat less important feature&quot; $ do
        ...</code></pre>
<h2 id="unit-test">Unit test</h2>
<p>Unit test tests a single case with fixed set of inputs. With pure functions these are a pleasure to write as they’re really just data in, data out, verify results. Below is two examples:</p>
<pre><code>spec :: Spec
spec = do
    describe &quot;Markov chain configuration&quot; $ do
        it &quot;Adding new starting element to empty configuration creates item with frequency of 1&quot; $ do
            let config = addStart (&quot;AA&quot; :: DT.Text) emptyConfig
            config ^? (configStartsL . _head . itemFreqL) `shouldBe` Just 1
            config ^? (configStartsL . _head . itemItemL . _Just) `shouldBe` Just &quot;AA&quot;

        it &quot;Adding same element twice to empty configuration creates item with frequency of 2&quot; $ do
            let config = addStart &quot;AA&quot; $
                         addStart (&quot;AA&quot; :: DT.Text) emptyConfig
            config ^? (configStartsL . _head . itemFreqL) `shouldBe` Just 2
            config ^? (configStartsL . _head . itemItemL . _Just) `shouldBe` Just &quot;AA&quot;</code></pre>
<p>Both are for testing configuring markov chains. First one checks that adding a starting element in empty configuration results correct item with correct weight being added. Second checks that adding same starting element twice results weight of 2.</p>
<p>Both tests use lenses for reading nested data structure. Episode doesn’t cover them much at all, as it’s enough to know that <code>(configStartsL . _head . itemFreqL)</code> focuses on starting elements of configuration, selects first item of the list and then selects frequency of that item. Lenses can also be used for modifying data and they don’t have to focus on only one element.</p>
<p>Unit tests are easy enough to write, they verify single thing about the unit being tested and are usually super fast to run and not error prone.</p>
<h2 id="property-based-test">Property based test</h2>
<p>Property based tests are used to check that a certain property holds with randomly generated input parameters. I’m using HSpec as testing framework and QuickCheck as tool for generating test data:</p>
<pre><code>spec :: Spec
spec = do
    describe &quot;planets&quot; $ do
        describe &quot;food&quot; $ do
            it &quot;food requirement for positive amount of population is more than zero&quot; $ do
                forAll positivePopulation $ \x -&gt; foodRequirement x  &gt; RawResource 0

            it &quot;food base production for farms is equal or greater than their amount&quot; $ do
                forAll someFarms $ \x -&gt; (sum (fmap foodBaseProduction x)) &gt; (RawResource $ length x)</code></pre>
<p>Above we have two tests. First one checks that with any non-zero population, <code>foodRequirement</code> is greater than 0. Second one check that with any positive amount of farm, <code>foodBaseProduction</code> is greater than amount of the farms.</p>
<p><code>positivePopulation</code> is Generator, that is used by QuickCheck to generate random data for testing. Its definition is shown below:</p>
<pre><code>singlePopulation :: Gen PlanetPopulation
singlePopulation = do
    let aPlanetId = toSqlKey 0
    let aRaceId = toSqlKey 0
    aPopulation &lt;- arbitrary `suchThat` \x -&gt; x &gt; 0
    return $ PlanetPopulation aPlanetId aRaceId aPopulation

positivePopulation :: Gen [PlanetPopulation]
positivePopulation = do
    k &lt;- arbitrary `suchThat` \x -&gt; x &gt; 0
    vectorOf k singlePopulation</code></pre>
<p>Generated data can be really simple or very complex. Generating complex data is often convenient to break into smaller steps and write generators for them.</p>
<p>Property based tests are somewhat harder to write than unit tests, but they can potentially cover edge cases that might otherwise not been discovered.</p>
<h2 id="working-with-database">Working with database</h2>
<p>All tests shown so far have been testing pure code, that is, code that is data in, data out. When database is introduced, things get more complicated. Suddenly there’s much more possibilities for errors. Below is an example of such a test:</p>
<pre><code>spec :: Spec
spec = withApp $ do

    describe &quot;Status handling&quot;  $ do
        describe &quot;Planet statuses&quot;  $ do
            it &quot;Expired planet statuses are removed and news created&quot; $ do

                sId &lt;- runDB $ insert $ StarSystem
                        { starSystemName = &quot;Aldebaraan&quot;
                        , starSystemCoordX = 10
                        , starSystemCoordY = 20
                        , starSystemRulerId = Nothing
                        }

                fId &lt;- runDB $ insert $ Faction
                        { factionName = &quot;Star lords&quot;
                        , factionHomeSystem = sId
                        , factionBiologicals = 10
                        , factionMechanicals = 10
                        , factionChemicals = 10
                        }

                pId1 &lt;- runDB $ insert $ Planet
                        { planetName = &quot;New Earth&quot;
                        , planetPosition = 3
                        , planetStarSystemId = sId
                        , planetOwnerId = Just fId
                        , planetGravity = 1.0
                        , planetRulerId = Nothing
                        }

                _ &lt;- runDB $ insert $ PlanetStatus
                        { planetStatusPlanetId = pId1
                        , planetStatusStatus = GoodHarvest
                        , planetStatusExpiration = Just 20201
                        }

                let status = Simulation 20201
                _ &lt;- runDB $ insert status

                news &lt;- runDB $ removeExpiredStatuses (simulationCurrentTime status)

                statuses &lt;- runDB $ selectList [ PlanetStatusPlanetId ==. pId1 ] []
                loadedNews &lt;- runDB $ selectList [] [ Asc NewsDate ]

                liftIO $ statuses `shouldSatisfy` (\x -&gt; length x == 0)
                liftIO $ news `shouldSatisfy` (\x -&gt; length x == 1)
                liftIO $ loadedNews `shouldSatisfy` (\x -&gt; length x == 1)</code></pre>
<p>There’s a lot more code that had to be written for this test and majority of it is for setting up database state. The test if for ensuring that when good harvest boost expires, it is removed from database and respective news article is created.</p>
<p>These kinds of tests have a lot more code and are much more slower to run because of the communication with a database. There’s also more cases where something can go wrong. But in the end, these kinds of tests are needed if one wants to verify that interaction with database is working as planned.</p>
<h2 id="testing-api">Testing API</h2>
<p>Last example is about testing REST API. There are two tests, where the first one is checking that proper access control is in place and second one checks that pending messages are correctly retrieved.</p>
<pre><code>spec :: Spec
spec = withApp $ do
    describe &quot;Message handling&quot; $ do
        it &quot;unauthenticated user can&#39;t access messages&quot; $ do
            _ &lt;- get ApiMessageR
            statusIs 401

        it &quot;pending messages are loaded&quot; $ do
            (pId, fId) &lt;- setupPerson
            _ &lt;- runDB $ insert $ researchCompleted 25250 fId HighSensitivitySensors
            user &lt;- createUser &quot;Pete&quot; (Just pId)
            authenticateAs user
            _ &lt;- get ApiMessageR
            resp &lt;- getResponse
            let jsonM = join (decode &lt;$&gt; simpleBody &lt;$&gt; resp) :: Maybe Value

            assertEq &quot;message tag&quot;
                     (jsonM ^? (_Just . _Array . _head . key &quot;tag&quot; . _String))
                     (Just &quot;ResearchCompleted&quot;)
            assertEq &quot;star date&quot;
                     (jsonM ^? (_Just . _Array . _head . key &quot;starDate&quot; . _Integer))
                     (Just 25250)
            assertEq &quot;technology&quot;
                     (jsonM ^? (_Just . _Array . _head . key &quot;contents&quot; . key &quot;Technology&quot; . _String))
                     (Just &quot;HighSensitivitySensors&quot;)

            statusIs 200</code></pre>
<p>Here extra complication is created by the fact that many features of the system are behind authentication and authorization. Luckily Yesod comes with helper function <code>authenticateAs</code>, that allows code to authenticate when system is running in development mode.</p>
<p>These test are even slower than any of the previous ones, but on the other hand, they test whole chain from user interaction to database and back.</p>
<h2 id="in-closing">In closing</h2>
<p>There’s lots of things that I couldn’t cover in such a short time, like various types of tests: UI testing, performance testing, security testing, long running testing…, the list goes on and on. But hopefully this episode gave you ideas what kinds of tests one can write and how to get started doing so using Haskell.</p>
<p>Best way to reach me is email or at fediverse, where I’m <code>Tuula@mastodon.social</code>.</p>
