|
| 1 | +package validation |
| 2 | + |
| 3 | +import ( |
| 4 | + "github.com/brianvoe/gofakeit/v5" |
| 5 | + "testing" |
| 6 | +) |
| 7 | + |
| 8 | +// mock true return in rule |
| 9 | +func testIntValidatorTrue(int int64) bool { |
| 10 | + return true |
| 11 | +} |
| 12 | + |
| 13 | +// mock false return in rule |
| 14 | +func testIntValidatorFalse(int int64) bool { |
| 15 | + return false |
| 16 | +} |
| 17 | + |
| 18 | +var errShouldBeTrue = NewError("test_err_should_be_true", "error should return true") |
| 19 | + |
| 20 | +func TestNewIntRule(t *testing.T) { |
| 21 | + // test raw int rule false |
| 22 | + rule := NewIntRule(testIntValidatorFalse, "this is a test, this should be false") |
| 23 | + err := rule.Validate(gofakeit.Int64()) |
| 24 | + if err == nil { |
| 25 | + t.Error("expected error when using testIntValidatorFalse") |
| 26 | + } |
| 27 | + |
| 28 | + // test raw int rule true |
| 29 | + rule = NewIntRule(testIntValidatorTrue, "this is a test, this should be false") |
| 30 | + rule.ErrorObject(errShouldBeTrue) |
| 31 | + rule.Error("this is a test, this should be false") |
| 32 | + err = rule.Validate(gofakeit.Int64()) |
| 33 | + if err != nil { |
| 34 | + t.Error("expected error when using testIntValidatorTrue") |
| 35 | + } |
| 36 | + |
| 37 | + // test intrule with error |
| 38 | + rule = NewIntRuleWithError(testIntValidatorFalse, errShouldBeTrue) |
| 39 | + err = rule.Validate(gofakeit.Int64()) |
| 40 | + if err == nil { |
| 41 | + t.Error("expected error") |
| 42 | + } |
| 43 | + |
| 44 | + // test wrong type |
| 45 | + rule = NewIntRuleWithError(testIntValidatorTrue, errShouldBeTrue) |
| 46 | + err = rule.Validate(gofakeit.Name()) |
| 47 | + if err == nil { |
| 48 | + t.Error("wrong type should result in err") |
| 49 | + } |
| 50 | + |
| 51 | +} |
0 commit comments