diff --git a/webapi-test/CHANGELOG.md b/webapi-test/CHANGELOG.md index b544d83..07b4b00 100644 --- a/webapi-test/CHANGELOG.md +++ b/webapi-test/CHANGELOG.md @@ -1,5 +1,63 @@ # Revision history for webapi-test +## 0.4.0.0 -- 2026-11-16 (zenbridge #2714: a scenario's moves, stages and checks) + +* **A fresh value is new each time it is drawn.** `FreshValue` begins a step + of its own, so the session's one-token-per-label-per-step cache no longer + hands a second draw of the same label the first draw's token (two things a + move made in one case had one "fresh" PO). +* **`EffectCall` runs in the sessions** (breaking). Its effect is + `LookUp -> WebApiSessions apps (Either Text res)`, was `IO`: a host's + own step (a document built from a spec and uploaded, several calls) runs + as the run's context. An `IO` effect lifts with `liftIO`. +* **A scenario's moves** (`Test.WebApi.Moves`). A move is one action by an + actor, written as DL: its things picked by the stage they are predicted + at (`pickAt`), a step that begins it (`MoveBegin`), its own steps, and a + step that ends it (`MoveSettle`). `anyMoves n` draws moves one after + another, `n` on average, each by its weight among the moves allowed at + that point (quickcheck-dynamic's own weighted choice). +* **The prediction** (`Test.WebApi.Prediction`). `ApiState` gains + `prediction`: the things a scenario tracks (`Thing`: its track, the stage + it is predicted at, the moves made on it, the labels its draws gave, its + value). A `Track` declares a kind of thing's stages, its refusal stages + and the platform's answers, the paths it takes by itself; the first + answer whose `when` holds is taken. A thing at a stage is also recorded + under the class `track@stage`. +* **A move's end is judged against what the host observes.** The host + settles what the move caused within the move's budget and observes it + (`MoveHost`, in `WebApiGlobalStateModel`'s new `appMoveHost`; + `defMoveHost` settles at once and observes nothing). The property's + `Judge` then holds every thing against the observation: its observed + stage against the predicted one, the checks at that stage, the checks + after the move for the things it touched, and the checks across things. + The host's own checks run too. A failure names the check and the thing. +* **Inconclusive.** A move that does not settle within its budget, or + cannot be observed, stops its case: neither passed nor failed. + QuickCheck discards the case. The trace says `inconclusive` and why + (`CaseOutcome.Inconclusive`, `ReplayOutcome.ReplayInconclusive`, + `StepRecord.inconclusive`). +* **Narrowing through the program** (`Test.WebApi.Replay.narrowThroughProgram`, + used by `propDL` and `propDLTraced`). quickcheck-dynamic keeps a shorter case's own + steps and checks them against the program only by `Eq`, which for a call + compares its operation and label, so a step under a narrowed pick kept + the request it was drawn with. Each shorter case is now made again from + its picks through the program, as a regression case is replayed. Every + pick is offered narrowed too: quickcheck-dynamic narrows a run of picks + only from its first. A move is kept or dropped whole. `forAllDLRecorded` + takes the narrowing as its first argument. +* A move's body reports what it gave (`MoveBody`: the values of the things + it makes, the labels its draws said, and the variables those values use + beyond their own, kept on the settle step, `MoveEnd.uses`, so narrowing + never keeps a move whose things refer to a step it dropped). +* The trace: step kinds `begin` and `settle`; `StepRecord.inMove` (the move + a step belongs to); `CheckRecord.subject` (the thing a check was about); + a case's `moves`, and the move counts, list a scenario's moves rather + than their steps. +* `AnyVal` moves to `Test.WebApi.Val` (still re-exported by + `Test.WebApi.StateModel`). +* A test suite, `moves`: two moves against a toy platform that does not + acknowledge a replacement 850. + ## 0.3.0.0 -- 2026-11-16 (zenbridge #2713: regression cases, with exact replay) * **A run's narrowed case, written out** (`Test.WebApi.Case`): the case diff --git a/webapi-test/quickcheck-dynamic/Test/WebApi/DynamicLogic.hs b/webapi-test/quickcheck-dynamic/Test/WebApi/DynamicLogic.hs index 64b137e..3aa3c3c 100644 --- a/webapi-test/quickcheck-dynamic/Test/WebApi/DynamicLogic.hs +++ b/webapi-test/quickcheck-dynamic/Test/WebApi/DynamicLogic.hs @@ -24,9 +24,12 @@ import Test.QuickCheck.Monadic import Test.QuickCheck.Monadic qualified as QC import Data.Reflection import Data.IORef -import Test.WebApi.Trace (Recorder, ReplayOutcome (..), ReplayRecord (..), beginCaseWith, noteReplay, recordedProperty, stepsFailure, takeSteps) +import Test.WebApi.Trace (Recorder, ReplayOutcome (..), ReplayRecord (..), StepRecord (..), beginCaseWith, noteReplay, recordedProperty, stepsFailure, takeSteps) +import Test.WebApi.Prediction (MoveInconclusive (..)) +import Control.Exception (catch) +import Data.List (find) import Test.WebApi.Case (CaseItem, CaseRecord (..)) -import Test.WebApi.Replay (caseItemsOf, forAllDLRecorded, replayTest, webApiReplayHooks) +import Test.WebApi.Replay (caseItemsOf, forAllDLRecorded, narrowThroughProgram, replayTest, webApiReplayHooks) import Test.QuickCheck.DynamicLogic.Internal (DynFormula (..), withDLScript) import qualified Test.QuickCheck as QC import qualified Data.Text as T @@ -43,13 +46,15 @@ propDL :: forall c xstate apps e s. , Show e , Reifies s (WebApiGlobalStateModel c xstate apps) ) => Proxy s -> (forall a. WebApiSessions apps a -> IO a) -> DL (ApiState s c xstate apps) () -> Property -propDL _ webapiRunner d = forAllDL d (prop_api undefined webapiRunner) +propDL _ webapiRunner d = forAllDLRecorded narrowThroughProgram (\_ _ -> ()) d (\() -> propApiWith Nothing webapiRunner) -- | 'propDL', each case it plays recorded into the recorder: the steps as -- they run, the case closed when QuickCheck finishes it (a generated case -- or a narrowing try alike; see "Test.WebApi.Trace"), and the case as a -- regression case would keep it ("Test.WebApi.Case"), so the narrowed one --- can be replayed. +-- can be replayed. Narrowing goes through the program +-- ('narrowThroughProgram'): a shorter case is made again from its picks, +-- and a scenario's move is kept or dropped whole. propDLTraced :: forall c xstate apps e s. ( DynLogicModel xstate , RunModel xstate IO @@ -59,7 +64,7 @@ propDLTraced :: forall c xstate apps e s. , Reifies s (WebApiGlobalStateModel c xstate apps) ) => Recorder -> Proxy s -> (forall a. WebApiSessions apps a -> IO a) -> DL (ApiState s c xstate apps) () -> Property propDLTraced rec _ webapiRunner d = recordedProperty rec $ - forAllDLRecorded (\size test -> (size, caseItemsOf test)) d (\c -> propApiWithCase (Just rec) (Just c) webapiRunner) + forAllDLRecorded narrowThroughProgram (\size test -> (size, caseItemsOf test)) d (\c -> propApiWithCase (Just rec) (Just c) webapiRunner) -- | Each regression case played once against the program as it is now -- (zenbridge #2713), before the property draws any of its own: how it @@ -82,16 +87,22 @@ replayCasesDL rec _ webapiRunner d kept = forM_ (zip [1 ..] kept) $ \(k, CaseRec (withDLScript dl (propApiWithCase (Just rec) Nothing webapiRunner) test) played <- takeSteps rec let (at, why) = stepsFailure played + unsettled = find (\StepRecord {inconclusive} -> inconclusive /= Nothing) played qcWhy = case res of QC.Failure {QC.reason = r} -> Just (T.pack r) _ -> Nothing - outcome = case res of - QC.Success {} -> ReplayPassed - QC.GaveUp {} -> CantReplay + outcome = case (unsettled, res) of + (Just _, _) -> ReplayInconclusive + (_, QC.Success {}) -> ReplayPassed + (_, QC.GaveUp {}) -> CantReplay _ -> ReplayFailed + replayWhy = case outcome of + CantReplay -> Just (T.pack "the program discards it") + ReplayInconclusive -> unsettled >>= \StepRecord {inconclusive} -> inconclusive + _ -> why <|> qcWhy noteReplay rec ReplayRecord { caseNumber = k, replayOutcome = outcome, replayAt = at - , replayWhy = if outcome == CantReplay then Just (T.pack "the program discards it") else why <|> qcWhy + , replayWhy , replaySteps = played } prop_api :: forall c xstate apps e s. @@ -135,7 +146,9 @@ propApiWithCase :: forall c xstate apps e s. -> Actions (ApiState s c xstate apps) -> Property propApiWithCase rec kept webapiRunner s = - monadic (ioProperty . webapiRunner . flip runReaderT (maybe initWebApiSessionsCxt tracingCxt rec)) $ do + -- a move that did not settle stops the case: neither passed nor failed, + -- so QuickCheck discards it (the trace says it was inconclusive) + monadic (\m -> ioProperty (webapiRunner (runReaderT m (maybe initWebApiSessionsCxt tracingCxt rec)) `catch` inconclusive)) $ do mapM_ (\r -> QC.run (liftIO (beginCaseWith r kept))) rec monitor $ counterexample "\nExecution\n" (_anonSt, _env) <- runActions s @@ -143,6 +156,9 @@ propApiWithCase rec kept webapiRunner s = -- newApiState = resolveNamedEntities env $ underlyingState anonSt -- liftIO $ writeIORef newStRef (Just newApiState) QC.assert True + where + inconclusive MoveInconclusive {move = mv, why} = + pure (QC.counterexample ("move " ++ T.unpack mv ++ " is inconclusive: " ++ T.unpack why) (QC.property QC.Discard)) -- runWebApiTest :: forall r apps. WebApiGlobalStateModel apps -> (forall (s :: Type). Reifies s (WebApiGlobalStateModel apps) => Proxy s -> r) -> r -- runWebApiTest gstate runner = reify gstate (\ps -> runner ps) diff --git a/webapi-test/quickcheck-dynamic/Test/WebApi/Moves.hs b/webapi-test/quickcheck-dynamic/Test/WebApi/Moves.hs new file mode 100644 index 0000000..8a24ee8 --- /dev/null +++ b/webapi-test/quickcheck-dynamic/Test/WebApi/Moves.hs @@ -0,0 +1,122 @@ +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE RecordWildCards #-} +-- | A scenario's moves, as DL (zenbridge #2714). +-- +-- A move is one action by an actor. Its things are picked by the stage +-- they are predicted at ('pickAt'); then it begins (a step that performs +-- nothing), plays its own steps (calls, glue, draws: ordinary DL), and +-- ends ('MoveSettle'): the prediction moves on, the host settles what the +-- move caused and observes it, and the property's 'Judge' holds every +-- thing against the observation. A move that does not settle within its +-- budget is inconclusive. +-- +-- > anyMoves 10 +-- > [ (3, send850) +-- > , (1, do o <- pickAt "orders" "855 sent" (\_ _ -> True) +-- > move Move { name = "replace850", picked = [(o, Just "850 arrives")], .. }) ] +-- +-- Narrowing keeps or drops a move whole, and makes every shorter case +-- again from its picks through the program +-- ('Test.WebApi.Replay.narrowThroughProgram'). +module Test.WebApi.Moves + ( module Test.WebApi.Prediction + , anyMoves + , pickAt + , Move (..) + , MoveBody (..) + , move + ) where + +import Control.Applicative (Alternative (..)) +import Control.Monad (void, when) +import qualified Data.Map.Strict as M +import qualified Data.Set as Set +import Data.Foldable (asum) +import Data.Text (Text) +import qualified Data.Text as T +import Test.QuickCheck.DynamicLogic (DL, action, exactlyQ, forAllQ, getModelStateDL, stopping, weight) +import Test.QuickCheck.StateModel.Variables (HasNoVariables (..)) +import Test.QuickCheck.StateModel (Action, Any, StateModel, Var) +import Test.WebApi.Prediction +import Test.WebApi.StateModel +import Test.WebApi.Trace (StepInfo) + +-- | Moves drawn one after another, @n@ on average (as 'Test.QuickCheck.DynamicLogic.anyActions' +-- draws actions), each by its weight among the moves allowed at that +-- point. A move that is not allowed now (its pick finds nothing) is +-- 'empty' and takes no share. +-- +-- Each draw of a move opens with a pick of nothing (a unit): once a case +-- is past its size, quickcheck-dynamic prefers to stop, and drops only +-- the branches that open with a pick or a drawn action; a move that makes +-- a thing opens with a plain step, and without the pick the case would +-- run on to the step limit. +anyMoves :: Int -> [(Double, DL s ())] -> DL s () +anyMoves n moves = loop + where + weighted = [ (w, m) | (w, m) <- moves, w > 0 ] + total = sum (map fst weighted) + loop = stopping <|> pure () <|> (aMove >> loop) + aMove = do + HasNoVariables () <- forAllQ (exactlyQ (HasNoVariables ())) + asum [ weight (fromIntegral n * w / total) >> m | (w, m) <- weighted ] + +-- | A thing of the track at the stage, among those the guard allows, by +-- position (a pick narrowing moves toward the oldest); 'empty' when there +-- is none. The guard sees the whole prediction. +pickAt :: (StateModel xstate, Eq (Action xstate Text)) => Text -> Text -> (Prediction -> Thing -> Bool) -> DL (ApiState s c xstate apps) Thing +pickAt tr sg allowed = do + ApiState {prediction} <- getModelStateDL + case [ t | t <- thingsAt tr sg prediction, allowed prediction t ] of + [] -> empty + ts -> elementsM ts + +-- | A move, as the layer above builds it once its things are picked. A +-- guard over several picks goes before it ('Control.Monad.guard'): once a +-- move has begun, it is played. +data Move s c xstate apps = Move + { name :: Text + , info :: StepInfo + -- ^ where it was written, for the trace and for a regression case + , picked :: [(Thing, Maybe Text)] + -- ^ each thing it picked and where it sends it (none: it stays, and + -- no answer moves it) + , makes :: [(Text, Text)] + -- ^ the track and stage of each thing it makes + , body :: DL (ApiState s c xstate apps) MoveBody + -- ^ its steps, and what they gave + , tracks :: M.Map Text Track + , judge :: Judge + , budget :: Int + -- ^ seconds the host may take to settle it + } + +-- | What a move's steps gave. +data MoveBody = MoveBody + { values :: [AnyVal] + -- ^ the values of the things it makes, one per 'makes' + , labels :: Set.Set Text + -- ^ what its draws said, onto every thing it touches + , uses :: Set.Set (Any Var) + -- ^ the variables those values refer to beyond their own ('Val's + -- carry theirs), for a value the engine cannot look into + } + +-- | The move played: it begins, its steps, it ends. +move :: (StateModel xstate, Eq (Action xstate ())) => Move s c xstate apps -> DL (ApiState s c xstate apps) () +move Move {..} = do + void (action (mkWebApiAction (MoveBegin name info))) + MoveBody {values, labels, uses} <- body + when (length values /= length makes) $ + fail ("move " <> T.unpack name <> " makes " <> show (length makes) <> " things, and its steps gave " <> show (length values)) + void $ action $ mkWebApiAction $ MoveSettle MoveEnd + { name + , info + , picked = [ (thingId, stage, to) | (Thing {thingId, stage}, to) <- picked ] + , makes = zipWith (\(tr, sg) v -> (tr, sg, v)) makes values + , labels + , tracks + , judge + , budget + , uses + } diff --git a/webapi-test/quickcheck-dynamic/Test/WebApi/Prediction.hs b/webapi-test/quickcheck-dynamic/Test/WebApi/Prediction.hs new file mode 100644 index 0000000..4f15885 --- /dev/null +++ b/webapi-test/quickcheck-dynamic/Test/WebApi/Prediction.hs @@ -0,0 +1,233 @@ +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE GADTs #-} +-- | What a scenario predicts (zenbridge #2714): the things it tracks, the +-- stage each is predicted to be at, and how the platform's own answers +-- move a thing on. A case is drawn against the prediction alone; after +-- each move settles, a 'Judge' holds it against what the host observes. +-- +-- * A /thing/ is one tracked item of a kind (an order, a shipment), made by +-- a move. Its id is its place in the order things were made. +-- * A /track/ is one kind of thing: its stages, the stages marked as +-- refusals, and the /answers/, the paths the platform takes by itself. +-- The answers leaving a stage are an ordered list; the first whose +-- @when@ holds is taken. +-- * A thing at a stage is also recorded under the class @track\@stage@ +-- ('stageClassName'), the model's ordinary classes. +-- +-- The engine names no host: what a thing's value means, what an +-- observation is and what the checks read are the layer above's. +module Test.WebApi.Prediction + ( -- * Things + ThingId (..) + , Thing (..) + , thingSubject + , Prediction (..) + , emptyPrediction + , predictedThings + , thingsAt + , stageClassName + -- * Tracks + , Answer (..) + , Track (..) + , follow + -- * Judging a move + , MoveEnd (..) + , Judge (..) + , noJudge + , StageOf (..) + , ThingCheck (..) + , PredictionCheck (..) + , SomeObservation (..) + -- * The host + , MoveHost (..) + , defMoveHost + , MoveInconclusive (..) + ) where + +import Control.Exception (Exception) +import qualified Data.Map.Strict as M +import qualified Data.Set as Set +import Data.Text (Text) +import qualified Data.Text as T +import Data.Typeable (Typeable) +import Test.QuickCheck.StateModel (Any, LookUp, Var) +import Test.WebApi (WebApiSessions) +import Test.WebApi.Trace (StepInfo) +import Test.WebApi.Val (AnyVal) + +-- --------------------------------------------------------------------------- +-- Things + +-- | A thing's place in the order things were made, from 1. +newtype ThingId = ThingId Int + deriving newtype (Show, Eq, Ord) + +data Thing = Thing + { thingId :: ThingId + , track :: Text + , stage :: Text + -- ^ the stage it is predicted to be at + , movesOn :: [Text] + -- ^ the moves made on it, oldest first (its making move included) + , labels :: Set.Set Text + -- ^ what the draws of its moves said of it + , value :: AnyVal + -- ^ what its making move gave it; a leaf still symbolic when the case + -- is drawn (a fresh value, an earlier step's result) stays opaque + } + +-- | How a check names the thing: its track and its id. +thingSubject :: Thing -> Text +thingSubject Thing {track, thingId = ThingId k} = track <> " #" <> T.pack (show k) + +data Prediction = Prediction + { things :: M.Map ThingId Thing + , nextThing :: Int + -- ^ the id the next thing made gets + } + +emptyPrediction :: Prediction +emptyPrediction = Prediction {things = M.empty, nextThing = 1} + +-- | Every thing, oldest first. +predictedThings :: Prediction -> [Thing] +predictedThings Prediction {things} = M.elems things + +-- | The things of the track at the stage, oldest first. +thingsAt :: Text -> Text -> Prediction -> [Thing] +thingsAt tr sg p = [ t | t@Thing {track, stage} <- predictedThings p, track == tr, stage == sg ] + +-- | The class a thing at a stage is recorded under. +stageClassName :: Text -> Text -> Text +stageClassName tr sg = tr <> "@" <> sg + +-- --------------------------------------------------------------------------- +-- Tracks + +-- | A path the platform takes by itself, from one stage to another. +data Answer = Answer + { from :: Text + , to :: Text + , when :: Maybe (Prediction -> Thing -> Bool) + -- ^ none: always taken (the last answer leaving its stage) + , label :: Maybe Text + -- ^ for the map + } + +data Track = Track + { name :: Text + , stages :: [Text] + , refusals :: Set.Set Text + -- ^ the stages a thing that should be refused ends at + , answers :: [Answer] + } + +-- | The thing carried along the track's answers from where it stands: +-- at each stage the first answer whose @when@ holds, until no answer +-- leaves the stage. 'Left' when the answers go round in a circle. +follow :: Track -> Prediction -> Thing -> Either Text Thing +follow Track {name = trackName, answers} Prediction {things = known, nextThing} = go Set.empty + where + go seen t@Thing {stage, thingId} + | Set.member stage seen = Left ("the answers of track " <> trackName <> " go round in a circle at " <> stage) + | otherwise = + let p = Prediction {things = M.insert thingId t known, nextThing} + taken = [ a | a@Answer {from, when} <- answers, from == stage, maybe True (\w -> w p t) when ] + in case taken of + [] -> Right t + Answer {to} : _ -> go (Set.insert stage seen) t {stage = to} + +-- --------------------------------------------------------------------------- +-- Judging a move + +-- | A move's closing step, as the engine plays it ("Test.WebApi.Moves"): +-- what it does to the prediction, and how the property judges it. +data MoveEnd = MoveEnd + { name :: Text + , info :: StepInfo + , picked :: [(ThingId, Text, Maybe Text)] + -- ^ each thing it picked, the stage it was picked at, and where it + -- goes (none: it stays, and no answer moves it) + , makes :: [(Text, Text, AnyVal)] + -- ^ each thing it makes: its track, its stage, its value + , labels :: Set.Set Text + -- ^ what the move's draws said, onto every thing it touches + , tracks :: M.Map Text Track + , judge :: Judge + , budget :: Int + -- ^ seconds the host may take to settle + , uses :: Set.Set (Any Var) + -- ^ the variables the things it makes refer to: the DL keeps the + -- steps that bind them + } + +-- | The stage a thing is observed at. +newtype StageOf obs = StageOf (LookUp -> obs -> Thing -> Either Text Text) + +-- | A check of one thing against the observation, seeing the prediction. +newtype ThingCheck obs = ThingCheck (LookUp -> Prediction -> Thing -> obs -> Either Text ()) + +-- | A check across things. +newtype PredictionCheck obs = PredictionCheck (LookUp -> Prediction -> obs -> Either Text ()) + +-- | A property's refinements and checks, over the observation the host +-- makes (its type is the layer above's: the host's observation is cast to +-- it). After every move, for every thing: its observed stage equals the +-- predicted one, then the checks at that stage; the checks after the move +-- for the things it touched; the checks across things. +data Judge where + Judge :: Typeable obs => + { stageOf :: M.Map Text (StageOf obs) + -- ^ by track; a track with none is not observed + , atStage :: [(Text, (Text, Text), ThingCheck obs)] + -- ^ name, (track, stage) + , afterMove :: [(Text, Text, ThingCheck obs)] + -- ^ name, move + , always :: [(Text, PredictionCheck obs)] + } -> Judge + +-- | Nothing to judge. +noJudge :: Judge +noJudge = Judge {stageOf = M.empty @Text @(StageOf ()), atStage = [], afterMove = [], always = []} + +-- | What the host observed, whatever its type. +data SomeObservation where + SomeObservation :: (Typeable o, Show o) => o -> SomeObservation + +instance Show SomeObservation where + show (SomeObservation o) = show o + +-- --------------------------------------------------------------------------- +-- The host + +-- | What the host does after a move: wait until what the move caused has +-- settled, within the move's budget; observe; and the checks it makes +-- itself on every flow. +data MoveHost apps = MoveHost + { settle :: Int -> WebApiSessions apps (Either Text ()) + -- ^ 'Left' says why it did not settle within the budget (seconds): + -- the move is inconclusive + , observe :: WebApiSessions apps (Either Text SomeObservation) + -- ^ 'Left': nothing could be observed, and the move is inconclusive + , hostChecks :: SomeObservation -> [(Text, Either Text ())] + } + +-- | A host whose moves settle at once, that observes nothing. +defMoveHost :: MoveHost apps +defMoveHost = MoveHost + { settle = \_ -> pure (Right ()) + , observe = pure (Right (SomeObservation ())) + , hostChecks = const [] + } + +-- | A move that did not settle within its budget, or could not be +-- observed: neither passed nor failed. The case runner discards the case +-- and the trace says so. +data MoveInconclusive = MoveInconclusive + { move :: Text + , why :: Text + } + deriving Show + +instance Exception MoveInconclusive diff --git a/webapi-test/quickcheck-dynamic/Test/WebApi/Replay.hs b/webapi-test/quickcheck-dynamic/Test/WebApi/Replay.hs index b925a14..cd22c40 100644 --- a/webapi-test/quickcheck-dynamic/Test/WebApi/Replay.hs +++ b/webapi-test/quickcheck-dynamic/Test/WebApi/Replay.hs @@ -13,6 +13,7 @@ -- ('runDL', exported by byteally's quickcheck-dynamic 4.0.1.1). module Test.WebApi.Replay ( forAllDLRecorded + , narrowThroughProgram , caseItemsOf -- * Replay , ReplayHooks (..) @@ -30,7 +31,7 @@ import qualified Test.QuickCheck as QC import Test.QuickCheck.DynamicLogic (DL, DynLogicModel, runDL) import Test.QuickCheck.DynamicLogic.Internal ( DynFormula (..), DynLogic (..), DynLogicTest (DLScript), TestContinuation (..), TestSequence (..), Witnesses (..) - , generateDLTest, getScript, initialStateFor, shrinkDLTest, withDLScript ) + , generateDLTest, getScript, initialStateFor, nextStateStep, shrinkDLTest, shrinkWitness, stepDLStep, stepDLWitness, withDLScript ) import Test.QuickCheck.DynamicLogic.SmartShrinking (shrinkSmart) import qualified Test.QuickCheck.DynamicLogic.Utils as QCU import Test.QuickCheck.DynamicLogic.Quantify (Quantification (..), QuantifyConstraints) @@ -42,26 +43,86 @@ import Data.Proxy (Proxy (..)) import Data.Reflection (Reifies, reflect) import Test.WebApi.StateModel ( ApiState, WebApiGlobalStateModel (..), drawnOf, moveIdentity, repointAction, requestLinks, stampDrawn, unWebApiAction ) -import Test.WebApi.Trace (StepInfo (..), kindText) +import Test.WebApi.Trace (StepInfo (..), StepKind (..), kindText) -- | 'Test.QuickCheck.DynamicLogic.forAllDL', the property handed each test --- it plays as @keep size test@ beside the test's actions. Generation and --- narrowing are quickcheck-dynamic's own ('forAllMappedScripts' with the --- test itself as its representation). +-- it plays as @keep size test@ beside the test's actions. Generation is +-- quickcheck-dynamic's own; so is narrowing, its candidates passed through +-- @narrow@ (the formula, the test being narrowed, its candidates) before +-- any is played ('narrowThroughProgram'). forAllDLRecorded :: (DynLogicModel s, Testable a) - => (Int -> DynLogicTest s -> b) + => (DynLogic s -> DynLogicTest s -> [DynLogicTest s] -> [DynLogicTest s]) + -> (Int -> DynLogicTest s -> b) -> DL s () -> (b -> Actions s -> a) -> Property -forAllDLRecorded keep d k = +forAllDLRecorded narrow keep d k = QCU.withSize $ \n -> let dl = unDynFormula (runDL initialAnnotatedState d) n in QC.forAllShrinkBlind (QC.Smart 0 <$> QC.sized (generateDLTest dl)) - (shrinkSmart (shrinkDLTest dl)) + (shrinkSmart (\test -> narrow dl test (shrinkDLTest dl test))) $ \(QC.Smart _ test) -> withDLScript dl (k (keep n test)) test +-- | Narrowing as the program plays it (zenbridge #2714). quickcheck-dynamic +-- keeps a shorter test's own steps and only checks each against the +-- program by its 'Eq', which for a call is its operation and label: a pick +-- narrowed under a step left the step as it was drawn. So each candidate +-- is made again from its picks through the program ('replayTest'), as a +-- regression case is. Every pick is offered narrowed too ('pickShrinks'): +-- quickcheck-dynamic narrows a run of picks only from its first, so a +-- first pick that cannot narrow keeps the rest as drawn. A candidate that +-- ends inside a scenario's move (a begin step with no settle step after +-- it) is dropped: a move is narrowed whole. So is one the program no +-- longer plays, one equal to the test being narrowed, and every repeat. +narrowThroughProgram + :: forall s c xstate apps. (StateModel xstate, Reifies s (WebApiGlobalStateModel c xstate apps), DynLogicModel (ApiState s c xstate apps)) + => DynLogic (ApiState s c xstate apps) + -> DynLogicTest (ApiState s c xstate apps) + -> [DynLogicTest (ApiState s c xstate apps)] + -> [DynLogicTest (ApiState s c xstate apps)] +narrowThroughProgram dl current = go [key current] . (++ pickShrinks dl current) + where + go _ [] = [] + go seen (t : rest) = case remade t of + Nothing -> go seen rest + Just t' + | k `elem` seen -> go seen rest + | otherwise -> t' : go (k : seen) rest + where k = key t' + remade t@(DLScript _) = case replayTest webApiReplayHooks dl (caseItemsOf t) of + Right t' | wholeMoves t' -> Just t' + _ -> Nothing + remade t = Just t + -- the items, a pick after the last step aside (it plays nothing) + key t = reverse (dropWhile isPick (reverse (caseItemsOf t))) + isPick = \case + ItemPick _ -> True + ItemMove _ -> False + wholeMoves t = not (or (scanOpen False [ kd | Right st <- flatten (getScript t), let (kd, _, _) = identity st ])) + identity (_ := ActionWithPolarity {polarAction = act}) = moveIdentity (unWebApiAction act) + -- whether a move is open after each step; the last must be closed + scanOpen o [] = [o] + scanOpen _ (KindBegin : ks) = scanOpen True ks + scanOpen _ (KindSettle : ks) = scanOpen False ks + scanOpen o (_ : ks) = scanOpen o ks + +-- | The test with one of its picks narrowed (by the quantifier the +-- program draws it with), every other item as it was: a step after it may +-- no longer match it, so the candidates are to be made again through the +-- program ('narrowThroughProgram'). +pickShrinks :: forall s. DynLogicModel s => DynLogic s -> DynLogicTest s -> [DynLogicTest s] +pickShrinks d0 test = map DLScript (go initialAnnotatedState d0 (getScript test)) + where + go :: Annotated s -> DynLogic s -> TestSequence s -> [TestSequence s] + go s d (TestSeq w) = case w of + Do ContStop -> [] + Do (ContStep st rest) -> [ TestSeq (Do (ContStep st r)) | r <- go (nextStateStep st s) (stepDLStep d s st) rest ] + Witness a k -> + [ TestSeq (Witness a' k) | a' <- shrinkWitness d a ] + ++ [ TestSeq (Witness a r) | TestSeq r <- go s (stepDLWitness d a) (TestSeq k) ] + -- | A pick, whatever its type. data AnyPick where PickOf :: QuantifyConstraints a => a -> AnyPick diff --git a/webapi-test/quickcheck-dynamic/Test/WebApi/StateModel.hs b/webapi-test/quickcheck-dynamic/Test/WebApi/StateModel.hs index f87379c..1018d90 100644 --- a/webapi-test/quickcheck-dynamic/Test/WebApi/StateModel.hs +++ b/webapi-test/quickcheck-dynamic/Test/WebApi/StateModel.hs @@ -21,6 +21,8 @@ module Test.WebApi.StateModel , module Test.WebApi.Val , ClientRequestVal (..) , WebApiGlobalStateModel (..) + , MoveHost (..) + , defMoveHost , NER (..) , HasApiSession (..) , WebApiSessionsCxt @@ -65,7 +67,6 @@ module Test.WebApi.StateModel , ActionConfig (..) , ActionConfigWith (..) , ApiGenM - , AnyVal (..) , GetOpIdName , runApiGenM , runApiGenMDrawing @@ -162,7 +163,7 @@ import WebApi.Contract import WebApi.Param import WebApi.ContentTypes import WebApi.Util -import Control.Exception (SomeException, evaluate, try) +import Control.Exception (SomeException, evaluate, throwIO, try) import Control.Applicative ((<|>)) import Data.Either (isRight) import Data.Foldable (forM_) @@ -171,7 +172,8 @@ import qualified Data.Text.Encoding.Error as TE import Test.WebApi.Trace ( StepInfo (..), stepLabel, StepKind (..), Expectation (..), RequestRecord (..), FileRecord (..) , AnswerRecord (..), CheckRecord (..), StageRecord (..), StepRecord (..), Recorder - , pushStep, amendStep, afterStep, clipText, bodyText ) + , pushStep, amendStep, afterStep, markInconclusive, clipText, bodyText ) +import Test.WebApi.Prediction import Data.ByteString (ByteString) import Data.Text (Text) import Data.Kind @@ -352,19 +354,31 @@ data WebApiAction s (c :: Type) (xstate :: Type) (apps :: [Type]) (a :: Type) wh -- execution): a fresh value the DL binds like any other result, so a -- request and a later assertion can share it and a replay makes a new one. FreshValue :: Text -> WebApiAction s c xstate apps Text - -- | A step that performs an effect outside the web API — a foreign - -- transform, say — its result bound like any other. The variables the + -- | A step that performs an effect outside one route's call — a foreign + -- transform, or a host's own step over several calls (a document built + -- and uploaded) — its result bound like any other. The variables the -- effect's closure references are declared up front, so the DL keeps the -- steps that bind them; the effect receives the 'LookUp' that resolves - -- them. A 'Left' is the effect's own failure, reported at the step. + -- them, and runs in the sessions, so it may call the apps as the run's + -- context. A 'Left' is the effect's own failure, reported at the step. EffectCall :: (Typeable res, Show res, Eq res, Eq (Action xstate res)) => String -> Maybe StepInfo -- ^ where it was written (a script's rule), for the trace -> Set.Set (Any Var) - -> (LookUp -> IO (Either T.Text res)) + -> (LookUp -> WebApiSessions apps (Either T.Text res)) -> WebApiAction s c xstate apps res XAction :: Action xstate a -> WebApiAction s c xstate apps a + -- | A move of a scenario begins ("Test.WebApi.Moves"): nothing is + -- performed. The move's own steps follow, and its 'MoveSettle' closes it; + -- narrowing keeps or drops the three together. + MoveBegin :: Text -> StepInfo -> WebApiAction s c xstate apps () + -- | A move ends: the prediction moves on (the things it picked go where + -- the move sends them, then along the platform's answers; the things it + -- makes are recorded), the host settles what the move caused and + -- observes it, and the property's judge holds every thing against the + -- observation. A move that does not settle is inconclusive. + MoveSettle :: MoveEnd -> WebApiAction s c xstate apps () -- | What an 'ErrorCall' expects of the response. data ExpectedFailure @@ -402,6 +416,8 @@ instance StateModel xstate => Show (WebApiAction s c xstate apps a) where FreshValue l -> "fresh " ++ T.unpack l EffectCall n _ _ _ -> n XAction xact -> show xact + MoveBegin n _ -> "begin " ++ T.unpack n + MoveSettle MoveEnd {name} -> "settle " ++ T.unpack name -- TODO: Revisit instance Eq (Action xstate a) => Eq (WebApiAction s c xstate apps a) where @@ -433,6 +449,12 @@ instance Eq (Action xstate a) => Eq (WebApiAction s c xstate apps a) where (==) (XAction xact1) = \case XAction xact2 -> xact1 == xact2 _ -> False + (==) (MoveBegin n1 i1) = \case + MoveBegin n2 i2 -> n1 == n2 && i1 == i2 + _ -> False + (==) (MoveSettle MoveEnd {name = n1, info = i1}) = \case + MoveSettle MoveEnd {name = n2, info = i2} -> n1 == n2 && i1 == i2 + _ -> False instance StateModel xstate => HasVariables (WebApiAction s c xstate apps a) where getAllVariables = \case @@ -445,13 +467,14 @@ instance StateModel xstate => HasVariables (WebApiAction s c xstate apps a) wher FreshValue {} -> mempty EffectCall _ _ vars _ -> vars XAction xact -> getAllVariables xact + MoveBegin {} -> mempty + -- the values of the things it makes refer to the move's steps (and to + -- earlier ones): the DL keeps the steps that bind them + MoveSettle MoveEnd {makes, uses} -> uses <> foldMap (\(_, _, v) -> getAllVariables v) makes newtype RefinementId = RefinementId Text deriving newtype (Show, Eq, Ord, Read) -data AnyVal where - SomeVal :: Typeable x => Val x -> AnyVal - -- | The entities the model knows, by type: each carries the class -- ('RefinementId') it was recorded under. A class is a *name* the model -- (or a script) gives a value at a position — never a property of the @@ -522,6 +545,9 @@ data ApiState (s :: Type) (c :: Type) (xstate :: Type) (apps :: [Type]) = ApiSta , classTypes :: M.Map RefinementId TypeRep -- ^ the type each registered class holds ('registerClass'); recording -- another type under it is a model bug + , prediction :: Prediction + -- ^ the things a scenario tracks and the stage each is predicted at + -- ("Test.WebApi.Moves"); each is also recorded under its stage's class -- , sessionState :: M.Map SessionKey NamedEntityTyped } @@ -560,6 +586,7 @@ initApiState f xstate = ApiState , xActionState = xstate , generateFrom = Nothing , classTypes = mempty + , prediction = emptyPrediction } -- | Register a class with the type its entities have; a second @@ -743,6 +770,9 @@ data WebApiGlobalStateModel c xstate apps = WebApiGlobalStateModel -- ^ a drawn action made again for a regression case, from its operation -- and the positions its generation drew ('runApiGenMRedrawing'); -- 'noRedraw' for a model whose actions are never drawn + , appMoveHost :: MoveHost apps + -- ^ what the host does after each move of a scenario: settle, observe, + -- its own checks ('defMoveHost': settles at once, observes nothing) } -- | A model whose actions are never drawn: a regression case holding a @@ -773,6 +803,8 @@ instance ( Reifies s (WebApiGlobalStateModel c xstate apps) MkWebApiAction (FreshValue {}) -> "fresh" MkWebApiAction (EffectCall n _ _ _) -> n MkWebApiAction (XAction xact) -> actionName xact + MkWebApiAction a@(MoveBegin {}) -> show a + MkWebApiAction (MoveSettle MoveEnd {name}) -> T.unpack name arbitraryAction varCxt s = case reflect (Proxy @s) of WebApiGlobalStateModel {appAribitaryAction} -> appAribitaryAction @s varCxt s @@ -791,6 +823,8 @@ instance ( Reifies s (WebApiGlobalStateModel c xstate apps) FreshValue {} -> s EffectCall {} -> s XAction xact -> ApiState {xActionState = nextState xActionState xact var, ..} + MoveBegin {} -> s + MoveSettle me -> settleNextState me s failureNextState s@ApiState{xActionState, ..} (MkWebApiAction act) = case act of SuccessCall _creq SuccessApiModel {apiFailureNextState=nsMay} _ _ -> maybe s (\ns -> ns s) nsMay @@ -802,6 +836,8 @@ instance ( Reifies s (WebApiGlobalStateModel c xstate apps) FreshValue {} -> s EffectCall {} -> s XAction xact -> ApiState {xActionState = failureNextState xActionState xact, ..} + MoveBegin {} -> s + MoveSettle {} -> s precondition s (MkWebApiAction act) = webApiPrecondition s act @@ -815,6 +851,8 @@ instance ( Reifies s (WebApiGlobalStateModel c xstate apps) FreshValue {} -> False EffectCall {} -> False XAction xact -> validFailingAction xActionState xact + MoveBegin {} -> False + MoveSettle {} -> False shrinkAction varCxt s@ApiState{xActionState} (MkWebApiAction act) = case act of -- by default a request shrinks one leaf at a time (a variable to an @@ -832,6 +870,9 @@ instance ( Reifies s (WebApiGlobalStateModel c xstate apps) FreshValue {} -> [] EffectCall {} -> [] XAction xact -> fmap (\(Some xact') -> Some $ MkWebApiAction $ XAction xact') $ shrinkAction varCxt xActionState xact + -- a move narrows by its picks and draws, which the program owns + MoveBegin {} -> [] + MoveSettle {} -> [] -- instance Functor (Action (ApiState s c xstate apps)) where @@ -908,11 +949,24 @@ instance ( Reifies s (WebApiGlobalStateModel c xstate apps) -- the step, then its record (when a recorder is listening): the request -- as it went out and the answer as received are the session's until -- the next step begins - perform st@ApiState {xActionState} act lkp = do - res <- performIt - ReaderT $ \WebApiSessionsCxt {traceRecorder} -> + perform st@ApiState {xActionState} act lkp = case act of + -- a move's end: the host settles what it caused, within its budget; + -- one that does not is inconclusive, recorded so before the case stops + MkWebApiAction (MoveSettle MoveEnd {name, budget}) -> ReaderT $ \WebApiSessionsCxt {traceRecorder} -> do + let WebApiGlobalStateModel {appMoveHost = MoveHost {settle}} = reflect (Proxy @s) + settled <- settle budget + let res = either (const (Right ())) Right settled forM_ traceRecorder $ \rec -> recordPerformed rec st act lkp res - pure res + case settled of + Right () -> pure res + Left why -> do + forM_ traceRecorder $ \rec -> liftIO (amendStep rec (markInconclusive why)) + liftIO (throwIO MoveInconclusive {move = name, why}) + _ -> do + res <- performIt + ReaderT $ \WebApiSessionsCxt {traceRecorder} -> + forM_ traceRecorder $ \rec -> recordPerformed rec st act lkp res + pure res where performIt = case act of MkWebApiAction (SuccessCall creq' SuccessApiModel {apiRetry} cookModMay f) -> ReaderT $ \_ -> do @@ -980,18 +1034,24 @@ instance ( Reifies s (WebApiGlobalStateModel c xstate apps) MkWebApiAction (SetContext c) -> Right <$> (liftIO $ setContext $ hashed c) MkWebApiAction (ClearContext pc) -> Right <$> (liftIO $ clearContext pc) MkWebApiAction (ModelOnly {}) -> pure (Right ()) - MkWebApiAction (FreshValue l) -> ReaderT $ \_ -> Right <$> freshToken ("fresh:" <> l) + -- a draw is a step of its own: its token is new each time it is + -- drawn (a second thing a move makes gets its own), never the + -- token an earlier draw of the same label got (zenbridge #2714) + MkWebApiAction (FreshValue l) -> ReaderT $ \_ -> Right <$> (beginStep >> freshToken ("fresh:" <> l)) MkWebApiAction (EffectCall _ _ _ eff) -> ReaderT $ \_ -> - either (Left . ResultError . MkResultError) Right <$> liftIO (eff lkp) + either (Left . ResultError . MkResultError) Right <$> eff lkp MkWebApiAction (XAction xact) -> ReaderT $ \_ -> do res <- liftIO $ perform xActionState xact lkp pure $ first (XActionError . AnyXActionError) res + MkWebApiAction (MoveBegin {}) -> pure (Right ()) + MkWebApiAction (MoveSettle {}) -> pure (Right ()) postcondition ss@(_, after) (MkWebApiAction act) lkp res = do (held, cs, ls, SomeLookUp lkp') <- case act of SuccessCall creq model _ _ -> withChecks creq model res ErrorCall creq _ model _ -> withChecks creq model res EffectCall {} -> pure (True, [], [], SomeLookUp (extendLookUp lkp res)) + MoveSettle me -> settleChecks me _ -> pure (True, [], [], SomeLookUp lkp) rec <- lift (asks (\WebApiSessionsCxt {traceRecorder} -> traceRecorder)) forM_ rec $ \r -> lift $ liftIO $ do @@ -1000,6 +1060,27 @@ instance ( Reifies s (WebApiGlobalStateModel c xstate apps) amendStep r (afterStep cs ls m stageAfter held) pure held where + -- a move's end: the host observes, then every thing is held against + -- the observation, and the host's own checks run. What cannot be + -- observed is inconclusive, as a move that does not settle is + settleChecks :: MoveEnd -> PostconditionM (ReaderT WebApiSessionsCxt (WebApiSessions apps)) (Bool, [CheckRecord], [Text], SomeLookUp) + settleChecks me@MoveEnd {name, labels} = do + let WebApiGlobalStateModel {appMoveHost = MoveHost {observe, hostChecks}} = reflect (Proxy @s) + observed <- lift (lift observe) + case observed of + Left why -> do + rec <- lift (asks (\WebApiSessionsCxt {traceRecorder} -> traceRecorder)) + lift $ liftIO $ do + forM_ rec $ \r -> amendStep r (markInconclusive ("nothing could be observed: " <> why)) + throwIO MoveInconclusive {move = name, why = "nothing could be observed: " <> why} + Right obs -> do + let + judged = judgeMove lkp me ss obs + ++ [ CheckRecord {check = nm, held = isRight r, why = either Just (const Nothing) r, subject = Nothing} | (nm, r) <- hostChecks obs ] + failed = [ (c, w) | CheckRecord {check = c, held = False, why = w} <- judged ] + forM_ failed $ \(c, w) -> counterexamplePost (" check " ++ T.unpack c ++ " failed: " ++ maybe "" T.unpack w) + forM_ (Set.toList labels) $ \l -> monitorPost (QC.classify True (T.unpack l)) + pure (null failed, judged, Set.toList labels, SomeLookUp lkp) -- the request as it went out: the step's fresh tokens are still those. -- Every check runs; each failure is reported, and the trace lists -- each check with whether it held, and the labels that held. The @@ -1012,7 +1093,7 @@ instance ( Reifies s (WebApiGlobalStateModel c xstate apps) case resolveRequest placeholders {freshOf = freshLookup toks} lkp creq of Left why -> do counterexamplePost (" postcondition failed: " ++ T.unpack why) - pure (False, [CheckRecord {check = "request", held = False, why = Just why}], [], SomeLookUp (extendLookUp lkp x)) + pure (False, [CheckRecord {check = "request", held = False, why = Just why, subject = Nothing}], [], SomeLookUp (extendLookUp lkp x)) Right req -> do let results = [ (nm, f ss lkp req x) | (nm, StepCheck f) <- apiChecks ] @@ -1022,7 +1103,7 @@ instance ( Reifies s (WebApiGlobalStateModel c xstate apps) forM_ heldLabels $ \l -> monitorPost (QC.classify True (T.unpack l)) pure ( all (isRight . snd) results - , [ CheckRecord {check = nm, held = isRight r, why = either Just (const Nothing) r} | (nm, r) <- results ] + , [ CheckRecord {check = nm, held = isRight r, why = either Just (const Nothing) r, subject = Nothing} | (nm, r) <- results ] , heldLabels , SomeLookUp (extendLookUp lkp x) ) @@ -1111,7 +1192,7 @@ recordPerformed rec st (MkWebApiAction act) lkp res = do stageBefore <- liftIO (stageOfGuarded lkp st) let engineStep k op i shown = StepRecord - { n = 0, kind = k, info = i, operation = op, method = Nothing, expect = Nothing, request = Nothing + { n = 0, kind = k, info = i, operation = op, method = Nothing, expect = Nothing, request = Nothing, inMove = Nothing, inconclusive = Nothing , answer = Just AnswerRecord { httpStatus = Nothing , body = Nothing @@ -1131,7 +1212,7 @@ recordPerformed rec st (MkWebApiAction act) lkp res = do let (req, meth) = requestRecordOf creq pure StepRecord { n = 0, kind = KindCall, info = Nothing, operation = T.pack (getOpIdFromRequest creq), method = Just meth - , expect = Nothing, request = Just req + , expect = Nothing, request = Just req, inMove = Nothing, inconclusive = Nothing , answer = Just AnswerRecord {httpStatus = H.statusCode . fst <$> raw, body = bodyMay >>= bodyText bodyClip, value = Nothing, failure = either (Just . shownText) (const Nothing) res} , checks = [], labels = [], model = Nothing , stage = StageRecord {before = stageBefore, after = Nothing} @@ -1143,6 +1224,8 @@ recordPerformed rec st (MkWebApiAction act) lkp res = do FreshValue l -> pure (engineStep KindFresh ("fresh " <> l) Nothing Just) EffectCall nm i _ _ -> pure (engineStep KindGlue (T.pack nm) i (Just . shownText)) XAction xact -> pure (engineStep KindOther (T.pack (actionName xact)) Nothing (const Nothing)) + MoveBegin nm i -> pure (engineStep KindBegin nm (Just i) (const Nothing)) + MoveSettle MoveEnd {name, info} -> pure (engineStep KindSettle name (Just info) (const Nothing)) liftIO (pushStep rec record) where expectedStatus = \case @@ -1163,6 +1246,8 @@ moveIdentity = \case FreshValue l -> (KindFresh, Nothing, "fresh " <> l) EffectCall nm i _ _ -> (KindGlue, i, T.pack nm) XAction xact -> (KindOther, Nothing, T.pack (actionName xact)) + MoveBegin nm i -> (KindBegin, Just i, nm) + MoveSettle MoveEnd {name, info} -> (KindSettle, Just info, name) -- | A call's record: the request as it went out (its fresh values as the -- step made them, its files by name), the answer as received, and the @@ -1185,6 +1270,8 @@ callRecord lkp creq i expectation res stageBefore = do , method = meth , expect = Just expectation , request = Just req + , inMove = Nothing + , inconclusive = Nothing , answer = Just AnswerRecord { httpStatus = (H.statusCode . fst <$> raw) <|> either errorStatus (const Nothing) res , body = bodyMay >>= bodyText bodyClip @@ -1209,11 +1296,11 @@ callRecord lkp creq i expectation res stageBefore = do callChecks :: Expectation -> Either ErrorState res -> [CheckRecord] callChecks expectation = \case Right _ -> [statusHeld] - Left (ResultError (MkResultError e)) -> [statusHeld, CheckRecord {check = "result", held = False, why = Just e}] - Left (InputNotSetError fld) -> [CheckRecord {check = "request", held = False, why = Just (fld <> " is not set")}] - Left err -> [CheckRecord {check = "status", held = False, why = Just (statusWhy err)}] + Left (ResultError (MkResultError e)) -> [statusHeld, CheckRecord {check = "result", held = False, why = Just e, subject = Nothing}] + Left (InputNotSetError fld) -> [CheckRecord {check = "request", held = False, why = Just (fld <> " is not set"), subject = Nothing}] + Left err -> [CheckRecord {check = "status", held = False, why = Just (statusWhy err), subject = Nothing}] where - statusHeld = CheckRecord {check = "status", held = True, why = Nothing} + statusHeld = CheckRecord {check = "status", held = True, why = Nothing, subject = Nothing} code st = T.pack (show (H.statusCode st)) expected = case expectation of GoesThrough -> "it to go through" @@ -1306,6 +1393,85 @@ instance ( Reifies s (WebApiGlobalStateModel c xstate apps) ) => DynLogicModel (ApiState s c xstate apps) where restricted _ = False +-- --------------------------------------------------------------------------- +-- A move's end ("Test.WebApi.Moves") + +-- | The prediction after a move: each thing it picked goes where the move +-- sends it, then along its track's answers (a thing the move leaves where +-- it is stays put); each thing it makes is recorded at its stage and +-- carried along the answers from there. Every thing it touches gains the +-- move and the labels its draws gave, and moves between the stages' +-- classes ('stageClassName'). +settleNextState :: MoveEnd -> ApiState s c xstate apps -> ApiState s c xstate apps +settleNextState MoveEnd {name, picked, makes, labels, tracks} st0 = + foldl makeOne (foldl moveOne st0 picked) makes + where + touched Thing {movesOn, labels = ls, ..} = Thing {movesOn = movesOn ++ [name], labels = ls <> labels, ..} + sentTo sg Thing {thingId, track, movesOn, labels = ls, value} = Thing {thingId, track, stage = sg, movesOn, labels = ls, value} + along t@Thing {track} p = case M.lookup track tracks of + Nothing -> error $ T.unpack $ "move " <> name <> ": no track " <> track + Just tr -> either (\why -> error (T.unpack ("move " <> name <> ": " <> why))) id (follow tr p t) + moveOne st (tid, _, toMay) = case M.lookup tid (thingsOf st) of + Nothing -> st + Just t@Thing {stage = before} -> + let p = predictionOf st + t' = case toMay of + Nothing -> touched t + Just to -> along (sentTo to (touched t)) p + in placed before t' st + makeOne st (tr, sg, v) = + let p@Prediction {nextThing, things} = predictionOf st + t = along Thing {thingId = ThingId nextThing, track = tr, stage = sg, movesOn = [name], labels, value = v} p + in placed "" t (setPrediction Prediction {nextThing = nextThing + 1, things} st) + -- the thing at its stage: out of the class it was in, into its stage's + placed before t@Thing {thingId, track, stage} st = + let st1 = if T.null before then st else removeNamedEntity (RefinementId (stageClassName track before)) (Const thingId) st + st2 = addTypedEntity (Const thingId) (stageNER track stage) st1 + Prediction {nextThing} = predictionOf st2 + in setPrediction Prediction {things = M.insert thingId t (thingsOf st2), nextThing} st2 + stageNER tr sg = let k = stageClassName tr sg in NER {refinementId = RefinementId k, entityName = k, desc = Nothing} + predictionOf ApiState {prediction} = prediction + thingsOf st = let Prediction {things} = predictionOf st in things + setPrediction p ApiState {..} = ApiState {prediction = p, ..} + +-- | A move's end judged: for every thing, its observed stage against the +-- predicted one and the checks at that stage; the checks after this move, +-- for the things it touched; the checks across things. Each record names +-- the check and the thing (the step is the move's). +judgeMove :: LookUp -> MoveEnd -> (ApiState s c xstate apps, ApiState s c xstate apps) -> SomeObservation -> [CheckRecord] +judgeMove lkp MoveEnd {name, picked, judge = Judge {stageOf, atStage, afterMove, always}} (before, after) (SomeObservation o0) = + case cast o0 of + Nothing + | nothingToJudge -> [] + | otherwise -> [CheckRecord {check = "observation", held = False, subject = Nothing, why = Just ("the host observed a " <> T.pack (show (typeOf o0)) <> ", which the property's checks do not read")}] + Just o -> stageChecks o ++ atChecks o ++ afterChecks o ++ alwaysChecks o + where + nothingToJudge = M.null stageOf && null atStage && null afterMove && null always + p@Prediction {nextThing = madeUpTo} = let ApiState {prediction} = after in prediction + Prediction {nextThing = madeFrom} = let ApiState {prediction} = before in prediction + everything = predictedThings p + touchedIds = Set.fromList ([ tid | (tid, _, _) <- picked ] ++ map ThingId [madeFrom .. madeUpTo - 1]) + record nm t r = CheckRecord {check = nm, held = isRight r, why = either Just (const Nothing) r, subject = thingSubject <$> t} + guarded :: Either Text () -> Either Text () + guarded r = unsafePerformIO $ either (\(e :: SomeException) -> Left ("the check could not be judged: " <> T.pack (show e))) id <$> try (evaluate (forcedE r)) + forcedE r = case r of + Left w -> T.length w `seq` r + Right () -> r + stageChecks o = + [ record "stage" (Just t) $ guarded $ case f lkp o t of + Right seen | seen == stage -> Right () + | otherwise -> Left ("predicted at " <> stage <> ", observed at " <> seen) + Left why -> Left why + | t@Thing {track, stage} <- everything, Just (StageOf f) <- [M.lookup track stageOf] ] + atChecks o = + [ record nm (Just t) (guarded (f lkp p t o)) + | (nm, (tr, sg), ThingCheck f) <- atStage, t <- thingsAt tr sg p ] + afterChecks o = + [ record nm (Just t) (guarded (f lkp p t o)) + | (nm, mv, ThingCheck f) <- afterMove, mv == name, t@Thing {thingId} <- everything, Set.member thingId touchedIds ] + alwaysChecks o = + [ record nm Nothing (guarded (f lkp p o)) | (nm, PredictionCheck f) <- always ] + successCall :: forall meth r app c xstate apps s. (WebApiActionCxt apps meth app r, Show (ApiOut meth (app :// r)), Eq (Action xstate (ApiOut meth (app :// r)))) => ClientRequestVal meth (app :// r) -> Action (ApiState s c xstate apps) (ApiOut meth (app :// r)) @@ -1834,7 +2000,7 @@ setGenerateFromDL names = modelOnlyDL ("generate from " ++ maybe "*" (show . Set -- | The model's precondition of an action (what 'precondition' answers), -- available without the reflected model. webApiPrecondition :: StateModel xstate => ApiState s c xstate apps -> WebApiAction s c xstate apps a -> Bool -webApiPrecondition s@ApiState{xActionState} = \case +webApiPrecondition s@ApiState{xActionState, prediction} = \case SuccessCall _creq SuccessApiModel {apiPrecondition=pcMay} _ _ -> maybe True (\pc -> pc s) pcMay ErrorCall _creq _ SuccessApiModel {apiPrecondition=pcMay} _ -> maybe True (\pc -> pc s) pcMay SomeExceptionCall {} -> True @@ -1844,6 +2010,11 @@ webApiPrecondition s@ApiState{xActionState} = \case FreshValue {} -> True EffectCall {} -> True XAction xact -> precondition xActionState xact + MoveBegin {} -> True + -- each thing it picked is still where it was picked + MoveSettle MoveEnd {picked} -> + let Prediction {things} = prediction + in and [ maybe False (\Thing {stage} -> stage == at) (M.lookup tid things) | (tid, at, _) <- picked ] -- | Run another next-state transition after the model's own. addNextState :: (Var a -> ApiState s c xstate apps -> ApiState s c xstate apps) -> SuccessApiModel s c xstate apps meth r a -> SuccessApiModel s c xstate apps meth r a diff --git a/webapi-test/quickcheck-dynamic/Test/WebApi/Trace.hs b/webapi-test/quickcheck-dynamic/Test/WebApi/Trace.hs index a609d13..79ebdd3 100644 --- a/webapi-test/quickcheck-dynamic/Test/WebApi/Trace.hs +++ b/webapi-test/quickcheck-dynamic/Test/WebApi/Trace.hs @@ -55,6 +55,8 @@ module Test.WebApi.Trace , pushStep , amendStep , afterStep + , markInconclusive + , caseMoves -- * Rendering helpers , clipText , bodyText @@ -95,10 +97,12 @@ data StepInfo = StepInfo stepLabel :: StepInfo -> Text stepLabel StepInfo {trail, summary} = T.intercalate "." trail <> ": " <> summary --- | What a step is. A /move/ is a call or a glue step; the rest are the --- engine's own (a fresh value, a context switch, a step that only moves --- the model). -data StepKind = KindCall | KindGlue | KindFresh | KindContext | KindModel | KindOther +-- | What a step is. A /move/ is a call or a glue step, or a scenario's +-- move ("Test.WebApi.Moves"): its 'KindBegin' step, its own steps, and its +-- 'KindSettle' step, which settles, observes and judges it. The rest are +-- the engine's own (a fresh value, a context switch, a step that only +-- moves the model). +data StepKind = KindCall | KindGlue | KindFresh | KindContext | KindModel | KindOther | KindBegin | KindSettle deriving (Eq, Show) kindText :: StepKind -> Text @@ -109,6 +113,8 @@ kindText = \case KindContext -> "context" KindModel -> "model" KindOther -> "other" + KindBegin -> "begin" + KindSettle -> "settle" isMove :: StepKind -> Bool isMove k = k == KindCall || k == KindGlue @@ -156,6 +162,8 @@ data CheckRecord = CheckRecord { check :: Text , held :: Bool , why :: Maybe Text + , subject :: Maybe Text + -- ^ the thing a scenario's check was about (@orders #2@) } deriving (Eq, Show) @@ -185,6 +193,12 @@ data StepRecord = StepRecord -- when the step failed (no next state is computed then) , stage :: StageRecord , ok :: Bool + , inMove :: Maybe Int + -- ^ the scenario's move the step belongs to (its begin and settle + -- steps included), numbered from 1 in its case + , inconclusive :: Maybe Text + -- ^ a move's settle step that did not settle, or could not observe: + -- why. Neither passed nor failed } deriving (Eq, Show) @@ -201,7 +215,7 @@ moveCountKey StepRecord {info, operation} = case info of Just StepInfo {name = Just nm} -> nm _ -> operation -data CaseOutcome = Passed | Failed | Discarded +data CaseOutcome = Passed | Failed | Discarded | Inconclusive deriving (Eq, Show) outcomeText :: CaseOutcome -> Text @@ -209,6 +223,7 @@ outcomeText = \case Passed -> "passed" Failed -> "failed" Discarded -> "discarded" + Inconclusive -> "inconclusive" -- | One generated case, in a line. data CaseSummary = CaseSummary @@ -255,6 +270,8 @@ data ReplayOutcome | CantReplay -- ^ the program no longer plays it (a move removed, a pick of another -- type, …); 'why' says what + | ReplayInconclusive + -- ^ a move did not settle within its budget; 'why' says why deriving (Eq, Show) data ReplayRecord = ReplayRecord @@ -334,7 +351,7 @@ instance ToJSON AnswerRecord where [ "http_status" .= httpStatus, "body" .= body, "value" .= value, "failure" .= failure ] instance ToJSON CheckRecord where - toJSON CheckRecord {..} = object ["check" .= check, "held" .= held, "why" .= why] + toJSON CheckRecord {..} = object ["check" .= check, "held" .= held, "why" .= why, "subject" .= subject] instance ToJSON StageRecord where toJSON StageRecord {..} = case (before, after) of @@ -357,7 +374,11 @@ instance ToJSON StepRecord where , "labels" .= labels , "model" .= model , "stage" .= stage - , "outcome" .= (if ok then "ok" else "failed" :: Text) + , "move" .= inMove + , "outcome" .= (case inconclusive of + Just _ -> "inconclusive" + Nothing -> if ok then "ok" else "failed" :: Text) + , "inconclusive" .= inconclusive ] instance ToJSON CaseSummary where @@ -378,6 +399,7 @@ instance ToJSON ReplayOutcome where ReplayPassed -> "passed" ReplayFailed -> "failed" CantReplay -> "cant_replay" + ReplayInconclusive -> "inconclusive" instance ToJSON ReplayRecord where toJSON ReplayRecord {..} = object @@ -498,10 +520,22 @@ takeSteps Recorder {current, currentCase} = do noteReplay :: Recorder -> ReplayRecord -> IO () noteReplay Recorder {gathered} r = modifyIORef' gathered $ \g@Gathered {replayLines} -> g {replayLines = replayLines |> r} --- | A step ran: append it, numbered. +-- | A step ran: append it, numbered, and with the scenario's move it +-- belongs to: a begin step opens the case's next move, and every step +-- after it up to its settle step is in it. pushStep :: Recorder -> StepRecord -> IO () pushStep Recorder {current} StepRecord {..} = - modifyIORef' current $ \s -> s |> StepRecord {n = Seq.length s + 1, ..} + modifyIORef' current $ \s -> + let + marks = [ (k, m) | StepRecord {kind = k, inMove = m} <- toList s, k == KindBegin || k == KindSettle ] + opened = length [ () | (KindBegin, _) <- marks ] + open = case reverse marks of + (KindBegin, m) : _ -> m + _ -> Nothing + inMove' = case kind of + KindBegin -> Just (opened + 1) + _ -> open + in s |> StepRecord {n = Seq.length s + 1, inMove = inMove', ..} -- | Change the step last pushed (its postcondition ran). amendStep :: Recorder -> (StepRecord -> StepRecord) -> IO () @@ -509,6 +543,15 @@ amendStep Recorder {current} f = modifyIORef' current $ \s -> case Seq.viewr s o Seq.EmptyR -> s rest Seq.:> lastStep -> rest |> f lastStep +-- | A move's settle step that did not settle (or could not observe): why. +markInconclusive :: Text -> StepRecord -> StepRecord +markInconclusive why StepRecord {..} = StepRecord {inconclusive = Just why, ok = False, ..} + +-- | The moves a case played, as its summary lists them: a scenario's move +-- once (by its settle step), and every call or glue step outside one. +caseMoves :: [StepRecord] -> [StepRecord] +caseMoves stepList = [ st | st@StepRecord {kind, inMove} <- stepList, kind == KindSettle || (isMove kind && inMove == Nothing) ] + -- | What a step's postcondition adds: its checks, the labels that held, -- the model after it, the stage after it, and whether it all held. afterStep :: [CheckRecord] -> [Text] -> M.Map Text [Text] -> Maybe Text -> Bool -> StepRecord -> StepRecord @@ -533,24 +576,33 @@ closeCase Recorder {current, currentCase, gathered, origin = (scenarioHash, prop stepList <- toList <$> atomicModifyIORef' current (\s -> (Seq.empty, s)) caseKept <- atomicModifyIORef' currentCase (\c -> (Nothing, c)) let - outcome = case P.ok res of - Just True -> Passed - Just False -> Failed - Nothing -> Discarded + unsettled = find (\StepRecord {inconclusive} -> inconclusive /= Nothing) stepList + outcome = case (unsettled, P.ok res) of + (Just _, _) -> Inconclusive + (_, Just True) -> Passed + (_, Just False) -> Failed + (_, Nothing) -> Discarded failing = find (\StepRecord {ok} -> not ok) stepList at = (\StepRecord {n} -> n) <$> failing why | outcome == Failed = (failing >>= stepWhy) <|> nonEmpty (T.pack (P.reason res)) + | outcome == Inconclusive = unsettled >>= \StepRecord {inconclusive} -> inconclusive | otherwise = Nothing played = not (null stepList) - moveList = [ moveName s | s@StepRecord {kind} <- stepList, isMove kind ] - countKeys = [ moveCountKey s | s@StepRecord {kind} <- stepList, isMove kind ] + moveList = map moveName (caseMoves stepList) + countKeys = map moveCountKey (caseMoves stepList) held = Set.toList (Set.fromList (map T.pack (P.classes res))) replayable = (\(sz, its) -> CaseRecord {format = caseFormat, scenario = scenarioHash, property = propertyName, size = sz, items = its}) <$> caseKept modifyIORef' gathered $ \g@Gathered {..} -> if not narrowingStarted then case outcome of Discarded -> g {discardedCount = discardedCount + 1} + -- QuickCheck discards it and draws another; the trace lists it, and + -- counts no label or move of it + Inconclusive -> + let k = caseCount + 1 + in g { caseCount = k + , caseLines = caseLines |> CaseSummary {number = k, played, moves = moveList, outcome, at, why, labels = []} } _ -> let k = caseCount + 1 line' = CaseSummary {number = k, played, moves = moveList, outcome, at, why, labels = held} diff --git a/webapi-test/quickcheck-dynamic/Test/WebApi/Val.hs b/webapi-test/quickcheck-dynamic/Test/WebApi/Val.hs index f468c1e..279de95 100644 --- a/webapi-test/quickcheck-dynamic/Test/WebApi/Val.hs +++ b/webapi-test/quickcheck-dynamic/Test/WebApi/Val.hs @@ -14,6 +14,7 @@ -- whole request. module Test.WebApi.Val ( Val (..) + , AnyVal (..) , GVal (..) , GValRep (..) , resolveVal @@ -162,6 +163,13 @@ freshLabels = \case Fresh l _ -> Set.singleton l TempFile _ c _ -> freshLabels c +-- | A value, whatever its type. +data AnyVal where + SomeVal :: Typeable x => Val x -> AnyVal + +instance HasVariables AnyVal where + getAllVariables (SomeVal v) = getAllVariables v + instance HasVariables (Val a) where getAllVariables = \case Const {} -> mempty diff --git a/webapi-test/test/Moves.hs b/webapi-test/test/Moves.hs new file mode 100644 index 0000000..03859be --- /dev/null +++ b/webapi-test/test/Moves.hs @@ -0,0 +1,255 @@ +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE RecordWildCards #-} +{-# LANGUAGE AllowAmbiguousTypes #-} +-- | A scenario's moves against a toy platform (zenbridge #2714): an +-- order's 850 is acknowledged by an 855, and the buggy platform does not +-- acknowledge a replacement (BEG01 05), as zenbridge #2698 did not. +-- +-- Two moves: @send850@ makes an order with a fresh PO, @replace850@ picks +-- an acknowledged order and sends its replacement. The host observes the +-- platform's documents; the track's @stageOf@ reads an order's stage off +-- them, and a check at @855 sent@ holds one 855 per 850 the moves sent. +module Main (main) where + +import Control.Monad (unless) +import Control.Monad.IO.Class (liftIO) +import Data.IORef +import Data.List (isInfixOf) +import qualified Data.Map.Strict as M +import qualified Data.Set as Set +import Data.Text (Text) +import qualified Data.Text as T +import Data.Typeable (Proxy (..), gcast) +import System.Exit (exitFailure) +import qualified Test.QuickCheck as QC +import Test.QuickCheck.DynamicLogic (DL, action) +import Test.QuickCheck.Random (mkQCGen) +import Test.QuickCheck.StateModel (Any (..), HasVariables (..), LookUp, initialState) +import Test.WebApi (emptyApp, runWebApis) +import Test.WebApi.Case (CaseRecord) +import Test.WebApi.DynamicLogic +import Test.WebApi.Moves +import Test.WebApi.Trace + +-- --------------------------------------------------------------------------- +-- The platform under test + +data Doc = Doc {kind :: Text, po :: Text, purpose :: Text} + deriving (Show, Eq) + +-- | The platform keeps its documents across cases, as a real one does: a +-- check reads only its own orders' (by PO). +data Platform = Platform + { docs :: IORef [Doc] + , orderCount :: IORef Int + , buggy :: Bool + , settles :: Bool + } + +-- | An 850 arrives; the platform acknowledges it, except a replacement +-- when it is buggy. +receive :: Platform -> Text -> Text -> IO () +receive Platform {docs, buggy} p purp = do + modifyIORef' docs (++ [Doc {kind = "850", po = p, purpose = purp}]) + unless (buggy && purp == "05") $ + modifyIORef' docs (++ [Doc {kind = "855", po = p, purpose = purp}]) + +-- | An original 850: the PO is the sender's fresh value, made unique here +-- (two cases may draw their tokens in the same millisecond). +receiveNew :: Platform -> Text -> IO Text +receiveNew pf@Platform {orderCount} token = do + k <- atomicModifyIORef' orderCount (\c -> (c + 1, c + 1)) + let p = token <> "/" <> T.pack (show k) + receive pf p "00" + pure p + +host :: Platform -> MoveHost '[] +host Platform {docs, settles} = MoveHost + { settle = \_ -> pure (if settles then Right () else Left "the platform is still busy") + , observe = liftIO (Right . SomeObservation <$> readIORef docs) + , hostChecks = const [] + } + +-- --------------------------------------------------------------------------- +-- The scenario + +type St s = ApiState s () NoXState '[] + +orders :: Track +orders = Track + { name = "orders" + , stages = ["850 arrives", "855 sent"] + , refusals = Set.empty + , answers = [Answer {from = "850 arrives", to = "855 sent", when = Nothing, label = Nothing}] + } + +poOf :: LookUp -> Thing -> Either Text Text +poOf lkp Thing {value = SomeVal v} = case gcast v of + Just (pv :: Val Text) -> resolveVal lkp pv + Nothing -> Left "an order's value is its PO" + +count :: Text -> Text -> [Doc] -> Int +count k p ds = length [ () | Doc {kind, po} <- ds, kind == k, po == p ] + +judge :: Judge +judge = Judge + { stageOf = M.singleton "orders" $ StageOf $ \lkp ds t -> do + p <- poOf lkp t + let sent = count "850" p ds + pure (if sent > 0 && count "855" p ds == sent then "855 sent" else "850 arrives") + , atStage = + [ ( "one-855-per-850", ("orders", "855 sent"), ThingCheck $ \lkp _ t@Thing {movesOn} ds -> do + p <- poOf lkp t + let acks = count "855" p ds + sends = length (filter (`elem` ["send850", "replace850"]) movesOn) + if acks == sends then Right () else Left (T.pack (show acks <> " 855s for " <> show sends <> " 850s sent")) ) ] + , afterMove = [] + , always = + [ ( "an 850 per move", PredictionCheck $ \lkp p ds -> + let ours = Set.fromList [ x | t <- predictedThings p, Right x <- [poOf lkp t] ] + moved = sum [ length movesOn | Thing {movesOn} <- predictedThings p ] + seen = length [ () | Doc {kind = "850", po} <- ds, Set.member po ours ] + in if moved == seen then Right () else Left (T.pack (show seen <> " 850s seen, " <> show moved <> " sent")) ) ] + } + +info :: Text -> StepInfo +info nm = StepInfo {trail = ["orders", "partner", nm], summary = nm, name = Just nm} + +-- | A glue step: the 850 sent; its value is the order's PO. +sendStep :: Platform -> Text -> (Text -> IO Text) -> Val Text -> DL (St s) (Val Text) +sendStep _ nm send pv = fmap (Var id) $ action $ mkWebApiAction $ + EffectCall (T.unpack nm) (Just (info nm)) (getAllVariables pv) $ \lkp -> case resolveVal lkp pv of + Right p -> Right <$> liftIO (send p) + Left why -> pure (Left why) + +send850 :: Platform -> DL (St s) () +send850 pf = move Move + { name = "send850", info = info "send850", picked = [], makes = [("orders", "850 arrives")] + , body = do + token <- freshM "po" + rush <- genValM (QC.arbitrary :: QC.Gen Bool) QC.shrink + pv <- sendStep pf "send850" (receiveNew pf) token + pure MoveBody {values = [SomeVal pv], labels = if rush then Set.singleton "rush" else Set.empty, uses = Set.empty} + , tracks = M.singleton "orders" orders, judge, budget = 1 } + +replace850 :: Platform -> DL (St s) () +replace850 pf = do + o <- pickAt "orders" "855 sent" (\_ _ -> True) + move Move + { name = "replace850", info = info "replace850", picked = [(o, Just "850 arrives")], makes = [] + , body = do + pv <- either (fail . T.unpack) pure (thingPo o) + _ <- sendStep pf "replace850" (\p -> p <$ receive pf p "05") pv + pure MoveBody {values = [], labels = Set.empty, uses = Set.empty} + , tracks = M.singleton "orders" orders, judge, budget = 1 } + where + thingPo Thing {value = SomeVal v} = maybe (Left "an order's value is its PO") Right (gcast v) + +scenario :: Platform -> Double -> DL (St s) () +scenario pf replaceWeight = anyMoves 6 [(3, send850 pf), (replaceWeight, replace850 pf)] + +model :: Platform -> WebApiGlobalStateModel () NoXState '[] +model pf = WebApiGlobalStateModel + { appAribitaryAction = \_ _ -> pure (Some (mkWebApiAction (ModelOnly "nothing" id))) + , appInitState = ApiState + { apiState = mempty, namedEntityTyped = mempty, defaultContext = Nothing, currentContext = Nothing + , xActionState = initialState, generateFrom = Nothing, classTypes = mempty, prediction = emptyPrediction } + , appStageOf = noStage + , appRedraw = noRedraw + , appMoveHost = host pf + } + +-- --------------------------------------------------------------------------- +-- Running it + +newPlatform :: Bool -> Bool -> IO Platform +newPlatform b s = do + r <- newIORef [] + c <- newIORef 0 + pure Platform {docs = r, orderCount = c, buggy = b, settles = s} + +-- | The scenario run, traced: QuickCheck's result and the run's trace. +run :: Platform -> Double -> Int -> IO (QC.Result, RunTrace) +run pf w n = do + rec <- newRecorderFor "toy" "orders" ["rush"] + res <- reify (model pf) $ \(ps :: Proxy s) -> + QC.quickCheckWithResult QC.stdArgs {QC.maxSuccess = n, QC.chatty = False, QC.replay = Just (mkQCGen 7, 0), QC.maxDiscardRatio = 3} + (propDLTraced rec ps (runWebApis emptyApp) (scenario @s pf w)) + (,) res <$> readRunTrace rec + +-- | The cases replayed against a platform. +replay :: Platform -> [CaseRecord] -> IO [ReplayRecord] +replay pf cases = do + rec <- newRecorderFor "toy" "orders" [] + reify (model pf) $ \(ps :: Proxy s) -> replayCasesDL rec ps (runWebApis emptyApp) (scenario @s pf 1) cases + RunTrace {replays} <- readRunTrace rec + pure replays + +check :: String -> Bool -> IO Bool +check what ok = do + putStrLn ((if ok then " ok " else " FAIL ") ++ what) + pure ok + +main :: IO () +main = do + results <- sequence + [ soundPlatform + , buggyPlatform + , unsettledPlatform + ] + unless (and (concat results)) exitFailure + +soundPlatform :: IO [Bool] +soundPlatform = do + putStrLn "a sound platform:" + pf <- newPlatform False True + (res, RunTrace {cases, moves, labels, firstFailure}) <- run pf 1 30 + unless (QC.isSuccess res) $ do + putStrLn (QC.output res) + mapM_ (\CaseTrace {steps} -> mapM_ print steps) firstFailure + let names = Set.fromList (concat [ ms | CaseSummary {moves = ms} <- cases ]) + played m = sum [ t | MoveCount {move = m', timesPlayed = t} <- moves, m' == m ] + sequence + [ check "the property passes" (QC.isSuccess res) + , check "every case passed" (all (\CaseSummary {outcome} -> outcome == Passed) cases) + , check ("a case lists its moves, not their steps: " <> show (Set.toList names)) (names `Set.isSubsetOf` Set.fromList ["orders.partner.send850", "orders.partner.replace850"] && not (Set.null names)) + , check ("the heavier move is drawn more: " <> show (played "send850", played "replace850")) (played "send850" > played "replace850" && played "replace850" > 0) + , check "a draw's label is counted" (any (\LabelCount {label, cases = k} -> label == "rush" && k > 0) labels) + ] + +buggyPlatform :: IO [Bool] +buggyPlatform = do + putStrLn "a platform that does not acknowledge a replacement:" + pf <- newPlatform True True + (res, RunTrace {narrowed}) <- run pf 1 30 + case narrowed of + Nothing -> sequence [check "the property fails, with a narrowed case" False] + Just CaseTrace {steps, replayable} -> do + let ms = [ operation | StepRecord {kind = KindSettle, operation} <- steps ] + failing = [ s | s@StepRecord {ok = False} <- steps ] + failedChecks = [ (c, subj) | StepRecord {checks} <- failing, CheckRecord {check = c, held = False, subject = subj} <- checks ] + outside = [ operation | StepRecord {inMove = Nothing, operation} <- steps ] + sound <- newPlatform False True + again <- replay pf (maybe [] pure replayable) + fixed <- replay sound (maybe [] pure replayable) + sequence + [ check "the property fails" (not (QC.isSuccess res)) + , check ("the narrowed case is two whole moves: " <> show ms) (ms == ["send850", "replace850"]) + , check ("every step is in a move: " <> show outside) (null outside) + , check ("it fails at replace850's settle step: " <> show [ operation | StepRecord {operation} <- failing ]) (map (\StepRecord {kind, operation} -> (kind, operation)) failing == [(KindSettle, "replace850")]) + , check ("the failure names the check and the order: " <> show failedChecks) (("stage", Just "orders #1") `elem` failedChecks) + , check "the narrowed case replays to the same failure" (map (\ReplayRecord {replayOutcome, replayAt} -> (replayOutcome, replayAt)) again == [(ReplayFailed, Just (length steps))]) + , check "and passes once the platform is fixed" (map (\ReplayRecord {replayOutcome} -> replayOutcome) fixed == [ReplayPassed]) + ] + +unsettledPlatform :: IO [Bool] +unsettledPlatform = do + putStrLn "a platform that never settles:" + pf <- newPlatform False False + (res, RunTrace {cases}) <- run pf 1 5 + let whys = [ w | CaseSummary {outcome = Inconclusive, why = Just w} <- cases ] + sequence + [ check "the property does not fail" (case res of QC.Failure {} -> False; _ -> True) + , check "no case failed" (all (\CaseSummary {outcome} -> outcome /= Failed) cases) + , check ("the cases that played a move are inconclusive, saying why: " <> show (take 1 whys)) (not (null whys) && all ("still busy" `isInfixOf`) (map T.unpack whys)) + ] diff --git a/webapi-test/webapi-test.cabal b/webapi-test/webapi-test.cabal index ee6bc87..18732bb 100644 --- a/webapi-test/webapi-test.cabal +++ b/webapi-test/webapi-test.cabal @@ -1,6 +1,6 @@ cabal-version: 3.0 name: webapi-test -version: 0.3.0.0 +version: 0.4.0.0 -- synopsis: -- description: license: BSD-3-Clause @@ -58,6 +58,8 @@ library qc-dynamic Test.WebApi.Trace Test.WebApi.Case Test.WebApi.Replay + Test.WebApi.Prediction + Test.WebApi.Moves -- other-modules: build-depends: webapi-test , aeson >= 2.0 @@ -97,3 +99,16 @@ library webapi-test-tasty , hashable hs-source-dirs: tasty default-language: GHC2021 + +-- A scenario's moves against a toy platform (zenbridge #2714). +test-suite moves + import: warnings + type: exitcode-stdio-1.0 + main-is: Moves.hs + hs-source-dirs: test + build-depends: webapi-test + , webapi-test:qc-dynamic + , QuickCheck >= 2.14 + , quickcheck-dynamic >= 4.0.1.1 && < 4.1 + , reflection >= 2.1 + default-language: GHC2021