threshold_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package config
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "testing"
  8. )
  9. func TestThresholdValid(t *testing.T) {
  10. for _, tt := range []struct {
  11. err error
  12. input *Threshold
  13. name string
  14. }{
  15. {
  16. name: "basic allow",
  17. input: &Threshold{
  18. Name: "basic-allow",
  19. Expression: &ExpressionOrList{Expression: "true"},
  20. Action: RuleAllow,
  21. },
  22. err: nil,
  23. },
  24. {
  25. name: "basic challenge",
  26. input: &Threshold{
  27. Name: "basic-challenge",
  28. Expression: &ExpressionOrList{Expression: "true"},
  29. Action: RuleChallenge,
  30. Challenge: &ChallengeRules{
  31. Algorithm: "fast",
  32. Difficulty: 1,
  33. },
  34. },
  35. err: nil,
  36. },
  37. {
  38. name: "no name",
  39. input: &Threshold{},
  40. err: ErrThresholdMustHaveName,
  41. },
  42. {
  43. name: "no expression",
  44. input: &Threshold{},
  45. err: ErrThresholdMustHaveName,
  46. },
  47. {
  48. name: "invalid expression",
  49. input: &Threshold{
  50. Expression: &ExpressionOrList{},
  51. },
  52. err: ErrExpressionEmpty,
  53. },
  54. {
  55. name: "invalid action",
  56. input: &Threshold{},
  57. err: ErrUnknownAction,
  58. },
  59. {
  60. name: "challenge action but no challenge",
  61. input: &Threshold{
  62. Action: RuleChallenge,
  63. },
  64. err: ErrThresholdChallengeMustHaveChallenge,
  65. },
  66. {
  67. name: "challenge invalid",
  68. input: &Threshold{
  69. Action: RuleChallenge,
  70. Challenge: &ChallengeRules{Difficulty: -1, ReportAs: -1},
  71. },
  72. err: ErrChallengeDifficultyTooLow,
  73. },
  74. } {
  75. t.Run(tt.name, func(t *testing.T) {
  76. if err := tt.input.Valid(); !errors.Is(err, tt.err) {
  77. t.Errorf("threshold is invalid: %v", err)
  78. }
  79. })
  80. }
  81. }
  82. func TestDefaultThresholdsValid(t *testing.T) {
  83. for i, th := range DefaultThresholds {
  84. t.Run(fmt.Sprintf("%d %s", i, th.Name), func(t *testing.T) {
  85. if err := th.Valid(); err != nil {
  86. t.Errorf("threshold invalid: %v", err)
  87. }
  88. })
  89. }
  90. }
  91. func TestLoadActuallyLoadsThresholds(t *testing.T) {
  92. fin, err := os.Open(filepath.Join(".", "testdata", "good", "thresholds.yaml"))
  93. if err != nil {
  94. t.Fatal(err)
  95. }
  96. defer fin.Close()
  97. c, err := Load(fin, fin.Name())
  98. if err != nil {
  99. t.Fatal(err)
  100. }
  101. if len(c.Thresholds) != 4 {
  102. t.Errorf("wanted 4 thresholds, got %d thresholds", len(c.Thresholds))
  103. }
  104. }