gpt4 book ai didi

file - 在Golang中跨不同测试加载数据文件

转载 作者:行者123 更新时间:2023-12-01 22:28:08 26 4
gpt4 key购买 nike

我有一个类似的目录结构:

./gen/items/items.go
./gen/items/items_test.go
./gen/items/data/items.xml
./engine/action/actions_test.go

items.go中,我有一个方法应该运行一次,并使用 items.xml加载的项目填充一些数据结构。我使用绝对路径执行此操作,当代码在 items_test.go中运行时可以使用,因为我假设go test中的当前工作目录是当前测试包的包根。

itemsXMLPath := "./data/items.xml"
absPath, err := path.Abs(itemsXMLPath)
if err != nil {
...
}
bytes, err := ioutil.ReadFile(absPath)

您可以在这里从 ./data/items.xml目录中看到为什么绝对路径 gen/items可以正常工作。

如果我在 actions_tests.go中运行测试,它将尝试使用 action的相对路径而失败,因为 data中没有 action dir。

当我在items.go中调用loadFromXML方法时,我希望它始终使用items目录中的相对路径,该路径将在下面搜索数据目录。

我假设由于调用代码在 items.go中,因此路径将从此处开始,但似乎它使用了测试运行程序或go运行程序的工作目录(如果我运行main.go)。

有没有一种方法可以确保是在测试运行中还是从主运行中使用,xml加载功能使用仓库中一致目录中的相对路径(例如,从MAIN或Windows 2000中运行时,我如何始终找到包根目录?一个测试)。

我敢肯定,有一种方法可以做到这一点,而不必复制测试数据,也可以不传递到loadFromXML函数的相对路径,该路径必须根据调用方法的位置进行调整!

最佳答案

我最终只是编写了一个可以从项目中任何正在运行的文件夹中找到根目录的函数,然后可以从此处应用相对路径。似乎是从主测试人员或测试运行人员开始运行的。

func getRootPath() string {
dir, err := os.Getwd()
if err != nil {
log.Fatal(err)
}

// Check if already in root directory (e.g. main.go)
lastSlashIndex := strings.LastIndex(dir, "/")
cName := dir[lastSlashIndex+1:]
if cName == "#root-folder-name#" {
return dir
}

// Get parent directory
parent := filepath.Dir(dir)
lastSlashIndex = strings.LastIndex(parent, "/")
pName := parent[lastSlashIndex+1:]

// If not at root, continue getting parent
for pName != "#root-folder-name#" {
parent = filepath.Dir(parent)
lastSlashIndex = strings.LastIndex(parent, "/")
pName = parent[lastSlashIndex+1:]
}
return parent
}

然后,我可以将该目录与相对路径连接起来,并在 filepath.Abs中使用
itemsXMLPath := getRootPath() + "/folder/path/data/items.xml"
absPath, err := filepath.Abs(itemsXMLPath)

关于file - 在Golang中跨不同测试加载数据文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58462402/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com