hie-bios-0.22.0: tests/Utils.hs
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Utils (
-- * Tasty ingredients
IgnoreToolDeps(..),
VerboseLogging(..),
KeepTempFiles(..),
ignoreToolTests,
verboseLogging,
keepTempFiles,
-- * Test Environment
TestM,
TestEnv,
TestConfig (..),
defConfig,
-- * Run Tests
runTestEnv,
runTestModeEnv,
runTestEnv',
runTestEnvLocal,
-- * Low-level test-env modification helpers
setCradle,
unsetCradle,
setLoadResult,
unsetLoadResult,
setLibDirResult,
setGhcVersionResult,
-- * Ask for test environment
askRoot,
askStep,
askLogger,
askCradle,
askLoadMode,
askLoadResult,
askOrLoadLibDir,
askLibDir,
askLibDirResult,
askGhcVersion,
askGhcVersionResult,
askCacheRootDir,
-- * Test setup helpers
step,
normFile,
relFile,
mainTarget,
findCradleLoc,
initCradle,
initCradleWithConfig,
initImplicitCradle,
loadComponentOptions,
loadRuntimeGhcLibDir,
loadRuntimeGhcVersion,
loadFileGhc,
isCabalMultipleCompSupportedM,
single,
ctx,
-- * Assertion helpers
assertCradle,
assertLibDirVersion,
assertGhcVersion,
assertLibDirVersionIs,
assertGhcVersionIs,
assertComponentOptions,
assertCradleError,
assertLoadSuccess,
assertLoadFailure,
assertLoadNone,
assertCradleLoadSuccess,
assertCradleLoadError,
-- * High-level test helpers
testDirectoryM,
testImplicitDirectoryM,
findCradleForModuleM,
) where
import Colog.Core
import qualified Colog.Core as L
import qualified Control.Exception as C
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.State
import Data.Function ((&))
import Data.List
import Data.Proxy
import qualified Data.Text as Text
import Data.Void
import qualified GHC as G
import HIE.Bios.Cradle
import HIE.Bios.Cradle.Cabal (isCabalMultipleCompSupported)
import HIE.Bios.Cradle.ProgramVersions (makeVersions)
import HIE.Bios.Environment
import HIE.Bios.Flags
import HIE.Bios.Ghc.Api
import qualified HIE.Bios.Ghc.Gap as G
import HIE.Bios.Ghc.Load
import HIE.Bios.Types as HIE
import Prettyprinter
import System.Directory
import System.Environment (lookupEnv)
import System.FilePath
import System.IO.Temp
import Test.Tasty.HUnit
import qualified Test.Tasty.Ingredients as Tasty
import qualified Test.Tasty.Options as Tasty
-- ---------------------------------------------------------------------------
-- Test configuration and information
-- ---------------------------------------------------------------------------
type TestM a = StateT (TestEnv Void) IO a
data TestConfig = TestConfig
{ useTemporaryDirectory :: Bool
, testProjectRoots :: FilePath
, testVerbose :: VerboseLogging
, testStepFunction :: String -> IO ()
, testLoadModeConfig :: LoadMode
, testKeepTempFiles :: KeepTempFiles
}
data TestEnv ext = TestEnv
{ testCradleType :: Maybe (Cradle ext)
, testLoadResult :: Maybe (CradleLoadResult ComponentOptions)
, testLibDirResult :: Maybe (CradleLoadResult FilePath)
, testGhcVersionResult :: Maybe (CradleLoadResult String)
, testRootDir :: FilePath
, testCacheRootDir :: CacheRootDir
, testLogger :: L.LogAction IO (L.WithSeverity HIE.Log)
, testLoadMode :: LoadMode
}
defConfig :: TestConfig
defConfig =
TestConfig
{ useTemporaryDirectory = True
, testProjectRoots = "./tests/projects"
, testVerbose = VerboseLogging False
, testStepFunction = unLogAction logStringStderr
, testLoadModeConfig = LoadFile
, testKeepTempFiles = KeepTempFiles False
}
runTestEnv :: FilePath -> TestM a -> TestConfig -> IO a
runTestEnv fp act testConf = runTestEnv' testConf fp act
runTestModeEnv :: FilePath -> LoadMode -> TestM a -> TestConfig -> IO a
runTestModeEnv fp loadMode act testConf = runTestEnv' testConf{testLoadModeConfig=loadMode} fp act
runTestEnvLocal :: FilePath -> TestM a -> TestConfig -> IO a
runTestEnvLocal fp act testConf = runTestEnv' testConf{useTemporaryDirectory = False} fp act
runTestEnv' :: TestConfig -> FilePath -> TestM a -> IO a
runTestEnv' config localDir act = do
mkeep <- lookupEnv "KEEP_TEMP_DIRS"
let keepTempDirs = mkeep == Just "true" || getKeepTempFiles (testKeepTempFiles config)
-- We need to copy over the directory to somewhere outside the source tree
-- when we test, since the cabal.project/stack.yaml/hie.yaml file in the root
-- of this repository interferes with the test cradles!
let wrapper r cont =
if useTemporaryDirectory config
then
withTempCopy keepTempDirs r cont
else
cont r
mkEnv root' cacheDir =
TestEnv
{ testCradleType = Nothing
, testLoadResult = Nothing
, testLibDirResult = Nothing
, testGhcVersionResult = Nothing
, testRootDir = root'
, testCacheRootDir = cacheDir
, testLogger = init_logger
, testLoadMode = testLoadModeConfig config
}
localDirAbs <- makeAbsolute $ testProjectRoots config </> localDir
withTempCacheRoot keepTempDirs $ \ cacheRootDir -> do
wrapper localDirAbs $ \root -> flip evalStateT (mkEnv root cacheRootDir) $ do
step $ "Run test in: " <> root
step $ "Cache dir: " <> unCacheRootDir cacheRootDir
act
where
init_logger = LogAction (testStepFunction config)
& L.cmap printLog
& L.filterBySeverity (if getVerboseLogging (testVerbose config) then Debug else Error) getSeverity
printLog (L.WithSeverity l sev) = "[" ++ show sev ++ "] " ++ show (pretty l)
-- ---------------------------------------------------------------------------
-- Modification helpers
-- ---------------------------------------------------------------------------
setCradle :: Cradle Void -> TestM ()
setCradle crd = modify' (\env -> env{testCradleType = Just crd})
unsetCradle :: TestM ()
unsetCradle = modify' (\env -> env{testCradleType = Nothing})
setLoadResult :: CradleLoadResult ComponentOptions -> TestM ()
setLoadResult clr = modify' (\env -> env{testLoadResult = Just clr})
unsetLoadResult :: TestM ()
unsetLoadResult = modify' (\env -> env{testLoadResult = Nothing})
setLibDirResult :: CradleLoadResult FilePath -> TestM ()
setLibDirResult libdir = modify' (\env -> env{testLibDirResult = Just libdir})
setGhcVersionResult :: CradleLoadResult String -> TestM ()
setGhcVersionResult ghcVersion = modify' (\env -> env{testGhcVersionResult = Just ghcVersion})
-- ---------------------------------------------------------------------------
-- Access the Test Environment
-- ---------------------------------------------------------------------------
askRoot :: TestM FilePath
askRoot = gets testRootDir
askStep :: TestM (String -> IO ())
askStep = do
logger <- gets testLogger
pure $ \s ->
logger <& LogAny (Text.pack s) `WithSeverity` Info
askCradle :: TestM (Cradle Void)
askCradle =
gets testCradleType >>= \case
Just crd -> pure crd
Nothing ->
liftIO $
assertFailure
"No Cradle set, use 'initCradle' or 'initImplicitCradle' before asking for it"
askLoadResult :: TestM (CradleLoadResult ComponentOptions)
askLoadResult =
gets testLoadResult >>= \case
Just crd -> pure crd
Nothing ->
liftIO $
assertFailure
"No CradleLoadResult set, use 'loadComponent' before asking for it"
askOrLoadLibDir :: TestM FilePath
askOrLoadLibDir =
gets testLibDirResult >>= \case
Just lrLibDir ->
assertCradleLoadSuccess lrLibDir
Nothing -> do
loadRuntimeGhcLibDir
askLibDir
askLibDir :: TestM FilePath
askLibDir = do
assertCradleLoadSuccess =<< askLibDirResult
askLibDirResult :: TestM (CradleLoadResult FilePath)
askLibDirResult =
gets testLibDirResult >>= \case
Just lrLibDir -> pure lrLibDir
Nothing ->
liftIO $
assertFailure
"No Lib Dir set, use 'loadRuntimeGhcLibDir' before asking for it"
askGhcVersion :: TestM String
askGhcVersion = do
assertCradleLoadSuccess =<< askGhcVersionResult
askGhcVersionResult :: TestM (CradleLoadResult String)
askGhcVersionResult =
gets testGhcVersionResult >>= \case
Just lrGhcVersion -> pure lrGhcVersion
Nothing ->
liftIO $
assertFailure
"No GHC version set, use 'loadRuntimeGhcVersion' before asking for it"
askLogger :: TestM (L.LogAction IO (L.WithSeverity HIE.Log))
askLogger = gets testLogger
askLoadMode :: TestM LoadMode
askLoadMode = gets testLoadMode
askCacheRootDir :: TestM CacheRootDir
askCacheRootDir = gets testCacheRootDir
-- ---------------------------------------------------------------------------
-- Test setup helpers
-- ---------------------------------------------------------------------------
single :: FilePath -> TargetWithContext
single fp = TargetWithContext fp []
ctx :: FilePath -> [FilePath] -> TargetWithContext
ctx fp fps = TargetWithContext fp fps
step :: String -> TestM ()
step msg = do
s <- askStep
liftIO $ s msg
normFile :: FilePath -> TestM FilePath
normFile fp = (</> fp) <$> gets testRootDir
mainTarget :: TargetWithContext -> TestM FilePath
mainTarget target = (</> targetFilePath target) <$> gets testRootDir
relFile :: FilePath -> TestM FilePath
relFile fp = (`makeRelative` fp) <$> gets testRootDir
findCradleLoc :: FilePath -> TestM (Maybe FilePath)
findCradleLoc fp = do
a_fp <- normFile fp
liftIO $ findCradle a_fp
initCradle :: FilePath -> TestM ()
initCradle fp = do
cacheLoc <- gets testCacheRootDir
let
conf =
CradleRunConfig
{ cradleCacheRootDir = Just cacheLoc
}
initCradleWithConfig conf fp
initCradleWithConfig :: CradleRunConfig -> FilePath -> TestM ()
initCradleWithConfig config fp = do
a_fp <- normFile fp
step $ "Finding Cradle for: " <> fp
mcfg <- findCradleLoc a_fp
relMcfg <- traverse relFile mcfg
step $ "Loading Cradle: " <> show relMcfg
logger <- askLogger
crd <- case mcfg of
Just cfg -> liftIO $ loadCradleWithConfig logger config cfg
Nothing -> liftIO $ loadImplicitCradleWithConfig logger config a_fp
step $ "Cradle: " ++ show crd
setCradle crd
initImplicitCradle :: FilePath -> TestM ()
initImplicitCradle fp = do
cacheLoc <- gets testCacheRootDir
let
conf =
CradleRunConfig
{ cradleCacheRootDir = Just cacheLoc
}
a_fp <- normFile fp
step $ "Loading implicit Cradle for: " <> fp
logger <- askLogger
crd <- liftIO $ loadImplicitCradleWithConfig logger conf a_fp
setCradle crd
loadComponentOptions :: TargetWithContext -> TestM ()
loadComponentOptions (TargetWithContext fp extraFps) = do
a_fp <- normFile fp
a_fps <- traverse normFile extraFps
crd <- askCradle
mode <- askLoadMode
step $ "Initialise flags for " <> fp <> " using " <> show mode
when (not $ null extraFps) $ do
step $ "Provided context: " <> show extraFps
clr <- liftIO $ getCompilerOptions (TargetWithContext a_fp a_fps) mode crd
setLoadResult clr
loadRuntimeGhcLibDir :: TestM ()
loadRuntimeGhcLibDir = do
crd <- askCradle
step "Load run-time ghc libdir"
libdirRes <- liftIO $ getRuntimeGhcLibDir crd
setLibDirResult libdirRes
loadRuntimeGhcVersion :: TestM ()
loadRuntimeGhcVersion = do
crd <- askCradle
step "Load run-time ghc version"
ghcVersionRes <- liftIO $ getRuntimeGhcVersion crd
setGhcVersionResult ghcVersionRes
isCabalMultipleCompSupportedM :: TestM Bool
isCabalMultipleCompSupportedM = do
cr <- askCradle
root <- askRoot
versions <- liftIO $ makeVersions (cradleLogger cr) root ((runGhcCmd . cradleOptsProg) cr)
liftIO $ isCabalMultipleCompSupported versions
loadFileGhc :: TargetWithContext -> TestM ()
loadFileGhc target = do
libdir <- askOrLoadLibDir
a_fp <- mainTarget target
stepF <- askStep
step "Cradle load"
loadComponentOptions target
opts <- assertLoadSuccess
ifaceCacheRoot <- askCacheRootDir
step $ "loadFileGhc with Cache Dir: " ++ unCacheRootDir ifaceCacheRoot
liftIO $
G.runGhc (Just libdir) $ do
let (ini, _) = initSessionWithMessage' (Just ifaceCacheRoot) (Just G.batchMsg) opts
sf <- ini
case sf of
-- Test resetting the targets
Succeeded -> do
liftIO $ stepF "Set target files"
setTargetFiles mempty [(a_fp, a_fp)]
Failed -> liftIO $ assertFailure "Module loading failed"
-- ---------------------------------------------------------------------------
-- Assertion helpers for hie-bios
-- ---------------------------------------------------------------------------
assertCradle :: (Cradle Void -> Bool) -> TestM ()
assertCradle cradlePred = do
crd <- askCradle
liftIO $ cradlePred crd @? "Must be the correct kind of cradle, got " ++ show (actionName $ cradleOptsProg crd)
assertLibDirVersion :: TestM ()
assertLibDirVersion = assertLibDirVersionIs VERSION_ghc
assertGhcVersion :: TestM ()
assertGhcVersion = assertGhcVersionIs VERSION_ghc
assertLibDirVersionIs :: String -> TestM ()
assertLibDirVersionIs ghcVersion = do
step $ "Verify runtime GHC library directory is: " <> ghcVersion
libdir <- askLibDir
liftIO $
ghcVersion `isInfixOf` libdir @? "Expected \"" <> ghcVersion
<> "\" to be infix of: "
<> libdir
assertGhcVersionIs :: String -> TestM ()
assertGhcVersionIs expectedVersion = do
step $ "Verify runtime GHC version is: " <> expectedVersion
ghcVersion <- askGhcVersion
liftIO $ ghcVersion @?= expectedVersion
assertComponentOptions :: (ComponentOptions -> Assertion) -> TestM ()
assertComponentOptions cont = do
opts <- assertLoadSuccess
liftIO $ cont opts
assertCradleError :: (CradleError -> Assertion) -> TestM ()
assertCradleError cont = do
err <- assertLoadFailure
liftIO $ cont err
assertLoadSuccess :: TestM ComponentOptions
assertLoadSuccess = do
askLoadResult >>= \case
CradleSuccess opts -> pure opts
other -> liftIO $ assertFailure $ "Expected CradleSuccess but got: " <> show other
assertLoadFailure :: TestM CradleError
assertLoadFailure = do
askLoadResult >>= \case
CradleFail err -> pure err
other -> liftIO $ assertFailure $ "Expected CradleFail but got: " <> show other
assertLoadNone :: TestM ()
assertLoadNone = do
askLoadResult >>= \case
CradleNone -> pure ()
other -> liftIO $ assertFailure $ "Expected CradleNone but got: " <> show other
assertCradleLoadSuccess :: CradleLoadResult a -> TestM a
assertCradleLoadSuccess = \case
(CradleSuccess x) -> pure x
CradleNone -> liftIO $ assertFailure "Unexpected none-Cradle"
(CradleFail (CradleError _deps _ex stde _err_loading_files)) ->
liftIO $ assertFailure ("Unexpected cradle fail" <> unlines stde)
assertCradleLoadError :: CradleLoadResult a -> TestM CradleError
assertCradleLoadError = \case
(CradleSuccess _) -> liftIO $ assertFailure "Unexpected CradleSuccess"
CradleNone -> liftIO $ assertFailure "Unexpected none-Cradle"
(CradleFail err) -> pure err
-- ---------------------------------------------------------------------------
-- High-level, re-usable assertions
-- ---------------------------------------------------------------------------
testDirectoryM :: (Cradle Void -> Bool) -> TargetWithContext -> TestM ()
testDirectoryM cradlePred target = do
initCradle $ targetFilePath target
assertCradle cradlePred
loadRuntimeGhcLibDir
assertLibDirVersion
loadRuntimeGhcVersion
assertGhcVersion
loadFileGhc target
testImplicitDirectoryM :: (Cradle Void -> Bool) -> TargetWithContext -> TestM ()
testImplicitDirectoryM cradlePred target = do
initImplicitCradle $ targetFilePath target
assertCradle cradlePred
loadRuntimeGhcLibDir
assertLibDirVersion
loadRuntimeGhcVersion
assertGhcVersion
loadFileGhc target
findCradleForModuleM :: FilePath -> Maybe FilePath -> TestM ()
findCradleForModuleM fp expected' = do
rootFp <- askRoot
let expected = fmap (rootFp </>) expected'
crd <- findCradleLoc fp
liftIO $ crd @?= expected
-- ---------------------------------------------------------------------------
-- Copy Directory system utilities
-- ---------------------------------------------------------------------------
withTempCopy :: Bool -> FilePath -> (FilePath -> IO a) -> IO a
withTempCopy keep srcDir f = getCanonicalTemporaryDirectory >>= \mainTmpDir -> do
C.bracket
(do
let
hieBiosMainTestDir = mainTmpDir </> hIE_BIOS_TEMP_DIR_ROOT
createDirectoryIfMissing True hieBiosMainTestDir
createTempDirectory hieBiosMainTestDir template
)
cleanup $ \ newDir -> do
exists <- doesDirectoryExist srcDir
when exists $ do
copyDir srcDir newDir
f newDir
where
template = takeFileName $ dropTrailingPathSeparator srcDir
cleanup dir
| keep = return ()
| otherwise = ignoringIOErrors $ removeDirectoryRecursive dir
ignoringIOErrors ioe = ioe `C.catch` (\e -> const (return ()) (e :: IOError))
withTempCacheRoot :: Bool -> (CacheRootDir -> IO a) -> IO a
withTempCacheRoot keep f = getCanonicalTemporaryDirectory >>= \mainTmpDir -> do
C.bracket
(do
let
hieBiosMainTestDir = mainTmpDir </> hIE_BIOS_TEMP_DIR_ROOT
createDirectoryIfMissing True hieBiosMainTestDir
CacheRootDir <$> createTempDirectory hieBiosMainTestDir "cache"
)
cleanup
f
where
cleanup (CacheRootDir dir)
| keep = return ()
| otherwise = ignoringIOErrors $ removeDirectoryRecursive dir
ignoringIOErrors ioe = ioe `C.catch` (\e -> const (return ()) (e :: IOError))
hIE_BIOS_TEMP_DIR_ROOT :: String
hIE_BIOS_TEMP_DIR_ROOT = "hie-bios"
copyDir :: FilePath -> FilePath -> IO ()
copyDir src dst = do
contents <- listDirectory src
forM_ contents $ \file -> do
unless (file `elem` ignored) $ do
let srcFp = src </> file
dstFp = dst </> file
isDir <- doesDirectoryExist srcFp
if isDir
then createDirectory dstFp >> copyDir srcFp dstFp
else copyFile srcFp dstFp
where
ignored = ["dist", "dist-newstyle", ".stack-work"]
---------------------------------------------------------------------
-- Tasty runners
---------------------------------------------------------------------
-- ------------------------------------------------------------------
-- Run test-suite ignoring run-time tool dependencies.
-- Can be used to force CI to run the whole test-suite.
-- Makes sure that the full test-suite is being run on a properly configured
-- environment.
-- ------------------------------------------------------------------
-- | This option, when set to 'True', specifies that we should
-- run tests with tool dependencies regardless whether the tools are present.
--
-- While for local development, you want to ignore tests that require more setup
-- (e.g., having a GHC 9.4.8 installed), on CI we want to fail if this dependency is missing.
newtype IgnoreToolDeps = IgnoreToolDeps Bool
deriving (Eq, Ord)
instance Tasty.IsOption IgnoreToolDeps where
defaultValue = IgnoreToolDeps False
parseValue = fmap IgnoreToolDeps . Tasty.safeReadBool
optionName = pure "ignore-tool-deps"
optionHelp = pure "Run tests whether their tool dependencies exist or not"
optionCLParser = Tasty.flagCLParser Nothing (IgnoreToolDeps True)
-- | The ingredient that provides the "ignore missing run-time dependencies" functionality
ignoreToolTests :: Tasty.Ingredient
ignoreToolTests = Tasty.TestManager [Tasty.Option (Proxy :: Proxy IgnoreToolDeps)] $
\_opts _tree -> Nothing
newtype VerboseLogging = VerboseLogging { getVerboseLogging :: Bool }
instance Tasty.IsOption VerboseLogging where
defaultValue = VerboseLogging False
parseValue = fmap VerboseLogging . Tasty.safeReadBool
optionName = pure "debug"
optionHelp = pure "Run the tests with verbose logging"
optionCLParser = Tasty.flagCLParser Nothing (VerboseLogging True)
-- | The ingredient that provides the "ignore missing run-time dependencies" functionality
verboseLogging :: Tasty.Ingredient
verboseLogging = Tasty.TestManager [Tasty.Option (Proxy :: Proxy VerboseLogging)] $
\_opts _tree -> Nothing
newtype KeepTempFiles = KeepTempFiles { getKeepTempFiles :: Bool }
instance Tasty.IsOption KeepTempFiles where
defaultValue = KeepTempFiles False
parseValue = fmap KeepTempFiles . Tasty.safeReadBool
optionName = pure "keep-temp-files"
optionHelp = pure "Keep temporary files after the run"
optionCLParser = Tasty.flagCLParser Nothing (KeepTempFiles True)
-- | The ingredient that provides the "ignore missing run-time dependencies" functionality
keepTempFiles :: Tasty.Ingredient
keepTempFiles = Tasty.TestManager [Tasty.Option (Proxy :: Proxy KeepTempFiles)] $
\_opts _tree -> Nothing