platform_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package platform_test
  2. import (
  3. "errors"
  4. "io/fs"
  5. "os"
  6. "path/filepath"
  7. "runtime"
  8. "testing"
  9. "github.com/v2fly/v2ray-core/v5/common"
  10. "github.com/v2fly/v2ray-core/v5/common/platform"
  11. )
  12. func TestNormalizeEnvName(t *testing.T) {
  13. cases := []struct {
  14. input string
  15. output string
  16. }{
  17. {
  18. input: "a",
  19. output: "A",
  20. },
  21. {
  22. input: "a.a",
  23. output: "A_A",
  24. },
  25. {
  26. input: "A.A.B",
  27. output: "A_A_B",
  28. },
  29. }
  30. for _, test := range cases {
  31. if v := platform.NormalizeEnvName(test.input); v != test.output {
  32. t.Error("unexpected output: ", v, " want ", test.output)
  33. }
  34. }
  35. }
  36. func TestEnvFlag(t *testing.T) {
  37. if v := (platform.EnvFlag{
  38. Name: "xxxxx.y",
  39. }.GetValueAsInt(10)); v != 10 {
  40. t.Error("env value: ", v)
  41. }
  42. }
  43. // TestWrongErrorCheckOnOSStat is a test to detect the misuse of error handling
  44. // in os.Stat, which will lead to failure to find & read geoip & geosite files.
  45. func TestWrongErrorCheckOnOSStat(t *testing.T) {
  46. theExpectedDir := filepath.Join("usr", "local", "share", "v2ray")
  47. getAssetLocation := func(file string) string {
  48. for _, p := range []string{
  49. filepath.Join(theExpectedDir, file),
  50. } {
  51. // errors.Is(fs.ErrNotExist, err) is a mistake supposed Not to
  52. // be discovered by the Go runtime, which will lead to failure to
  53. // find & read geoip & geosite files.
  54. // The correct code is `errors.Is(err, fs.ErrNotExist)`
  55. if _, err := os.Stat(p); err != nil && errors.Is(fs.ErrNotExist, err) {
  56. continue
  57. }
  58. // asset found
  59. return p
  60. }
  61. return filepath.Join("the", "wrong", "path", "not-exist.txt")
  62. }
  63. notExist := getAssetLocation("not-exist.txt")
  64. if filepath.Dir(notExist) != theExpectedDir {
  65. t.Error("asset dir:", notExist, "not in", theExpectedDir)
  66. }
  67. }
  68. func TestGetAssetLocation(t *testing.T) {
  69. exec, err := os.Executable()
  70. common.Must(err)
  71. loc := platform.GetAssetLocation("t")
  72. if filepath.Dir(loc) != filepath.Dir(exec) {
  73. t.Error("asset dir: ", loc, " not in ", exec)
  74. }
  75. os.Setenv("v2ray.location.asset", "/v2ray")
  76. if runtime.GOOS == "windows" {
  77. if v := platform.GetAssetLocation("t"); v != "\\v2ray\\t" {
  78. t.Error("asset loc: ", v)
  79. }
  80. } else {
  81. if v := platform.GetAssetLocation("t"); v != "/v2ray/t" {
  82. t.Error("asset loc: ", v)
  83. }
  84. }
  85. }