geodb_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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)
  39. if err != nil {
  40. t.Errorf("error creating store: %v", err)
  41. return
  42. }
  43. // Test an IP address that should return a valid country code
  44. ip := "8.8.8.8"
  45. expected := "US"
  46. info, err := store.ResolveCountryCodeFromIP(ip)
  47. if err != nil {
  48. t.Errorf("error resolving country code for IP %s: %v", ip, err)
  49. return
  50. }
  51. if info.CountryIsoCode != expected {
  52. t.Errorf("expected country code %s, but got %s for IP %s", expected, info.CountryIsoCode, ip)
  53. }
  54. // Test an IP address that should return an empty country code
  55. ip = "127.0.0.1"
  56. expected = ""
  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. }