diff --git a/webapi-session/src/WebApi/Client/Session.hs b/webapi-session/src/WebApi/Client/Session.hs index cccbffe..e1582ad 100644 --- a/webapi-session/src/WebApi/Client/Session.hs +++ b/webapi-session/src/WebApi/Client/Session.hs @@ -23,6 +23,7 @@ module WebApi.Client.Session , beginStep , setStepHeaders , getLastResponse + , getLastResponseBody , freshToken , freshTokens @@ -319,8 +320,8 @@ testClientWith :: forall meth r app. -> WebApiSession app (Response meth r) testClientWith extras creq = fst <$> testClientRawWith extras creq --- | 'testClientWith', answering the wire's status and headers as received --- beside the typed response. +-- | 'testClientWith', answering the wire's status, headers and body as +-- received beside the typed response. testClientRawWith :: forall meth r app. ( WebApi app , app ~ NamespaceOf r @@ -340,15 +341,15 @@ testClientRawWith :: forall meth r app. ) => [H.Header] -> ClientRequest meth r - -> WebApiSession app (Response meth r, (H.Status, [H.Header])) + -> WebApiSession app (Response meth r, (H.Status, [H.Header], LBS.ByteString)) testClientRawWith extras (MKClientRequest creq) = do waiReq0 <- liftIO $ toWaiRequest creq let waiReq = case extras of [] -> waiReq0 _ -> waiReq0 { requestHeaders = extras ++ requestHeaders waiReq0 } - sresp@SResponse {simpleStatus = status, simpleHeaders = hdrs} <- WebApiSession $ request waiReq + sresp@SResponse {simpleStatus = status, simpleHeaders = hdrs, simpleBody = body} <- WebApiSession $ request waiReq resp <- WebApiSession $ fromResponse sresp - pure (resp, (status, hdrs)) + pure (resp, (status, hdrs, body)) runWebApi :: forall app a. @@ -372,6 +373,11 @@ data ClientsState = ClientsState -- that reads a header the contract does not declare (an error id a -- failure names, say). 'Nothing' until a call answers, after a -- transport failure, and at 'beginStep' + , lastBody :: Maybe LBS.ByteString + -- ^ the body of that same response, as received — for a report of + -- what the step got back (a trace), which the typed value, decoded + -- and only 'Show'able, cannot stand for. 'Nothing' exactly when + -- 'lastResponse' is } @@ -391,8 +397,8 @@ initFreshSupply = FreshSupply { nonce = "", next = 0, current = mempty } -- | Start a step: the tokens made for the previous one are forgotten, -- and so are its headers and the answer it last saw. beginStep :: WebApiSessions apps () -beginStep = modify' $ \ClientsState {clientStates, freshSupply = FreshSupply {nonce, next}} -> - ClientsState {clientStates, freshSupply = FreshSupply {nonce, next, current = mempty}, stepHeaders = [], lastResponse = Nothing} +beginStep = modify' $ \st@ClientsState {freshSupply = FreshSupply {nonce, next}} -> + st {freshSupply = FreshSupply {nonce, next, current = mempty}, stepHeaders = [], lastResponse = Nothing, lastBody = Nothing} -- | Headers the step being run wants on its wire requests — set after -- 'beginStep', merged in front by both transports, gone at the next step. @@ -406,17 +412,22 @@ setStepHeaders hs = modify' $ \st -> st {stepHeaders = hs} getLastResponse :: WebApiSessions apps (Maybe (H.Status, [H.Header])) getLastResponse = gets $ \ClientsState {lastResponse} -> lastResponse +-- | The body of the wire's last answer, as received (see +-- 'getLastResponse'): what a report shows the step got back. +getLastResponseBody :: WebApiSessions apps (Maybe LBS.ByteString) +getLastResponseBody = gets $ \ClientsState {lastBody} -> lastBody + -- | The token for a label in the step being run: made once per step (the -- same label asks again and gets the same one), never twice in a run. freshToken :: Text -> WebApiSessions apps Text freshToken label = do - ClientsState {clientStates, freshSupply = FreshSupply {nonce, next, current}, stepHeaders, lastResponse} <- get + st@ClientsState {freshSupply = FreshSupply {nonce, next, current}} <- get case M.lookup label current of Just t -> pure t Nothing -> do let t = nonce <> "n" <> T.pack (show next) - put ClientsState {clientStates, freshSupply = FreshSupply {nonce, next = next + 1, current = M.insert label t current}, stepHeaders, lastResponse} + put st {freshSupply = FreshSupply {nonce, next = next + 1, current = M.insert label t current}} pure t @@ -459,7 +470,7 @@ initApps = Applications } initClientsState :: ClientsState -initClientsState = ClientsState { clientStates = mempty, freshSupply = initFreshSupply, stepHeaders = [], lastResponse = Nothing } +initClientsState = ClientsState { clientStates = mempty, freshSupply = initFreshSupply, stepHeaders = [], lastResponse = Nothing, lastBody = Nothing } newtype WebApiSessions (apps :: [Type]) a = WebApiSessions (ReaderT Applications (StateT ClientsState IO) a) @@ -500,8 +511,8 @@ testClients creq = do case M.lookup appRep css of Nothing -> error $ "Panic: app not found for: " <> show appRep Just cstate -> do - ((a, raw), s) <- liftIO $ runStateT (runReaderT (runWebApiSession $ testClientRawWith extras creq) app) cstate - modify' $ \st@ClientsState {clientStates = css'} -> st {clientStates = M.insert appRep s css', lastResponse = Just raw} + ((a, (status, hdrs, body)), s) <- liftIO $ runStateT (runReaderT (runWebApiSession $ testClientRawWith extras creq) app) cstate + modify' $ \st@ClientsState {clientStates = css'} -> st {clientStates = M.insert appRep s css', lastResponse = Just (status, hdrs), lastBody = Just body} pure a Nothing -> case M.lookup appRep external of @@ -509,7 +520,11 @@ testClients creq = do ClientsState {clientStates = css, stepHeaders = extras} <- get let cstate = M.findWithDefault WaiInt.initState appRep css (a, raw, s) <- liftIO $ externalClient extras ext cstate (fromClientRequest creq) - modify' $ \st@ClientsState {clientStates = css'} -> st {clientStates = M.insert appRep s css', lastResponse = raw} + modify' $ \st@ClientsState {clientStates = css'} -> st + { clientStates = M.insert appRep s css' + , lastResponse = (\(status, hdrs, _) -> (status, hdrs)) <$> raw + , lastBody = (\(_, _, body) -> body) <$> raw + } pure a Nothing -> error $ "Panic: app not found for: " <> show appRep @@ -518,8 +533,8 @@ testClients creq = do -- following (the model asserts on 3xx + Location, exactly as wai-test does), -- cookies out merged back into the jar. Transport failures surface as -- 'OtherError' rather than exceptions so the model can judge them. The --- raw status and headers come back beside the typed response (none after --- a transport failure). +-- raw status, headers and body come back beside the typed response (none +-- after a transport failure). externalClient :: forall meth r. ( ToParam 'PathParam (PathParam meth r) @@ -535,7 +550,7 @@ externalClient :: forall meth r. , ToHListRecTuple (StripContents (RequestBody meth r)) , MkPathFormatString r , SingMethod meth - ) => [H.Header] -> ExternalApp -> WaiInt.ClientState -> Request meth r -> IO (Response meth r, Maybe (H.Status, [H.Header]), WaiInt.ClientState) + ) => [H.Header] -> ExternalApp -> WaiInt.ClientState -> Request meth r -> IO (Response meth r, Maybe (H.Status, [H.Header], LBS.ByteString), WaiInt.ClientState) externalClient extras ExternalApp {baseRequest, manager} cstate req = do now <- getCurrentTime @@ -577,7 +592,7 @@ externalClient extras ExternalApp {baseRequest, manager} cstate req = do (HC.responseHeaders hresp) (M.toList $ fmap renderSetCookieBS cooks) (HC.responseBody hresp) - pure (resp, Just (HC.responseStatus hresp, HC.responseHeaders hresp), cstate') + pure (resp, Just (HC.responseStatus hresp, HC.responseHeaders hresp, HC.responseBody hresp), cstate') -- | A stored 'SetCookie' as an http-client cookie for @host@. A cookie without @@ -637,10 +652,10 @@ addApp waapp WebApiSessionsConfig {applications, clientsState} = app = getWaiApp waapp appRep = typeRep (Proxy @app) Applications {native, external} = applications - ClientsState {clientStates = cstate, freshSupply, stepHeaders, lastResponse} = clientsState + ClientsState {clientStates = cstate} = clientsState in WebApiSessionsConfig { applications = Applications { native = M.insert appRep app native, external} - , clientsState = ClientsState { clientStates = M.insert appRep WaiInt.initState cstate, freshSupply, stepHeaders, lastResponse } + , clientsState = clientsState { clientStates = M.insert appRep WaiInt.initState cstate } } -- | Register an app reached over HTTP. @base@ is the parsed base request — @@ -651,10 +666,10 @@ addExternalApp base mgr WebApiSessionsConfig {applications, clientsState} = let appRep = typeRep (Proxy @app) Applications {native, external} = applications - ClientsState {clientStates = cstate, freshSupply, stepHeaders, lastResponse} = clientsState + ClientsState {clientStates = cstate} = clientsState in WebApiSessionsConfig { applications = Applications { native, external = M.insert appRep (ExternalApp base mgr) external } - , clientsState = ClientsState { clientStates = M.insert appRep WaiInt.initState cstate, freshSupply, stepHeaders, lastResponse } + , clientsState = clientsState { clientStates = M.insert appRep WaiInt.initState cstate } } -- | Run the sessions; each run gets its own nonce for fresh tokens. @@ -665,8 +680,8 @@ runWebApis' :: WebApiSessionsConfig apps -> WebApiSessions apps a -> IO (a, WebA runWebApis' WebApiSessionsConfig {applications, clientsState} (WebApiSessions sess) = do n <- newNonce let - ClientsState {clientStates, freshSupply = FreshSupply {next, current}, stepHeaders, lastResponse} = clientsState - st0 = ClientsState {clientStates, freshSupply = FreshSupply {nonce = n, next, current}, stepHeaders, lastResponse} + ClientsState {freshSupply = FreshSupply {next, current}} = clientsState + st0 = clientsState {freshSupply = FreshSupply {nonce = n, next, current}} (a, clientsStateNew) <- runStateT (runReaderT sess applications) st0 pure (a, WebApiSessionsConfig {applications, clientsState = clientsStateNew}) diff --git a/webapi-session/webapi-session.cabal b/webapi-session/webapi-session.cabal index 393602e..e6a9b48 100644 --- a/webapi-session/webapi-session.cabal +++ b/webapi-session/webapi-session.cabal @@ -1,6 +1,6 @@ cabal-version: 3.0 name: webapi-session -version: 0.1.0.0 +version: 0.1.1.0 synopsis: The concrete session client over webapi contracts -- Moved out of webapi-test (M8a): multi-app routing, wai + http-client -- transports, cookie jars, fresh values. Test-named packages never diff --git a/webapi-test/CHANGELOG.md b/webapi-test/CHANGELOG.md index cc71d70..92cb083 100644 --- a/webapi-test/CHANGELOG.md +++ b/webapi-test/CHANGELOG.md @@ -1,5 +1,33 @@ # Revision history for webapi-test +## 0.2.0.0 -- 2026-11-15 (zenbridge #2712: a run's trace) + +* **A run's trace, as data** (`Test.WebApi.Trace`, qc-dynamic). A + `Recorder` keeps one record per step a case played: the request as sent + (fresh values filled, credentials masked, the body clipped), the answer as + received (status, body, the step's value), every check by name with + whether it held, the labels that held, the model after the step (each + class with its values) and the stage before and after. For the run + (`RunTrace`): a line per generated case and per narrowing try (`taken` + when it still failed), the first failing case and the narrowed one in + full, and the label and move counts over the generated cases; JSON in + snake_case. `propDLTraced` records a property; the cases close through + QuickCheck's own callbacks (`PostTest` after every test, narrowing tries + included; `PostFinalFailure` on the narrowed case). `propDL` records + nothing, as before. +* **Checks by name.** A step's postcondition is a list of named checks + (`andCheck`; `andPostcondition` adds one named `postcondition`, + `ensuresRefinement`/`refutesRefinement` add `ensures `/`refutes `). + Every check runs and every failure is reported; it was the first only. +* **Labels** (`andClassify`): a step gives its case a label where a + predicate holds, through QuickCheck's `classify`; a label never fails. +* **Where a step was written** (`setStep`, `StepInfo`): a rule's trail, + summary and operation name, for the trace; it also sets the label. + `EffectCall` carries one (a new field, before the variables). +* **A model's stages**: `WebApiGlobalStateModel` gains `appStageOf` + (`noStage` for a model with none). +* `WebApiSessionsCxt` carries the recorder (`tracingCxt`). + ## 0.1.0.0 -- YYYY-mm-dd * First version. Released on an unsuspecting world. diff --git a/webapi-test/quickcheck-dynamic/Test/WebApi/DynamicLogic.hs b/webapi-test/quickcheck-dynamic/Test/WebApi/DynamicLogic.hs index cbab5a6..b3a04ca 100644 --- a/webapi-test/quickcheck-dynamic/Test/WebApi/DynamicLogic.hs +++ b/webapi-test/quickcheck-dynamic/Test/WebApi/DynamicLogic.hs @@ -1,5 +1,6 @@ module Test.WebApi.DynamicLogic ( propDL + , propDLTraced , prop_api -- , runWebApiTest -- , apiAction @@ -22,6 +23,7 @@ import Test.QuickCheck.Monadic import Test.QuickCheck.Monadic qualified as QC import Data.Reflection import Data.IORef +import Test.WebApi.Trace (Recorder, beginCase, recordedProperty) -- import Control.Monad.IO.Class import Control.Monad.Reader @@ -35,6 +37,19 @@ propDL :: forall c xstate apps e s. ) => 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', 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"). +propDLTraced :: forall c xstate apps e s. + ( DynLogicModel xstate + , RunModel xstate IO + , XActionError e ~ Error xstate IO + , Typeable e + , Show e + , 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 $ forAllDL d (propApiWith (Just rec) webapiRunner) + prop_api :: forall c xstate apps e s. ( DynLogicModel xstate , RunModel xstate IO @@ -46,10 +61,23 @@ prop_api :: forall c xstate apps e s. -> (forall a. WebApiSessions apps a -> IO a) -> Actions (ApiState s c xstate apps) -> Property -prop_api _newStRef webapiRunner s = - -- let - -- runner = - monadic (ioProperty . webapiRunner . flip runReaderT initWebApiSessionsCxt) $ do +prop_api _newStRef = propApiWith Nothing + +-- | The actions run, recorded when there is a recorder. +propApiWith :: forall c xstate apps e s. + ( DynLogicModel xstate + , RunModel xstate IO + , XActionError e ~ Error xstate IO + , Typeable e + , Show e + , Reifies s (WebApiGlobalStateModel c xstate apps) + ) => Maybe Recorder + -> (forall a. WebApiSessions apps a -> IO a) + -> Actions (ApiState s c xstate apps) + -> Property +propApiWith rec webapiRunner s = + monadic (ioProperty . webapiRunner . flip runReaderT (maybe initWebApiSessionsCxt tracingCxt rec)) $ do + mapM_ (QC.run . liftIO . beginCase) rec monitor $ counterexample "\nExecution\n" (_anonSt, _env) <- runActions s -- let diff --git a/webapi-test/quickcheck-dynamic/Test/WebApi/StateModel.hs b/webapi-test/quickcheck-dynamic/Test/WebApi/StateModel.hs index ff193d7..7037207 100644 --- a/webapi-test/quickcheck-dynamic/Test/WebApi/StateModel.hs +++ b/webapi-test/quickcheck-dynamic/Test/WebApi/StateModel.hs @@ -95,7 +95,12 @@ module Test.WebApi.StateModel , setPostcondition , setPostconditionOnFailure , setLabel + , setStep , andPostcondition + , andCheck + , andClassify + , tracingCxt + , noStage , addVariables , initApiState , initApiState_ @@ -149,7 +154,16 @@ import WebApi.Contract import WebApi.Param import WebApi.ContentTypes import WebApi.Util -import Control.Exception (SomeException) +import Control.Exception (SomeException, evaluate, try) +import Control.Applicative ((<|>)) +import Data.Either (isRight) +import Data.Foldable (forM_) +import qualified Data.Text.Encoding as TE +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 ) import Data.ByteString (ByteString) import Data.Text (Text) import Data.Kind @@ -334,6 +348,8 @@ data WebApiAction s (c :: Type) (xstate :: Type) (apps :: [Type]) (a :: Type) wh -- them. 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)) -> WebApiAction s c xstate apps res @@ -373,7 +389,7 @@ instance StateModel xstate => Show (WebApiAction s c xstate apps a) where ClearContext pc -> "Clear-Context: " ++ show (typeRep pc) ModelOnly n _ -> "Model: " ++ n FreshValue l -> "fresh " ++ T.unpack l - EffectCall n _ _ -> n + EffectCall n _ _ _ -> n XAction xact -> show xact -- TODO: Revisit @@ -400,8 +416,8 @@ instance Eq (Action xstate a) => Eq (WebApiAction s c xstate apps a) where (==) (FreshValue l1) = \case FreshValue l2 -> l1 == l2 _ -> False - (==) (EffectCall n1 _ _) = \case - EffectCall n2 _ _ -> n1 == n2 + (==) (EffectCall n1 _ _ _) = \case + EffectCall n2 _ _ _ -> n1 == n2 _ -> False (==) (XAction xact1) = \case XAction xact2 -> xact1 == xact2 @@ -416,7 +432,7 @@ instance StateModel xstate => HasVariables (WebApiAction s c xstate apps a) wher ClearContext {} -> mempty ModelOnly {} -> mempty FreshValue {} -> mempty - EffectCall _ vars _ -> vars + EffectCall _ _ vars _ -> vars XAction xact -> getAllVariables xact newtype RefinementId = RefinementId Text @@ -563,9 +579,15 @@ data SuccessApiModel s c xstate apps meth r a = SuccessApiModel , apiPrecondition :: Maybe (ApiState s c xstate apps -> Bool) , apiValidFailingAction :: Maybe (ApiState s c xstate apps -> Bool) , apiShrinkAction :: Maybe (VarContext -> ApiState s c xstate apps -> [Any (Action (ApiState s c xstate apps))]) - , apiPostcondition :: (ApiState s c xstate apps, ApiState s c xstate apps) -> LookUp -> ClientRequest meth r -> a -> Either Text () - -- ^ over the request as it went out and the result of the call; 'Left' - -- says why it does not hold (the counterexample carries it) + , apiChecks :: [(Text, StepCheck s c xstate apps meth r a ())] + -- ^ the step's checks, each by name ('andCheck'), over the request as + -- it went out and the result of the call. Every one runs; a 'Left' says + -- why it does not hold (the counterexample and the trace carry it) + , apiClassify :: [(Text, StepCheck s c xstate apps meth r a Bool)] + -- ^ the labels the step gives its case where their predicate holds, + -- over the same ('andClassify'); a label never fails the step + , apiStep :: Maybe StepInfo + -- ^ where the step was written ('setStep'), for the trace , apiPostconditionOnFailure :: (ApiState s c xstate apps, ApiState s c xstate apps) -> LookUp -> Either ErrorState a -> Bool , apiVariables :: Set.Set (Any Var) -- ^ variables the model's hooks look up besides the request's (a @@ -586,6 +608,11 @@ data SuccessApiModel s c xstate apps meth r a = SuccessApiModel -- asynchronously ('eventually') } +-- | A judgement over a step: the model before and after, the lookup, the +-- request as it went out and the step's value ('apiChecks', 'apiClassify'). +newtype StepCheck s c xstate apps meth r a b = StepCheck + ((ApiState s c xstate apps, ApiState s c xstate apps) -> LookUp -> ClientRequest meth r -> a -> Either Text b) + defSuccessApiModel :: SuccessApiModel s c xstate apps meth r a defSuccessApiModel = SuccessApiModel { apiNextState = Nothing @@ -593,7 +620,9 @@ defSuccessApiModel = SuccessApiModel , apiPrecondition = Nothing , apiValidFailingAction = Nothing , apiShrinkAction = Nothing - , apiPostcondition = \_ _ _ _ -> Right () + , apiChecks = [] + , apiClassify = [] + , apiStep = Nothing , apiPostconditionOnFailure = \_ _ _ -> True , label = Nothing , apiVariables = mempty @@ -628,16 +657,34 @@ setShrinkAction :: (VarContext -> ApiState s c xstate apps -> [Any (Action (ApiS setShrinkAction f SuccessApiModel {..} = SuccessApiModel {apiShrinkAction = Just f, ..} setPostcondition :: ((ApiState s c xstate apps, ApiState s c xstate apps) -> LookUp -> ClientRequest meth r -> a -> Either Text ()) -> SuccessApiModel s c xstate apps meth r a -> SuccessApiModel s c xstate apps meth r a -setPostcondition f SuccessApiModel {..} = SuccessApiModel {apiPostcondition = f, ..} +setPostcondition f SuccessApiModel {..} = SuccessApiModel {apiChecks = [("postcondition", StepCheck f)], ..} --- | Require another postcondition besides the model's own (the model's is --- checked first; the first failure is reported). +-- | Require another postcondition besides the model's own, named +-- @postcondition@ (see 'andCheck'). andPostcondition :: ((ApiState s c xstate apps, ApiState s c xstate apps) -> LookUp -> ClientRequest meth r -> a -> Either Text ()) -> SuccessApiModel s c xstate apps meth r a -> SuccessApiModel s c xstate apps meth r a -andPostcondition f SuccessApiModel {apiPostcondition, ..} = SuccessApiModel {apiPostcondition = \ss lkp req a -> apiPostcondition ss lkp req a >> f ss lkp req a, ..} +andPostcondition = andCheck "postcondition" + +-- | Require another check, by name, after the model's own. Every check +-- runs and every failure is reported; the trace lists each with whether +-- it held. +andCheck :: Text -> ((ApiState s c xstate apps, ApiState s c xstate apps) -> LookUp -> ClientRequest meth r -> a -> Either Text ()) -> SuccessApiModel s c xstate apps meth r a -> SuccessApiModel s c xstate apps meth r a +andCheck nm f SuccessApiModel {apiChecks, ..} = SuccessApiModel {apiChecks = apiChecks ++ [(nm, StepCheck f)], ..} + +-- | Give the step's case a label where the predicate holds (QuickCheck's +-- 'QC.classify'): a case carries it if any of its steps' predicates held. +-- A 'Left' (the predicate could not be judged) gives no label; a label +-- never fails the step. +andClassify :: Text -> ((ApiState s c xstate apps, ApiState s c xstate apps) -> LookUp -> ClientRequest meth r -> a -> Either Text Bool) -> SuccessApiModel s c xstate apps meth r a -> SuccessApiModel s c xstate apps meth r a +andClassify nm f SuccessApiModel {apiClassify, ..} = SuccessApiModel {apiClassify = apiClassify ++ [(nm, StepCheck f)], ..} setLabel :: Text -> SuccessApiModel s c xstate apps meth r a -> SuccessApiModel s c xstate apps meth r a setLabel l SuccessApiModel {..} = SuccessApiModel {label = Just l, ..} +-- | Where the step was written (a script's rule): the trace's trail and +-- summary, and the label the counterexample shows (@rule: summary@). +setStep :: StepInfo -> SuccessApiModel s c xstate apps meth r a -> SuccessApiModel s c xstate apps meth r a +setStep i SuccessApiModel {..} = SuccessApiModel {apiStep = Just i, label = Just (stepLabel i), ..} + -- | Declare variables the model's hooks look up (see 'apiVariables'). addVariables :: Set.Set (Any Var) -> SuccessApiModel s c xstate apps meth r a -> SuccessApiModel s c xstate apps meth r a addVariables vs SuccessApiModel {apiVariables, ..} = SuccessApiModel {apiVariables = apiVariables <> vs, ..} @@ -673,8 +720,15 @@ unWebApiAction (MkWebApiAction a) = a data WebApiGlobalStateModel c xstate apps = WebApiGlobalStateModel { appAribitaryAction :: forall (s :: Type). VarContext -> ApiState s c xstate apps -> QC.Gen (Any (Action (ApiState s c xstate apps))) , appInitState :: forall (s :: Type). ApiState s c xstate apps + , appStageOf :: forall (s :: Type). LookUp -> ApiState s c xstate apps -> Maybe Text + -- ^ the stage the model is at, as the trace shows it before and after + -- each step; 'noStage' for a model that declares none } +-- | A model with no stages: the trace's stage stays empty. +noStage :: LookUp -> ApiState s c xstate apps -> Maybe Text +noStage _ _ = Nothing + deriving newtype instance Eq (Action xstate a) => Eq (Action (ApiState s c xstate apps) a) instance ( Reifies s (WebApiGlobalStateModel c xstate apps) @@ -692,7 +746,7 @@ instance ( Reifies s (WebApiGlobalStateModel c xstate apps) MkWebApiAction a@(ClearContext {}) -> show a MkWebApiAction a@(ModelOnly {}) -> show a MkWebApiAction (FreshValue {}) -> "fresh" - MkWebApiAction (EffectCall n _ _) -> n + MkWebApiAction (EffectCall n _ _ _) -> n MkWebApiAction (XAction xact) -> actionName xact arbitraryAction varCxt s = case reflect (Proxy @s) of @@ -803,14 +857,20 @@ data ResultError = MkResultError -- ModifyClientCookies moved to WebApi.Client.Session (M8a). data WebApiSessionsCxt = WebApiSessionsCxt - { -- defaultClientsState :: ClientsState + { traceRecorder :: Maybe Recorder + -- ^ where the steps are recorded as they run ('tracingCxt'); none: + -- nothing is recorded } initWebApiSessionsCxt :: WebApiSessionsCxt initWebApiSessionsCxt = WebApiSessionsCxt - { + { traceRecorder = Nothing } +-- | The steps recorded into the recorder as they run. +tracingCxt :: Recorder -> WebApiSessionsCxt +tracingCxt rec = WebApiSessionsCxt {traceRecorder = Just rec} + instance ( Reifies s (WebApiGlobalStateModel c xstate apps) , RunModel xstate IO , Typeable e @@ -820,99 +880,140 @@ instance ( Reifies s (WebApiGlobalStateModel c xstate apps) , StateModel xstate ) => RunModel (ApiState s c xstate apps) (ReaderT WebApiSessionsCxt (WebApiSessions apps)) where type Error (ApiState s c xstate apps) (ReaderT WebApiSessionsCxt (WebApiSessions apps)) = ErrorState - perform (ApiState {xActionState}) act lkp = case act of - MkWebApiAction (SuccessCall creq' SuccessApiModel {apiRetry} cookModMay f) -> ReaderT $ \_ -> do - sup <- stepSuppliers lkp creq' - case resolveRequest sup lkp creq' of - Right creq -> do - let - once = testClients creq >>= \case - Success code out headerOut cookieOut -> do - let apiSucc = ApiSuccess {code, out, headerOut, cookieOut, sent = creq} - case cookModMay of - Nothing -> pure () - Just cookMod -> case cookMod apiSucc of - modCk@(SetClientCookies setcooks) -> mapM_ (setClientCookie modCk) setcooks - modCk@(ModifyClientCookies modcooks) -> modifyClientCookies modCk modcooks - modCk@(DeleteClientCookies delcooks) -> mapM_ (deleteClientCookie modCk) delcooks - pure $ either (Left . ResultError) Right $ f apiSucc + -- 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} -> + 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 + sup <- stepSuppliers lkp creq' + case resolveRequest sup lkp creq' of + Right creq -> do + let + once = testClients creq >>= \case + Success code out headerOut cookieOut -> do + let apiSucc = ApiSuccess {code, out, headerOut, cookieOut, sent = creq} + case cookModMay of + Nothing -> pure () + Just cookMod -> case cookMod apiSucc of + modCk@(SetClientCookies setcooks) -> mapM_ (setClientCookie modCk) setcooks + modCk@(ModifyClientCookies modcooks) -> modifyClientCookies modCk modcooks + modCk@(DeleteClientCookies delcooks) -> mapM_ (deleteClientCookie modCk) delcooks + pure $ either (Left . ResultError) Right $ f apiSucc + Failure (Right oerr) -> pure $ Left UnExpectedApiCrash + { status = H.status500 -- TODO: Fix this + , headerOut = [] -- TODO: Fix this + , someError = oerr + } + Failure (Left (ApiError code _err hd _)) -> pure $ Left UnExpectedApiError + { status = code + , headerOut = maybe [] toHeader hd + } + -- what the platform does asynchronously shows up eventually + attempt n = once >>= \case + Left _ | n > 1 -> liftIO (threadDelay (1000 * maybe 0 snd apiRetry)) >> attempt (n - 1) + r -> pure r + attempt (maybe 1 fst apiRetry) + Left field -> pure $ Left (InputNotSetError field) + MkWebApiAction (ErrorCall creq' expected _model f) -> ReaderT $ \_ -> do + sup <- stepSuppliers lkp creq' + case resolveRequest sup lkp creq' of + Right creq -> testClients creq >>= \case + Failure (Left apiErr@(ApiError code _err hd _)) + | matchesFailure expected code -> pure $ either (Left . ResultError) Right $ f apiErr + | otherwise -> pure $ Left UnexpectedStatus + { expected + , status = code + , headerOut = maybe [] toHeader hd + } Failure (Right oerr) -> pure $ Left UnExpectedApiCrash { status = H.status500 -- TODO: Fix this , headerOut = [] -- TODO: Fix this , someError = oerr } - Failure (Left (ApiError code _err hd _)) -> pure $ Left UnExpectedApiError - { status = code - , headerOut = maybe [] toHeader hd - } - -- what the platform does asynchronously shows up eventually - attempt n = once >>= \case - Left _ | n > 1 -> liftIO (threadDelay (1000 * maybe 0 snd apiRetry)) >> attempt (n - 1) - r -> pure r - attempt (maybe 1 fst apiRetry) - Left field -> pure $ Left (InputNotSetError field) - MkWebApiAction (ErrorCall creq' expected _model f) -> ReaderT $ \_ -> do - sup <- stepSuppliers lkp creq' - case resolveRequest sup lkp creq' of - Right creq -> testClients creq >>= \case - Failure (Left apiErr@(ApiError code _err hd _)) - | matchesFailure expected code -> pure $ either (Left . ResultError) Right $ f apiErr - | otherwise -> pure $ Left UnexpectedStatus - { expected - , status = code - , headerOut = maybe [] toHeader hd - } - Failure (Right oerr) -> pure $ Left UnExpectedApiCrash - { status = H.status500 -- TODO: Fix this - , headerOut = [] -- TODO: Fix this - , someError = oerr - } - Success code _out headerOut _cookieOut -> pure $ Left $ UnExpectedApiSuccess - { status = code - , headerOut = toHeader headerOut - } - Left field -> pure $ Left (InputNotSetError field) - MkWebApiAction (SomeExceptionCall creq) -> ReaderT $ \_ -> do - testClients creq >>= \case - Failure (Right (OtherError e)) -> pure $ Right e - Failure (Left (ApiError code _err hd _)) -> pure $ Left UnExpectedApiError - { status = code - , headerOut = maybe [] toHeader hd - } - Success code _out headerOut _cookieOut -> pure $ Left $ UnExpectedApiSuccess - { status = code - , headerOut = toHeader headerOut - } - 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) - MkWebApiAction (EffectCall _ _ eff) -> ReaderT $ \_ -> - either (Left . ResultError . MkResultError) Right <$> liftIO (eff lkp) - MkWebApiAction (XAction xact) -> ReaderT $ \_ -> do - res <- liftIO $ perform xActionState xact lkp - pure $ first (XActionError . AnyXActionError) res - - postcondition ss (MkWebApiAction act) lkp res = case act of - SuccessCall creq model _ _ -> check creq model res - ErrorCall creq _ model _ -> check creq model res - _ -> pure True + Success code _out headerOut _cookieOut -> pure $ Left $ UnExpectedApiSuccess + { status = code + , headerOut = toHeader headerOut + } + Left field -> pure $ Left (InputNotSetError field) + MkWebApiAction (SomeExceptionCall creq) -> ReaderT $ \_ -> do + testClients creq >>= \case + Failure (Right (OtherError e)) -> pure $ Right e + Failure (Left (ApiError code _err hd _)) -> pure $ Left UnExpectedApiError + { status = code + , headerOut = maybe [] toHeader hd + } + Success code _out headerOut _cookieOut -> pure $ Left $ UnExpectedApiSuccess + { status = code + , headerOut = toHeader headerOut + } + 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) + MkWebApiAction (EffectCall _ _ _ eff) -> ReaderT $ \_ -> + either (Left . ResultError . MkResultError) Right <$> liftIO (eff lkp) + MkWebApiAction (XAction xact) -> ReaderT $ \_ -> do + res <- liftIO $ perform xActionState xact lkp + pure $ first (XActionError . AnyXActionError) res + + 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)) + _ -> pure (True, [], [], SomeLookUp lkp) + rec <- lift (asks (\WebApiSessionsCxt {traceRecorder} -> traceRecorder)) + forM_ rec $ \r -> lift $ liftIO $ do + m <- renderModel lkp' after + stageAfter <- stageOfGuarded lkp' after + amendStep r (afterStep cs ls m stageAfter held) + pure held where - -- the request as it went out: the step's fresh tokens are still those - check :: forall meth r x. SingMethod meth => ClientRequestVal meth r -> SuccessApiModel s c xstate apps meth r x -> x -> PostconditionM (ReaderT WebApiSessionsCxt (WebApiSessions apps)) Bool - check creq SuccessApiModel {apiPostcondition} x = do + -- 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 + -- model after the step is read with this step's own value bound + -- (quickcheck-dynamic hands a postcondition the lookup from before it) + withChecks :: forall meth r x. (SingMethod meth, Typeable x) => ClientRequestVal meth r -> SuccessApiModel s c xstate apps meth r x -> x -> PostconditionM (ReaderT WebApiSessionsCxt (WebApiSessions apps)) (Bool, [CheckRecord], [Text], SomeLookUp) + withChecks creq SuccessApiModel {apiChecks, apiClassify} x = do toks <- lift (lift freshTokens) -- the files were written for the call; the view names them - case resolveRequest placeholders {freshOf = freshLookup toks} lkp creq >>= \req -> apiPostcondition ss lkp req x of - Right () -> pure True + case resolveRequest placeholders {freshOf = freshLookup toks} lkp creq of Left why -> do counterexamplePost (" postcondition failed: " ++ T.unpack why) - pure False - - postconditionOnFailure ss (MkWebApiAction act) lkp res = pure $ case act of - SuccessCall _ SuccessApiModel {apiPostconditionOnFailure} _ _ -> apiPostconditionOnFailure ss lkp res - ErrorCall _ _ SuccessApiModel {apiPostconditionOnFailure} _ -> apiPostconditionOnFailure ss lkp res - _ -> True + pure (False, [CheckRecord {check = "request", held = False, why = Just why}], [], SomeLookUp (extendLookUp lkp x)) + Right req -> do + let + results = [ (nm, f ss lkp req x) | (nm, StepCheck f) <- apiChecks ] + heldLabels = [ l | (l, StepCheck p) <- apiClassify, Right True <- [p ss lkp req x] ] + forM_ [ why | (_, Left why) <- results ] $ \why -> + counterexamplePost (" postcondition failed: " ++ T.unpack why) + 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 ] + , heldLabels + , SomeLookUp (extendLookUp lkp x) + ) + + postconditionOnFailure ss@(_, after) (MkWebApiAction act) lkp res = do + rec <- lift (asks (\WebApiSessionsCxt {traceRecorder} -> traceRecorder)) + forM_ rec $ \r -> lift $ liftIO $ do + m <- renderModel lkp after + stageAfter <- stageOfGuarded lkp after + amendStep r (afterStep [] [] m stageAfter held) + pure held + where + held = case act of + SuccessCall _ SuccessApiModel {apiPostconditionOnFailure} _ _ -> apiPostconditionOnFailure ss lkp res + ErrorCall _ _ SuccessApiModel {apiPostconditionOnFailure} _ -> apiPostconditionOnFailure ss lkp res + _ -> True monitoring _ (MkWebApiAction act) lkp res = QC.counterexample $ case act of SuccessCall creq _ _ _ -> stepReport (show act) (requestReport lkp creq) (outcome res) @@ -967,6 +1068,199 @@ requestReport lkp creq = case resolveRequest placeholders lkp creq of (pre, []) -> pre (pre, _) -> pre ++ "…" +-- --------------------------------------------------------------------------- +-- The trace's records ("Test.WebApi.Trace"): what a step that ran is +-- recorded as. Rendering never fails a step: a value that cannot be shown +-- yet reads as a placeholder. + +-- | How much of a body, and of a value, a record keeps. +bodyClip, valueClip :: Int +bodyClip = 32768 +valueClip = 4000 + +-- | The step that just ran, recorded: the request and the answer while +-- the session still holds them, the stage before it. +recordPerformed :: forall s c xstate apps a. (Reifies s (WebApiGlobalStateModel c xstate apps), StateModel xstate) + => Recorder -> ApiState s c xstate apps -> Action (ApiState s c xstate apps) a -> LookUp -> Either ErrorState a -> WebApiSessions apps () +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 + , answer = Just AnswerRecord + { httpStatus = Nothing + , body = Nothing + , value = either (const Nothing) shown res + , failure = either (Just . shownText) (const Nothing) res + } + , checks = [], labels = [], model = Nothing + , stage = StageRecord {before = stageBefore, after = Nothing} + , ok = isRight res + } + record <- case act of + SuccessCall creq SuccessApiModel {apiStep} _ _ -> callRecord lkp creq apiStep GoesThrough res stageBefore + ErrorCall creq expected SuccessApiModel {apiStep} _ -> callRecord lkp creq apiStep (Refused (expectedStatus expected)) res stageBefore + SomeExceptionCall creq -> do + raw <- getLastResponse + bodyMay <- getLastResponseBody + 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 + , 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} + , ok = isRight res + } + SetContext c -> pure (engineStep KindContext "setContext" Nothing (const (Just (shownText c)))) + ClearContext {} -> pure (engineStep KindContext "clearContext" Nothing (const Nothing)) + ModelOnly nm _ -> pure (engineStep KindModel (T.pack nm) Nothing (const Nothing)) + 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)) + liftIO (pushStep rec record) + where + expectedStatus = \case + AnyFailure -> Nothing + FailureStatus code -> Just code + +-- | 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 +-- check that its status was the one expected. +callRecord :: forall meth app r res apps. (WebApiActionCxt apps meth app r, Show res) + => LookUp -> ClientRequestVal meth (app :// r) -> Maybe StepInfo -> Expectation -> Either ErrorState res -> Maybe Text -> WebApiSessions apps StepRecord +callRecord lkp creq i expectation res stageBefore = do + toks <- freshTokens + raw <- getLastResponse + bodyMay <- getLastResponseBody + let + (req, meth) = case resolveRequest placeholders {freshOf = freshLookup toks} lkp creq of + Left fld -> (RequestUnset fld, Nothing) + Right resolved -> second Just (requestRecordOf resolved) + pure StepRecord + { n = 0 + , kind = KindCall + , info = i + , operation = T.pack (getOpIdFromRequest creq) + , method = meth + , expect = Just expectation + , request = Just req + , answer = Just AnswerRecord + { httpStatus = (H.statusCode . fst <$> raw) <|> either errorStatus (const Nothing) res + , body = bodyMay >>= bodyText bodyClip + , value = either (const Nothing) (Just . shownText) res + , failure = either (Just . shownText) (const Nothing) res + } + , checks = callChecks expectation res + , labels = [] + , model = Nothing + , stage = StageRecord {before = stageBefore, after = Nothing} + , ok = isRight res + } + where + errorStatus = \case + UnExpectedApiError {status} -> Just (H.statusCode status) + UnExpectedApiSuccess {status} -> Just (H.statusCode status) + UnexpectedStatus {status} -> Just (H.statusCode status) + _ -> Nothing + +-- | The checks a call's answer itself makes: its status was the expected +-- one, and the model could read it. +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)}] + where + statusHeld = CheckRecord {check = "status", held = True, why = Nothing} + code st = T.pack (show (H.statusCode st)) + expected = case expectation of + GoesThrough -> "it to go through" + Refused Nothing -> "a refusal" + Refused (Just c) -> "a refusal with " <> T.pack (show c) + statusWhy = \case + UnExpectedApiError {status} -> "answered " <> code status <> ", expected " <> expected + UnExpectedApiSuccess {status} -> "answered " <> code status <> ", expected " <> expected + UnexpectedStatus {status} -> "answered " <> code status <> ", expected " <> expected + UnExpectedApiCrash {someError} -> "no answer: " <> T.pack (show someError) + other -> T.pack (show other) + +-- | The request as the client sends it (method, path, query, headers, +-- form, files, body), credentials masked; and its method. +requestRecordOf :: forall meth r. + ( ToParam 'PathParam (PathParam meth r) + , ToParam 'QueryParam (QueryParam meth r) + , ToParam 'FormParam (FormParam meth r) + , ToParam 'FileParam (FileParam meth r) + , ToHeader (HeaderIn meth r) + , PartEncodings (RequestBody meth r) + , ToHListRecTuple (StripContents (RequestBody meth r)) + , MkPathFormatString r + , SingMethod meth + ) => ClientRequest meth r -> (RequestRecord, Text) +requestRecordOf resolved = + let + RequestParts {uriPath, meth, qitms, hdrs, formPar, filePar, bodyPart} = requestParts BC.empty [] (fromClientRequest resolved) + in + ( RequestSent + { line = utf8 meth <> " " <> utf8 uriPath <> utf8 (H.renderQuery True qitms) + , headers = [ (utf8 (CI.original k), maskedText (CI.original k) v) | (k, v) <- hdrs, k /= H.hAccept ] + , form = [ (utf8 k, maskedText k v) | (k, v) <- formPar ] + , files = [ FileRecord {field = utf8 k, fileName = utf8 fileName, contentType = utf8 fileContentType} + | (k, FileInfo {fileName, fileContentType}) <- filePar ] + , body = bodyPart >>= bodyText bodyClip . snd + , bodyType = utf8 . fst <$> bodyPart + } + , utf8 meth + ) + where + utf8 = TE.decodeUtf8With TE.lenientDecode + -- credentials do not belong in a test report + maskedText k v + | any (`T.isInfixOf` T.toLower (utf8 k)) ["password", "authorization", "cookie", "token"] = "" + | otherwise = utf8 v + +-- | A value as a record shows it. +shownText :: Show x => x -> Text +shownText = clipText valueClip . T.pack . show + +-- | The model's entities, each class with its values, as far as the +-- lookup can resolve them. +renderModel :: LookUp -> ApiState s c xstate apps -> IO (M.Map Text [Text]) +renderModel lkp ApiState {namedEntityTyped = NamedEntityTyped NamedEntity {namedEntity}} = do + rows <- forM (concat (M.elems namedEntity)) $ \(Some NamedVal {name = RefinementId nm, val}) -> do + shown <- try (evaluate (forced (either (\why -> "<" <> why <> ">") shownText (resolveVal lkp val)))) + pure (nm, [either (\(_ :: SomeException) -> "") id shown]) + pure (M.fromListWith (flip (++)) rows) + where + forced t = T.length t `seq` t + +-- | The model's stage by its hook; a hook that fails reads as none. +stageOfGuarded :: forall s c xstate apps. Reifies s (WebApiGlobalStateModel c xstate apps) => LookUp -> ApiState s c xstate apps -> IO (Maybe Text) +stageOfGuarded lkp st = case reflect (Proxy @s) of + WebApiGlobalStateModel {appStageOf} -> do + r <- try (evaluate (forced (appStageOf lkp st))) + pure (either (\(_ :: SomeException) -> Nothing) id r) + where + forced = \case + Nothing -> Nothing + Just t -> T.length t `seq` Just t + +-- | A lookup, carried where a polymorphic one cannot go (a tuple). +newtype SomeLookUp = SomeLookUp LookUp + +-- | The lookup with the step's own value bound: quickcheck-dynamic hands a +-- postcondition the lookup from before the step, in which only the step's +-- own variable is unbound — so a variable the lookup does not know, at the +-- value's type, is the step's. +extendLookUp :: forall x. Typeable x => LookUp -> x -> LookUp +extendLookUp lkp x v = unsafePerformIO $ do + r <- try (evaluate (lkp v)) + case r of + Right y -> pure y + Left (_ :: SomeException) -> maybe (evaluate (lkp v)) pure (cast x) + instance ( Reifies s (WebApiGlobalStateModel c xstate apps) , DynLogicModel xstate ) => DynLogicModel (ApiState s c xstate apps) where @@ -1011,14 +1305,16 @@ expectingFailure :: Eq (Action xstate ()) => -> Action (ApiState s c xstate apps) a -> Maybe (Action (ApiState s c xstate apps) ()) expectingFailure expected pre (MkWebApiAction act) = case act of - SuccessCall creq SuccessApiModel {apiFailureNextState, label, apiVariables} _ _ -> Just $ mkWebApiAction $ ErrorCall creq expected + SuccessCall creq SuccessApiModel {apiFailureNextState, label, apiVariables, apiStep} _ _ -> Just $ mkWebApiAction $ ErrorCall creq expected SuccessApiModel { apiNextState = (\ns _ st -> ns st) <$> apiFailureNextState , apiFailureNextState , apiPrecondition = Just pre , apiValidFailingAction = Nothing , apiShrinkAction = Nothing - , apiPostcondition = \_ _ _ _ -> Right () + , apiChecks = [] + , apiClassify = [] + , apiStep , apiPostconditionOnFailure = \_ _ _ -> True , label , apiVariables @@ -1170,14 +1466,14 @@ ensuresRefinement r = noteEnsured . foldr ((.) . check) id (chain r) where chain x@Refinement {refines} = x : concatMap chain refines check Refinement {refinementName = RefinementId n, holds} = - andPostcondition (\_ lkp req x -> either (\why -> Left ("refinement " <> n <> ": " <> why)) Right (holds lkp req x)) + andCheck ("ensures " <> n) (\_ lkp req x -> either (\why -> Left ("refinement " <> n <> ": " <> why)) Right (holds lkp req x)) noteEnsured SuccessApiModel {apiEnsures, ..} = SuccessApiModel {apiEnsures = apiEnsures <> Set.fromList (refinementNames r), ..} -- | Check the step's value is *not* in the refinement: outside a class -- means its predicate fails or one of its bases' does (the class is their -- conjunction). Refuting never makes a class drawable. refutesRefinement :: forall meth r a s c xstate apps. Refinement meth r a -> SuccessApiModel s c xstate apps meth r a -> SuccessApiModel s c xstate apps meth r a -refutesRefinement r@Refinement {refinementName = rid@(RefinementId n)} = noteRefuted . andPostcondition (\_ lkp req x -> check lkp req x) +refutesRefinement r@Refinement {refinementName = rid@(RefinementId n)} = noteRefuted . andCheck ("refutes " <> n) (\_ lkp req x -> check lkp req x) where check :: LookUp -> ClientRequest meth r -> a -> Either Text () check lkp req x = case [ () | Refinement {holds} <- chain r, Left _ <- [holds lkp req x] ] of diff --git a/webapi-test/quickcheck-dynamic/Test/WebApi/Trace.hs b/webapi-test/quickcheck-dynamic/Test/WebApi/Trace.hs new file mode 100644 index 0000000..783993f --- /dev/null +++ b/webapi-test/quickcheck-dynamic/Test/WebApi/Trace.hs @@ -0,0 +1,533 @@ +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE RecordWildCards #-} +-- | A run's trace (zenbridge #2712): what each case played, step by step, +-- as data rather than as QuickCheck's counterexample text. +-- +-- * One 'StepRecord' per step a case played: the request as sent, the +-- answer as received, every check by name with whether it held, the +-- labels that held, the model after the step, and the stage before and +-- after it (a model's own hook; none by default). +-- * For the run ('RunTrace'): one summary per generated case and per +-- narrowing try, the first failing case and the narrowed one in full, +-- and the label and move counts over the generated cases. +-- +-- The records are plain text and numbers: the engine renders what it can +-- show and names no model. A 'Recorder' is one property's sink. The state +-- model's @perform@ and @postcondition@ write the case being played into +-- it ("Test.WebApi.StateModel"), and the property's QuickCheck callbacks +-- close each case ('recordedProperty'): 'P.PostTest' fires after every +-- test, a generated case and each narrowing try alike, and +-- 'P.PostFinalFailure' once, on the narrowed case. So the phases are told +-- apart without reading any text. +module Test.WebApi.Trace + ( -- * The records + StepInfo (..) + , stepLabel + , StepKind (..) + , Expectation (..) + , RequestRecord (..) + , FileRecord (..) + , AnswerRecord (..) + , CheckRecord (..) + , StageRecord (..) + , StepRecord (..) + , CaseOutcome (..) + , CaseSummary (..) + , TrySummary (..) + , CaseTrace (..) + , LabelCount (..) + , MoveCount (..) + , RunTrace (..) + -- * Recording + , Recorder + , newRecorder + , recordedProperty + , readRunTrace + , beginCase + , pushStep + , amendStep + , afterStep + -- * Rendering helpers + , clipText + , bodyText + ) where + +import Control.Applicative ((<|>)) +import Data.Aeson (ToJSON (..), Value (..), object, (.=)) +import qualified Data.Aeson.Key as K +import qualified Data.ByteString.Lazy as LBS +import Data.Foldable (toList) +import Data.IORef +import Data.List (find) +import qualified Data.Map.Strict as M +import Data.Sequence (Seq, (|>)) +import qualified Data.Sequence as Seq +import qualified Data.Set as Set +import Data.Text (Text) +import qualified Data.Text as T +import qualified Data.Text.Encoding as TE +import Test.QuickCheck (Property) +import qualified Test.QuickCheck.Property as P + +-- --------------------------------------------------------------------------- +-- The records + +-- | Where a step was written, when a layer above the engine knows (a +-- script's rule): the rule's trail, its summary, and the name the layer +-- knows the step's operation by (the engine knows only the operation id). +data StepInfo = StepInfo + { trail :: [Text] + , summary :: Text + , name :: Maybe Text + } + deriving (Eq, Show) + +-- | The step's label as the counterexample text shows it: @rule: summary@. +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 + deriving (Eq, Show) + +kindText :: StepKind -> Text +kindText = \case + KindCall -> "call" + KindGlue -> "glue" + KindFresh -> "fresh" + KindContext -> "context" + KindModel -> "model" + KindOther -> "other" + +isMove :: StepKind -> Bool +isMove k = k == KindCall || k == KindGlue + +-- | What a call expects of its answer. +data Expectation + = GoesThrough + | Refused (Maybe Int) + -- ^ refused with this status (any error status: 'Nothing') + deriving (Eq, Show) + +data FileRecord = FileRecord + { field :: Text + , fileName :: Text + , contentType :: Text + } + deriving (Eq, Show) + +-- | The request as it went out: its fresh values filled in, credentials +-- masked, the body clipped. Or the field nobody supplied, when it never +-- went out. +data RequestRecord + = RequestSent + { line :: Text + , headers :: [(Text, Text)] + , form :: [(Text, Text)] + , files :: [FileRecord] + , body :: Maybe Text + , bodyType :: Maybe Text + } + | RequestUnset Text + deriving (Eq, Show) + +-- | What came back: the status and the body as received (a call), the +-- step's value as the engine shows it, or why there was none. +data AnswerRecord = AnswerRecord + { httpStatus :: Maybe Int + , body :: Maybe Text + , value :: Maybe Text + , failure :: Maybe Text + } + deriving (Eq, Show) + +data CheckRecord = CheckRecord + { check :: Text + , held :: Bool + , why :: Maybe Text + } + deriving (Eq, Show) + +data StageRecord = StageRecord + { before :: Maybe Text + , after :: Maybe Text + } + deriving (Eq, Show) + +data StepRecord = StepRecord + { n :: Int + -- ^ the step's position in its case, from 1 + , kind :: StepKind + , info :: Maybe StepInfo + , operation :: Text + -- ^ the operation id (a call), the transform (a glue step), or what the + -- engine step is + , method :: Maybe Text + , expect :: Maybe Expectation + , request :: Maybe RequestRecord + , answer :: Maybe AnswerRecord + , checks :: [CheckRecord] + , labels :: [Text] + -- ^ the labels that held at this step + , model :: Maybe (M.Map Text [Text]) + -- ^ the model after the step: each class with its values; 'Nothing' + -- when the step failed (no next state is computed then) + , stage :: StageRecord + , ok :: Bool + } + deriving (Eq, Show) + +-- | The name a summary lists a move by: its rule, else its operation. +moveName :: StepRecord -> Text +moveName StepRecord {info, operation} = case info of + Just StepInfo {trail = t@(_ : _)} -> T.intercalate "." t + _ -> operation + +-- | The name the move counts go by: the operation's name where the layer +-- above knows one, else the operation id. +moveCountKey :: StepRecord -> Text +moveCountKey StepRecord {info, operation} = case info of + Just StepInfo {name = Just nm} -> nm + _ -> operation + +data CaseOutcome = Passed | Failed | Discarded + deriving (Eq, Show) + +outcomeText :: CaseOutcome -> Text +outcomeText = \case + Passed -> "passed" + Failed -> "failed" + Discarded -> "discarded" + +-- | One generated case, in a line. +data CaseSummary = CaseSummary + { number :: Int + , played :: Bool + -- ^ whether any step ran: a case the draw refused (a failing + -- @assertModel@) plays nothing + , moves :: [Text] + , outcome :: CaseOutcome + , at :: Maybe Int + -- ^ the failing step's 'n' + , why :: Maybe Text + , labels :: [Text] + } + deriving (Eq, Show) + +-- | One narrowing try, in a line: 'taken' when it still failed, so +-- narrowing went on from it. +data TrySummary = TrySummary + { number :: Int + , played :: Bool + , moves :: [Text] + , outcome :: CaseOutcome + , at :: Maybe Int + , why :: Maybe Text + , taken :: Bool + } + deriving (Eq, Show) + +-- | A case in full: @case 3@ or @try 7@. +data CaseTrace = CaseTrace + { from :: Text + , steps :: [StepRecord] + } + deriving (Eq, Show) + +-- | In how many of the generated cases a label held. A declared label no +-- case reached counts 0. +data LabelCount = LabelCount + { label :: Text + , cases :: Int + , outOf :: Int + } + deriving (Eq, Show) + +-- | How many times a move was played over the generated cases. +data MoveCount = MoveCount + { move :: Text + , timesPlayed :: Int + } + deriving (Eq, Show) + +data RunTrace = RunTrace + { cases :: [CaseSummary] + , discarded :: Int + -- ^ the generated cases discarded before they counted (QuickCheck + -- draws again); they are not in 'cases' + , narrowing :: [TrySummary] + , firstFailure :: Maybe CaseTrace + , narrowed :: Maybe CaseTrace + , labels :: [LabelCount] + , moves :: [MoveCount] + } + deriving (Eq, Show) + +-- --------------------------------------------------------------------------- +-- JSON (snake_case, the names the plan runs' per-rule record uses where a +-- field means the same) + +instance ToJSON StepKind where + toJSON = String . kindText + +instance ToJSON Expectation where + toJSON = \case + GoesThrough -> String "goes through" + Refused st -> object ["refused" .= st] + +instance ToJSON FileRecord where + toJSON FileRecord {..} = object ["field" .= field, "name" .= fileName, "content_type" .= contentType] + +instance ToJSON RequestRecord where + toJSON = \case + RequestSent {..} -> object + [ "line" .= line + , "headers" .= pairs headers + , "form" .= pairs form + , "files" .= files + , "body" .= body + , "body_type" .= bodyType + ] + RequestUnset fld -> object ["unset" .= fld] + where + pairs kvs = object [ K.fromText k .= v | (k, v) <- kvs ] + +instance ToJSON AnswerRecord where + toJSON AnswerRecord {..} = object + [ "http_status" .= httpStatus, "body" .= body, "value" .= value, "failure" .= failure ] + +instance ToJSON CheckRecord where + toJSON CheckRecord {..} = object ["check" .= check, "held" .= held, "why" .= why] + +instance ToJSON StageRecord where + toJSON StageRecord {..} = case (before, after) of + (Nothing, Nothing) -> Null + _ -> object ["before" .= before, "after" .= after] + +instance ToJSON StepRecord where + toJSON StepRecord {..} = object + [ "n" .= n + , "kind" .= kind + , "trail" .= maybe [] (\StepInfo {trail} -> trail) info + , "summary" .= fmap (\StepInfo {summary} -> summary) info + , "fqn" .= maybe operation id (info >>= \StepInfo {name} -> name) + , "operation" .= operation + , "method" .= method + , "expect" .= expect + , "request" .= request + , "answer" .= answer + , "checks" .= checks + , "labels" .= labels + , "model" .= model + , "stage" .= stage + , "outcome" .= (if ok then "ok" else "failed" :: Text) + ] + +instance ToJSON CaseSummary where + toJSON CaseSummary {..} = object + [ "case" .= number, "played" .= played, "moves" .= moves, "outcome" .= outcomeText outcome + , "at" .= at, "why" .= why, "labels" .= labels ] + +instance ToJSON TrySummary where + toJSON TrySummary {..} = object + [ "try" .= number, "played" .= played, "moves" .= moves, "outcome" .= outcomeText outcome + , "at" .= at, "why" .= why, "taken" .= taken ] + +instance ToJSON CaseTrace where + toJSON CaseTrace {..} = object ["from" .= from, "moves" .= steps] + +instance ToJSON LabelCount where + toJSON LabelCount {..} = object ["label" .= label, "cases" .= cases, "of" .= outOf] + +instance ToJSON MoveCount where + toJSON MoveCount {..} = object ["move" .= move, "played" .= timesPlayed] + +instance ToJSON RunTrace where + toJSON RunTrace {..} = object + [ "cases" .= cases + , "discarded" .= discarded + , "narrowing" .= narrowing + , "first_failure" .= firstFailure + , "narrowed" .= narrowed + , "labels" .= labels + , "moves" .= moves + ] + +-- --------------------------------------------------------------------------- +-- Rendering helpers + +-- | At most @k@ characters, an ellipsis marking a cut. +clipText :: Int -> Text -> Text +clipText k t + | T.length t <= k = t + | otherwise = T.take k t <> "…" + +-- | A body as text: UTF-8 as it is (clipped), anything else by its size. +bodyText :: Int -> LBS.ByteString -> Maybe Text +bodyText k bs + | LBS.null bs = Nothing + | otherwise = Just $ case TE.decodeUtf8' (LBS.toStrict bs) of + Right t -> clipText k t + Left _ -> "<" <> T.pack (show (LBS.length bs)) <> " bytes, not text>" + +-- --------------------------------------------------------------------------- +-- Recording + +-- | One property's sink: the case being played, and what the run has +-- gathered so far. +data Recorder = Recorder + { current :: IORef (Seq StepRecord) + , gathered :: IORef Gathered + , declared :: [Text] + } + +data Gathered = Gathered + { narrowingStarted :: Bool + , caseCount :: Int + , tryCount :: Int + , discardedCount :: Int + , caseLines :: Seq CaseSummary + , tryLines :: Seq TrySummary + , firstFailing :: Maybe CaseTrace + , lastTaken :: Maybe CaseTrace + , final :: Maybe CaseTrace + , countedCases :: Int + , labelCounts :: M.Map Text Int + , moveCounts :: M.Map Text Int + } + +-- | A recorder for one property, given the labels its steps declare (a +-- declared label no case reaches reads 0, not absent). +newRecorder :: [Text] -> IO Recorder +newRecorder declaredLabels = do + cur <- newIORef Seq.empty + g <- newIORef Gathered + { narrowingStarted = False + , caseCount = 0 + , tryCount = 0 + , discardedCount = 0 + , caseLines = Seq.empty + , tryLines = Seq.empty + , firstFailing = Nothing + , lastTaken = Nothing + , final = Nothing + , countedCases = 0 + , labelCounts = M.empty + , moveCounts = M.empty + } + pure Recorder {current = cur, gathered = g, declared = declaredLabels} + +-- | A case starts: whatever an interrupted one left is dropped. +beginCase :: Recorder -> IO () +beginCase Recorder {current} = writeIORef current Seq.empty + +-- | A step ran: append it, numbered. +pushStep :: Recorder -> StepRecord -> IO () +pushStep Recorder {current} StepRecord {..} = + modifyIORef' current $ \s -> s |> StepRecord {n = Seq.length s + 1, ..} + +-- | Change the step last pushed (its postcondition ran). +amendStep :: Recorder -> (StepRecord -> StepRecord) -> IO () +amendStep Recorder {current} f = modifyIORef' current $ \s -> case Seq.viewr s of + Seq.EmptyR -> s + rest Seq.:> lastStep -> rest |> f lastStep + +-- | 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 +afterStep cs ls m stageAfter held StepRecord {checks, stage = StageRecord {before}, ok, ..} = StepRecord + { checks = checks ++ cs + , labels = ls + , model = Just m + , stage = StageRecord {before, after = stageAfter} + , ok = ok && held + , .. + } + +-- | The property, its cases closed into the recorder as QuickCheck +-- finishes each one. +recordedProperty :: Recorder -> Property -> Property +recordedProperty rec = + P.callback (P.PostFinalFailure P.NotCounterexample (\_ _ -> finalFailure rec)) + . P.callback (P.PostTest P.NotCounterexample (\_ res -> closeCase rec res)) + +closeCase :: Recorder -> P.Result -> IO () +closeCase Recorder {current, gathered} res = do + stepList <- toList <$> atomicModifyIORef' current (\s -> (Seq.empty, s)) + let + outcome = case P.ok res of + 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)) + | otherwise = Nothing + played = not (null stepList) + moveList = [ moveName s | s@StepRecord {kind} <- stepList, isMove kind ] + countKeys = [ moveCountKey s | s@StepRecord {kind} <- stepList, isMove kind ] + held = Set.toList (Set.fromList (map T.pack (P.classes res))) + modifyIORef' gathered $ \g@Gathered {..} -> + if not narrowingStarted + then case outcome of + Discarded -> g {discardedCount = discardedCount + 1} + _ -> + let k = caseCount + 1 + line' = CaseSummary {number = k, played, moves = moveList, outcome, at, why, labels = held} + in g { caseCount = k + , caseLines = caseLines |> line' + , countedCases = countedCases + 1 + , labelCounts = M.unionWith (+) labelCounts (M.fromList [ (l, 1) | l <- held ]) + , moveCounts = M.unionWith (+) moveCounts (M.fromListWith (+) [ (m, 1) | m <- countKeys ]) + , firstFailing = if outcome == Failed then Just CaseTrace {from = "case " <> tshow k, steps = stepList} else firstFailing + , narrowingStarted = outcome == Failed + } + else + let k = tryCount + 1 + taken = outcome == Failed + line' = TrySummary {number = k, played, moves = moveList, outcome, at, why, taken} + in g { tryCount = k + , tryLines = tryLines |> line' + , lastTaken = if taken then Just CaseTrace {from = "try " <> tshow k, steps = stepList} else lastTaken + } + where + stepWhy StepRecord {checks, answer} = + case [ w | CheckRecord {held = False, why = Just w} <- checks ] of + (w : _) -> Just w + [] -> answer >>= \AnswerRecord {failure} -> failure + nonEmpty t = if T.null (T.strip t) then Nothing else Just t + +finalFailure :: Recorder -> IO () +finalFailure Recorder {gathered} = modifyIORef' gathered $ \g@Gathered {lastTaken, firstFailing} -> + g {final = lastTaken <|> firstFailing} + +-- | The run as recorded so far (read it once the property has run). +readRunTrace :: Recorder -> IO RunTrace +readRunTrace Recorder {gathered, declared} = do + Gathered {..} <- readIORef gathered + let + seen = M.keys labelCounts + extra = filter (`notElem` declared) seen + labelOrder = dedupe declared ++ extra + pure RunTrace + { cases = toList caseLines + , discarded = discardedCount + , narrowing = toList tryLines + , firstFailure = firstFailing + , narrowed = final <|> (if narrowingStarted then lastTaken <|> firstFailing else Nothing) + , labels = [ LabelCount {label = l, cases = M.findWithDefault 0 l labelCounts, outOf = countedCases} | l <- labelOrder ] + , moves = [ MoveCount {move = m, timesPlayed = c} | (m, c) <- M.toList moveCounts ] + } + where + dedupe = go Set.empty + where + go _ [] = [] + go s (x : xs) + | Set.member x s = go s xs + | otherwise = x : go (Set.insert x s) xs + +tshow :: Show a => a -> Text +tshow = T.pack . show diff --git a/webapi-test/webapi-test.cabal b/webapi-test/webapi-test.cabal index 1d1bd2a..84d74b5 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.1.0.0 +version: 0.2.0.0 -- synopsis: -- description: license: BSD-3-Clause @@ -55,8 +55,10 @@ library qc-dynamic exposed-modules: Test.WebApi.Val Test.WebApi.StateModel Test.WebApi.DynamicLogic + Test.WebApi.Trace -- other-modules: build-depends: webapi-test + , aeson >= 2.0 , wai-extra >= 3.1 , cookie , http-types