You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

118 lines
2.3 KiB

  1. package types
  2. import (
  3. "context"
  4. "fmt"
  5. "testing"
  6. "github.com/stretchr/testify/assert"
  7. "github.com/stretchr/testify/require"
  8. "github.com/tendermint/tendermint/crypto"
  9. )
  10. func TestValidatorProtoBuf(t *testing.T) {
  11. val, _ := randValidator(true, 100)
  12. testCases := []struct {
  13. msg string
  14. v1 *Validator
  15. expPass1 bool
  16. expPass2 bool
  17. }{
  18. {"success validator", val, true, true},
  19. {"failure empty", &Validator{}, false, false},
  20. {"failure nil", nil, false, false},
  21. }
  22. for _, tc := range testCases {
  23. protoVal, err := tc.v1.ToProto()
  24. if tc.expPass1 {
  25. require.NoError(t, err, tc.msg)
  26. } else {
  27. require.Error(t, err, tc.msg)
  28. }
  29. val, err := ValidatorFromProto(protoVal)
  30. if tc.expPass2 {
  31. require.NoError(t, err, tc.msg)
  32. require.Equal(t, tc.v1, val, tc.msg)
  33. } else {
  34. require.Error(t, err, tc.msg)
  35. }
  36. }
  37. }
  38. func TestValidatorValidateBasic(t *testing.T) {
  39. priv := NewMockPV()
  40. pubKey, _ := priv.GetPubKey(context.Background())
  41. testCases := []struct {
  42. val *Validator
  43. err bool
  44. msg string
  45. }{
  46. {
  47. val: NewValidator(pubKey, 1),
  48. err: false,
  49. msg: "",
  50. },
  51. {
  52. val: nil,
  53. err: true,
  54. msg: "nil validator",
  55. },
  56. {
  57. val: &Validator{
  58. PubKey: nil,
  59. },
  60. err: true,
  61. msg: "validator does not have a public key",
  62. },
  63. {
  64. val: NewValidator(pubKey, -1),
  65. err: true,
  66. msg: "validator has negative voting power",
  67. },
  68. {
  69. val: &Validator{
  70. PubKey: pubKey,
  71. Address: nil,
  72. },
  73. err: true,
  74. msg: "validator address is the wrong size: ",
  75. },
  76. {
  77. val: &Validator{
  78. PubKey: pubKey,
  79. Address: []byte{'a'},
  80. },
  81. err: true,
  82. msg: "validator address is the wrong size: 61",
  83. },
  84. }
  85. for _, tc := range testCases {
  86. err := tc.val.ValidateBasic()
  87. if tc.err {
  88. if assert.Error(t, err) {
  89. assert.Equal(t, tc.msg, err.Error())
  90. }
  91. } else {
  92. assert.NoError(t, err)
  93. }
  94. }
  95. }
  96. // Testing util functions
  97. // deterministicValidator returns a deterministic validator, useful for testing.
  98. // UNSTABLE
  99. func deterministicValidator(key crypto.PrivKey) (*Validator, PrivValidator) {
  100. privVal := NewMockPV()
  101. privVal.PrivKey = key
  102. var votePower int64 = 50
  103. pubKey, err := privVal.GetPubKey(context.TODO())
  104. if err != nil {
  105. panic(fmt.Errorf("could not retrieve pubkey %w", err))
  106. }
  107. val := NewValidator(pubKey, votePower)
  108. return val, privVal
  109. }