From 4bbe672ffd71f8c306398187a7fe841a0c41215d Mon Sep 17 00:00:00 2001 From: Loyalsoldier <10487845+Loyalsoldier@users.noreply.github.com> Date: Tue, 13 Apr 2021 10:52:01 +0800 Subject: [PATCH] Test: add test to avoid the error of missing geoip & geosite (#895) --- common/platform/platform_test.go | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/common/platform/platform_test.go b/common/platform/platform_test.go index f02e9b682..b7dbab351 100644 --- a/common/platform/platform_test.go +++ b/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)