1
0

geodb_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package geodb_test
  2. import (
  3. "testing"
  4. "imuslab.com/zoraxy/mod/geodb"
  5. )
  6. /*
  7. func TestTrieConstruct(t *testing.T) {
  8. tt := geodb.NewTrie()
  9. data := [][]string{
  10. {"1.0.16.0", "1.0.31.255", "JP"},
  11. {"1.0.32.0", "1.0.63.255", "CN"},
  12. {"1.0.64.0", "1.0.127.255", "JP"},
  13. {"1.0.128.0", "1.0.255.255", "TH"},
  14. {"1.1.0.0", "1.1.0.255", "CN"},
  15. {"1.1.1.0", "1.1.1.255", "AU"},
  16. {"1.1.2.0", "1.1.63.255", "CN"},
  17. {"1.1.64.0", "1.1.127.255", "JP"},
  18. {"1.1.128.0", "1.1.255.255", "TH"},
  19. {"1.2.0.0", "1.2.2.255", "CN"},
  20. {"1.2.3.0", "1.2.3.255", "AU"},
  21. }
  22. for _, entry := range data {
  23. startIp := entry[0]
  24. endIp := entry[1]
  25. cc := entry[2]
  26. tt.Insert(startIp, cc)
  27. tt.Insert(endIp, cc)
  28. }
  29. t.Log(tt.Search("1.0.16.20"), "== JP") //JP
  30. t.Log(tt.Search("1.2.0.122"), "== CN") //CN
  31. t.Log(tt.Search("1.2.1.0"), "== CN") //CN
  32. t.Log(tt.Search("1.0.65.243"), "== JP") //JP
  33. t.Log(tt.Search("1.0.62.243"), "== CN") //CN
  34. }
  35. */
  36. func TestResolveCountryCodeFromIP(t *testing.T) {
  37. // Create a new store
  38. store, err := geodb.NewGeoDb(nil, &geodb.StoreOptions{
  39. false,
  40. true,
  41. })
  42. if err != nil {
  43. t.Errorf("error creating store: %v", err)
  44. return
  45. }
  46. // Test an IP address that should return a valid country code
  47. knownIpCountryMap := [][]string{
  48. {"3.224.220.101", "US"},
  49. {"176.113.115.113", "RU"},
  50. {"65.21.233.213", "FI"},
  51. {"94.23.207.193", "FR"},
  52. {"77.131.21.232", "FR"},
  53. }
  54. for _, testcase := range knownIpCountryMap {
  55. ip := testcase[0]
  56. expected := testcase[1]
  57. info, err := store.ResolveCountryCodeFromIP(ip)
  58. if err != nil {
  59. t.Errorf("error resolving country code for IP %s: %v", ip, err)
  60. return
  61. }
  62. if info.CountryIsoCode != expected {
  63. t.Errorf("expected country code %s, but got %s for IP %s", expected, info.CountryIsoCode, ip)
  64. }
  65. }
  66. // Test an IP address that should return an empty country code
  67. ip := "127.0.0.1"
  68. expected := ""
  69. info, err := store.ResolveCountryCodeFromIP(ip)
  70. if err != nil {
  71. t.Errorf("error resolving country code for IP %s: %v", ip, err)
  72. return
  73. }
  74. if info.CountryIsoCode != expected {
  75. t.Errorf("expected country code %s, but got %s for IP %s", expected, info.CountryIsoCode, ip)
  76. }
  77. }