我正在为单元测试编写实用程序函数,单元测试在多个包中使用.此实用程序函数必须读取特定文件(始终是同一文件).这里有三个不起作用的解决方案,用于解释我在寻找什么以及为什么.
硬编码绝对路径.这会失败,因为尝试测试项目的另一个用户可能在绝对路径上有不同的前缀.
硬编码定义实用程序功能的文件路径的相对路径.这会失败,因为导入和使用此函数的包不一定与文件层次结构的级别与定义实用程序函数的文件相同,并且相对路径是相对于导入程序解释的,而不是导入的.
传入每个调用者相对于调用者包的文件的相对路径.这实际上有效,但似乎非常冗长,因为现在必须更改每个调用者以传递一个文件.
我看到第四个解决方案,我可以在实用程序函数中硬编码一个相对于顶级包的根目录的路径.但是,我还没有找到一种方法来获取代码中的根目录,虽然我怀疑有一个,因为可以从根解析导入.
那么,我怎么能得到抢手的根目录呢?
我查看了各种Go文档,但迄今为止未能找到解决方案.我也看到了这个问题,但解决方法相当于上面的#3.
Ole*_*hel 42
您也可以在没有C的情况下使用我的方法
package mypackage
import (
"path/filepath"
"runtime"
"fmt"
)
var (
_, b, _, _ = runtime.Caller(0)
basepath = filepath.Dir(b)
)
func PrintMyPath() {
fmt.Println(basepath)
}
Run Code Online (Sandbox Code Playgroud)
https://play.golang.org/p/ifVRIq7Tx0
Xeo*_*oss 14
基于Oleksiy的答案,您可以在您的项目中创建一个子包,./internal/projectpath/projectpath.go并粘贴以下内容:
package projectpath
import (
"path/filepath"
"runtime"
)
var (
_, b, _, _ = runtime.Caller(0)
// Root folder of this project
Root = filepath.Join(filepath.Dir(b), "../..")
)
Run Code Online (Sandbox Code Playgroud)
然后你可以projectpath.Root在任何其他包中使用你的项目的根文件夹。
Del*_*ele 14
返回应用程序的根:
import (
"path"
"path/filepath"
"runtime"
)
func RootDir() string {
_, b, _, _ := runtime.Caller(0)
d := path.Join(path.Dir(b))
return filepath.Dir(d)
}
Run Code Online (Sandbox Code Playgroud)
转到目录:
// from Executable Directory
ex, _ := os.Executable()
fmt.Println("Executable DIR:", filepath.Dir(ex))
// Current working directory
dir, _ := os.Getwd()
fmt.Println("CWD:", dir)
// Relative on runtime DIR:
_, b, _, _ := runtime.Caller(0)
d1 := path.Join(path.Dir(b))
fmt.Println("Relative", d1)
Run Code Online (Sandbox Code Playgroud)
小智 -3
是的,可以查找包路径:
路径查找.go:
package main
/*
const char* GetMyPathFILE = __FILE__;
*/
import "C"
import "path/filepath"
var basepath = ""
//GetMyPath Returns the absolute directory of this(pathfind.go) file
func GetMyPath() string {
if basepath == "" {
g := C.GoString(C.GetMyPathFILE)
basepath = filepath.Dir(g)
}
return basepath
}
Run Code Online (Sandbox Code Playgroud)
您所要做的就是将此文件复制到您的项目中。请记住,这会带来文件的路径,而不是调用者的路径,因此您必须将函数/文件复制到需要该函数的每个项目中。此外,如果您将其与其他代码一起放入文件中,请务必尊重CGO' s 导入规则。
| 归档时间: |
|
| 查看次数: |
9234 次 |
| 最近记录: |