Skip to content

Commit

Permalink
Add generators and coverage for TxIn
Browse files Browse the repository at this point in the history
  • Loading branch information
sevanspowell committed Oct 21, 2021
1 parent be62d58 commit 34e43a4
Show file tree
Hide file tree
Showing 2 changed files with 103 additions and 0 deletions.
41 changes: 41 additions & 0 deletions lib/core/src/Cardano/Api/Gen.hs
@@ -0,0 +1,41 @@
{-# LANGUAGE GADTs #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeApplications #-}

module Cardano.Api.Gen
( genTxIn
, genTxId
, genTxIndex
, genShelleyHash
) where

import Prelude

import Cardano.Api hiding
( txIns )
import Test.QuickCheck
( Gen, Large (..), arbitrary )

import qualified Cardano.Binary as CBOR
import qualified Cardano.Crypto.Hash as Crypto
import qualified Shelley.Spec.Ledger.TxBody as Ledger
( EraIndependentTxBody )

genShelleyHash
:: Gen (Crypto.Hash Crypto.Blake2b_256 Ledger.EraIndependentTxBody)
genShelleyHash = return . Crypto.castHash $ Crypto.hashWith CBOR.serialize' ()

genTxIn :: Gen TxIn
genTxIn = TxIn <$> genTxId <*> genTxIndex

genTxId :: Gen TxId
genTxId = TxId <$> genShelleyHash

genTxIndex :: Gen TxIx
genTxIndex = do
(Large (n :: Word)) <- arbitrary
pure $ TxIx n
62 changes: 62 additions & 0 deletions lib/core/test/unit/Cardano/Api/GenSpec.hs
@@ -0,0 +1,62 @@
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RankNTypes #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}

module Cardano.Api.GenSpec (spec) where

import Prelude

import Cardano.Api
( TxIn (..), TxIx (..) )
import Cardano.Api.Gen
import Data.Function
( (&) )
import Data.Word
( Word32 )
import Test.Hspec
import Test.QuickCheck
( Arbitrary
, Property
, arbitrary
, checkCoverage
, counterexample
, cover
, label
, property
)

spec :: Spec
spec =
describe "Cardano.Api.Gen" $
describe "Generator coverage" $ do
it "genTxIx" $
property genTxIxCoverage
it "genTxIn" $
property genTxInCoverage

genTxIxCoverage :: TxIx -> Property
genTxIxCoverage txIx = checkCoverage
$ cover 1 (txIx == TxIx 0)
"txIx is zero"
$ cover 2 (txIx >= veryLargeTxIx)
"txIx is very large"
$ cover 10 (txIx > TxIx 0 && txIx < veryLargeTxIx)
"txIx is between smallest and very large"
$ label "no txIx is negative" (txIx >= TxIx 0)
& counterexample "txIx was negative"
where
veryLargeTxIx :: TxIx
veryLargeTxIx = TxIx $ fromInteger $ toInteger (maxBound :: Word32)

instance Arbitrary TxIx where
arbitrary = genTxIndex

genTxInCoverage :: TxIn -> Property
genTxInCoverage (TxIn _id ix) =
-- We don't provide any coverage for genShelleyHash, and so we don't provide
-- any coverage for txId either (as txId consists of a shelleyHash).
genTxIxCoverage ix

instance Arbitrary TxIn where
arbitrary = genTxIn

0 comments on commit 34e43a4

Please sign in to comment.