Browse Source

Test: add test to avoid the error of missing geoip & geosite (#895)

Loyalsoldier 4 years ago
parent
commit
4bbe672ffd
1 changed files with 29 additions and 0 deletions
  1. 29 0
      common/platform/platform_test.go

+ 29 - 0
common/platform/platform_test.go

@@ -1,6 +1,8 @@
 package platform_test
 
 import (
+	"errors"
+	"io/fs"
 	"os"
 	"path/filepath"
 	"runtime"
@@ -43,6 +45,33 @@ func TestEnvFlag(t *testing.T) {
 	}
 }
 
+// TestWrongErrorCheckOnOSStat is a test to detect the misuse of error handling
+// in os.Stat, which will lead to failure to find & read geoip & geosite files.
+func TestWrongErrorCheckOnOSStat(t *testing.T) {
+	theExpectedDir := filepath.Join("usr", "local", "share", "v2ray")
+	getAssetLocation := func(file string) string {
+		for _, p := range []string{
+			filepath.Join(theExpectedDir, file),
+		} {
+			// errors.Is(fs.ErrNotExist, err) is a mistake supposed Not to
+			// be discovered by the Go runtime, which will lead to failure to
+			// find & read geoip & geosite files.
+			// The correct code is `errors.Is(err, fs.ErrNotExist)`
+			if _, err := os.Stat(p); err != nil && errors.Is(fs.ErrNotExist, err) {
+				continue
+			}
+			// asset found
+			return p
+		}
+		return filepath.Join("the", "wrong", "path", "not-exist.txt")
+	}
+
+	notExist := getAssetLocation("not-exist.txt")
+	if filepath.Dir(notExist) != theExpectedDir {
+		t.Error("asset dir:", notExist, "not in", theExpectedDir)
+	}
+}
+
 func TestGetAssetLocation(t *testing.T) {
 	exec, err := os.Executable()
 	common.Must(err)