Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions webapi-test/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
36 changes: 26 additions & 10 deletions webapi-test/quickcheck-dynamic/Test/WebApi/DynamicLogic.hs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -135,14 +146,19 @@ 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
-- let
-- 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)
Expand Down
122 changes: 122 additions & 0 deletions webapi-test/quickcheck-dynamic/Test/WebApi/Moves.hs
Original file line number Diff line number Diff line change
@@ -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
}
Loading
Loading