geodb_test.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. false,
  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. }
  53. for _, testcase := range knownIpCountryMap {
  54. ip := testcase[0]
  55. expected := testcase[1]
  56. info, err := store.ResolveCountryCodeFromIP(ip)
  57. if err != nil {
  58. t.Errorf("error resolving country code for IP %s: %v", ip, err)
  59. return
  60. }
  61. if info.CountryIsoCode != expected {
  62. t.Errorf("expected country code %s, but got %s for IP %s", expected, info.CountryIsoCode, ip)
  63. }
  64. }
  65. // Test an IP address that should return an empty country code
  66. ip := "127.0.0.1"
  67. expected := ""
  68. info, err := store.ResolveCountryCodeFromIP(ip)
  69. if err != nil {
  70. t.Errorf("error resolving country code for IP %s: %v", ip, err)
  71. return
  72. }
  73. if info.CountryIsoCode != expected {
  74. t.Errorf("expected country code %s, but got %s for IP %s", expected, info.CountryIsoCode, ip)
  75. }
  76. }