论go的测试依赖如何解决(相对/绝对路径)/获取真实项目根目录

众所周知, go的测试深受吐嘈, 整个项目运行并不会有依赖问题, 但是分开测试时, 常常会提示无法找到依赖


import "github.com/dreamlu/gt/tool/file/file_func"

// dir: default is conf/
// change dir to abs /xxx/conf/
// new abs conf dir
func newConf(dir string) string {
    return file_func.ProjectPath() + dir
}
func ProjectPath() (path string) {
	// default linux/mac os
	var (
		sp = "/"
		ss []string
	)
	if runtime.GOOS == "windows" {
		sp = "\\"
	}

	// GOMOD
	// in go source code:
	// // Check for use of modules by 'go env GOMOD',
	// // which reports a go.mod file path if modules are enabled.
	// stdout, _ := exec.Command("go", "env", "GOMOD").Output()
	// gomod := string(bytes.TrimSpace(stdout))
	stdout, _ := exec.Command("go", "env", "GOMOD").Output()
	path = string(bytes.TrimSpace(stdout))
	if path != "" {
		ss = strings.Split(path, sp)
		ss = ss[:len(ss)-1]
		path = strings.Join(ss, sp) + sp
		return
	}

	// GOPATH
	fileDir, _ := os.Getwd()
	path = os.Getenv("GOPATH") // < go 1.17 use
	ss = strings.Split(fileDir, path)
	if path != "" {
		ss2 := strings.Split(ss[1], sp)
		path += sp
		for i := 1; i < len(ss2); i++ {
			path += ss2[i] + sp
			if Exists(path) {
				return path
			}
		}
	}
	return
}

经测试, linux上, 任何路径下的测试文件均可以执行, 不会缺少依赖文件