rule_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package rule_test
  2. import (
  3. "context"
  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/platform"
  11. "github.com/v2fly/v2ray-core/v4/common/platform/filesystem"
  12. "github.com/v2fly/v2ray-core/v4/infra/conf/cfgcommon"
  13. "github.com/v2fly/v2ray-core/v4/infra/conf/geodata"
  14. "github.com/v2fly/v2ray-core/v4/infra/conf/rule"
  15. _ "github.com/v2fly/v2ray-core/v4/infra/conf/geodata/standard"
  16. )
  17. const (
  18. geoipURL = "https://raw.githubusercontent.com/v2fly/geoip/release/geoip.dat"
  19. )
  20. func init() {
  21. wd, err := os.Getwd()
  22. common.Must(err)
  23. tempPath := filepath.Join(wd, "..", "..", "testing", "temp")
  24. geoipPath := filepath.Join(tempPath, "geoip.dat")
  25. os.Setenv("v2ray.location.asset", tempPath)
  26. common.Must(os.MkdirAll(tempPath, 0755))
  27. if _, err := os.Stat(platform.GetAssetLocation("geoip.dat")); err != nil && errors.Is(err, fs.ErrNotExist) {
  28. if _, err := os.Stat(geoipPath); err != nil && errors.Is(err, fs.ErrNotExist) {
  29. geoipBytes, err := common.FetchHTTPContent(geoipURL)
  30. common.Must(err)
  31. common.Must(filesystem.WriteFile(geoipPath, geoipBytes))
  32. }
  33. }
  34. }
  35. func TestToCidrList(t *testing.T) {
  36. t.Log(os.Getenv("v2ray.location.asset"))
  37. common.Must(filesystem.CopyFile(platform.GetAssetLocation("geoiptestrouter.dat"), platform.GetAssetLocation("geoip.dat")))
  38. ips := cfgcommon.StringList([]string{
  39. "geoip:us",
  40. "geoip:cn",
  41. "geoip:!cn",
  42. "ext:geoiptestrouter.dat:!cn",
  43. "ext:geoiptestrouter.dat:ca",
  44. "ext-ip:geoiptestrouter.dat:!cn",
  45. "ext-ip:geoiptestrouter.dat:!ca",
  46. })
  47. cfgctx := cfgcommon.NewConfigureLoadingContext(context.Background())
  48. if loader, err := geodata.GetGeoDataLoader("standard"); err == nil {
  49. cfgcommon.SetGeoDataLoader(cfgctx, loader)
  50. } else {
  51. t.Fatal(err)
  52. }
  53. _, err := rule.ToCidrList(cfgctx, ips)
  54. if err != nil {
  55. t.Fatalf("Failed to parse geoip list, got %s", err)
  56. }
  57. }