Testing And Benchmarking in PureScript

Here’s the translation of the Go code to PureScript, along with explanations in Markdown format suitable for Hugo:

Unit testing is an important part of writing principled PureScript programs. The Test.Unit package provides the tools we need to write unit tests.

For the sake of demonstration, this code is in the Main module, but it could be any module. Testing code typically lives in a separate test module.

module Main where

import Prelude
import Test.Unit (suite, test)
import Test.Unit.Main (runTest)
import Test.Unit.Assert as Assert

We’ll be testing this simple implementation of an integer minimum. Typically, the code we’re testing would be in a source file named something like IntUtils.purs, and the test file for it would then be named Test.IntUtils.purs.

intMin :: Int -> Int -> Int
intMin a b = if a < b then a else b

A test is created by using the test function from the Test.Unit module.

main = runTest do
  suite "IntMin" do
    test "basic test" do
      Assert.equal (-2) (intMin 2 (-2))

Writing tests can be repetitive, so it’s idiomatic to use a table-driven style, where test inputs and expected outputs are listed in a table and a single loop walks over them and performs the test logic.

    test "table driven" do
      let tests = [
            { a: 0, b: 1, want: 0 },
            { a: 1, b: 0, want: 0 },
            { a: 2, b: -2, want: -2 },
            { a: 0, b: -1, want: -1 },
            { a: -1, b: 0, want: -1 }
          ]
      
      for_ tests \tt ->
        Assert.equal tt.want (intMin tt.a tt.b)

PureScript doesn’t have built-in benchmarking tools like Go does. For benchmarking, you might need to use external tools or libraries, or implement your own benchmarking logic.

To run the tests, you would typically use a test runner like spago test. The exact command might vary depending on your project setup.

$ spago test

This will run all the tests in your project and output the results.

Note that PureScript’s testing ecosystem is different from Go’s. While Go has a standard testing package, PureScript relies on community-created testing libraries. The example above uses purescript-test-unit, but there are other options available, such as purescript-spec or purescript-quickcheck.

Also, PureScript doesn’t have a direct equivalent to Go’s benchmarking features. For performance testing in PureScript, you might need to use JavaScript benchmarking tools or create custom benchmarking logic.