validators_string_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package validators
  15. import (
  16. "testing"
  17. )
  18. func TestStringLenValidator(t *testing.T) {
  19. cases := []*C{
  20. {
  21. Name: "missing non-optional",
  22. In: `{}`,
  23. Out: `{}`,
  24. Optional: false,
  25. Err: ERR_MISSING_KEY,
  26. ValueWant: "",
  27. },
  28. {
  29. Name: "missing optional",
  30. In: `{}`,
  31. Out: `{}`,
  32. Optional: true,
  33. ValueWant: "",
  34. },
  35. {
  36. Name: "missing with default",
  37. In: `{}`,
  38. Out: `{s: "12345"}`,
  39. Default: "12345",
  40. ValueWant: "12345",
  41. },
  42. {
  43. Name: "stringified",
  44. In: `{"s": 100}`,
  45. Out: `{s: "100"}`,
  46. ValueWant: "100",
  47. },
  48. {
  49. Name: "stringified too long",
  50. In: `{"s": 9876543210}`,
  51. Out: `{"s": 9876543210}`,
  52. Err: ERR_INVALID_LENGTH,
  53. ValueWant: "",
  54. },
  55. {
  56. Name: "stringified too short",
  57. In: `{"s": 0}`,
  58. Out: `{"s": 0}`,
  59. Err: ERR_INVALID_LENGTH,
  60. ValueWant: "",
  61. },
  62. {
  63. Name: "good length",
  64. In: `{"s": "abcde"}`,
  65. Out: `{"s": "abcde"}`,
  66. ValueWant: "abcde",
  67. },
  68. {
  69. Name: "bad length (too short)",
  70. In: `{"s": "0"}`,
  71. Out: `{"s": "0"}`,
  72. Err: ERR_INVALID_LENGTH,
  73. ValueWant: "",
  74. },
  75. {
  76. Name: "bad length (too long)",
  77. In: `{"s": "9876543210"}`,
  78. Out: `{"s": "9876543210"}`,
  79. Err: ERR_INVALID_LENGTH,
  80. ValueWant: "",
  81. },
  82. }
  83. for _, c := range cases {
  84. t.Run(c.Name, func(t *testing.T) {
  85. v := NewStringLenRangeValidator("s", 2, 5)
  86. if c.Default != nil {
  87. s := c.Default.(string)
  88. v.Default(s)
  89. }
  90. if c.Optional {
  91. v.Optional(true)
  92. }
  93. testS(t, v, c)
  94. })
  95. }
  96. }