asnchecker_test.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package thoth_test
  2. import (
  3. "fmt"
  4. "net/http/httptest"
  5. "testing"
  6. "github.com/TecharoHQ/anubis/lib/policy/checker"
  7. "github.com/TecharoHQ/anubis/lib/thoth"
  8. iptoasnv1 "github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1"
  9. )
  10. var _ checker.Impl = &thoth.ASNChecker{}
  11. func TestASNChecker(t *testing.T) {
  12. cli := loadSecrets(t)
  13. asnc := cli.ASNCheckerFor([]uint32{13335})
  14. for _, cs := range []struct {
  15. ipAddress string
  16. wantMatch bool
  17. wantError bool
  18. }{
  19. {
  20. ipAddress: "1.1.1.1",
  21. wantMatch: true,
  22. wantError: false,
  23. },
  24. {
  25. ipAddress: "2.2.2.2",
  26. wantMatch: false,
  27. wantError: false,
  28. },
  29. {
  30. ipAddress: "taco",
  31. wantMatch: false,
  32. wantError: false,
  33. },
  34. {
  35. ipAddress: "127.0.0.1",
  36. wantMatch: false,
  37. wantError: false,
  38. },
  39. } {
  40. t.Run(fmt.Sprintf("%v", cs), func(t *testing.T) {
  41. req := httptest.NewRequest("GET", "/", nil)
  42. req.Header.Set("X-Real-Ip", cs.ipAddress)
  43. match, err := asnc.Check(req)
  44. if match != cs.wantMatch {
  45. t.Errorf("Wanted match: %v, got: %v", cs.wantMatch, match)
  46. }
  47. switch {
  48. case err != nil && !cs.wantError:
  49. t.Errorf("Did not want error but got: %v", err)
  50. case err == nil && cs.wantError:
  51. t.Error("Wanted error but got none")
  52. }
  53. })
  54. }
  55. }
  56. func BenchmarkWithCache(b *testing.B) {
  57. cli := loadSecrets(b)
  58. req := &iptoasnv1.LookupRequest{IpAddress: "1.1.1.1"}
  59. _, err := cli.IPToASN.Lookup(b.Context(), req)
  60. if err != nil {
  61. b.Error(err)
  62. }
  63. for b.Loop() {
  64. _, err := cli.IPToASN.Lookup(b.Context(), req)
  65. if err != nil {
  66. b.Error(err)
  67. }
  68. }
  69. }