![](/img/trans.png)
[英]Use Viper in a Go app and make sure both tests and runtime work
[英]How to make Go tests Work with Filesystem
我在使用VsCode测试我的Go应用程序时遇到了一些问题。 这是我的launch.json
{
"name": "Test",
"type": "go",
"request": "launch",
"mode": "test",
"program": "${workspaceFolder}/test",
"env": {},
"args": []
}
现在我有一个问题,我的应用程序应该在子文件夹(atm是./temp)中写入文件。 为此,我有2个功能,第一个是确定文件路径
func getFilePath() string {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
panic(err)
}
return dir + "/temp/ocicd-config.yaml"
}
另一个用于保存文件
func SaveToYaml(Config Structs.Project) {
fmt.Println("Saving Config")
yaml, err := yaml.Marshal(Config)
if err != nil {
panic(err)
}
fmt.Println(string(yaml))
ioutil.WriteFile(getFilePath(), yaml, 0644)
}
以及加载文件
func Load() Structs.Project {
fmt.Println("Loading Config")
file, err := ioutil.ReadFile(getFilePath())
if err != nil {
panic(err)
}
project := Structs.Project{}
err = yaml.Unmarshal(file, &project)
if err != nil {
panic(err)
}
return project
}
现在的问题是VsCode使应用程序在./test子文件夹中运行,这使我的应用程序尝试从中加载并保存到./test/temp,这不是我想要的。 我试图将launch.json更改为实际使用$ {workspace}作为程序,并使用“ ./test”作为参数,但这使测试无法一起工作。 现在我很迷路。 有什么想法可以解决这个问题吗?
与其让测试直接写到磁盘上的文件(此模型可能导致并发问题), ioutil
将文件系统之上使用抽象层(而不是ioutil
)。
github.com/spf13/afero
是一个很棒的库,可用于此目的。 对于您的测试用例,您可以简单地传递MemFs层而不是OsFs( 此处的说明)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.