decode_test.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package geodata_test
  2. import (
  3. "bytes"
  4. "errors"
  5. "io/fs"
  6. "os"
  7. "path/filepath"
  8. "testing"
  9. "github.com/v2fly/v2ray-core/v4/common"
  10. "github.com/v2fly/v2ray-core/v4/common/geodata"
  11. "github.com/v2fly/v2ray-core/v4/common/platform"
  12. "github.com/v2fly/v2ray-core/v4/common/platform/filesystem"
  13. )
  14. const (
  15. geoipURL = "https://raw.githubusercontent.com/v2fly/geoip/release/geoip.dat"
  16. geositeURL = "https://raw.githubusercontent.com/v2fly/domain-list-community/release/dlc.dat"
  17. )
  18. func init() {
  19. wd, err := os.Getwd()
  20. common.Must(err)
  21. tempPath := filepath.Join(wd, "..", "..", "testing", "temp")
  22. os.Setenv("v2ray.location.asset", tempPath)
  23. geoipPath := platform.GetAssetLocation("geoip.dat")
  24. geositePath := platform.GetAssetLocation("geosite.dat")
  25. if _, err := os.Stat(geoipPath); err != nil && errors.Is(err, fs.ErrNotExist) {
  26. common.Must(os.MkdirAll(tempPath, 0755))
  27. geoipBytes, err := common.FetchHTTPContent(geoipURL)
  28. common.Must(err)
  29. common.Must(filesystem.WriteFile(geoipPath, geoipBytes))
  30. }
  31. if _, err := os.Stat(geositePath); err != nil && errors.Is(err, fs.ErrNotExist) {
  32. common.Must(os.MkdirAll(tempPath, 0755))
  33. geositeBytes, err := common.FetchHTTPContent(geositeURL)
  34. common.Must(err)
  35. common.Must(filesystem.WriteFile(geositePath, geositeBytes))
  36. }
  37. }
  38. func TestDecodeGeoIP(t *testing.T) {
  39. filename := platform.GetAssetLocation("geoip.dat")
  40. result, err := geodata.Decode(filename, "test")
  41. if err != nil {
  42. t.Error(err)
  43. }
  44. expected := []byte{10, 4, 84, 69, 83, 84, 18, 8, 10, 4, 127, 0, 0, 0, 16, 8}
  45. if !bytes.Equal(result, expected) {
  46. t.Errorf("failed to load geoip:test, expected: %v, got: %v", expected, result)
  47. }
  48. }
  49. func TestDecodeGeoSite(t *testing.T) {
  50. filename := platform.GetAssetLocation("geosite.dat")
  51. result, err := geodata.Decode(filename, "test")
  52. if err != nil {
  53. t.Error(err)
  54. }
  55. expected := []byte{10, 4, 84, 69, 83, 84, 18, 20, 8, 3, 18, 16, 116, 101, 115, 116, 46, 101, 120, 97, 109, 112, 108, 101, 46, 99, 111, 109}
  56. if !bytes.Equal(result, expected) {
  57. t.Errorf("failed to load geosite:test, expected: %v, got: %v", expected, result)
  58. }
  59. }