effectful-config-file-0.1.3.0: test/Effectful/Config/WatchSpec.hs
{-# LANGUAGE OverloadedStrings #-}
module Effectful.Config.WatchSpec (
spec,
) where
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (withAsync)
import Control.Concurrent.MVar (
MVar,
newEmptyMVar,
newMVar,
putMVar,
readMVar,
takeMVar,
tryTakeMVar,
)
import Effectful (liftIO, runEff)
import Effectful.Config.Log (runLog)
import Effectful.Config.Watch (watchConfig)
import Effectful.Reader.Static (runReader)
import System.FilePath ((</>))
import System.IO.Temp (withSystemTempDirectory)
import System.Timeout (timeout)
import Test.Hspec (Spec, describe, it, shouldBe)
import Toml.Schema (FromValue (..), parseTableFromValue, reqKey)
newtype C = C Int
deriving (Eq, Show)
instance FromValue C where
fromValue = parseTableFromValue (C <$> reqKey "n")
spec :: Spec
spec = describe "watchConfig" $ do
it "reloads on change and calls back" $
withWatcher $ \file cfg seen -> do
writeFile file "n = 2\n"
timeout 5000000 (takeMVar seen) `shouldReturnJust` (C 1, C 2)
readMVar cfg `shouldReturnC` C 2
it "keeps old value on invalid TOML" $
withWatcher $ \file cfg seen -> do
writeFile file "n = = nope\n"
threadDelay 1000000
readMVar cfg `shouldReturnC` C 1
writeFile file "n = 3\n"
timeout 5000000 (takeMVar seen) `shouldReturnJust` (C 1, C 3)
where
shouldReturnJust act v = act >>= (`shouldBe` Just v)
shouldReturnC act v = act >>= (`shouldBe` v)
withWatcher :: (FilePath -> MVar C -> MVar (C, C) -> IO ()) -> IO ()
withWatcher body = withSystemTempDirectory "watch" $ \dir -> do
let file = dir </> "c.toml"
writeFile file "n = 1\n"
cfg <- newMVar (C 1)
seen <- newEmptyMVar
let run =
runEff . runLog (\_ _ _ _ -> pure ()) . runReader cfg $
watchConfig file (\o n -> liftIO (putMVar seen (o, n)))
withAsync run $ \_ -> threadDelay 500000 >> tryTakeMVar seen >> body file cfg seen