天天看点

go 测试依赖/项目根目录

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

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

转载注明:csdn链接https://blog.csdn.net/qq_35244529/article/details/114312616

  • 如何简要解决

    1.经过大量测试与实验, 目前发现通过

    $GOPATH

    的方式最为简单方便, 实现如下

    2.前提: 拥有

    GOPATH

    环境变量, 项目目录在

    GOPATH

    下,或者项目使用

    go modules

    ,go.mod与执行文件同级
  • 测试的配置文件读取(源码 gt conf_func.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
}
           
  • 获取项目根目录(源码:gt file_func.go)

思路来源: go env 命令

原理: 借助GOPATH和GOMOD两种方式实现项目目录的获取

ps: 之所以使用exec.Command(“go”, “env”, “GOMOD”), 不使用os.Getenv(“GOMOD”),感兴趣的可以试试

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
}
           
  • 来看上面函数作用

    1.将默认依赖的配置 相对路径

    conf/

    转换成绝对路径(结合

    GOPATH

    GOMOD

    )

    2.如过不满足前提, 则使用默认的相对路径

    conf/

    3.采用目录递归和执行文件的路径, 一级一级的方式查找

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

来自我的小站: https://deercoder.com/2020/05/12/go.html