host_test.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package model
  2. import (
  3. "strings"
  4. "testing"
  5. "github.com/go-playground/validator/v10"
  6. )
  7. // TestHostTableName locks the table name the rest of the feature (queries,
  8. // prune, migration) keys off.
  9. func TestHostTableName(t *testing.T) {
  10. if got := (Host{}).TableName(); got != "hosts" {
  11. t.Fatalf("Host.TableName() = %q, want hosts", got)
  12. }
  13. }
  14. // TestHostValidation locks the struct-tag constraints enforced by the request
  15. // binder (middleware.BindAndValidate -> validate.Struct).
  16. func TestHostValidation(t *testing.T) {
  17. v := validator.New(validator.WithRequiredStructEnabled())
  18. valid := Host{InboundId: 1, Remark: "cdn-front", Port: 8443, Security: "tls", MihomoIpVersion: "dual"}
  19. if err := v.Struct(valid); err != nil {
  20. t.Fatalf("valid host rejected: %v", err)
  21. }
  22. bad := []struct {
  23. name string
  24. h Host
  25. }{
  26. {"missing inbound", Host{Remark: "ok"}},
  27. {"empty remark", Host{InboundId: 1, Remark: ""}},
  28. {"remark too long", Host{InboundId: 1, Remark: strings.Repeat("x", 257)}},
  29. {"port too high", Host{InboundId: 1, Remark: "ok", Port: 70000}},
  30. {"port negative", Host{InboundId: 1, Remark: "ok", Port: -1}},
  31. {"bad security", Host{InboundId: 1, Remark: "ok", Security: "bogus"}},
  32. {"bad mihomo ip version", Host{InboundId: 1, Remark: "ok", MihomoIpVersion: "nope"}},
  33. }
  34. for _, tc := range bad {
  35. if err := v.Struct(tc.h); err == nil {
  36. t.Fatalf("%s: expected validation error, got nil", tc.name)
  37. }
  38. }
  39. }