tests cleanup

cleanup
This commit is contained in:
rigelrozanski 2017-03-23 20:51:50 -04:00 committed by Rigel Rozanski
parent 16ff0ccf4f
commit 0720a03dae
12 changed files with 566 additions and 629 deletions

View File

@ -6,6 +6,8 @@ import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
abci "github.com/tendermint/abci/types"
"github.com/tendermint/basecoin/types"
"github.com/tendermint/go-crypto"
@ -13,11 +15,6 @@ import (
eyes "github.com/tendermint/merkleeyes/client"
)
//TODO:
//Query -
//Commit - see if commit works before and after
/////////////////////
// Testing functions
@ -70,157 +67,172 @@ func TestSetOption(t *testing.T) {
assert.NotEqual(res, "Success")
}
//////////////////////// TxTest
type testValues struct {
t *testing.T
app *Basecoin
accsFoo []types.PrivAccount
accsBar []types.PrivAccount
}
func (tv *testValues) acc2app(acc types.Account) {
accBytes, err := json.Marshal(acc)
require.Nil(tv.t, err)
res := tv.app.SetOption("base/account", string(accBytes))
require.EqualValues(tv.t, res, "Success")
}
func (tv *testValues) appInit() {
tv.accsFoo = makeAccs([]string{"foo"})
tv.accsBar = makeAccs([]string{"bar"})
eyesCli := eyes.NewLocalClient("", 0)
tv.app = NewBasecoin(eyesCli)
res := tv.app.SetOption("base/chain_id", chainID)
require.EqualValues(tv.t, res, "Success")
tv.acc2app(tv.accsFoo[0].Account)
tv.acc2app(tv.accsBar[0].Account)
resabci := tv.app.Commit()
require.True(tv.t, resabci.IsOK(), resabci)
}
func accs2TxInputs(accs []types.PrivAccount, seq int) []types.TxInput {
var txs []types.TxInput
for _, acc := range accs {
tx := types.NewTxInput(
acc.Account.PubKey,
types.Coins{{"mycoin", 5}},
seq)
txs = append(txs, tx)
}
return txs
}
//turn a list of accounts into basic list of transaction outputs
func accs2TxOutputs(accs []types.PrivAccount) []types.TxOutput {
var txs []types.TxOutput
for _, acc := range accs {
tx := types.TxOutput{
acc.Account.PubKey.Address(),
types.Coins{{"mycoin", 4}}}
txs = append(txs, tx)
}
return txs
}
func (tv testValues) getTx(seq int) *types.SendTx {
txs := &types.SendTx{
Gas: 0,
Fee: types.Coin{"mycoin", 1},
Inputs: accs2TxInputs(tv.accsFoo, seq),
Outputs: accs2TxOutputs(tv.accsBar),
}
signBytes := txs.SignBytes(chainID)
for i, _ := range txs.Inputs {
txs.Inputs[i].Signature = crypto.SignatureS{tv.accsFoo[i].Sign(signBytes)}
}
return txs
}
func (tv testValues) exec(tx *types.SendTx, checkTx bool) (res abci.Result, foo, fooExp, bar, barExp types.Coins) {
initBalFoo := tv.app.GetState().GetAccount(tv.accsFoo[0].Account.PubKey.Address()).Balance
initBalBar := tv.app.GetState().GetAccount(tv.accsBar[0].Account.PubKey.Address()).Balance
txBytes := []byte(wire.BinaryBytes(struct {
types.Tx `json:"unwrap"`
}{tx}))
if checkTx {
res = tv.app.CheckTx(txBytes)
} else {
res = tv.app.DeliverTx(txBytes)
}
endBalFoo := tv.app.GetState().GetAccount(tv.accsFoo[0].Account.PubKey.Address()).Balance
endBalBar := tv.app.GetState().GetAccount(tv.accsBar[0].Account.PubKey.Address()).Balance
decrBalFooExp := tx.Outputs[0].Coins.Plus(types.Coins{tx.Fee})
return res, endBalFoo, initBalFoo.Minus(decrBalFooExp), endBalBar, initBalBar.Plus(tx.Outputs[0].Coins)
}
//CheckTx - bad bytes, bad tx, good tx.
//DeliverTx - bad bytes, bad tx, good tx.
func TestTx(t *testing.T) {
assert := assert.New(t)
var accsFoo, accsBar []types.PrivAccount
var app *Basecoin
acc2app := func(acc types.Account) {
accBytes, err := json.Marshal(acc)
assert.Nil(err)
res := app.SetOption("base/account", string(accBytes))
assert.EqualValues(res, "Success")
}
reset := func() {
accsFoo = makeAccs([]string{"foo"})
accsBar = makeAccs([]string{"bar"})
eyesCli := eyes.NewLocalClient("", 0)
app = NewBasecoin(eyesCli)
res := app.SetOption("base/chain_id", chainID)
assert.EqualValues(res, "Success")
acc2app(accsFoo[0].Account)
acc2app(accsBar[0].Account)
resabci := app.Commit()
assert.True(resabci.IsOK(), resabci)
}
reset()
accs2TxInputs := func(accs []types.PrivAccount, seq int) []types.TxInput {
var txs []types.TxInput
for _, acc := range accs {
tx := types.NewTxInput(
acc.Account.PubKey,
types.Coins{{"mycoin", 5}},
seq)
txs = append(txs, tx)
}
return txs
}
//turn a list of accounts into basic list of transaction outputs
accs2TxOutputs := func(accs []types.PrivAccount) []types.TxOutput {
var txs []types.TxOutput
for _, acc := range accs {
tx := types.TxOutput{
acc.Account.PubKey.Address(),
types.Coins{{"mycoin", 4}}}
txs = append(txs, tx)
}
return txs
}
getTx := func(seq int) *types.SendTx {
txs := &types.SendTx{
Gas: 0,
Fee: types.Coin{"mycoin", 1},
Inputs: accs2TxInputs(accsFoo, seq),
Outputs: accs2TxOutputs(accsBar),
}
signBytes := txs.SignBytes(chainID)
for i, _ := range txs.Inputs {
txs.Inputs[i].Signature = crypto.SignatureS{accsFoo[i].Sign(signBytes)}
}
return txs
}
txs := getTx(1)
exec := func(checkTx bool) (res abci.Result, foo, fooExp, bar, barExp types.Coins) {
initBalFoo := app.GetState().GetAccount(accsFoo[0].Account.PubKey.Address()).Balance
initBalBar := app.GetState().GetAccount(accsBar[0].Account.PubKey.Address()).Balance
txBytes := []byte(wire.BinaryBytes(struct {
types.Tx `json:"unwrap"`
}{txs}))
if checkTx {
res = app.CheckTx(txBytes)
} else {
res = app.DeliverTx(txBytes)
}
endBalFoo := app.GetState().GetAccount(accsFoo[0].Account.PubKey.Address()).Balance
endBalBar := app.GetState().GetAccount(accsBar[0].Account.PubKey.Address()).Balance
decrBalFooExp := txs.Outputs[0].Coins.Plus(types.Coins{txs.Fee})
return res, endBalFoo, initBalFoo.Minus(decrBalFooExp), endBalBar, initBalBar.Plus(txs.Outputs[0].Coins)
}
tv := testValues{t: t}
tv.appInit()
//Bad Balance
accsFoo[0].Balance = types.Coins{{"mycoin", 2}}
acc2app(accsFoo[0].Account)
res, _, _, _, _ := exec(true)
tv.accsFoo[0].Balance = types.Coins{{"mycoin", 2}}
tv.acc2app(tv.accsFoo[0].Account)
res, _, _, _, _ := tv.exec(tv.getTx(1), true)
assert.True(res.IsErr(), fmt.Sprintf("ExecTx/Bad CheckTx: Expected error return from ExecTx, returned: %v", res))
res, foo, fooexp, bar, barexp := exec(false)
res, foo, fooexp, bar, barexp := tv.exec(tv.getTx(1), false)
assert.True(res.IsErr(), fmt.Sprintf("ExecTx/Bad DeliverTx: Expected error return from ExecTx, returned: %v", res))
assert.True(!foo.IsEqual(fooexp), fmt.Sprintf("ExecTx/Bad DeliverTx: shouldn't be equal, foo: %v, fooExp: %v", foo, fooexp))
assert.True(!bar.IsEqual(barexp), fmt.Sprintf("ExecTx/Bad DeliverTx: shouldn't be equal, bar: %v, barExp: %v", bar, barexp))
//Regular CheckTx
reset()
res, _, _, _, _ = exec(true)
tv.appInit()
res, _, _, _, _ = tv.exec(tv.getTx(1), true)
assert.True(res.IsOK(), fmt.Sprintf("ExecTx/Good CheckTx: Expected OK return from ExecTx, Error: %v", res))
//Regular DeliverTx
reset()
res, foo, fooexp, bar, barexp = exec(false)
tv.appInit()
res, foo, fooexp, bar, barexp = tv.exec(tv.getTx(1), false)
assert.True(res.IsOK(), fmt.Sprintf("ExecTx/Good DeliverTx: Expected OK return from ExecTx, Error: %v", res))
assert.True(foo.IsEqual(fooexp), fmt.Sprintf("ExecTx/good DeliverTx: unexpected change in input coins, foo: %v, fooExp: %v", foo, fooexp))
assert.True(bar.IsEqual(barexp), fmt.Sprintf("ExecTx/good DeliverTx: unexpected change in output coins, bar: %v, barExp: %v", bar, barexp))
}
///////////////////////
//test Commit/Query
//After Delivered TX foo should have no more coins to send,
// but because the state hasn't yet been committed, checkTx should still
// pass but after a commit it shouldn't
func TestQuery(t *testing.T) {
assert := assert.New(t)
tv := testValues{t: t}
tv.appInit()
reset()
txs = getTx(1)
res, _, _, _, _ = exec(false)
res, _, _, _, _ := tv.exec(tv.getTx(1), false)
assert.True(res.IsOK(), fmt.Sprintf("Commit, CheckTx: Expected OK return from CheckTx, Error: %v", res))
txs = getTx(2)
res, _, _, _, _ = exec(true)
assert.True(res.IsOK(), fmt.Sprintf("Commit, CheckTx: Expected OK return from CheckTx, Error: %v", res))
resQueryPreCommit := app.Query(abci.RequestQuery{
resQueryPreCommit := tv.app.Query(abci.RequestQuery{
Path: "/account",
Data: accsFoo[0].Account.PubKey.Address(),
Data: tv.accsFoo[0].Account.PubKey.Address(),
})
res = app.Commit()
res = tv.app.Commit()
assert.True(res.IsOK(), res)
resQueryPostCommit := app.Query(abci.RequestQuery{
resQueryPostCommit := tv.app.Query(abci.RequestQuery{
Path: "/account",
Data: accsFoo[0].Account.PubKey.Address(),
Data: tv.accsFoo[0].Account.PubKey.Address(),
})
fmt.Println(resQueryPreCommit)
fmt.Println(resQueryPostCommit)
assert.NotEqual(resQueryPreCommit, resQueryPostCommit, "Query should change before/after commit")
txs = getTx(3)
res, _, _, _, _ = exec(true)
assert.True(res.IsErr(), fmt.Sprintf("Commit, CheckTx: Expected error return from CheckTx, returned: %v", res))
}
func TestCommit(t *testing.T) {
assert := assert.New(t)
tv := testValues{t: t}
tv.appInit()
//After Delivered TX foo should have no more coins to send,
// but because the state hasn't yet been committed, checkTx should still
// pass but after a commit it shouldn't
res, _, _, _, _ := tv.exec(tv.getTx(1), false)
assert.True(res.IsOK(), fmt.Sprintf("Commit, CheckTx: Expected OK return from CheckTx, Error: %v", res))
res, _, _, _, _ = tv.exec(tv.getTx(2), true)
assert.True(res.IsOK(), fmt.Sprintf("Commit, CheckTx: Expected OK return from CheckTx, Error: %v", res))
res = tv.app.Commit()
assert.True(res.IsOK(), res)
res, _, _, _, _ = tv.exec(tv.getTx(3), true)
assert.True(res.IsErr(), fmt.Sprintf("Commit, CheckTx: Expected error return from CheckTx, returned: %v", res))
}

View File

@ -9,6 +9,7 @@ import (
)
func TestHex(t *testing.T) {
assert := assert.New(t)
//test isHex
hexNoPrefix := hex.EncodeToString([]byte("foobar"))
@ -16,27 +17,17 @@ func TestHex(t *testing.T) {
str := "foobar"
strWPrefix := "0xfoobar"
//define the list of coin tests
var testList = []struct {
testPass bool
errMsg string
}{
{isHex(hexWPrefix), "isHex not identifying hex with 0x prefix"},
{!isHex(hexNoPrefix), "isHex shouldn't identify hex without 0x prefix"},
{!isHex(str), "isHex shouldn't identify non-hex string"},
{!isHex(strWPrefix), "isHex shouldn't identify non-hex string with 0x prefix"},
{StripHex(hexWPrefix) == hexNoPrefix, "StripHex doesn't remove first two characters"},
}
//execute the tests
for _, tl := range testList {
assert.True(t, tl.testPass, tl.errMsg)
}
assert.True(isHex(hexWPrefix), "isHex not identifying hex with 0x prefix")
assert.False(isHex(hexNoPrefix), "isHex shouldn't identify hex without 0x prefix")
assert.False(isHex(str), "isHex shouldn't identify non-hex string")
assert.False(isHex(strWPrefix), "isHex shouldn't identify non-hex string with 0x prefix")
assert.True(StripHex(hexWPrefix) == hexNoPrefix, "StripHex doesn't remove first two characters")
}
//Test the parse coin and parse coins functionality
func TestParse(t *testing.T) {
assert := assert.New(t)
makeCoin := func(str string) types.Coin {
coin, err := ParseCoin(str)
@ -54,27 +45,16 @@ func TestParse(t *testing.T) {
return coin
}
//define the list of coin tests
var testList = []struct {
testPass bool
errMsg string
}{
//testing ParseCoin Function
{types.Coin{} == makeCoin(""), "parseCoin makes bad empty coin"},
{types.Coin{"fooCoin", 1} == makeCoin("1fooCoin"), "parseCoin makes bad coins"},
{types.Coin{"barCoin", 10} == makeCoin("10 barCoin"), "parseCoin makes bad coins"},
//testing ParseCoin Function
assert.Equal(types.Coin{}, makeCoin(""), "parseCoin makes bad empty coin")
assert.Equal(types.Coin{"fooCoin", 1}, makeCoin("1fooCoin"), "parseCoin makes bad coins")
assert.Equal(types.Coin{"barCoin", 10}, makeCoin("10 barCoin"), "parseCoin makes bad coins")
//testing ParseCoins Function
{types.Coins{{"fooCoin", 1}}.IsEqual(makeCoins("1fooCoin")),
"parseCoins doesn't parse a single coin"},
{types.Coins{{"barCoin", 99}, {"fooCoin", 1}}.IsEqual(makeCoins("99barCoin,1fooCoin")),
"parseCoins doesn't properly parse two coins"},
{types.Coins{{"barCoin", 99}, {"fooCoin", 1}}.IsEqual(makeCoins("99 barCoin, 1 fooCoin")),
"parseCoins doesn't properly parse two coins which use spaces"},
}
//execute the tests
for _, tl := range testList {
assert.True(t, tl.testPass, tl.errMsg)
}
//testing ParseCoins Function
assert.True(types.Coins{{"fooCoin", 1}}.IsEqual(makeCoins("1fooCoin")),
"parseCoins doesn't parse a single coin")
assert.True(types.Coins{{"barCoin", 99}, {"fooCoin", 1}}.IsEqual(makeCoins("99barCoin,1fooCoin")),
"parseCoins doesn't properly parse two coins")
assert.True(types.Coins{{"barCoin", 99}, {"fooCoin", 1}}.IsEqual(makeCoins("99 barCoin, 1 fooCoin")),
"parseCoins doesn't properly parse two coins which use spaces")
}

View File

@ -15,6 +15,7 @@ import (
)
func TestCounterPlugin(t *testing.T) {
assert := assert.New(t)
// Basecoin initialization
eyesCli := eyescli.NewLocalClient("", 0)
@ -64,39 +65,40 @@ func TestCounterPlugin(t *testing.T) {
// Test a basic send, no fee
res := DeliverCounterTx(0, types.Coin{}, types.Coins{{"", 1}}, 1, types.Coins{})
assert.True(t, res.IsOK(), res.String())
assert.True(res.IsOK(), res.String())
// Test fee prevented transaction
res = DeliverCounterTx(0, types.Coin{"", 2}, types.Coins{{"", 1}}, 2, types.Coins{})
assert.True(t, res.IsErr(), res.String())
assert.True(res.IsErr(), res.String())
// Test input equals fee
res = DeliverCounterTx(0, types.Coin{"", 2}, types.Coins{{"", 2}}, 2, types.Coins{})
assert.True(t, res.IsOK(), res.String())
assert.True(res.IsOK(), res.String())
// Test more input than fee
res = DeliverCounterTx(0, types.Coin{"", 2}, types.Coins{{"", 3}}, 3, types.Coins{})
assert.True(t, res.IsOK(), res.String())
assert.True(res.IsOK(), res.String())
// Test input equals fee+appFee
res = DeliverCounterTx(0, types.Coin{"", 1}, types.Coins{{"", 3}, {"gold", 1}}, 4, types.Coins{{"", 2}, {"gold", 1}})
assert.True(t, res.IsOK(), res.String())
assert.True(res.IsOK(), res.String())
// Test fee+appFee prevented transaction, not enough ""
res = DeliverCounterTx(0, types.Coin{"", 1}, types.Coins{{"", 2}, {"gold", 1}}, 5, types.Coins{{"", 2}, {"gold", 1}})
assert.True(t, res.IsErr(), res.String())
assert.True(res.IsErr(), res.String())
// Test fee+appFee prevented transaction, not enough "gold"
res = DeliverCounterTx(0, types.Coin{"", 1}, types.Coins{{"", 3}, {"gold", 1}}, 5, types.Coins{{"", 2}, {"gold", 2}})
assert.True(t, res.IsErr(), res.String())
assert.True(res.IsErr(), res.String())
// Test more input than fee, more ""
res = DeliverCounterTx(0, types.Coin{"", 1}, types.Coins{{"", 4}, {"gold", 1}}, 6, types.Coins{{"", 2}, {"gold", 1}})
assert.True(t, res.IsOK(), res.String())
assert.True(res.IsOK(), res.String())
// Test more input than fee, more "gold"
res = DeliverCounterTx(0, types.Coin{"", 1}, types.Coins{{"", 3}, {"gold", 2}}, 7, types.Coins{{"", 2}, {"gold", 1}})
assert.True(t, res.IsOK(), res.String())
assert.True(res.IsOK(), res.String())
// REF: DeliverCounterTx(gas, fee, inputCoins, inputSequence, appFee) {w
// REF: DeliverCounterTx(gas, fee, inputCoins, inputSequence, appFee) {
}

View File

@ -65,6 +65,7 @@ func (pas PrivAccountsByAddress) Swap(i, j int) {
//--------------------------------------------------------------------------------
func TestIBCPlugin(t *testing.T) {
assert := assert.New(t)
eyesClient := eyes.NewLocalClient("", 0)
store := types.NewKVCache(eyesClient)
@ -88,7 +89,7 @@ func TestIBCPlugin(t *testing.T) {
Genesis: "<THIS IS NOT JSON>",
},
}}))
assert.Equal(t, IBCCodeEncodingError, res.Code)
assert.Equal(IBCCodeEncodingError, res.Code)
t.Log(">>", strings.Join(store.GetLogLines(), "\n"))
store.ClearLogLines()
@ -99,7 +100,7 @@ func TestIBCPlugin(t *testing.T) {
Genesis: string(genDocJSON_1),
},
}}))
assert.True(t, res.IsOK(), res.Log)
assert.True(res.IsOK(), res.Log)
t.Log(">>", strings.Join(store.GetLogLines(), "\n"))
store.ClearLogLines()
@ -110,7 +111,7 @@ func TestIBCPlugin(t *testing.T) {
Genesis: string(genDocJSON_1),
},
}}))
assert.Equal(t, IBCCodeChainAlreadyExists, res.Code, res.Log)
assert.Equal(IBCCodeChainAlreadyExists, res.Code, res.Log)
t.Log(">>", strings.Join(store.GetLogLines(), "\n"))
store.ClearLogLines()
@ -125,7 +126,7 @@ func TestIBCPlugin(t *testing.T) {
res = ibcPlugin.RunTx(store, ctx, wire.BinaryBytes(struct{ IBCTx }{IBCPacketCreateTx{
Packet: packet,
}}))
assert.Equal(t, abci.CodeType_OK, res.Code, res.Log)
assert.Equal(abci.CodeType_OK, res.Code, res.Log)
t.Log(">>", strings.Join(store.GetLogLines(), "\n"))
store.ClearLogLines()
@ -133,7 +134,7 @@ func TestIBCPlugin(t *testing.T) {
res = ibcPlugin.RunTx(store, ctx, wire.BinaryBytes(struct{ IBCTx }{IBCPacketCreateTx{
Packet: packet,
}}))
assert.Equal(t, IBCCodePacketAlreadyExists, res.Code, res.Log)
assert.Equal(IBCCodePacketAlreadyExists, res.Code, res.Log)
t.Log(">>", strings.Join(store.GetLogLines(), "\n"))
store.ClearLogLines()
@ -175,7 +176,7 @@ func TestIBCPlugin(t *testing.T) {
Header: header,
Commit: commit,
}}))
assert.Equal(t, abci.CodeType_OK, res.Code, res.Log)
assert.Equal(abci.CodeType_OK, res.Code, res.Log)
t.Log(">>", strings.Join(store.GetLogLines(), "\n"))
store.ClearLogLines()
@ -190,10 +191,10 @@ func TestIBCPlugin(t *testing.T) {
Data: packetKey,
Prove: true,
})
assert.Nil(t, err)
assert.Nil(err)
var proof *merkle.IAVLProof
err = wire.ReadBinaryBytes(resQuery.Proof, &proof)
assert.Nil(t, err)
assert.Nil(err)
// Post a packet
res = ibcPlugin.RunTx(store, ctx, wire.BinaryBytes(struct{ IBCTx }{IBCPacketPostTx{
@ -202,12 +203,13 @@ func TestIBCPlugin(t *testing.T) {
Packet: packet,
Proof: proof,
}}))
assert.Equal(t, abci.CodeType_OK, res.Code, res.Log)
assert.Equal(abci.CodeType_OK, res.Code, res.Log)
t.Log(">>", strings.Join(store.GetLogLines(), "\n"))
store.ClearLogLines()
}
func TestIBCPluginBadCommit(t *testing.T) {
assert := assert.New(t)
eyesClient := eyes.NewLocalClient("", 0)
store := types.NewKVCache(eyesClient)
@ -231,7 +233,7 @@ func TestIBCPluginBadCommit(t *testing.T) {
Genesis: string(genDocJSON_1),
},
}}))
assert.True(t, res.IsOK(), res.Log)
assert.True(res.IsOK(), res.Log)
t.Log(">>", strings.Join(store.GetLogLines(), "\n"))
store.ClearLogLines()
@ -273,13 +275,14 @@ func TestIBCPluginBadCommit(t *testing.T) {
Header: header,
Commit: commit,
}}))
assert.Equal(t, IBCCodeInvalidCommit, res.Code, res.Log)
assert.Equal(IBCCodeInvalidCommit, res.Code, res.Log)
t.Log(">>", strings.Join(store.GetLogLines(), "\n"))
store.ClearLogLines()
}
func TestIBCPluginBadProof(t *testing.T) {
assert := assert.New(t)
eyesClient := eyes.NewLocalClient("", 0)
store := types.NewKVCache(eyesClient)
@ -303,7 +306,7 @@ func TestIBCPluginBadProof(t *testing.T) {
Genesis: string(genDocJSON_1),
},
}}))
assert.True(t, res.IsOK(), res.Log)
assert.True(res.IsOK(), res.Log)
t.Log(">>", strings.Join(store.GetLogLines(), "\n"))
store.ClearLogLines()
@ -318,7 +321,7 @@ func TestIBCPluginBadProof(t *testing.T) {
res = ibcPlugin.RunTx(store, ctx, wire.BinaryBytes(struct{ IBCTx }{IBCPacketCreateTx{
Packet: packet,
}}))
assert.Equal(t, abci.CodeType_OK, res.Code, res.Log)
assert.Equal(abci.CodeType_OK, res.Code, res.Log)
t.Log(">>", strings.Join(store.GetLogLines(), "\n"))
store.ClearLogLines()
@ -360,7 +363,7 @@ func TestIBCPluginBadProof(t *testing.T) {
Header: header,
Commit: commit,
}}))
assert.Equal(t, abci.CodeType_OK, res.Code, res.Log)
assert.Equal(abci.CodeType_OK, res.Code, res.Log)
t.Log(">>", strings.Join(store.GetLogLines(), "\n"))
store.ClearLogLines()
@ -375,10 +378,10 @@ func TestIBCPluginBadProof(t *testing.T) {
Data: packetKey,
Prove: true,
})
assert.Nil(t, err)
assert.Nil(err)
var proof *merkle.IAVLProof
err = wire.ReadBinaryBytes(resQuery.Proof, &proof)
assert.Nil(t, err)
assert.Nil(err)
// Mutate the proof
proof.InnerNodes[0].Height += 1
@ -390,7 +393,7 @@ func TestIBCPluginBadProof(t *testing.T) {
Packet: packet,
Proof: proof,
}}))
assert.Equal(t, IBCCodeInvalidProof, res.Code, res.Log)
assert.Equal(IBCCodeInvalidProof, res.Code, res.Log)
t.Log(">>", strings.Join(store.GetLogLines(), "\n"))
store.ClearLogLines()
}

View File

@ -15,8 +15,8 @@ Address: D9B727742AA29FA638DC63D70813C976014C4CE0
*/
func main() {
tAcc := tests.PrivAccountFromSecret("test")
fmt.Println("PrivKey:", fmt.Sprintf("%X", tAcc.PrivKey.Bytes()))
fmt.Println("PubKey:", fmt.Sprintf("%X", tAcc.Account.PubKey.Bytes()))
fmt.Println("Address:", fmt.Sprintf("%X", tAcc.Account.PubKey.Address()))
fmt.Printf("PrivKey:%X\n", tAcc.PrivKey.Bytes())
fmt.Printf("PubKey:%X\n", tAcc.Account.PubKey.Bytes())
fmt.Printf("Address:%X\n", tAcc.Account.PubKey.Address())
fmt.Println(string(wire.JSONBytesPretty(tAcc)))
}

View File

@ -11,339 +11,319 @@ import (
"github.com/tendermint/go-crypto"
)
func TestExecution(t *testing.T) {
//States and Stores for tests
var (
store types.KVStore
state *State
accsFoo, accsBar, accsFooBar, accsDup []types.PrivAccount
chainID string = "test_chain_id"
)
//States and Stores for tests
var store types.KVStore
var state *State
var accsFoo, accsBar, accsFooBar, accsDup []types.PrivAccount
chainID := "test_chain_id"
func makeAccs(secrets []string) (accs []types.PrivAccount) {
makeAccs := func(secrets []string) (accs []types.PrivAccount) {
for _, secret := range secrets {
privAcc := types.PrivAccountFromSecret(secret)
privAcc.Account.Balance = types.Coins{{"mycoin", 1000}}
accs = append(accs, privAcc)
}
return accs
for _, secret := range secrets {
privAcc := types.PrivAccountFromSecret(secret)
privAcc.Account.Balance = types.Coins{{"mycoin", 1000}}
accs = append(accs, privAcc)
}
return accs
}
acc2State := func(accs []types.PrivAccount) {
for _, acc := range accs {
state.SetAccount(acc.Account.PubKey.Address(), &acc.Account)
}
func acc2State(accs []types.PrivAccount) {
for _, acc := range accs {
state.SetAccount(acc.Account.PubKey.Address(), &acc.Account)
}
}
//each tx input signs the tx bytes
signSend := func(tx *types.SendTx, accs []types.PrivAccount) {
signBytes := tx.SignBytes(chainID)
for i, _ := range tx.Inputs {
tx.Inputs[i].Signature = crypto.SignatureS{accs[i].Sign(signBytes)}
}
//each tx input signs the tx bytes
func signSend(tx *types.SendTx, accs []types.PrivAccount) {
signBytes := tx.SignBytes(chainID)
for i, _ := range tx.Inputs {
tx.Inputs[i].Signature = crypto.SignatureS{accs[i].Sign(signBytes)}
}
}
//turn a list of accounts into basic list of transaction inputs
accs2TxInputs := func(accs []types.PrivAccount) []types.TxInput {
var txs []types.TxInput
for _, acc := range accs {
tx := types.NewTxInput(
acc.Account.PubKey,
types.Coins{{"mycoin", 5}},
1)
txs = append(txs, tx)
}
return txs
//turn a list of accounts into basic list of transaction inputs
func accs2TxInputs(accs []types.PrivAccount) []types.TxInput {
var txs []types.TxInput
for _, acc := range accs {
tx := types.NewTxInput(
acc.Account.PubKey,
types.Coins{{"mycoin", 5}},
1)
txs = append(txs, tx)
}
return txs
}
//turn a list of accounts into basic list of transaction outputs
accs2TxOutputs := func(accs []types.PrivAccount) []types.TxOutput {
var txs []types.TxOutput
for _, acc := range accs {
tx := types.TxOutput{
acc.Account.PubKey.Address(),
types.Coins{{"mycoin", 4}}}
txs = append(txs, tx)
}
return txs
//turn a list of accounts into basic list of transaction outputs
func accs2TxOutputs(accs []types.PrivAccount) []types.TxOutput {
var txs []types.TxOutput
for _, acc := range accs {
tx := types.TxOutput{
acc.Account.PubKey.Address(),
types.Coins{{"mycoin", 4}}}
txs = append(txs, tx)
}
return txs
}
//reset the store/state/Inputs
reset := func() {
accsFoo = makeAccs([]string{"foo"})
accsBar = makeAccs([]string{"bar"})
accsFooBar = makeAccs([]string{"foo", "bar"})
accsDup = makeAccs([]string{"foo", "foo", "foo"})
//reset the store/state/Inputs
func reset() {
accsFoo = makeAccs([]string{"foo"})
accsBar = makeAccs([]string{"bar"})
accsFooBar = makeAccs([]string{"foo", "bar"})
accsDup = makeAccs([]string{"foo", "foo", "foo"})
store = types.NewMemKVStore()
state = NewState(store)
state.SetChainID(chainID)
}
store = types.NewMemKVStore()
state = NewState(store)
state.SetChainID(chainID)
}
type er struct {
exp bool //assert true
msg string //msg is assert fails
}
func TestGetInputs(t *testing.T) {
assert := assert.New(t)
//define the test list
testList := []struct {
tester func() []er
}{
///////////////
//getInputs
//nil submissions
reset()
acc, res := getInputs(nil, nil)
assert.False(res.IsErr(), "getInputs: error on nil submission")
assert.Zero(len(acc), "getInputs: accounts returned on nil submission")
//nil submissions
{func() []er {
acc, res := getInputs(nil, nil)
return []er{
{!res.IsErr(), "getInputs: error on nil submission"},
{len(acc) == 0, "getInputs: accounts returned on nil submission"},
}
}},
//test getInputs for registered, non-registered account
reset()
txs := accs2TxInputs(accsFoo)
_, res = getInputs(state, txs)
assert.True(res.IsErr(), "getInputs: expected to getInput from registered Input")
//test getInputs for registered, non-registered account
{func() []er {
txs := accs2TxInputs(accsFoo)
_, res1 := getInputs(state, txs)
acc2State(accsFoo)
_, res2 := getInputs(state, txs)
return []er{
{res1.IsErr(), "getInputs: expected to getInput from registered Input"},
{!res2.IsErr(), "getInputs: expected to getInput from registered Input"},
}
}},
acc2State(accsFoo)
_, res = getInputs(state, txs)
assert.False(res.IsErr(), "getInputs: expected to getInput from registered Input")
//test sending duplicate accounts
{func() []er {
acc2State(accsDup)
txs := accs2TxInputs(accsDup)
_, res := getInputs(state, txs)
return []er{{res.IsErr(), "getInputs: expected error when sending duplicate accounts"}}
}},
//test sending duplicate accounts
reset()
acc2State(accsDup)
txs = accs2TxInputs(accsDup)
_, res = getInputs(state, txs)
assert.True(res.IsErr(), "getInputs: expected error when sending duplicate accounts")
}
///////////////////
//getOrMakeOutputs
func TestGetOrMakeOutputs(t *testing.T) {
assert := assert.New(t)
//nil submissions
{func() []er {
acc, res := getOrMakeOutputs(nil, nil, nil)
return []er{
{!res.IsErr(), "getOrMakeOutputs: error on nil submission"},
{len(acc) == 0, "getOrMakeOutputs: accounts returned on nil submission"},
}
}},
//nil submissions
reset()
acc, res := getOrMakeOutputs(nil, nil, nil)
assert.False(res.IsErr(), "getOrMakeOutputs: error on nil submission")
assert.Zero(len(acc), "getOrMakeOutputs: accounts returned on nil submission")
//test sending duplicate accounts
{func() []er {
txs := accs2TxOutputs(accsDup)
_, res := getOrMakeOutputs(state, nil, txs)
return []er{{res.IsErr(), "getOrMakeOutputs: expected error when sending duplicate accounts"}}
}},
//test sending duplicate accounts
reset()
txs := accs2TxOutputs(accsDup)
_, res = getOrMakeOutputs(state, nil, txs)
assert.True(res.IsErr(), "getOrMakeOutputs: expected error when sending duplicate accounts")
//test sending to existing/new account account
{func() []er {
txs1 := accs2TxOutputs(accsFoo)
txs2 := accs2TxOutputs(accsBar)
//test sending to existing/new account account
reset()
txs1 := accs2TxOutputs(accsFoo)
txs2 := accs2TxOutputs(accsBar)
acc2State(accsFoo)
_, res1 := getOrMakeOutputs(state, nil, txs1)
mapRes2, res2 := getOrMakeOutputs(state, nil, txs2)
acc2State(accsFoo)
_, res = getOrMakeOutputs(state, nil, txs1)
assert.False(res.IsErr(), "getOrMakeOutputs: error when sending to existing account")
//test the map results
_, map2ok := mapRes2[string(txs2[0].Address)]
mapRes2, res := getOrMakeOutputs(state, nil, txs2)
assert.False(res.IsErr(), "getOrMakeOutputs: error when sending to new account")
return []er{
{!res1.IsErr(), "getOrMakeOutputs: error when sending to existing account"},
{!res2.IsErr(), "getOrMakeOutputs: error when sending to new account"},
{map2ok, "getOrMakeOutputs: account output does not contain new account map item"},
}
}},
//validate input basic
{func() []er {
txs := accs2TxInputs(accsFoo)
res1 := validateInputsBasic(txs)
txs[0].Coins[0].Amount = 0
res2 := validateInputsBasic(txs)
return []er{
{!res1.IsErr(), fmt.Sprintf("validateInputsBasic: expected no error on good tx input. Error: %v", res1.Error())},
{res2.IsErr(), "validateInputsBasic: expected error on bad tx input"},
}
}},
//validate inputs advanced
{func() []er {
txs := types.SendTx{
Gas: 0,
Fee: types.Coin{"mycoin", 1},
Inputs: accs2TxInputs(accsFooBar),
Outputs: accs2TxOutputs(accsBar),
}
acc2State(accsFooBar)
accMap, res1 := getInputs(state, txs.Inputs)
signBytes := txs.SignBytes(chainID)
//test bad case, unsigned
totalCoins, res2 := validateInputsAdvanced(accMap, signBytes, txs.Inputs)
//test good case sgined
signSend(&txs, accsFooBar)
totalCoins, res3 := validateInputsAdvanced(accMap, signBytes, txs.Inputs)
return []er{
{!res1.IsErr(), fmt.Sprintf("validateInputsAdvanced: error retrieving accMap. Error: %v", res1.Error())},
{res2.IsErr(), "validateInputsAdvanced: expected an error on an unsigned tx input"},
{!res3.IsErr(), fmt.Sprintf("validateInputsAdvanced: expected no error on good tx input. Error: %v", res3.Error())},
{totalCoins.IsEqual(txs.Inputs[0].Coins.Plus(txs.Inputs[1].Coins)), "ValidateInputsAdvanced: transaction total coins are not equal"},
}
}},
//validate input advanced
{func() []er {
txs := types.SendTx{
Gas: 0,
Fee: types.Coin{"mycoin", 1},
Inputs: accs2TxInputs(accsFooBar),
Outputs: accs2TxOutputs(accsBar),
}
acc2State(accsFooBar)
signBytes := txs.SignBytes(chainID)
//unsigned case
res1 := validateInputAdvanced(&accsFooBar[0].Account, signBytes, txs.Inputs[0])
//good signed case
signSend(&txs, accsFooBar)
res2 := validateInputAdvanced(&accsFooBar[0].Account, signBytes, txs.Inputs[0])
//bad sequence case
accsFooBar[0].Sequence = 2
signSend(&txs, accsFooBar)
res3 := validateInputAdvanced(&accsFooBar[0].Account, signBytes, txs.Inputs[0])
accsFooBar[0].Account.Sequence = 1 //restore sequence
//bad balance case
accsFooBar[1].Balance = types.Coins{{"mycoin", 2}}
signSend(&txs, accsFooBar)
res4 := validateInputAdvanced(&accsFooBar[0].Account, signBytes, txs.Inputs[0])
return []er{
{res1.IsErr(), "validateInputAdvanced: expected error on tx input without signature"},
{!res2.IsErr(), fmt.Sprintf("validateInputAdvanced: expected no error on good tx input. Error: %v", res1.Error())},
{res3.IsErr(), "validateInputAdvanced: expected error on tx input with bad sequence"},
{res4.IsErr(), "validateInputAdvanced: expected error on tx input with insufficient funds"},
}
}},
//validateOutputsBasic
{func() []er {
txs := accs2TxOutputs(accsFoo)
res1 := validateOutputsBasic(txs)
txs[0].Coins[0].Amount = 0
res2 := validateOutputsBasic(txs)
return []er{{!res1.IsErr(), fmt.Sprintf("validateOutputsBasic: expected no error on good tx input. Error: %v", res1.Error())},
{res2.IsErr(), fmt.Sprintf("validateInputBasic: expected error on bad tx inputi. Error: %v", res2.Error())}}
}},
//SumOutput
{func() []er {
txs := accs2TxOutputs(accsFooBar)
total := sumOutputs(txs)
return []er{{total.IsEqual(txs[0].Coins.Plus(txs[1].Coins)), "sumOutputs: total coins are not equal"}}
}},
//adjustByInputs/adjustByOutputs
//sending transaction from Foo to Bar
{func() []er {
initBalFoo := accsFooBar[0].Account.Balance
initBalBar := accsFooBar[1].Account.Balance
acc2State(accsFooBar)
txIn := accs2TxInputs(accsFoo)
txOut := accs2TxOutputs(accsBar)
accMap, _ := getInputs(state, txIn)
accMap, _ = getOrMakeOutputs(state, accMap, txOut)
adjustByInputs(state, accMap, txIn)
adjustByOutputs(state, accMap, txOut, false)
endBalFoo := accMap[string(accsFooBar[0].Account.PubKey.Address())].Balance
endBalBar := accMap[string(accsFooBar[1].Account.PubKey.Address())].Balance
decrBalFoo := initBalFoo.Minus(endBalFoo)
incrBalBar := endBalBar.Minus(initBalBar)
return []er{
{decrBalFoo.IsEqual(txIn[0].Coins),
fmt.Sprintf("adjustByInputs: total coins are not equal. diff: %v, tx: %v", decrBalFoo.String(), txIn[0].Coins.String())},
{incrBalBar.IsEqual(txOut[0].Coins),
fmt.Sprintf("adjustByInputs: total coins are not equal. diff: %v, tx: %v", incrBalBar.String(), txOut[0].Coins.String())},
}
}},
//ExecTx
{func() []er {
txs := &types.SendTx{
Gas: 0,
Fee: types.Coin{"mycoin", 1},
Inputs: accs2TxInputs(accsFoo),
Outputs: accs2TxOutputs(accsBar),
}
acc2State(accsFoo)
acc2State(accsBar)
signSend(txs, accsFoo)
exec := func(checkTx bool) (ExecTxRes abci.Result, foo, fooExp, bar, barExp types.Coins) {
initBalFoo := state.GetAccount(accsFoo[0].Account.PubKey.Address()).Balance
initBalBar := state.GetAccount(accsBar[0].Account.PubKey.Address()).Balance
res := ExecTx(state, nil, txs, checkTx, nil)
endBalFoo := state.GetAccount(accsFoo[0].Account.PubKey.Address()).Balance
endBalBar := state.GetAccount(accsBar[0].Account.PubKey.Address()).Balance
decrBalFooExp := txs.Outputs[0].Coins.Plus(types.Coins{txs.Fee})
return res, endBalFoo, initBalFoo.Minus(decrBalFooExp), endBalBar, initBalBar.Plus(txs.Outputs[0].Coins)
}
//Bad Balance
accsFoo[0].Balance = types.Coins{{"mycoin", 2}}
acc2State(accsFoo)
res1, _, _, _, _ := exec(true)
res2, foo2, fooexp2, bar2, barexp2 := exec(false)
//Regular CheckTx
reset()
acc2State(accsFoo)
acc2State(accsBar)
res3, _, _, _, _ := exec(true)
//Regular DeliverTx
reset()
acc2State(accsFoo)
acc2State(accsBar)
res4, foo4, fooexp4, bar4, barexp4 := exec(false)
return []er{
{res1.IsErr(), fmt.Sprintf("ExecTx/Bad CheckTx: Expected error return from ExecTx, returned: %v", res1)},
{res2.IsErr(), fmt.Sprintf("ExecTx/Bad DeliverTx: Expected error return from ExecTx, returned: %v", res2)},
{!foo2.IsEqual(fooexp2), fmt.Sprintf("ExecTx/Bad DeliverTx: shouldn't be equal, foo: %v, fooExp: %v", foo2, fooexp2)},
{!bar2.IsEqual(barexp2), fmt.Sprintf("ExecTx/Bad DeliverTx: shouldn't be equal, bar: %v, barExp: %v", bar2, barexp2)},
{res3.IsOK(), fmt.Sprintf("ExecTx/Good CheckTx: Expected OK return from ExecTx, Error: %v", res3)},
{res4.IsOK(), fmt.Sprintf("ExecTx/Good DeliverTx: Expected OK return from ExecTx, Error: %v", res4)},
{foo4.IsEqual(fooexp4), fmt.Sprintf("ExecTx/good DeliverTx: unexpected change in input coins, foo: %v, fooExp: %v", foo4, fooexp4)},
{bar4.IsEqual(barexp4), fmt.Sprintf("ExecTx/good DeliverTx: unexpected change in output coins, bar: %v, barExp: %v", bar4, barexp4)},
}
}},
}
//execute the tests
for _, tl := range testList {
reset()
for _, tr := range tl.tester() { //loop through all outputs of a test
assert.True(t, tr.exp, tr.msg)
}
}
//test the map results
_, map2ok := mapRes2[string(txs2[0].Address)]
assert.True(map2ok, "getOrMakeOutputs: account output does not contain new account map item")
}
func TestValidateInputsBasic(t *testing.T) {
assert := assert.New(t)
//validate input basic
reset()
txs := accs2TxInputs(accsFoo)
res := validateInputsBasic(txs)
assert.False(res.IsErr(), fmt.Sprintf("validateInputsBasic: expected no error on good tx input. Error: %v", res.Error()))
txs[0].Coins[0].Amount = 0
res = validateInputsBasic(txs)
assert.True(res.IsErr(), "validateInputsBasic: expected error on bad tx input")
}
func TestValidateInputsAdvanced(t *testing.T) {
assert := assert.New(t)
//validate inputs advanced
reset()
txs := types.SendTx{
Gas: 0,
Fee: types.Coin{"mycoin", 1},
Inputs: accs2TxInputs(accsFooBar),
Outputs: accs2TxOutputs(accsBar),
}
acc2State(accsFooBar)
accMap, res := getInputs(state, txs.Inputs)
assert.False(res.IsErr(), fmt.Sprintf("validateInputsAdvanced: error retrieving accMap. Error: %v", res.Error()))
signBytes := txs.SignBytes(chainID)
//test bad case, unsigned
totalCoins, res := validateInputsAdvanced(accMap, signBytes, txs.Inputs)
assert.True(res.IsErr(), "validateInputsAdvanced: expected an error on an unsigned tx input")
//test good case sgined
signSend(&txs, accsFooBar)
totalCoins, res = validateInputsAdvanced(accMap, signBytes, txs.Inputs)
assert.False(res.IsErr(), fmt.Sprintf("validateInputsAdvanced: expected no error on good tx input. Error: %v", res.Error()))
assert.True(totalCoins.IsEqual(txs.Inputs[0].Coins.Plus(txs.Inputs[1].Coins)), "ValidateInputsAdvanced: transaction total coins are not equal")
}
func TestValidateInputAdvanced(t *testing.T) {
assert := assert.New(t)
//validate input advanced
reset()
txs := types.SendTx{
Gas: 0,
Fee: types.Coin{"mycoin", 1},
Inputs: accs2TxInputs(accsFooBar),
Outputs: accs2TxOutputs(accsBar),
}
acc2State(accsFooBar)
signBytes := txs.SignBytes(chainID)
//unsigned case
res := validateInputAdvanced(&accsFooBar[0].Account, signBytes, txs.Inputs[0])
assert.True(res.IsErr(), "validateInputAdvanced: expected error on tx input without signature")
//good signed case
signSend(&txs, accsFooBar)
res = validateInputAdvanced(&accsFooBar[0].Account, signBytes, txs.Inputs[0])
assert.False(res.IsErr(), fmt.Sprintf("validateInputAdvanced: expected no error on good tx input. Error: %v", res.Error()))
//bad sequence case
accsFooBar[0].Sequence = 2
signSend(&txs, accsFooBar)
res = validateInputAdvanced(&accsFooBar[0].Account, signBytes, txs.Inputs[0])
assert.True(res.IsErr(), "validateInputAdvanced: expected error on tx input with bad sequence")
accsFooBar[0].Account.Sequence = 1 //restore sequence
//bad balance case
accsFooBar[1].Balance = types.Coins{{"mycoin", 2}}
signSend(&txs, accsFooBar)
res = validateInputAdvanced(&accsFooBar[0].Account, signBytes, txs.Inputs[0])
assert.True(res.IsErr(), "validateInputAdvanced: expected error on tx input with insufficient funds")
}
func TestValidateOutputsAdvanced(t *testing.T) {
assert := assert.New(t)
//validateOutputsBasic
reset()
txs := accs2TxOutputs(accsFoo)
res := validateOutputsBasic(txs)
assert.False(res.IsErr(), fmt.Sprintf("validateOutputsBasic: expected no error on good tx input. Error: %v", res.Error()))
txs[0].Coins[0].Amount = 0
res = validateOutputsBasic(txs)
assert.True(res.IsErr(), fmt.Sprintf("validateInputBasic: expected error on bad tx inputi. Error: %v", res.Error()))
}
func TestSumOutput(t *testing.T) {
assert := assert.New(t)
//SumOutput
reset()
txs := accs2TxOutputs(accsFooBar)
total := sumOutputs(txs)
assert.True(total.IsEqual(txs[0].Coins.Plus(txs[1].Coins)), "sumOutputs: total coins are not equal")
}
func TestAdjustBy(t *testing.T) {
assert := assert.New(t)
//adjustByInputs/adjustByOutputs
//sending transaction from Foo to Bar
reset()
initBalFoo := accsFooBar[0].Account.Balance
initBalBar := accsFooBar[1].Account.Balance
acc2State(accsFooBar)
txIn := accs2TxInputs(accsFoo)
txOut := accs2TxOutputs(accsBar)
accMap, _ := getInputs(state, txIn)
accMap, _ = getOrMakeOutputs(state, accMap, txOut)
adjustByInputs(state, accMap, txIn)
adjustByOutputs(state, accMap, txOut, false)
endBalFoo := accMap[string(accsFooBar[0].Account.PubKey.Address())].Balance
endBalBar := accMap[string(accsFooBar[1].Account.PubKey.Address())].Balance
decrBalFoo := initBalFoo.Minus(endBalFoo)
incrBalBar := endBalBar.Minus(initBalBar)
assert.True(decrBalFoo.IsEqual(txIn[0].Coins),
fmt.Sprintf("adjustByInputs: total coins are not equal. diff: %v, tx: %v", decrBalFoo.String(), txIn[0].Coins.String()))
assert.True(incrBalBar.IsEqual(txOut[0].Coins),
fmt.Sprintf("adjustByInputs: total coins are not equal. diff: %v, tx: %v", incrBalBar.String(), txOut[0].Coins.String()))
}
func TestExecTx(t *testing.T) {
assert := assert.New(t)
//ExecTx
reset()
txs := &types.SendTx{
Gas: 0,
Fee: types.Coin{"mycoin", 1},
Inputs: accs2TxInputs(accsFoo),
Outputs: accs2TxOutputs(accsBar),
}
acc2State(accsFoo)
acc2State(accsBar)
signSend(txs, accsFoo)
exec := func(checkTx bool) (ExecTxRes abci.Result, foo, fooExp, bar, barExp types.Coins) {
initBalFoo := state.GetAccount(accsFoo[0].Account.PubKey.Address()).Balance
initBalBar := state.GetAccount(accsBar[0].Account.PubKey.Address()).Balance
res := ExecTx(state, nil, txs, checkTx, nil)
endBalFoo := state.GetAccount(accsFoo[0].Account.PubKey.Address()).Balance
endBalBar := state.GetAccount(accsBar[0].Account.PubKey.Address()).Balance
decrBalFooExp := txs.Outputs[0].Coins.Plus(types.Coins{txs.Fee})
return res, endBalFoo, initBalFoo.Minus(decrBalFooExp), endBalBar, initBalBar.Plus(txs.Outputs[0].Coins)
}
//Bad Balance
accsFoo[0].Balance = types.Coins{{"mycoin", 2}}
acc2State(accsFoo)
res, _, _, _, _ := exec(true)
assert.True(res.IsErr(), fmt.Sprintf("ExecTx/Bad CheckTx: Expected error return from ExecTx, returned: %v", res))
res, foo, fooexp, bar, barexp := exec(false)
assert.True(res.IsErr(), fmt.Sprintf("ExecTx/Bad DeliverTx: Expected error return from ExecTx, returned: %v", res))
assert.False(foo.IsEqual(fooexp), fmt.Sprintf("ExecTx/Bad DeliverTx: shouldn't be equal, foo: %v, fooExp: %v", foo, fooexp))
assert.False(bar.IsEqual(barexp), fmt.Sprintf("ExecTx/Bad DeliverTx: shouldn't be equal, bar: %v, barExp: %v", bar, barexp))
//Regular CheckTx
reset()
acc2State(accsFoo)
acc2State(accsBar)
res, _, _, _, _ = exec(true)
assert.True(res.IsOK(), fmt.Sprintf("ExecTx/Good CheckTx: Expected OK return from ExecTx, Error: %v", res))
//Regular DeliverTx
reset()
acc2State(accsFoo)
acc2State(accsBar)
res, foo, fooexp, bar, barexp = exec(false)
assert.True(res.IsOK(), fmt.Sprintf("ExecTx/Good DeliverTx: Expected OK return from ExecTx, Error: %v", res))
assert.True(foo.IsEqual(fooexp), fmt.Sprintf("ExecTx/good DeliverTx: unexpected change in input coins, foo: %v, fooExp: %v", foo, fooexp))
assert.True(bar.IsEqual(barexp), fmt.Sprintf("ExecTx/good DeliverTx: unexpected change in output coins, bar: %v, barExp: %v", bar, barexp))
}

View File

@ -11,6 +11,7 @@ import (
)
func TestState(t *testing.T) {
assert := assert.New(t)
//States and Stores for tests
store := types.NewMemKVStore()
@ -63,44 +64,33 @@ func TestState(t *testing.T) {
return true
}
//define the test list
testList := []struct {
testPass func() bool
errMsg string
}{
//test chainID
{func() bool { state.SetChainID("testchain"); return state.GetChainID() == "testchain" },
"ChainID is improperly stored"},
//test chainID
state.SetChainID("testchain")
assert.Equal(state.GetChainID(), "testchain", "ChainID is improperly stored")
//test basic retrieve
{func() bool { setRecords(state); return storeHasAll(state) },
"state doesn't retrieve after Set"},
//test basic retrieve
setRecords(state)
assert.True(storeHasAll(state), "state doesn't retrieve after Set")
// Test account retrieve
{func() bool { state.SetAccount(dumAddr, acc); return state.GetAccount(dumAddr).Sequence == 1 },
"GetAccount not retrieving"},
// Test account retrieve
state.SetAccount(dumAddr, acc)
assert.Equal(state.GetAccount(dumAddr).Sequence, 1, "GetAccount not retrieving")
//Test CacheWrap with local mem store
{func() bool { reset(); setRecords(cache); return !storeHasAll(store) },
"store retrieving before CacheSync"},
{func() bool { cache.CacheSync(); return storeHasAll(store) },
"store doesn't retrieve after CacheSync"},
//Test CacheWrap with local mem store
reset()
setRecords(cache)
assert.False(storeHasAll(store), "store retrieving before CacheSync")
cache.CacheSync()
assert.True(storeHasAll(store), "store doesn't retrieve after CacheSync")
//Test Commit on state with non-merkle store
{func() bool { return !state.Commit().IsOK() },
"Commit shouldn't work with non-merkle store"},
//Test Commit on state with non-merkle store
assert.False(state.Commit().IsOK(), "Commit shouldn't work with non-merkle store")
//Test CacheWrap with merkleeyes client store
{func() bool { useEyesCli(); setRecords(cache); return !storeHasAll(eyesCli) },
"eyesCli retrieving before Commit"},
{func() bool { cache.CacheSync(); return state.Commit().IsOK() },
"Bad Commit"},
{func() bool { return storeHasAll(eyesCli) },
"eyesCli doesn't retrieve after Commit"},
}
//execute the tests
for _, tl := range testList {
assert.True(t, tl.testPass(), tl.errMsg)
}
//Test CacheWrap with merkleeyes client store
useEyesCli()
setRecords(cache)
assert.False(storeHasAll(eyesCli), "eyesCli retrieving before Commit")
cache.CacheSync()
assert.True(state.Commit().IsOK(), "Bad Commit")
assert.True(storeHasAll(eyesCli), "eyesCli doesn't retrieve after Commit")
}

View File

@ -1,6 +1,7 @@
package types
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
@ -12,8 +13,9 @@ func TestNilAccount(t *testing.T) {
//test Copy
accCopy := acc.Copy()
assert.True(t, &acc != accCopy, "Account Copy Error")
assert.True(t, acc.Sequence == accCopy.Sequence)
//note that the assert.True is used instead of assert.Equal because looking at pointers
assert.True(t, &acc != accCopy, fmt.Sprintf("Account Copy Error, acc1: %v, acc2: %v", &acc, accCopy))
assert.Equal(t, acc.Sequence, accCopy.Sequence)
//test sending nils for panic
var nilAcc *Account

View File

@ -1,14 +1,14 @@
package types
import (
"fmt"
"testing"
cmn "github.com/tendermint/go-common"
"github.com/stretchr/testify/assert"
)
func TestCoins(t *testing.T) {
assert := assert.New(t)
//Define the coins to be used in tests
good := Coins{
@ -42,24 +42,14 @@ func TestCoins(t *testing.T) {
Coin{"MINERAL", 1},
}
//define the list of coin tests
var testList = []struct {
testPass bool
errMsg string
}{
{good.IsValid(), "Coins are valid"},
{good.IsPositive(), cmn.Fmt("Expected coins to be positive: %v", good)},
{good.IsGTE(empty), cmn.Fmt("Expected %v to be >= %v", good, empty)},
{!neg.IsPositive(), cmn.Fmt("Expected neg coins to not be positive: %v", neg)},
{len(sum) == 0, "Expected 0 coins"},
{!badSort1.IsValid(), "Coins are not sorted"},
{!badSort2.IsValid(), "Coins are not sorted"},
{!badAmt.IsValid(), "Coins cannot include 0 amounts"},
{!dup.IsValid(), "Duplicate coin"},
}
assert.True(good.IsValid(), "Coins are valid")
assert.True(good.IsPositive(), fmt.Sprintf("Expected coins to be positive: %v", good))
assert.True(good.IsGTE(empty), fmt.Sprintf("Expected %v to be >= %v", good, empty))
assert.False(neg.IsPositive(), fmt.Sprintf("Expected neg coins to not be positive: %v", neg))
assert.Zero(len(sum), "Expected 0 coins")
assert.False(badSort1.IsValid(), "Coins are not sorted")
assert.False(badSort2.IsValid(), "Coins are not sorted")
assert.False(badAmt.IsValid(), "Coins cannot include 0 amounts")
assert.False(dup.IsValid(), "Duplicate coin")
//execute the tests
for _, tl := range testList {
assert.True(t, tl.testPass, tl.errMsg)
}
}

View File

@ -8,6 +8,7 @@ import (
)
func TestKVStore(t *testing.T) {
assert := assert.New(t)
//stores to be tested
ms := NewMemKVStore()
@ -40,40 +41,30 @@ func TestKVStore(t *testing.T) {
return true
}
//define the test list
var testList = []struct {
testPass func() bool
errMsg string
}{
//test read/write for MemKVStore
{func() bool { setRecords(ms); return storeHasAll(ms) },
"MemKVStore doesn't retrieve after Set"},
//test read/write for MemKVStore
setRecords(ms)
assert.True(storeHasAll(ms), "MemKVStore doesn't retrieve after Set")
//test read/write for KVCache
{func() bool { setRecords(kvc); return storeHasAll(kvc) },
"KVCache doesn't retrieve after Set"},
//test read/write for KVCache
setRecords(kvc)
assert.True(storeHasAll(kvc), "KVCache doesn't retrieve after Set")
//test reset
{func() bool { kvc.Reset(); return !storeHasAll(kvc) },
"KVCache retrieving after reset"},
//test reset
kvc.Reset()
assert.False(storeHasAll(kvc), "KVCache retrieving after reset")
//test sync
{func() bool { setRecords(kvc); return !storeHasAll(store) },
"store retrieving before synced"},
{func() bool { kvc.Sync(); return storeHasAll(store) },
"store isn't retrieving after synced"},
//test sync
setRecords(kvc)
assert.False(storeHasAll(store), "store retrieving before synced")
kvc.Sync()
assert.True(storeHasAll(store), "store isn't retrieving after synced")
//test logging
{func() bool { return len(kvc.GetLogLines()) == 0 },
"logging events existed before using SetLogging"},
{func() bool { kvc.SetLogging(); setRecords(kvc); return len(kvc.GetLogLines()) == 2 },
"incorrect number of logging events recorded"},
{func() bool { kvc.ClearLogLines(); return len(kvc.GetLogLines()) == 0 },
"logging events still exists after ClearLogLines"},
}
//test logging
assert.Zero(len(kvc.GetLogLines()), "logging events existed before using SetLogging")
kvc.SetLogging()
setRecords(kvc)
assert.Equal(len(kvc.GetLogLines()), 2, "incorrect number of logging events recorded")
kvc.ClearLogLines()
assert.Zero(len(kvc.GetLogLines()), "logging events still exists after ClearLogLines")
//execute the tests
for _, tl := range testList {
assert.True(t, tl.testPass(), tl.errMsg)
}
}

View File

@ -32,25 +32,10 @@ func (d *Dummy) EndBlock(store KVStore, height uint64) (res abci.ResponseEndBloc
//----------------------------------
func TestPlugin(t *testing.T) {
assert := assert.New(t)
plugins := NewPlugins()
//define the test list
var testList = []struct {
testPass func() bool
errMsg string
}{
{func() bool { return (len(plugins.GetList()) == 0) },
"plugins object init with a objects"},
{func() bool { plugins.RegisterPlugin(&Dummy{}); return (len(plugins.GetList()) == 1) },
"plugin wasn't added to plist after registered"},
{func() bool { return (plugins.GetByName("dummy").Name() == "dummy") },
"plugin wasn't retrieved properly with GetByName"},
}
//execute the tests
for _, tl := range testList {
assert.True(t, tl.testPass(), tl.errMsg)
}
assert.Zero(len(plugins.GetList()), "plugins object init with a objects")
plugins.RegisterPlugin(&Dummy{})
assert.Equal(len(plugins.GetList()), 1, "plugin wasn't added to plist after registered")
assert.Equal(plugins.GetByName("dummy").Name(), "dummy", "plugin wasn't retrieved properly with GetByName")
}

View File

@ -1,11 +1,11 @@
package types
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
cmn "github.com/tendermint/go-common"
crypto "github.com/tendermint/go-crypto"
data "github.com/tendermint/go-data"
)
@ -40,11 +40,11 @@ func TestSendTxSignable(t *testing.T) {
},
}
signBytes := sendTx.SignBytes(chainID)
signBytesHex := cmn.Fmt("%X", signBytes)
signBytesHex := fmt.Sprintf("%X", signBytes)
expected := "010A746573745F636861696E0100000000000000DE00000000000000006F01020106696E7075743101010000000000000030390301093200000106696E70757432010100000000000000006F01DE0000010201076F757470757431010100000000000000014D01076F75747075743201010000000000000001BC"
assert.True(t, signBytesHex == expected,
cmn.Fmt("Got unexpected sign string for SendTx. Expected:\n%v\nGot:\n%v", expected, signBytesHex))
assert.Equal(t, signBytesHex, expected,
fmt.Sprintf("Got unexpected sign string for SendTx. Expected:\n%v\nGot:\n%v", expected, signBytesHex))
}
func TestAppTxSignable(t *testing.T) {
@ -60,14 +60,16 @@ func TestAppTxSignable(t *testing.T) {
Data: []byte("data1"),
}
signBytes := callTx.SignBytes(chainID)
signBytesHex := cmn.Fmt("%X", signBytes)
signBytesHex := fmt.Sprintf("%X", signBytes)
expected := "010A746573745F636861696E0100000000000000DE00000000000000006F0101580106696E70757431010100000000000000303903010932000001056461746131"
assert.True(t, signBytesHex == expected,
cmn.Fmt("Got unexpected sign string for SendTx. Expected:\n%v\nGot:\n%v", expected, signBytesHex))
assert.Equal(t, signBytesHex, expected,
fmt.Sprintf("Got unexpected sign string for SendTx. Expected:\n%v\nGot:\n%v", expected, signBytesHex))
}
func TestSendTxJSON(t *testing.T) {
assert, require := assert.New(t), require.New(t)
chainID := "test_chain_id"
test1PrivAcc := PrivAccountFromSecret("sendtx1")
test2PrivAcc := PrivAccountFromSecret("sendtx2")
@ -89,37 +91,37 @@ func TestSendTxJSON(t *testing.T) {
// serialize this as json and back
js, err := data.ToJSON(TxS{tx})
require.Nil(t, err)
require.Nil(err)
// fmt.Println(string(js))
txs := TxS{}
err = data.FromJSON(js, &txs)
require.Nil(t, err)
require.Nil(err)
tx2, ok := txs.Tx.(*SendTx)
require.True(t, ok)
require.True(ok)
// make sure they are the same!
signBytes := tx.SignBytes(chainID)
signBytes2 := tx2.SignBytes(chainID)
assert.Equal(t, signBytes, signBytes2)
assert.Equal(t, tx, tx2)
assert.Equal(signBytes, signBytes2)
assert.Equal(tx, tx2)
// sign this thing
sig := test1PrivAcc.Sign(signBytes)
// we handle both raw sig and wrapped sig the same
tx.SetSignature(test1PrivAcc.PubKey.Address(), sig)
tx2.SetSignature(test1PrivAcc.PubKey.Address(), crypto.SignatureS{sig})
assert.Equal(t, tx, tx2)
assert.Equal(tx, tx2)
// let's marshal / unmarshal this with signature
js, err = data.ToJSON(TxS{tx})
require.Nil(t, err)
require.Nil(err)
// fmt.Println(string(js))
err = data.FromJSON(js, &txs)
require.Nil(t, err)
require.Nil(err)
tx2, ok = txs.Tx.(*SendTx)
require.True(t, ok)
require.True(ok)
// and make sure the sig is preserved
assert.Equal(t, tx, tx2)
assert.False(t, tx2.Inputs[0].Signature.Empty())
assert.Equal(tx, tx2)
assert.False(tx2.Inputs[0].Signature.Empty())
}