mock-time (empty) → 0.1.0
raw patch · 9 files changed
+469/−0 lines, 9 filesdep +QuickCheckdep +basedep +error-orsetup-changed
Dependencies added: QuickCheck, base, error-or, error-or-utils, exceptions, inbox, mock-time, mtl, primitive, resourcet, stm, tasty, tasty-hunit, tasty-quickcheck, time, unliftio-core
Files
- LICENSE +30/−0
- README.md +4/−0
- Setup.hs +2/−0
- mock-time.cabal +72/−0
- src/Control/Monad/Time.hs +29/−0
- src/Control/Monad/Time/DefaultInstance.hs +22/−0
- src/Control/Monad/Trans/SimulatedTime.hs +144/−0
- src/Test/SimulatedTime.hs +104/−0
- tests/Tests.hs +62/−0
+ LICENSE view
@@ -0,0 +1,30 @@+Copyright Kamil Dworakowski (c) 2020++All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++ * Redistributions of source code must retain the above copyright+ notice, this list of conditions and the following disclaimer.++ * Redistributions in binary form must reproduce the above+ copyright notice, this list of conditions and the following+ disclaimer in the documentation and/or other materials provided+ with the distribution.++ * Neither the name of Author name here nor the names of other+ contributors may be used to endorse or promote products derived+ from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ README.md view
@@ -0,0 +1,4 @@+# mock-time++Allows to mock out Data.Time.getCurrentTime and Control.Concrurent.threadDelay+
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ mock-time.cabal view
@@ -0,0 +1,72 @@+cabal-version: 1.12++-- This file has been generated from package.yaml by hpack version 0.33.0.+--+-- see: https://github.com/sol/hpack+--+-- hash: f70ad4f0d259256d4dd856fc4bce3eb41bb5f2766f36c5baf158d814f0f83acb++name: mock-time+version: 0.1.0+synopsis: Mock time in tests+description: Allows to mock out Data.Time.getCurrentTime and Control.Concrurent.threadDelay+category: Test+homepage: https://github.com/luntain/error-or-bundle/blob/master/mock-time#readme+author: Kamil Dworakowski+maintainer: kamil@dworakowski.name+copyright: 2020 Kamil Dworakowski+license: BSD3+license-file: LICENSE+tested-with: GHC==8.0.1, GHC==8.2.2, GHC==8.8.1, GHC==8.8.3, GHC==8.10.2+build-type: Simple+extra-source-files:+ README.md++library+ exposed-modules:+ Control.Monad.Time+ Control.Monad.Time.DefaultInstance+ Control.Monad.Trans.SimulatedTime+ Test.SimulatedTime+ other-modules:+ Paths_mock_time+ hs-source-dirs:+ src+ build-depends:+ base >=4.7 && <5+ , error-or+ , exceptions+ , mtl+ , primitive+ , resourcet+ , stm+ , time+ , unliftio-core+ default-language: Haskell2010++test-suite my-test-suite+ type: exitcode-stdio-1.0+ main-is: Tests.hs+ other-modules:+ Paths_mock_time+ hs-source-dirs:+ tests+ ghc-options: -threaded -rtsopts -with-rtsopts=-N -Wall+ build-depends:+ QuickCheck+ , base >=4.7 && <5+ , error-or+ , error-or-utils+ , exceptions+ , inbox+ , mock-time+ , mtl+ , primitive+ , resourcet+ , stm+ , tasty+ , tasty-hunit+ , tasty-quickcheck+ , time+ , unliftio-core+ default-language: Haskell2010
+ src/Control/Monad/Time.hs view
@@ -0,0 +1,29 @@+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE UndecidableInstances #-}++module Control.Monad.Time+ ( MonadTime (..),+ )+where++import Control.Monad.Trans+import Data.Time hiding (getCurrentTime)++-- | A class interface with overridable time implementation.+-- Import `Control.Monad.Time.DefaultInstance` for the default+-- implementation using the real underlying time functions.+-- See `Control.Monad.Trans.SimulatedTime` for an instance+-- that allows to control time.+class Monad m => MonadTime m where+ getCurrentTime :: m UTCTime+ threadDelay :: Int -> m ()++instance {-# OVERLAPPABLE #-}+ ( MonadTime m,+ MonadTrans t,+ Monad (t m)+ ) =>+ MonadTime (t m)+ where+ getCurrentTime = lift getCurrentTime+ threadDelay a = lift (threadDelay a)
+ src/Control/Monad/Time/DefaultInstance.hs view
@@ -0,0 +1,22 @@+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE FlexibleInstances #-}+-- | The instance of 'MonadTime' for IO, using the underlying system time and does+-- This is to be used in production code, or in thoses tests where controling time+-- is not needed.+--+-- This is only and instance for IO, for instances for monad transformers see+-- 'Control.Monad.Trans.SimulatedTime'.+module Control.Monad.Time.DefaultInstance (+module Control.Monad.Time.DefaultInstance,+module Control.Monad.Time) where++import Control.Monad.Time+import Control.Monad.Trans (liftIO)++import Data.Time (getCurrentTime)+import Control.Concurrent (threadDelay)++instance {-# OVERLAPPING #-}+ MonadTime IO where+ getCurrentTime = liftIO Data.Time.getCurrentTime+ threadDelay delay = liftIO $ Control.Concurrent.threadDelay delay
+ src/Control/Monad/Trans/SimulatedTime.hs view
@@ -0,0 +1,144 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE TypeApplications #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE RankNTypes #-}+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE UnboxedTuples #-}+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE PolyKinds #-}++-- | An implementation of `Control.Monad.Time.MonadTime` with a monad transformer.+module Control.Monad.Trans.SimulatedTime+ ( SimulatedTimeT (..),+ runSimulatedTimeT,+ RealTimeT(..),+ getTimeEnv,+ module Test.SimulatedTime+ )+where++import Control.Applicative (Alternative)+import qualified Control.Concurrent+import Control.Monad.Catch (MonadCatch, MonadMask(..), MonadThrow)+import Control.Monad.Cont (MonadCont)+import Control.Monad.Except (MonadError)+import Control.Monad.Primitive (PrimMonad)+import Control.Monad.RWS (MonadState, MonadWriter)+import Control.Monad.Reader+import Control.Monad.Time+import Control.Monad.Trans.Resource (MonadResource)+import Control.Monad.Zip (MonadZip)+import qualified Data.Time+import Control.Monad.IO.Unlift+import Test.SimulatedTime++#if __GLASGOW_HASKELL__ < 880+import Control.Monad.Fail (MonadFail(..))+#endif++-- | A newtype wrapper over `ReaderT` `TimeEnv`+newtype SimulatedTimeT m a = SimulatedTimeT {unSimulatedTimeT :: ReaderT TimeEnv m a}+ deriving+ ( Functor,+ Applicative,+ Alternative,+ Monad,+ MonadIO,+ MonadState s,+ MonadWriter w,+ MonadTrans,+ MonadFail,+ MonadThrow,+ MonadCatch,+ MonadError e,+ MonadCont,+ MonadPlus,+ MonadFix,+ -- MonadUnliftIO, -- gives an incomprehensible typing error+ MonadResource,+ MonadZip+#if MIN_VERSION_GLASGOW_HASKELL(8,2,0,0)+ , PrimMonad+#endif+ )++-- | Run the reader+runSimulatedTimeT :: SimulatedTimeT m a -> TimeEnv -> m a+runSimulatedTimeT = runReaderT . unSimulatedTimeT++instance MonadReader r m => MonadReader r (SimulatedTimeT m) where+ ask = lift ask+ local f = SimulatedTimeT . mapReaderT (local f) . unSimulatedTimeT+ reader = lift . reader++instance MonadIO m => MonadTime (SimulatedTimeT m) where+ getCurrentTime = SimulatedTimeT $ do+ env <- ask+ liftIO $ getSimulatedTime env++ threadDelay delay = SimulatedTimeT $ do+ env <- ask+ liftIO $ threadDelay' env delay++-- | Use 'TimeEnv' to control the simulated time, for instance call+-- 'Time.SimlatedTime.advance' on it to advance in simulated time.+getTimeEnv :: Monad m => SimulatedTimeT m TimeEnv+getTimeEnv = SimulatedTimeT ask++instance MonadUnliftIO m => MonadUnliftIO (SimulatedTimeT m) where+ withRunInIO (inner :: (forall a. SimulatedTimeT m a -> IO a) -> IO b) =+ SimulatedTimeT (withRunInIO (\x -> inner (x . unSimulatedTimeT))) -- \x is needed to avoid some typing problems++instance MonadMask m => MonadMask (SimulatedTimeT m) where+ mask inner = SimulatedTimeT $ mask (\unmask -> unSimulatedTimeT $ inner (SimulatedTimeT . unmask . unSimulatedTimeT))+ uninterruptibleMask inner = SimulatedTimeT (uninterruptibleMask (\unmask -> unSimulatedTimeT $ inner (SimulatedTimeT . unmask . unSimulatedTimeT)))+ generalBracket acquire release inner =+ SimulatedTimeT $ generalBracket (unSimulatedTimeT acquire) (fmap (fmap unSimulatedTimeT) release) (fmap (unSimulatedTimeT) inner)++-- | An implementation for `MonadTime` that uses real time directly,+-- not allowing for control. Use it from code where you need to choose+-- implementation for MockTime, but don't need to control the time.+--+-- Example: use this one in the executable, while `SimulatedTimeT` is+-- used in tests that need to control time.+newtype RealTimeT m a = RealTimeT {runRealTimeT :: m a}+ deriving+ ( Functor,+ Applicative,+ Alternative,+ Monad,+ MonadIO,+ MonadReader s,+ MonadState s,+ MonadWriter w,+ --MonadTrans, "cannot eta-reduce the representation type enough", says ghc+ MonadFail,+ MonadThrow,+ MonadCatch,+ MonadError e,+ MonadCont,+ MonadPlus,+ MonadFix,+ MonadResource,+ MonadZip+#if MIN_VERSION_GLASGOW_HASKELL(8,2,0,0)+ , PrimMonad+#endif+ )++instance MonadIO m => MonadTime (RealTimeT m) where+ getCurrentTime = RealTimeT $ liftIO $ Data.Time.getCurrentTime+ threadDelay delay = RealTimeT $ do liftIO $ Control.Concurrent.threadDelay delay++instance MonadUnliftIO m => MonadUnliftIO (RealTimeT m) where+ withRunInIO (inner :: (forall a. RealTimeT m a -> IO a) -> IO b) =+ RealTimeT (withRunInIO (\x -> inner (x . runRealTimeT))) -- \x is needed to avoid some typing problems++instance MonadMask m => MonadMask (RealTimeT m) where+ mask inner = RealTimeT $ mask (\unmask -> runRealTimeT $ inner (RealTimeT . unmask . runRealTimeT))+ uninterruptibleMask inner = RealTimeT (uninterruptibleMask (\unmask -> runRealTimeT $ inner (RealTimeT . unmask . runRealTimeT)))+ generalBracket acquire release inner =+ RealTimeT $ generalBracket (runRealTimeT acquire) (fmap (fmap runRealTimeT) release) (fmap (runRealTimeT) inner)
+ src/Test/SimulatedTime.hs view
@@ -0,0 +1,104 @@+{-# LANGUAGE TypeApplications #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE UnboxedTuples #-}++-- | Contains a simulated-time implementaion. It can be used directly,+-- to implement the simulated versions of getCurrentTime and+-- threadDelay, or can be used via monad transformers defined in+-- `Control.Monad.Trans.SimulatedTime`+module Test.SimulatedTime+ ( TimeEnv,+ create,+ advance,+ triggerEvents,+ getSimulatedTime,+ threadDelay',+ )+where++import Control.Concurrent hiding (threadDelay)+import qualified Control.Concurrent+import Control.Concurrent.STM+import Control.Monad (unless, when)+import Data.Foldable (forM_)+import Data.Function (on)+import Data.Functor (void)+import Data.List (insertBy, partition)+import Data.Maybe (listToMaybe)+import Data.Time hiding (getCurrentTime)+import qualified Data.Time+import Data.Bifunctor (Bifunctor(first))++-- | It remembers the offset from system time and keeps a list of+-- sleeping threads (threads in 'threadDelay'' call)+data TimeEnv+ = TimeEnv+ { offset :: TVar NominalDiffTime,+ events :: TVar [(UTCTime, MVar ())]+ }++-- | Create the simulated time env from the given time start point. For example+--+-- @+-- timeEnv <- create (fromGregorian 2000 1 1) 0+-- getSimulatedTime timeEnv+-- @+create :: UTCTime -> IO TimeEnv+create epoch = do+ now <- Data.Time.getCurrentTime+ TimeEnv <$> newTVarIO (diffUTCTime epoch now) <*> newTVarIO []++-- | The current simulated time+getSimulatedTime :: TimeEnv -> IO UTCTime+getSimulatedTime t = do+ now <- Data.Time.getCurrentTime+ offset <- readTVarIO (offset t)+ return $ addUTCTime offset now++-- | Wake up due sleeping threads, based on TimeEnv. This happens on+-- its own, but this call can quicken things up. Under the hood it is+-- just @advance tenv 0@+triggerEvents :: TimeEnv -> IO ()+triggerEvents t = advance t 0++-- | Move the simulated time by a delta+advance :: TimeEnv -> NominalDiffTime -> IO ()+advance t diff = do+ now <- Data.Time.getCurrentTime+ due <- atomically $ do+ unless (diff == 0) $ modifyTVar (offset t) (+ diff)+ modifyTVar (events t) (map (first (addUTCTime (- diff))))+ extractDueEvents t now+ forM_ due (flip putMVar ())+ scheduleNextWakeUp t now++-- the 'now' is the system time now, as opposed to simulated now+extractDueEvents :: TimeEnv -> UTCTime -> STM [MVar ()]+extractDueEvents t now = do+ (due, inTheFuture) <- partition ((<= now) . fst) <$> readTVar (events t)+ writeTVar (events t) inTheFuture+ return (map snd due)++scheduleNextWakeUp :: TimeEnv -> UTCTime -> IO ()+scheduleNextWakeUp t now = do+ nextEvent <- listToMaybe . map fst <$> readTVarIO (events t)+ case nextEvent of+ Nothing -> return ()+ Just tm -> do+ let us = ceiling (diffUTCTime tm now * 1000000)+ void (forkIO (Control.Concurrent.threadDelay us >> triggerEvents t))++-- | Simulated alternative to `Control.Concurrent.threadDelay`, sleep+-- for the given number of microseconds. Threads wakes up according to+-- the simulated time.+threadDelay' :: TimeEnv -> Int -> IO ()+threadDelay' t us = do+ mvar <- newEmptyMVar+ now <- Data.Time.getCurrentTime+ shouldScheduleWakeUp <- atomically $ do+ nextWakeUp <- listToMaybe . map fst <$> readTVar (events t)+ let eventTime = addUTCTime (fromIntegral us / (1000 * 1000)) now+ modifyTVar (events t) (insertBy (compare `on` fst) (eventTime, mvar))+ return (maybe True (eventTime <) nextWakeUp)+ when shouldScheduleWakeUp (scheduleNextWakeUp t now)+ readMVar mvar
+ tests/Tests.hs view
@@ -0,0 +1,62 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# language OverloadedStrings #-}+import Control.Concurrent (forkIO)+import Control.Monad+import Data.ErrorOr+import Data.Time+import Data.ErrorOr.Validation+import Test.Inbox+import Test.QuickCheck+import Test.QuickCheck.Monadic+import qualified Test.SimulatedTime as SimTime+import Test.Tasty+import Test.Tasty.HUnit+import Test.Tasty.QuickCheck+#if __GLASGOW_HASKELL__ < 880+import Data.Semigroup+#endif++main :: IO ()+main =+ defaultMain $+ testGroup+ "tests"+ [ testCase "put" $ do+ tenv <- SimTime.create (UTCTime (fromGregorian 2015 7 18) 0)+ box <- newInbox+ _ <- forkIO (SimTime.threadDelay' tenv 50000 >> putInbox box "50ms")+ _ <- forkIO (SimTime.threadDelay' tenv 500000 >> putInbox box ".5s")+ _ <- forkIO (SimTime.threadDelay' tenv 1000000 >> putInbox box "1s")+ t0 <- Data.Time.getCurrentTime+ takeInbox box (equalTo "50ms")+ t1 <- Data.Time.getCurrentTime+ let elapsed = diffUTCTime t1 t0+ toE $ (elapsed <! 0.070) <> (elapsed >! 0.049),++ -- takes around 5.5s+ testProperty "advance" $ do+ let sorted :: [Int] =+ [ 50000,+ 10^6,+ 10^7+ ]+ shuffled <- shuffle sorted+ return . monadicIO . run $ do+ fluxCapacitor <- SimTime.create (UTCTime (fromGregorian 2015 7 18) 0)+ inbox <- newInbox+ t0 <- Data.Time.getCurrentTime+ forM_ shuffled $ \delay -> void $ forkIO $ do+ SimTime.threadDelay' fluxCapacitor delay+ putInbox inbox delay+ takeInbox inbox (equalTo 50000)+ elapsed <- flip diffUTCTime t0 <$> Data.Time.getCurrentTime+ toE (elapsed >! 0.049)+ toE =<< expectEmpty inbox+ SimTime.advance fluxCapacitor 1+ takeInbox inbox (equalTo $ 10^6)+ toE . tag "1s" =<< expectEmpty inbox+ SimTime.advance fluxCapacitor 10+ takeInbox inbox (equalTo $ 10^7)+ toE . tag "10s" =<< expectEmpty inbox+ ]