relay-pagination-conformance 0.1.1.2 → 0.2.0.0
raw patch · 11 files changed
+286/−131 lines, 11 filesdep ~relay-paginationdep ~relay-pagination-hasqldep ~relay-pagination-servantPVP ok
version bump matches the API change (PVP)
Dependency ranges changed: relay-pagination, relay-pagination-hasql, relay-pagination-servant
API changes (from Hackage documentation)
+ Relay.Pagination.Conformance.Check: TotalCountConsistency :: InvariantName
+ Relay.Pagination.Conformance.Check: [checkTotalCount] :: ConformanceConfig -> !Bool
- Relay.Pagination.Conformance.Check: ConformanceConfig :: !Int -> !Int -> !Bool -> !Bool -> ConformanceConfig
+ Relay.Pagination.Conformance.Check: ConformanceConfig :: !Int -> !Int -> !Bool -> !Bool -> !Bool -> ConformanceConfig
Files
- CHANGELOG.md +11/−0
- relay-pagination-conformance.cabal +63/−57
- src/Relay/Pagination/Conformance/Check.hs +42/−7
- test/Broken.hs +29/−4
- test/CheckSpec.hs +37/−8
- test/DbFixture.hs +16/−2
- test/DbSpec.hs +19/−11
- test/HttpSpec.hs +54/−36
- test/MutationSpec.hs +2/−1
- test/Oracle.hs +7/−2
- test/WalkSpec.hs +6/−3
CHANGELOG.md view
@@ -2,6 +2,17 @@ Versioning follows the [Haskell Package Versioning Policy](https://pvp.haskell.org/). +## 0.2.0.0 — 2026-11-18++### Added++- Enable `checkTotalCount` to compare every walked page's count against the number of distinct keys in the forward walk over a stable dataset.++### Breaking changes++- `ConformanceConfig` has a strict `checkTotalCount` field. Use `False` for the previous behavior, which remains the default.+- Handle `TotalCountConsistency` in exhaustive matches on `InvariantName`.+ ## 0.1.1.2 — 2026-10-06 ### Fixed
relay-pagination-conformance.cabal view
@@ -1,7 +1,7 @@-cabal-version: 3.0-name: relay-pagination-conformance-version: 0.1.1.2-synopsis: Conformance suite proving no-skip/no-duplicate pagination+cabal-version: 3.0+name: relay-pagination-conformance+version: 0.2.0.0+synopsis: Conformance suite proving no-skip/no-duplicate pagination description: A conformance suite that services run against their own paginated endpoints to prove no-skip/no-duplicate behavior: a page walker with@@ -9,26 +9,31 @@ reports. Pages are fetched through a plain callback, so the suite stays decoupled from any session runner or HTTP client. -license: BSD-3-Clause-license-file: LICENSE-author: Nadeem Bitar-maintainer: Nadeem Bitar-category: Testing, Web-build-type: Simple+license: BSD-3-Clause+license-file: LICENSE+author: Nadeem Bitar+maintainer: Nadeem Bitar+category: Testing, Web+build-type: Simple extra-doc-files: CHANGELOG.md source-repository head- type: git+ type: git location: https://github.com/shinzui/relay-pagination common warnings ghc-options:- -Wall -Wcompat -Widentities -Wincomplete-record-updates- -Wincomplete-uni-patterns -Wredundant-constraints -Wunused-packages+ -Wall+ -Wcompat+ -Widentities+ -Wincomplete-record-updates+ -Wincomplete-uni-patterns+ -Wredundant-constraints+ -Wunused-packages common lang- import: warnings- default-language: GHC2024+ import: warnings+ default-language: GHC2024 default-extensions: DeriveAnyClass DuplicateRecordFields@@ -36,8 +41,8 @@ OverloadedStrings library- import: lang- hs-source-dirs: src+ import: lang+ hs-source-dirs: src exposed-modules: Relay.Pagination.Conformance Relay.Pagination.Conformance.Check@@ -45,25 +50,26 @@ Relay.Pagination.Conformance.Walk build-depends:- , base >=4.21 && <5- , bytestring >=0.11 && <0.13- , containers >=0.7 && <0.9- , relay-pagination ^>=0.1.1.2- , tasty >=1.4 && <1.6- , tasty-hunit >=0.10 && <0.11- , text >=2.0 && <2.2+ base >=4.21 && <5,+ bytestring >=0.11 && <0.13,+ containers >=0.7 && <0.9,+ relay-pagination ^>=0.2.0.0,+ tasty >=1.4 && <1.6,+ tasty-hunit >=0.10 && <0.11,+ text >=2.0 && <2.2, test-suite relay-pagination-conformance-test- import: lang- type: exitcode-stdio-1.0- hs-source-dirs: test test-support- main-is: Main.hs+ import: lang+ type: exitcode-stdio-1.0+ hs-source-dirs:+ test+ test-support + main-is: Main.hs -- MultilineStrings: fixture DDL and the multi-row insert (ADR 1) default-extensions: MultilineStrings- -- warp (M6 HTTP walk) requires the threaded RTS- ghc-options: -threaded+ ghc-options: -threaded other-modules: Broken CheckSpec@@ -77,30 +83,30 @@ WalkSpec build-depends:- , aeson >=2.2 && <2.3- , base- , bytestring- , containers- , directory- , ephemeral-pg >=0.3.1 && <0.4- , hasql >=1.10 && <1.11- , hasql-dynamic-statements >=0.5 && <0.6- , http-client >=0.7 && <0.8- , quickcheck-instances >=0.3 && <0.4- , relay-pagination ^>=0.1.1.2- , relay-pagination-conformance- , relay-pagination-hasql ^>=0.1.1.2- , relay-pagination-servant ^>=0.1.1.2- , servant >=0.20.3 && <0.21- , servant-client >=0.20.3 && <0.21- , servant-client-core- , servant-server- , sop-core >=0.5 && <0.6- , tasty >=1.4 && <1.6- , tasty-hunit >=0.10 && <0.11- , tasty-quickcheck >=0.10 && <0.12- , text- , time >=1.12 && <1.15- , unix- , uuid-types >=1.0 && <1.1- , warp >=3.3 && <3.5+ aeson >=2.2 && <2.3,+ base,+ bytestring,+ containers,+ directory,+ ephemeral-pg >=0.3.1 && <0.4,+ hasql >=1.10 && <1.11,+ hasql-dynamic-statements >=0.5 && <0.6,+ http-client >=0.7 && <0.8,+ quickcheck-instances >=0.3 && <0.4,+ relay-pagination ^>=0.2.0.0,+ relay-pagination-conformance,+ relay-pagination-hasql ^>=0.2.0.0,+ relay-pagination-servant ^>=0.2.0.0,+ servant >=0.20.3 && <0.21,+ servant-client >=0.20.3 && <0.21,+ servant-client-core,+ servant-server,+ sop-core >=0.5 && <0.6,+ tasty >=1.4 && <1.6,+ tasty-hunit >=0.10 && <0.11,+ tasty-quickcheck >=0.10 && <0.12,+ text,+ time >=1.12 && <1.15,+ unix,+ uuid-types >=1.0 && <1.1,+ warp >=3.3 && <3.5,
src/Relay/Pagination/Conformance/Check.hs view
@@ -1,7 +1,7 @@ {-# LANGUAGE BlockArguments #-} -- | The invariant checker: walk an endpoint forward (and backward), then--- assert the six conformance invariants against the expected result set.+-- assert the enabled conformance invariants against the expected result set. -- Each invariant guards a way infinite scrolling breaks in production: -- -- ['Completeness'] The forward walk returns exactly the expected rows —@@ -40,6 +40,10 @@ -- if it disagrees with the edges, the next request continues from the -- wrong position. --+-- ['TotalCountConsistency'] With 'checkTotalCount' enabled, every page+-- in each enabled walk reports the number of distinct forward-walk keys.+-- This check assumes the dataset stays stable throughout the walks.+-- -- A walk that aborts ('WalkFailure') is reported under 'WalkTerminated' — -- a paginator that loops forever is maximally non-conformant. module Relay.Pagination.Conformance.Check@@ -56,8 +60,10 @@ import Data.List (isInfixOf) import Data.Map.Strict qualified as Map+import Data.Set qualified as Set import Data.Text (Text) import Data.Text qualified as Text+import Numeric.Natural (Natural) import Relay.Pagination import Relay.Pagination.Conformance.Walk @@ -70,21 +76,24 @@ -- | Off for forward-only endpoints. checkBackward :: !Bool, -- | Off when the source mutates during the run.- checkDeterminism :: !Bool+ checkDeterminism :: !Bool,+ -- | Opt in for counted endpoints over a stable dataset.+ checkTotalCount :: !Bool } deriving stock (Eq, Show) --- | All checks on, walker cap 10 000.+-- | Total count checking off, all other checks on, walker cap 10 000. defaultConformanceConfig :: Int -> ConformanceConfig defaultConformanceConfig size = ConformanceConfig { pageSize = size, maxWalkPages = 10000, checkBackward = True,- checkDeterminism = True+ checkDeterminism = True,+ checkTotalCount = False } --- | The six invariants (see the module haddock), plus 'WalkTerminated' for+-- | The seven invariants (see the module haddock), plus 'WalkTerminated' for -- walks that abort. data InvariantName = Completeness@@ -94,6 +103,7 @@ | EdgeOrderInvariance | PageInfoCursorConsistency | WalkTerminated+ | TotalCountConsistency deriving stock (Eq, Ord, Show, Enum, Bounded) -- | One observed violation.@@ -154,7 +164,8 @@ { pageSize = size, maxWalkPages = cap, checkBackward = doBackward,- checkDeterminism = doDeterminism+ checkDeterminism = doDeterminism,+ checkTotalCount = doTotalCount } = config walkConfig = WalkConfig {maxWalkPages = cap} expectedKeys = map keyOf expected@@ -168,6 +179,10 @@ pagesWalked = 0 } Right forward -> do+ let distinctKeys = Set.fromList [keyOf n | Edge {node = n} <- walkEdges forward]+ countViolations whichWalk pages+ | doTotalCount = totalCountViolations (fromIntegral (Set.size distinctKeys)) whichWalk pages+ | otherwise = [] determinismViolations <- if doDeterminism then determinismCheck keyOf fetchPage forward@@ -182,7 +197,8 @@ ( symmetryViolations keyOf forward backward <> boundaryViolations "hasPreviousPage" (null expected) (walkPages backward) <> orderViolations keyOf expectedKeys "backward" (walkPages backward)- <> pageInfoViolations "backward" (walkPages backward),+ <> pageInfoViolations "backward" (walkPages backward)+ <> countViolations "backward" (walkPages backward), length (walkPages backward) ) else pure ([], 0)@@ -193,6 +209,7 @@ <> boundaryViolations "hasNextPage" (null expected) (walkPages forward) <> orderViolations keyOf expectedKeys "forward" (walkPages forward) <> pageInfoViolations "forward" (walkPages forward)+ <> countViolations "forward" (walkPages forward) <> backwardViolations <> determinismViolations, pagesWalked = length (walkPages forward) + backwardPages@@ -380,6 +397,24 @@ [violation "edge cursor sequence" | firstCursors /= againCursors], [violation "PageInfo" | pageInfo (pageOf w) /= pageInfo again] ]++-- | Invariant 7: every walked page declares the distinct forward key count.+totalCountViolations :: Natural -> Text -> [WalkedPage row] -> [ConformanceViolation]+totalCountViolations expectedCount whichWalk pages =+ [ ConformanceViolation+ { invariant = TotalCountConsistency,+ pageIndex = Just (indexOf w),+ detail =+ whichWalk+ <> " page: expected totalCount "+ <> tshow expectedCount+ <> ", "+ <> maybe "totalCount is missing" (\n -> "got " <> tshow n) actual+ }+ | w <- pages,+ let actual = totalCount (pageOf w),+ actual /= Just expectedCount+ ] -- * Field access helpers (DuplicateRecordFields makes bare selectors ambiguous here)
test/Broken.hs view
@@ -8,6 +8,9 @@ floatCursorBytes, floatRoundTripMicros, brokenFloatCursor,+ brokenRemainingCount,+ brokenWrongCount,+ brokenMissingCount, ) where @@ -19,6 +22,25 @@ import Oracle (oraclePaginate) import Relay.Pagination +-- | Misreport the count as the number of rows left in the walk direction.+brokenRemainingCount :: (row -> ByteString) -> [row] -> PageRequest -> Connection row+brokenRemainingCount cursorOf rows req@PageRequest {direction, cursor = mCursor} =+ let remaining = case mCursor of+ Nothing -> rows+ Just c -> case direction of+ Forward -> drop 1 (dropWhile (not . matches c) rows)+ Backward -> takeWhile (not . matches c) rows+ matches c row = Cursor (cursorOf row) == c+ in (oraclePaginate cursorOf rows req) {totalCount = Just (fromIntegral (length remaining))}++brokenWrongCount :: (row -> ByteString) -> [row] -> PageRequest -> Connection row+brokenWrongCount cursorOf rows req =+ (oraclePaginate cursorOf rows req) {totalCount = Just (fromIntegral (length rows) + 1)}++-- | A correct uncounted endpoint, used where the caller requires a count.+brokenMissingCount :: (row -> ByteString) -> [row] -> PageRequest -> Connection row+brokenMissingCount = oraclePaginate+ -- | Production Bug A verbatim: delegate to the correct oracle, then -- overwrite the walk-direction boundary flag with @length == pageSize@. -- Whenever the remaining row count is an exact multiple of the page size,@@ -39,7 +61,7 @@ PageInfo {hasNextPage = full, hasPreviousPage = prevFlag, startCursor = sc, endCursor = ec} Backward -> PageInfo {hasNextPage = nextFlag, hasPreviousPage = full, startCursor = sc, endCursor = ec}- in Connection {edges = edges correct, pageInfo = dishonest}+ in Connection {edges = edges correct, pageInfo = dishonest, totalCount = Nothing} -- | The reference implementation's third failure mode: backward pages -- returned in reversed (SQL-flipped) order, start/end cursors swapped to@@ -64,7 +86,8 @@ hasPreviousPage = prevFlag, startCursor = ec, endCursor = sc- }+ },+ totalCount = Nothing } -- | A row whose sort key is an exact integer-microsecond timestamp; ordered@@ -114,7 +137,8 @@ hasPreviousPage = False, startCursor = Nothing, endCursor = Nothing- }+ },+ totalCount = Nothing } Forward -> let rest = case mCursor of@@ -144,5 +168,6 @@ endCursor = case reverse slice of r : _ -> Just (Cursor (floatCursorBytes r)) [] -> Nothing- }+ },+ totalCount = Nothing }
test/CheckSpec.hs view
@@ -8,8 +8,7 @@ import Data.ByteString.Char8 qualified as Char8 import Data.List (nub, sort) import Data.Text qualified as Text-import Oracle (oraclePaginate)-import Relay.Pagination+import Oracle (oracleCounted, oraclePaginate) import Relay.Pagination.Conformance.Check import Relay.Pagination.Conformance.Tasty (testConformance) import Test.Tasty@@ -74,7 +73,8 @@ { pageSize = 6, maxWalkPages = 10000, checkBackward = False, -- forward-only model- checkDeterminism = True+ checkDeterminism = True,+ checkTotalCount = False } rowIdent (\req -> pure (brokenFloatCursor rows req))@@ -96,7 +96,8 @@ let names = nub (sort (map invariant (violations report))) assertBool "BackwardSymmetry violated" (BackwardSymmetry `elem` names) assertBool "EdgeOrderInvariance violated" (EdgeOrderInvariance `elem` names)- ]+ ],+ totalCountTests ] where forwardOnly3 =@@ -104,13 +105,41 @@ { pageSize = 3, maxWalkPages = 10000, checkBackward = False,- checkDeterminism = True+ checkDeterminism = True,+ checkTotalCount = False } - intBytes :: Int -> Char8.ByteString- intBytes = Char8.pack . show- identFor n = "f" <> (if n < 10 then "0" else "") <> Text.pack (show n) -- Around 2026-01-02T03:04:05 UTC in microseconds. baseStamp = 1767323045123456++totalCountTests :: TestTree+totalCountTests =+ testGroup+ "total count conformance"+ [ testGroup+ "counted oracle passes"+ [ testCase (show n <> " rows") do+ report <- checkCount oracleCounted [1 .. n]+ violations report @?= []+ | n <- [0, 1, 7 :: Int]+ ],+ broken "wrong count" brokenWrongCount [0, 1, 2, 0, 1, 2],+ broken "count of remaining rows" brokenRemainingCount [1, 2, 1, 2],+ broken "missing count" brokenMissingCount [0, 1, 2, 0, 1, 2]+ ]+ where+ checkCount paginate rows =+ checkConformance+ ((defaultConformanceConfig 3) {checkTotalCount = True})+ id+ (pure . paginate intBytes rows)+ rows+ broken name paginate pages = testCase name do+ report <- checkCount paginate [1 .. 7]+ nub (map invariant (violations report)) @?= [TotalCountConsistency]+ map pageIndex (violations report) @?= map Just pages++intBytes :: Int -> Char8.ByteString+intBytes = Char8.pack . show
test/DbFixture.hs view
@@ -14,6 +14,7 @@ resetRows, insertRows, fetchViaEngine,+ fetchCountedViaEngine, testSortSpec, testRowDecoder, run,@@ -38,12 +39,14 @@ import Hasql.Session qualified as Session import Hasql.Statement (Statement) import Hasql.Statement qualified as Statement-import Relay.Pagination (Connection, PageRequest)+import Relay.Pagination (Connection, CountedConnection, PageRequest, countedConnection) import Relay.Pagination.Hasql- ( KeyColumn (..),+ ( CountedPage (..),+ KeyColumn (..), SortDirection (..), SortSpec (..), paginate,+ paginateCounted, timestamptzKey, uuidKey, )@@ -90,6 +93,17 @@ case paginate testSortSpec req baseQuery testRowDecoder of Left err -> fail ("cursor rejected by the engine: " <> show err) Right stmt -> run conn (Session.statement () stmt)++-- | Counted variant for the stable database and HTTP fixtures.+fetchCountedViaEngine :: HasqlConn.Connection -> PageRequest -> IO (CountedConnection TestRow)+fetchCountedViaEngine conn req =+ case paginateCounted testSortSpec req baseQuery testRowDecoder of+ Left err -> fail ("cursor rejected by the engine: " <> show err)+ Right p ->+ run conn $+ countedConnection+ <$> Session.statement () (countStatement p)+ <*> Session.statement () (pageStatement p) -- | One cached-initdb server plus one connection, with the schema created. acquireDb :: IO (Pg.Database, HasqlConn.Connection)
test/DbSpec.hs view
@@ -12,7 +12,9 @@ import DbFixture import Generators import Hasql.Connection qualified as HasqlConn+import Relay.Pagination (toConnection) import Relay.Pagination.Conformance.Check+import Relay.Pagination.Conformance.Walk (FetchPage) import Test.Tasty import Test.Tasty.QuickCheck @@ -22,22 +24,28 @@ -- given how adversarial the generators are. The group is sequential: -- its tests share one connection and one table, and the -threaded RTS -- (needed for warp in HttpSpec) lets tasty run tests concurrently.- localOption (QuickCheckTests 20) $- sequentialTestGroup- "db (EP-3 engine over ephemeral-pg)"- AllFinish- [ conformanceProperty getDb "heavy ties: boundaries inside tie runs" genHeavyTies,- conformanceProperty getDb "adjacent microseconds" genAdjacentMicros,- conformanceProperty getDb "exact page-boundary sizes" genExactBoundaries,- conformanceProperty getDb "extreme page sizes (1 and 100)" genExtremeSizes- ]+ let uncounted = conformanceProperty getDb defaultConformanceConfig fetchViaEngine+ countedConfig size = (defaultConformanceConfig size) {checkTotalCount = True}+ countedFetch conn = fmap toConnection . fetchCountedViaEngine conn+ in localOption (QuickCheckTests 20) $+ sequentialTestGroup+ "db (EP-3 engine over ephemeral-pg)"+ AllFinish+ [ uncounted "heavy ties: boundaries inside tie runs" genHeavyTies,+ uncounted "adjacent microseconds" genAdjacentMicros,+ uncounted "exact page-boundary sizes" genExactBoundaries,+ uncounted "extreme page sizes (1 and 100)" genExtremeSizes,+ conformanceProperty getDb countedConfig countedFetch "counted engine agrees with the full walk" genExactBoundaries+ ] conformanceProperty :: IO (db, HasqlConn.Connection) ->+ (Int -> ConformanceConfig) ->+ (HasqlConn.Connection -> FetchPage TestRow) -> TestName -> Gen (Int, [TestRow]) -> TestTree-conformanceProperty getDb name gen =+conformanceProperty getDb configFor fetch name gen = testProperty name $ forAll gen \(size, rows) -> ioProperty do (_, conn) <- getDb@@ -45,7 +53,7 @@ insertRows conn rows let expected = sortBy canonicalOrder rows report <-- checkConformance (defaultConformanceConfig size) rowId (fetchViaEngine conn) expected+ checkConformance (configFor size) rowId (fetch conn) expected pure $ counterexample (Text.unpack (renderConformanceReport report))
test/HttpSpec.hs view
@@ -8,6 +8,7 @@ -- JSON round-trip do not perturb the conformance guarantees. module HttpSpec (tests) where +import Control.Exception (onException) import Control.Monad.IO.Class (liftIO) import Data.List (sortBy) import Data.Proxy (Proxy (..))@@ -27,26 +28,26 @@ import Servant (Application, serve) import Servant.API (JSON, NamedRoutes, StdMethod (GET), (:-), (:>)) import Servant.API.MultiVerb (AsUnion (..), MultiVerb, Respond)-import Servant.Client (BaseUrl (..), ClientM, Scheme (Http), mkClientEnv, runClientM)+import Servant.Client (BaseUrl (..), ClientEnv, ClientM, Scheme (Http), mkClientEnv, runClientM) import Servant.Client.Generic (AsClientT, genericClient) import Servant.Server.Generic (AsServerT) import Servant.Server.Internal (Handler) import Test.Tasty import Test.Tasty.HUnit -type RowsPageResponses =- '[ Respond 200 "Page of rows" (Connection TestRow),+type RowsPageResponses page =+ '[ Respond 200 "Page of rows" page, Respond 400 "Invalid pagination" RelayPageError ] -data RowsPageResult- = RowsPageOk !(Connection TestRow)+data RowsPageResult page+ = RowsPageOk !page | RowsPageBadRequest !RelayPageError deriving stock (Show) -- | Hand-written, per ADR 1: status/constructor mapping breaks at compile -- time if the response list changes.-instance AsUnion RowsPageResponses RowsPageResult where+instance AsUnion (RowsPageResponses page) (RowsPageResult page) where toUnion = \case RowsPageOk value -> Z (I value) RowsPageBadRequest err -> S (Z (I err))@@ -55,12 +56,12 @@ S (Z (I err)) -> RowsPageBadRequest err S (S impossible) -> case impossible of {} +type RowsEndpoint page =+ RelayPage 5 50 :> MultiVerb 'GET '[JSON] (RowsPageResponses page) (RowsPageResult page)+ data RowsRoutes mode = RowsRoutes- { rows ::- mode- :- "rows"- :> RelayPage 5 50- :> MultiVerb 'GET '[JSON] RowsPageResponses RowsPageResult+ { rows :: mode :- "rows" :> RowsEndpoint (Connection TestRow),+ countedRows :: mode :- "counted-rows" :> RowsEndpoint (CountedConnection TestRow) } deriving stock (Generic) @@ -71,7 +72,10 @@ rowsServer :: HasqlConn.Connection -> RowsRoutes (AsServerT Handler) rowsServer conn =- RowsRoutes {rows = \pageRequest -> liftIO (RowsPageOk <$> fetchViaEngine conn pageRequest)}+ RowsRoutes+ { rows = liftIO . fmap RowsPageOk . fetchViaEngine conn,+ countedRows = liftIO . fmap RowsPageOk . fetchCountedViaEngine conn+ } rowsApp :: HasqlConn.Connection -> Application rowsApp conn = serve rowsApi (rowsServer conn)@@ -88,33 +92,47 @@ Backward -> backwardPage size mCursor tests :: TestTree-tests = withResource acquireDb releaseDb \getDb ->+tests = withResource acquireAndSeed releaseDb \getDb -> testGroup "http (RelayPage over warp)"- [ testCase "conformance walk through servant-client" do- (_, conn) <- getDb- resetRows conn- insertRows conn fixtureRows- testWithApplication (pure (rowsApp conn)) \port -> do- manager <- HttpClient.newManager HttpClient.defaultManagerSettings- let env = mkClientEnv manager (BaseUrl Http "127.0.0.1" port "")- fetchPage :: FetchPage TestRow- fetchPage req =- runClientM (rows rowsClient (toClientPage req)) env >>= \case- Right (RowsPageOk page) -> pure page- Right (RowsPageBadRequest err) ->- fail ("server rejected pagination: " <> show err)- Left clientError -> fail ("transport failure: " <> show clientError)- report <-- checkConformance- (defaultConformanceConfig 5)- rowId- fetchPage- (sortBy canonicalOrder fixtureRows)- assertBool- (Text.unpack (renderConformanceReport report))- (conformancePassed report)+ [ walkThroughClient getDb "conformance walk through servant-client" config (clientFetch id (rows rowsClient)),+ walkThroughClient+ getDb+ "counted conformance walk through servant-client"+ (config {checkTotalCount = True})+ (clientFetch toConnection (countedRows rowsClient)) ]+ where+ config = defaultConformanceConfig 5+ acquireAndSeed = do+ resource@(_, conn) <- acquireDb+ insertRows conn fixtureRows `onException` releaseDb resource+ pure resource++walkThroughClient ::+ IO (db, HasqlConn.Connection) ->+ TestName ->+ ConformanceConfig ->+ (ClientEnv -> FetchPage TestRow) ->+ TestTree+walkThroughClient getDb name config fetch = testCase name do+ (_, conn) <- getDb+ testWithApplication (pure (rowsApp conn)) \port -> do+ manager <- HttpClient.newManager HttpClient.defaultManagerSettings+ let env = mkClientEnv manager (BaseUrl Http "127.0.0.1" port "")+ report <- checkConformance config rowId (fetch env) (sortBy canonicalOrder fixtureRows)+ assertBool (Text.unpack (renderConformanceReport report)) (conformancePassed report)++clientFetch ::+ (page -> Connection TestRow) ->+ (ClientPage -> ClientM (RowsPageResult page)) ->+ ClientEnv ->+ FetchPage TestRow+clientFetch unwrap request env req =+ runClientM (request (toClientPage req)) env >>= \case+ Right (RowsPageOk page) -> pure (unwrap page)+ Right (RowsPageBadRequest err) -> fail ("server rejected pagination: " <> show err)+ Left clientError -> fail ("transport failure: " <> show clientError) -- | 25 deterministic rows in the EP-3 integration fixture's adversarial -- shape: two ten-way timestamp ties, a microsecond-adjacent pair, three
test/MutationSpec.hs view
@@ -246,7 +246,8 @@ endCursor = case reverse edgeList of Edge {cursor = c} : _ -> Just c [] -> Nothing- }+ },+ totalCount = Nothing } offsetStatement :: Statement (Int64, Int64) [TestRow]
test/Oracle.hs view
@@ -4,7 +4,7 @@ -- -- Cursors are a stable per-row token (the row's unique key rendered to -- bytes), never a positional offset.-module Oracle (oraclePaginate) where+module Oracle (oraclePaginate, oracleCounted) where import Data.ByteString (ByteString) import Data.Maybe (isJust)@@ -52,7 +52,12 @@ endCursor = case reverse slice of r : _ -> Just (Cursor (cursorOf r)) [] -> Nothing- }+ },+ totalCount = Nothing } lastN n xs = drop (max 0 (length xs - n)) xs++oracleCounted :: (row -> ByteString) -> [row] -> PageRequest -> Connection row+oracleCounted cursorOf rows req =+ (oraclePaginate cursorOf rows req) {totalCount = Just (fromIntegral (length rows))}
test/WalkSpec.hs view
@@ -45,7 +45,8 @@ hasPreviousPage = False, startCursor = Just (cursorFor 1), endCursor = Nothing- }+ },+ totalCount = Nothing } result <- walkForward missing 3 failureOf result @?= WalkMissingCursor 0@@ -72,7 +73,8 @@ hasPreviousPage = False, startCursor = Just (cursorFor 42), endCursor = Just (cursorFor 42)- }+ },+ totalCount = Nothing } pageWithEnd bytes =@@ -84,7 +86,8 @@ hasPreviousPage = False, startCursor = Just (Cursor bytes), endCursor = Just (Cursor bytes)- }+ },+ totalCount = Nothing } -- | The shared oracle wired as a 'FetchPage' over a list of Ints.