rule_test.go 1.8 KB

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