th-test-utils

Utility functions for testing Template Haskell code, including functions for testing failures in the Q monad.


Keywords
library, testing, Propose Tags , Skip to Readme, , Index, Quick Jump, Language.Haskell.TH.TestUtils, Language.Haskell.TH.TestUtils.QMode, Language.Haskell.TH.TestUtils.QState, th-test-utils-1.2.1.tar.gz, browse, Package description, package maintainers, edit package information , 1.0.0, 1.0.1, 1.0.2, 1.1.0, recover doesn't currently return
License
BSD-3-Clause
Install
cabal install th-test-utils-1.2.1

Documentation

th-test-utils

GitHub Actions codecov Hackage

This package implements tryTestQ and related helpers in order to better test Template Haskell code. It supports returning the actual error message that recover doesn't currently return as well as mocking out Q actions, so that you can run Template Haskell code at runtime.

Usage

-- e.g. $(showInfo "Bool") generates a string corresponding
-- to the reify `Info` for `Bool`.
showInfo :: String -> Q Exp
showInfo s = do
  mName <- lookupTypeName s
  case mName of
    Nothing -> fail $ "Unknown type: " ++ s
    Just name -> do
      info <- reify name
      lift $ show info
-- example using tasty-hunit
main :: IO ()
main = defaultMain $ testGroup "my-project"
  [ testCase "showInfo unmocked" $(do
      result1 <- tryTestQ unmockedState $ showInfo "Bool"
      runIO $ isRight result1 @? ("Unexpected error: " ++ show result1)

      result2 <- tryTestQ unmockedState $ showInfo "Foo"
      runIO $ result2 @?= Left "Unknown type: Foo"

      [| return () |]
    )

  , testCase "showInfo mocked success" $ do
      let state = QState
            { mode = MockQ
            , knownNames = [("Bool", ''Bool)]
            , reifyInfo = $(loadNames [''Bool])
            }

      let result1 = tryTestQ state $ showInfo "Bool"
      isRight result1 @? ("Unexpected error: " ++ show result1)

      let result2 = tryTestQ state $ showInfo "Foo"
      result2 @?= Left "Unknown type: Foo"
  ]