Setup integration tests and CI (#11)

- Setup integration tests following pattern suggested in cosmos-sdk docs:
  https://docs.cosmos.network/v0.50/build/building-modules/testing#integration-tests
- Add tests for laconic modules query services
- Setup a CI workflow to run the integration tests

Reviewed-on: deep-stack/laconic2d#11
Co-authored-by: Prathamesh Musale <prathamesh.musale0@gmail.com>
Co-committed-by: Prathamesh Musale <prathamesh.musale0@gmail.com>
This commit is contained in:
2024-02-29 11:54:35 +00:00
committed by ashwin
parent d2505367aa
commit 0af44b5f17
26 changed files with 2326 additions and 129 deletions
@@ -0,0 +1,30 @@
package keeper_test
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
integrationTest "git.vdb.to/cerc-io/laconic2d/tests/integration"
types "git.vdb.to/cerc-io/laconic2d/x/auction"
)
type KeeperTestSuite struct {
suite.Suite
integrationTest.TestFixture
queryClient types.QueryClient
}
func (kts *KeeperTestSuite) SetupTest() {
err := kts.TestFixture.Setup()
assert.Nil(kts.T(), err)
qr := kts.App.QueryHelper()
kts.queryClient = types.NewQueryClient(qr)
}
func TestAuctionKeeperTestSuite(t *testing.T) {
suite.Run(t, new(KeeperTestSuite))
}
@@ -0,0 +1,349 @@
package keeper_test
import (
"context"
"fmt"
"cosmossdk.io/math"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
integrationTest "git.vdb.to/cerc-io/laconic2d/tests/integration"
types "git.vdb.to/cerc-io/laconic2d/x/auction"
)
const testCommitHash = "71D8CF34026E32A3A34C2C2D4ADF25ABC8D7943A4619761BE27F196603D91B9D"
func (kts *KeeperTestSuite) TestGrpcQueryParams() {
testCases := []struct {
msg string
req *types.QueryParamsRequest
}{
{
"fetch params",
&types.QueryParamsRequest{},
},
}
for _, test := range testCases {
kts.Run(fmt.Sprintf("Case %s", test.msg), func() {
resp, err := kts.queryClient.Params(context.Background(), test.req)
kts.Require().Nil(err)
kts.Require().Equal(*(resp.Params), types.DefaultParams())
})
}
}
func (kts *KeeperTestSuite) TestGrpcGetAuction() {
testCases := []struct {
msg string
req *types.QueryAuctionRequest
createAuction bool
}{
{
"fetch auction with empty auction ID",
&types.QueryAuctionRequest{},
false,
},
{
"fetch auction with valid auction ID",
&types.QueryAuctionRequest{},
true,
},
}
for _, test := range testCases {
kts.Run(fmt.Sprintf("Case %s", test.msg), func() {
var expectedAuction types.Auction
if test.createAuction {
auction, _, err := kts.createAuctionAndCommitBid(false)
kts.Require().Nil(err)
test.req.Id = auction.Id
expectedAuction = *auction
}
resp, err := kts.queryClient.GetAuction(context.Background(), test.req)
if test.createAuction {
kts.Require().Nil(err)
kts.Require().NotNil(resp.GetAuction())
kts.Require().EqualExportedValues(expectedAuction, *(resp.GetAuction()))
} else {
kts.Require().NotNil(err)
kts.Require().Error(err)
}
})
}
}
func (kts *KeeperTestSuite) TestGrpcGetAllAuctions() {
testCases := []struct {
msg string
req *types.QueryAuctionsRequest
createAuctions bool
auctionCount int
}{
{
"fetch auctions when no auctions exist",
&types.QueryAuctionsRequest{},
false,
0,
},
{
"fetch auctions with one auction created",
&types.QueryAuctionsRequest{},
true,
1,
},
}
for _, test := range testCases {
kts.Run(fmt.Sprintf("Case %s", test.msg), func() {
if test.createAuctions {
_, _, err := kts.createAuctionAndCommitBid(false)
kts.Require().Nil(err)
}
resp, _ := kts.queryClient.Auctions(context.Background(), test.req)
kts.Require().Equal(test.auctionCount, len(resp.GetAuctions().Auctions))
})
}
}
func (kts *KeeperTestSuite) TestGrpcGetBids() {
testCases := []struct {
msg string
req *types.QueryBidsRequest
createAuction bool
commitBid bool
bidCount int
}{
{
"fetch all bids when no auction exists",
&types.QueryBidsRequest{},
false,
false,
0,
},
{
"fetch all bids for valid auction but no added bids",
&types.QueryBidsRequest{},
true,
false,
0,
},
{
"fetch all bids for valid auction and valid bid",
&types.QueryBidsRequest{},
true,
true,
1,
},
}
for _, test := range testCases {
kts.Run(fmt.Sprintf("Case %s", test.msg), func() {
if test.createAuction {
auction, _, err := kts.createAuctionAndCommitBid(test.commitBid)
kts.Require().NoError(err)
test.req.AuctionId = auction.Id
}
resp, err := kts.queryClient.GetBids(context.Background(), test.req)
if test.createAuction {
kts.Require().Nil(err)
kts.Require().Equal(test.bidCount, len(resp.GetBids()))
} else {
kts.Require().NotNil(err)
kts.Require().Error(err)
}
})
}
}
func (kts *KeeperTestSuite) TestGrpcGetBid() {
testCases := []struct {
msg string
req *types.QueryBidRequest
createAuctionAndBid bool
}{
{
"fetch bid when bid does not exist",
&types.QueryBidRequest{},
false,
},
{
"fetch bid when valid bid exists",
&types.QueryBidRequest{},
true,
},
}
for _, test := range testCases {
kts.Run(fmt.Sprintf("Case %s", test.msg), func() {
if test.createAuctionAndBid {
auction, bid, err := kts.createAuctionAndCommitBid(test.createAuctionAndBid)
kts.Require().NoError(err)
test.req.AuctionId = auction.Id
test.req.Bidder = bid.BidderAddress
}
resp, err := kts.queryClient.GetBid(context.Background(), test.req)
if test.createAuctionAndBid {
kts.Require().NoError(err)
kts.Require().NotNil(resp.Bid)
kts.Require().Equal(test.req.Bidder, resp.Bid.BidderAddress)
} else {
kts.Require().NotNil(err)
kts.Require().Error(err)
}
})
}
}
func (kts *KeeperTestSuite) TestGrpcGetAuctionsByBidder() {
testCases := []struct {
msg string
req *types.QueryAuctionsByBidderRequest
createAuctionAndCommitBid bool
auctionCount int
}{
{
"get auctions by bidder with invalid bidder address",
&types.QueryAuctionsByBidderRequest{},
false,
0,
},
{
"get auctions by bidder with valid auction and bid",
&types.QueryAuctionsByBidderRequest{},
true,
1,
},
}
for _, test := range testCases {
kts.Run(fmt.Sprintf("Case %s", test.msg), func() {
if test.createAuctionAndCommitBid {
_, bid, err := kts.createAuctionAndCommitBid(test.createAuctionAndCommitBid)
kts.Require().NoError(err)
test.req.BidderAddress = bid.BidderAddress
}
resp, err := kts.queryClient.AuctionsByBidder(context.Background(), test.req)
if test.createAuctionAndCommitBid {
kts.Require().NoError(err)
kts.Require().NotNil(resp.Auctions)
kts.Require().Equal(test.auctionCount, len(resp.Auctions.Auctions))
} else {
kts.Require().NotNil(err)
kts.Require().Error(err)
}
})
}
}
func (kts *KeeperTestSuite) TestGrpcGetAuctionsByOwner() {
testCases := []struct {
msg string
req *types.QueryAuctionsByOwnerRequest
createAuction bool
auctionCount int
}{
{
"get auctions by owner with invalid owner address",
&types.QueryAuctionsByOwnerRequest{},
false,
0,
},
{
"get auctions by owner with valid auction",
&types.QueryAuctionsByOwnerRequest{},
true,
1,
},
}
for _, test := range testCases {
kts.Run(fmt.Sprintf("Case %s", test.msg), func() {
if test.createAuction {
auction, _, err := kts.createAuctionAndCommitBid(false)
kts.Require().NoError(err)
test.req.OwnerAddress = auction.OwnerAddress
}
resp, err := kts.queryClient.AuctionsByOwner(context.Background(), test.req)
if test.createAuction {
kts.Require().NoError(err)
kts.Require().NotNil(resp.Auctions)
kts.Require().Equal(test.auctionCount, len(resp.Auctions.Auctions))
} else {
kts.Require().NotNil(err)
kts.Require().Error(err)
}
})
}
}
func (kts *KeeperTestSuite) TestGrpcQueryBalance() {
testCases := []struct {
msg string
req *types.QueryGetAuctionModuleBalanceRequest
createAuction bool
auctionCount int
}{
{
"get balance with no auctions created",
&types.QueryGetAuctionModuleBalanceRequest{},
false,
0,
},
{
"get balance with single auction created",
&types.QueryGetAuctionModuleBalanceRequest{},
true,
1,
},
}
for _, test := range testCases {
if test.createAuction {
_, _, err := kts.createAuctionAndCommitBid(true)
kts.Require().NoError(err)
}
resp, err := kts.queryClient.GetAuctionModuleBalance(context.Background(), test.req)
kts.Require().NoError(err)
kts.Require().Equal(test.auctionCount, len(resp.GetBalance()))
}
}
func (kts *KeeperTestSuite) createAuctionAndCommitBid(commitBid bool) (*types.Auction, *types.Bid, error) {
ctx, k := kts.SdkCtx, kts.AuctionKeeper
accCount := 1
if commitBid {
accCount++
}
// Create funded account(s)
accounts := simtestutil.AddTestAddrs(kts.BankKeeper, integrationTest.BondDenomProvider{}, ctx, accCount, math.NewInt(100))
params, err := k.GetParams(ctx)
if err != nil {
return nil, nil, err
}
auction, err := k.CreateAuction(ctx, types.NewMsgCreateAuction(*params, accounts[0]))
if err != nil {
return nil, nil, err
}
if commitBid {
bid, err := k.CommitBid(ctx, types.NewMsgCommitBid(auction.Id, testCommitHash, accounts[1]))
if err != nil {
return nil, nil, err
}
return auction, bid, nil
}
return auction, nil, nil
}
@@ -0,0 +1,30 @@
package keeper_test
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
integrationTest "git.vdb.to/cerc-io/laconic2d/tests/integration"
types "git.vdb.to/cerc-io/laconic2d/x/bond"
)
type KeeperTestSuite struct {
suite.Suite
integrationTest.TestFixture
queryClient types.QueryClient
}
func (kts *KeeperTestSuite) SetupTest() {
err := kts.TestFixture.Setup()
assert.Nil(kts.T(), err)
qr := kts.App.QueryHelper()
kts.queryClient = types.NewQueryClient(qr)
}
func TestBondKeeperTestSuite(t *testing.T) {
suite.Run(t, new(KeeperTestSuite))
}
@@ -0,0 +1,210 @@
package keeper_test
import (
"context"
"fmt"
"cosmossdk.io/math"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
integrationTest "git.vdb.to/cerc-io/laconic2d/tests/integration"
types "git.vdb.to/cerc-io/laconic2d/x/bond"
)
func (kts *KeeperTestSuite) TestGrpcQueryParams() {
testCases := []struct {
msg string
req *types.QueryParamsRequest
}{
{
"fetch params",
&types.QueryParamsRequest{},
},
}
for _, test := range testCases {
kts.Run(fmt.Sprintf("Case %s", test.msg), func() {
resp, err := kts.queryClient.Params(context.Background(), test.req)
kts.Require().Nil(err)
kts.Require().Equal(*(resp.Params), types.DefaultParams())
})
}
}
func (kts *KeeperTestSuite) TestGrpcQueryBondsList() {
testCases := []struct {
msg string
req *types.QueryGetBondsRequest
resp *types.QueryGetBondsResponse
noOfBonds int
createBonds bool
}{
{
"empty request",
&types.QueryGetBondsRequest{},
&types.QueryGetBondsResponse{},
0,
false,
},
{
"Get Bonds",
&types.QueryGetBondsRequest{},
&types.QueryGetBondsResponse{},
1,
true,
},
}
for _, test := range testCases {
kts.Run(fmt.Sprintf("Case %s ", test.msg), func() {
if test.createBonds {
_, err := kts.createBond()
kts.Require().NoError(err)
}
resp, _ := kts.queryClient.Bonds(context.Background(), test.req)
kts.Require().Equal(test.noOfBonds, len(resp.GetBonds()))
})
}
}
func (kts *KeeperTestSuite) TestGrpcQueryBondByBondId() {
testCases := []struct {
msg string
req *types.QueryGetBondByIdRequest
createBonds bool
errResponse bool
bondId string
}{
{
"empty request",
&types.QueryGetBondByIdRequest{},
false,
true,
"",
},
{
"Get Bond By ID",
&types.QueryGetBondByIdRequest{},
true,
false,
"",
},
}
for _, test := range testCases {
kts.Run(fmt.Sprintf("Case %s ", test.msg), func() {
if test.createBonds {
bond, err := kts.createBond()
kts.Require().NoError(err)
test.req.Id = bond.Id
}
resp, err := kts.queryClient.GetBondById(context.Background(), test.req)
if !test.errResponse {
kts.Require().Nil(err)
kts.Require().NotNil(resp.GetBond())
kts.Require().Equal(test.req.Id, resp.GetBond().GetId())
} else {
kts.Require().NotNil(err)
kts.Require().Error(err)
}
})
}
}
func (kts *KeeperTestSuite) TestGrpcGetBondsByOwner() {
testCases := []struct {
msg string
req *types.QueryGetBondsByOwnerRequest
noOfBonds int
createBonds bool
errResponse bool
bondId string
}{
{
"empty request",
&types.QueryGetBondsByOwnerRequest{},
0,
false,
true,
"",
},
{
"Get Bond By Owner",
&types.QueryGetBondsByOwnerRequest{},
1,
true,
false,
"",
},
}
for _, test := range testCases {
kts.Run(fmt.Sprintf("Case %s ", test.msg), func() {
if test.createBonds {
bond, err := kts.createBond()
kts.Require().NoError(err)
test.req.Owner = bond.Owner
}
resp, err := kts.queryClient.GetBondsByOwner(context.Background(), test.req)
if !test.errResponse {
kts.Require().Nil(err)
kts.Require().NotNil(resp.GetBonds())
kts.Require().Equal(test.noOfBonds, len(resp.GetBonds()))
} else {
kts.Require().NotNil(err)
kts.Require().Error(err)
}
})
}
}
func (kts *KeeperTestSuite) TestGrpcGetModuleBalance() {
testCases := []struct {
msg string
req *types.QueryGetBondModuleBalanceRequest
noOfBonds int
createBonds bool
errResponse bool
}{
{
"empty request",
&types.QueryGetBondModuleBalanceRequest{},
0,
true,
false,
},
}
for _, test := range testCases {
kts.Run(fmt.Sprintf("Case %s ", test.msg), func() {
if test.createBonds {
_, err := kts.createBond()
kts.Require().NoError(err)
}
resp, err := kts.queryClient.GetBondsModuleBalance(context.Background(), test.req)
if !test.errResponse {
kts.Require().Nil(err)
kts.Require().NotNil(resp.GetBalance())
kts.Require().Equal(resp.GetBalance(), sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(10))))
} else {
kts.Require().NotNil(err)
kts.Require().Error(err)
}
})
}
}
func (kts *KeeperTestSuite) createBond() (*types.Bond, error) {
ctx, k := kts.SdkCtx, kts.BondKeeper
accCount := 1
// Create funded account(s)
accounts := simtestutil.AddTestAddrs(kts.BankKeeper, integrationTest.BondDenomProvider{}, ctx, accCount, math.NewInt(1000))
bond, err := k.CreateBond(ctx, accounts[0], sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(10))))
if err != nil {
return nil, err
}
return bond, nil
}
+157
View File
@@ -0,0 +1,157 @@
package integration_test
import (
"context"
"cosmossdk.io/core/appmodule"
"cosmossdk.io/log"
storetypes "cosmossdk.io/store/types"
cmtprototypes "github.com/cometbft/cometbft/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/codec"
addresscodec "github.com/cosmos/cosmos-sdk/codec/address"
"github.com/cosmos/cosmos-sdk/runtime"
"github.com/cosmos/cosmos-sdk/testutil/integration"
sdk "github.com/cosmos/cosmos-sdk/types"
moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil"
"github.com/cosmos/cosmos-sdk/x/auth"
authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper"
authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/x/bank"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
auctionTypes "git.vdb.to/cerc-io/laconic2d/x/auction"
auctionkeeper "git.vdb.to/cerc-io/laconic2d/x/auction/keeper"
auctionmodule "git.vdb.to/cerc-io/laconic2d/x/auction/module"
bondTypes "git.vdb.to/cerc-io/laconic2d/x/bond"
bondkeeper "git.vdb.to/cerc-io/laconic2d/x/bond/keeper"
bondmodule "git.vdb.to/cerc-io/laconic2d/x/bond/module"
registryTypes "git.vdb.to/cerc-io/laconic2d/x/registry"
registrykeeper "git.vdb.to/cerc-io/laconic2d/x/registry/keeper"
registrymodule "git.vdb.to/cerc-io/laconic2d/x/registry/module"
)
type TestFixture struct {
App *integration.App
SdkCtx sdk.Context
cdc codec.Codec
keys map[string]*storetypes.KVStoreKey
AccountKeeper authkeeper.AccountKeeper
BankKeeper bankkeeper.Keeper
AuctionKeeper *auctionkeeper.Keeper
BondKeeper *bondkeeper.Keeper
RegistryKeeper registrykeeper.Keeper
}
func (tf *TestFixture) Setup() error {
keys := storetypes.NewKVStoreKeys(
authtypes.StoreKey, banktypes.StoreKey, auctionTypes.StoreKey, bondTypes.StoreKey, registryTypes.StoreKey,
)
cdc := moduletestutil.MakeTestEncodingConfig(
auth.AppModuleBasic{},
auctionmodule.AppModule{},
bondmodule.AppModule{},
registrymodule.AppModule{},
).Codec
logger := log.NewNopLogger() // Use log.NewTestLogger(kts.T()) for help with debugging
cms := integration.CreateMultiStore(keys, logger)
newCtx := sdk.NewContext(cms, cmtprototypes.Header{}, true, logger)
authority := authtypes.NewModuleAddress("gov")
maccPerms := map[string][]string{
minttypes.ModuleName: {authtypes.Minter},
auctionTypes.ModuleName: {},
auctionTypes.AuctionBurnModuleAccountName: {},
bondTypes.ModuleName: {},
registryTypes.ModuleName: {},
registryTypes.RecordRentModuleAccountName: {},
registryTypes.AuthorityRentModuleAccountName: {},
}
accountKeeper := authkeeper.NewAccountKeeper(
cdc,
runtime.NewKVStoreService(keys[authtypes.StoreKey]),
authtypes.ProtoBaseAccount,
maccPerms,
addresscodec.NewBech32Codec(sdk.Bech32MainPrefix),
sdk.Bech32MainPrefix,
authority.String(),
)
blockedAddresses := map[string]bool{
accountKeeper.GetAuthority(): false,
}
bankKeeper := bankkeeper.NewBaseKeeper(
cdc,
runtime.NewKVStoreService(keys[banktypes.StoreKey]),
accountKeeper,
blockedAddresses,
authority.String(),
log.NewNopLogger(),
)
auctionKeeper := auctionkeeper.NewKeeper(cdc, runtime.NewKVStoreService(keys[auctionTypes.StoreKey]), accountKeeper, bankKeeper)
bondKeeper := bondkeeper.NewKeeper(cdc, runtime.NewKVStoreService(keys[bondTypes.StoreKey]), accountKeeper, bankKeeper)
registryKeeper := registrykeeper.NewKeeper(cdc, runtime.NewKVStoreService(keys[registryTypes.StoreKey]), accountKeeper, bankKeeper, bondKeeper, auctionKeeper)
authModule := auth.NewAppModule(cdc, accountKeeper, authsims.RandomGenesisAccounts, nil)
bankModule := bank.NewAppModule(cdc, bankKeeper, accountKeeper, nil)
auctionModule := auctionmodule.NewAppModule(cdc, auctionKeeper)
bondModule := bondmodule.NewAppModule(cdc, bondKeeper)
registryModule := registrymodule.NewAppModule(cdc, registryKeeper)
integrationApp := integration.NewIntegrationApp(newCtx, logger, keys, cdc, map[string]appmodule.AppModule{
authtypes.ModuleName: authModule,
banktypes.ModuleName: bankModule,
auctionTypes.ModuleName: auctionModule,
bondTypes.ModuleName: bondModule,
registryTypes.ModuleName: registryModule,
})
sdkCtx := sdk.UnwrapSDKContext(integrationApp.Context())
// Register MsgServer and QueryServer
auctionTypes.RegisterMsgServer(integrationApp.MsgServiceRouter(), auctionkeeper.NewMsgServerImpl(auctionKeeper))
auctionTypes.RegisterQueryServer(integrationApp.QueryHelper(), auctionkeeper.NewQueryServerImpl(auctionKeeper))
bondTypes.RegisterMsgServer(integrationApp.MsgServiceRouter(), bondkeeper.NewMsgServerImpl(bondKeeper))
bondTypes.RegisterQueryServer(integrationApp.QueryHelper(), bondkeeper.NewQueryServerImpl(bondKeeper))
registryTypes.RegisterMsgServer(integrationApp.MsgServiceRouter(), registrykeeper.NewMsgServerImpl(registryKeeper))
registryTypes.RegisterQueryServer(integrationApp.QueryHelper(), registrykeeper.NewQueryServerImpl(registryKeeper))
// set default params
if err := auctionKeeper.Params.Set(sdkCtx, auctionTypes.DefaultParams()); err != nil {
return err
}
if err := bondKeeper.Params.Set(sdkCtx, bondTypes.DefaultParams()); err != nil {
return err
}
if err := registryKeeper.Params.Set(sdkCtx, registryTypes.DefaultParams()); err != nil {
return err
}
tf.App = integrationApp
tf.SdkCtx, tf.cdc, tf.keys = sdkCtx, cdc, keys
tf.AccountKeeper, tf.BankKeeper = accountKeeper, bankKeeper
tf.AuctionKeeper, tf.BondKeeper, tf.RegistryKeeper = auctionKeeper, bondKeeper, registryKeeper
return nil
}
type BondDenomProvider struct{}
func (bdp BondDenomProvider) BondDenom(ctx context.Context) (string, error) {
return sdk.DefaultBondDenom, nil
}
@@ -0,0 +1,7 @@
record:
attr1: value1
attr2: value2
link1:
/: QmSnuWmxptJZdLJpKRarxBMS2Ju2oANVrgbr2xWbie9b2D
link2:
/: QmP8jTG1m9GSDJLCbeWhVSVgEzCPPwXRdCRuJtQ5Tz9Kc9
@@ -0,0 +1,7 @@
record:
type: GeneralRecord
name: foo
version: 1.0.0
tags:
- tagA
- tagB
@@ -0,0 +1,13 @@
record:
type: ServiceProviderRegistration
bond_id: madeUpBondID
laconic_id: madeUpLaconicID
version: 1.0.0
x500:
common_name: cerc-io
organization_unit: xyz
organization_name: abc
state_name: california
country: US
locality_name: local
@@ -0,0 +1,7 @@
record:
type: WebsiteRegistrationRecord
url: https://cerc.io
repo_registration_record_cid: QmSnuWmxptJZdLJpKRarxBMS2Ju2oANVrgbr2xWbie9b2D
build_artifact_cid: QmP8jTG1m9GSDJLCbeWhVSVgEzCPPwXRdCRuJtQ5Tz9Kc9
tls_cerc_cid: QmbWqxBEKC3P8tqsKc98xmWNzrzDtRLMiMPL8wBuTGsMnR
version: 1.0.0
@@ -0,0 +1,59 @@
package keeper_test
import (
"testing"
"cosmossdk.io/math"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
integrationTest "git.vdb.to/cerc-io/laconic2d/tests/integration"
bondTypes "git.vdb.to/cerc-io/laconic2d/x/bond"
types "git.vdb.to/cerc-io/laconic2d/x/registry"
)
type KeeperTestSuite struct {
suite.Suite
integrationTest.TestFixture
queryClient types.QueryClient
accounts []sdk.AccAddress
bond bondTypes.Bond
}
func (kts *KeeperTestSuite) SetupTest() {
kts.TestFixture.Setup()
// set default params
err := kts.RegistryKeeper.Params.Set(kts.SdkCtx, types.DefaultParams())
assert.Nil(kts.T(), err)
qr := kts.App.QueryHelper()
kts.queryClient = types.NewQueryClient(qr)
// Create a bond
bond, err := kts.createBond()
assert.Nil(kts.T(), err)
kts.bond = *bond
}
func TestRegistryKeeperTestSuite(t *testing.T) {
suite.Run(t, new(KeeperTestSuite))
}
func (kts *KeeperTestSuite) createBond() (*bondTypes.Bond, error) {
ctx := kts.SdkCtx
// Create a funded account
kts.accounts = simtestutil.AddTestAddrs(kts.BankKeeper, integrationTest.BondDenomProvider{}, ctx, 1, math.NewInt(100000000000))
bond, err := kts.BondKeeper.CreateBond(ctx, kts.accounts[0], sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(1000000000))))
if err != nil {
return nil, err
}
return bond, nil
}
@@ -0,0 +1,421 @@
package keeper_test
import (
"context"
"fmt"
"path/filepath"
"reflect"
types "git.vdb.to/cerc-io/laconic2d/x/registry"
"git.vdb.to/cerc-io/laconic2d/x/registry/client/cli"
"git.vdb.to/cerc-io/laconic2d/x/registry/helpers"
registryKeeper "git.vdb.to/cerc-io/laconic2d/x/registry/keeper"
)
func (kts *KeeperTestSuite) TestGrpcQueryParams() {
testCases := []struct {
msg string
req *types.QueryParamsRequest
}{
{
"Get Params",
&types.QueryParamsRequest{},
},
}
for _, test := range testCases {
kts.Run(fmt.Sprintf("Case %s ", test.msg), func() {
resp, _ := kts.queryClient.Params(context.Background(), test.req)
defaultParams := types.DefaultParams()
kts.Require().Equal(defaultParams.String(), resp.GetParams().String())
})
}
}
func (kts *KeeperTestSuite) TestGrpcGetRecordLists() {
ctx, queryClient := kts.SdkCtx, kts.queryClient
sr := kts.Require()
var recordId string
examples := []string{
"../../data/examples/service_provider_example.yml",
"../../data/examples/website_registration_example.yml",
"../../data/examples/general_record_example.yml",
}
testCases := []struct {
msg string
req *types.QueryRecordsRequest
createRecords bool
expErr bool
noOfRecords int
}{
{
"Empty Records",
&types.QueryRecordsRequest{},
false,
false,
0,
},
{
"List Records",
&types.QueryRecordsRequest{},
true,
false,
3,
},
{
"Filter with type",
&types.QueryRecordsRequest{
Attributes: []*types.QueryRecordsRequest_KeyValueInput{
{
Key: "type",
Value: &types.QueryRecordsRequest_ValueInput{
Value: &types.QueryRecordsRequest_ValueInput_String_{String_: "WebsiteRegistrationRecord"},
},
},
},
All: true,
},
true,
false,
1,
},
// Skip the following test as querying with recursive values not supported (PR https://git.vdb.to/cerc-io/laconicd/pulls/112)
// See function RecordsFromAttributes (QueryValueToJSON call) in the registry keeper implementation (x/registry/keeper/keeper.go)
// {
// "Filter with tag (extant) (https://git.vdb.to/cerc-io/laconicd/issues/129)",
// &types.QueryRecordsRequest{
// Attributes: []*types.QueryRecordsRequest_KeyValueInput{
// {
// Key: "tags",
// // Value: &types.QueryRecordsRequest_ValueInput{
// // Value: &types.QueryRecordsRequest_ValueInput_String_{"tagA"},
// // },
// Value: &types.QueryRecordsRequest_ValueInput{
// Value: &types.QueryRecordsRequest_ValueInput_Array{Array: &types.QueryRecordsRequest_ArrayInput{
// Values: []*types.QueryRecordsRequest_ValueInput{
// {
// Value: &types.QueryRecordsRequest_ValueInput_String_{"tagA"},
// },
// },
// }},
// },
// // Throws: "Recursive query values are not supported"
// },
// },
// All: true,
// },
// true,
// false,
// 1,
// },
{
"Filter with tag (non-existent) (https://git.vdb.to/cerc-io/laconicd/issues/129)",
&types.QueryRecordsRequest{
Attributes: []*types.QueryRecordsRequest_KeyValueInput{
{
Key: "tags",
Value: &types.QueryRecordsRequest_ValueInput{
Value: &types.QueryRecordsRequest_ValueInput_String_{String_: "NOEXIST"},
},
},
},
All: true,
},
true,
false,
0,
},
{
"Filter test for key collision (https://git.vdb.to/cerc-io/laconicd/issues/122)",
&types.QueryRecordsRequest{
Attributes: []*types.QueryRecordsRequest_KeyValueInput{
{
Key: "typ",
Value: &types.QueryRecordsRequest_ValueInput{
Value: &types.QueryRecordsRequest_ValueInput_String_{String_: "eWebsiteRegistrationRecord"},
},
},
},
All: true,
},
true,
false,
0,
},
{
"Filter with attributes ServiceProviderRegistration",
&types.QueryRecordsRequest{
Attributes: []*types.QueryRecordsRequest_KeyValueInput{
{
Key: "x500state_name",
Value: &types.QueryRecordsRequest_ValueInput{
Value: &types.QueryRecordsRequest_ValueInput_String_{String_: "california"},
},
},
},
All: true,
},
true,
false,
1,
},
}
for _, test := range testCases {
kts.Run(fmt.Sprintf("Case %s ", test.msg), func() {
if test.createRecords {
for _, example := range examples {
filePath, err := filepath.Abs(example)
sr.NoError(err)
payloadType, err := cli.GetPayloadFromFile(filePath)
sr.NoError(err)
payload := payloadType.ToPayload()
record, err := kts.RegistryKeeper.SetRecord(ctx, types.MsgSetRecord{
BondId: kts.bond.GetId(),
Signer: kts.accounts[0].String(),
Payload: payload,
})
sr.NoError(err)
sr.NotNil(record.Id)
}
}
resp, err := queryClient.Records(context.Background(), test.req)
if test.expErr {
kts.Error(err)
} else {
sr.NoError(err)
sr.Equal(test.noOfRecords, len(resp.GetRecords()))
if test.createRecords && test.noOfRecords > 0 {
recordId = resp.GetRecords()[0].GetId()
sr.NotZero(resp.GetRecords())
sr.Equal(resp.GetRecords()[0].GetBondId(), kts.bond.GetId())
for _, record := range resp.GetRecords() {
recAttr := helpers.MustUnmarshalJSON[types.AttributeMap](record.Attributes)
for _, attr := range test.req.GetAttributes() {
enc, err := registryKeeper.QueryValueToJSON(attr.Value)
sr.NoError(err)
av := helpers.MustUnmarshalJSON[any](enc)
if nil != av && nil != recAttr[attr.Key] &&
reflect.Slice == reflect.TypeOf(recAttr[attr.Key]).Kind() &&
reflect.Slice != reflect.TypeOf(av).Kind() {
found := false
allValues := recAttr[attr.Key].([]interface{})
for i := range allValues {
if av == allValues[i] {
fmt.Printf("Found %s in %s", allValues[i], recAttr[attr.Key])
found = true
}
}
sr.Equal(true, found, fmt.Sprintf("Unable to find %s in %s", av, recAttr[attr.Key]))
} else {
if attr.Key[:4] == "x500" {
sr.Equal(av, recAttr["x500"].(map[string]interface{})[attr.Key[4:]])
} else {
sr.Equal(av, recAttr[attr.Key])
}
}
}
}
}
}
})
}
// Get the records by record id
testCases1 := []struct {
msg string
req *types.QueryRecordByIdRequest
createRecord bool
expErr bool
noOfRecords int
}{
{
"Invalid Request without record id",
&types.QueryRecordByIdRequest{},
false,
true,
0,
},
{
"With Record ID",
&types.QueryRecordByIdRequest{
Id: recordId,
},
true,
false,
1,
},
}
for _, test := range testCases1 {
kts.Run(fmt.Sprintf("Case %s ", test.msg), func() {
resp, err := queryClient.GetRecord(context.Background(), test.req)
if test.expErr {
kts.Error(err)
} else {
sr.NoError(err)
sr.NotNil(resp.GetRecord())
if test.createRecord {
sr.Equal(resp.GetRecord().BondId, kts.bond.GetId())
sr.Equal(resp.GetRecord().Id, recordId)
}
}
})
}
// Get the records by record id
testCasesByBondID := []struct {
msg string
req *types.QueryRecordsByBondIdRequest
createRecord bool
expErr bool
noOfRecords int
}{
{
"Invalid Request without bond id",
&types.QueryRecordsByBondIdRequest{},
false,
true,
0,
},
{
"With Bond ID",
&types.QueryRecordsByBondIdRequest{
Id: kts.bond.GetId(),
},
true,
false,
1,
},
}
for _, test := range testCasesByBondID {
kts.Run(fmt.Sprintf("Case %s ", test.msg), func() {
resp, err := queryClient.GetRecordsByBondId(context.Background(), test.req)
if test.expErr {
sr.Zero(resp.GetRecords())
} else {
sr.NoError(err)
sr.NotNil(resp.GetRecords())
if test.createRecord {
sr.NotZero(resp.GetRecords())
sr.Equal(resp.GetRecords()[0].GetBondId(), kts.bond.GetId())
}
}
})
}
}
func (kts *KeeperTestSuite) TestGrpcQueryRegistryModuleBalance() {
queryClient, ctx := kts.queryClient, kts.SdkCtx
sr := kts.Require()
examples := []string{
"../../data/examples/service_provider_example.yml",
"../../data/examples/website_registration_example.yml",
}
testCases := []struct {
msg string
req *types.QueryGetRegistryModuleBalanceRequest
createRecords bool
expErr bool
noOfRecords int
}{
{
"Get Module Balance",
&types.QueryGetRegistryModuleBalanceRequest{},
true,
false,
1,
},
}
for _, test := range testCases {
kts.Run(fmt.Sprintf("Case %s ", test.msg), func() {
if test.createRecords {
for _, example := range examples {
filePath, err := filepath.Abs(example)
sr.NoError(err)
payloadType, err := cli.GetPayloadFromFile(filePath)
sr.NoError(err)
payload := payloadType.ToPayload()
record, err := kts.RegistryKeeper.SetRecord(ctx, types.MsgSetRecord{
BondId: kts.bond.GetId(),
Signer: kts.accounts[0].String(),
Payload: payload,
})
sr.NoError(err)
sr.NotNil(record.Id)
}
}
resp, err := queryClient.GetRegistryModuleBalance(context.Background(), test.req)
if test.expErr {
kts.Error(err)
} else {
sr.NoError(err)
sr.Equal(test.noOfRecords, len(resp.GetBalances()))
if test.createRecords {
balance := resp.GetBalances()[0]
sr.Equal(balance.AccountName, types.RecordRentModuleAccountName)
}
}
})
}
}
func (kts *KeeperTestSuite) TestGrpcQueryWhoIs() {
queryClient, ctx := kts.queryClient, kts.SdkCtx
sr := kts.Require()
authorityName := "TestGrpcQueryWhoIs"
testCases := []struct {
msg string
req *types.QueryWhoisRequest
createName bool
expErr bool
noOfRecords int
}{
{
"Invalid Request without name",
&types.QueryWhoisRequest{},
false,
true,
1,
},
{
"Success",
&types.QueryWhoisRequest{},
true,
false,
1,
},
}
for _, test := range testCases {
kts.Run(fmt.Sprintf("Case %s ", test.msg), func() {
if test.createName {
err := kts.RegistryKeeper.ReserveAuthority(ctx, types.MsgReserveAuthority{
Name: authorityName,
Signer: kts.accounts[0].String(),
Owner: kts.accounts[0].String(),
})
sr.NoError(err)
test.req = &types.QueryWhoisRequest{Name: authorityName}
}
resp, err := queryClient.Whois(context.Background(), test.req)
if test.expErr {
kts.Error(err)
sr.Nil(resp)
} else {
sr.NoError(err)
if test.createName {
nameAuth := resp.NameAuthority
sr.NotNil(nameAuth)
sr.Equal(nameAuth.OwnerAddress, kts.accounts[0].String())
sr.Equal(types.AuthorityActive, nameAuth.Status)
}
}
})
}
}