[英]How to make Go tests Work with Filesystem
I'm experiencing some problems testing my Go application with VsCode. 我在使用VsCode测试我的Go应用程序时遇到了一些问题。 This is my launch.json
这是我的launch.json
{
"name": "Test",
"type": "go",
"request": "launch",
"mode": "test",
"program": "${workspaceFolder}/test",
"env": {},
"args": []
}
Now i have the problem that my application is supposed to write files in a subfolder (atm it's ./temp). 现在我有一个问题,我的应用程序应该在子文件夹(atm是./temp)中写入文件。 To do this i have 2 functions the first one is to determine the filepath
为此,我有2个功能,第一个是确定文件路径
func getFilePath() string {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
panic(err)
}
return dir + "/temp/ocicd-config.yaml"
}
and another one to Save the file 另一个用于保存文件
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)
}
as well as to load the file 以及加载文件
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
}
Now the problem is that VsCode makes the application run in the ./test subfolder which makes my application try to load from and save to ./test/temp which is not what i want. 现在的问题是VsCode使应用程序在./test子文件夹中运行,这使我的应用程序尝试从中加载并保存到./test/temp,这不是我想要的。 I tried to change my launch.json to actually use ${workspace} as program and use "./test" as an argument but that makes the tests stop working alltogether.
我试图将launch.json更改为实际使用$ {workspace}作为程序,并使用“ ./test”作为参数,但这使测试无法一起工作。 Now I am pretty lost.
现在我很迷路。 Any ideas how I could solve this problem?
有什么想法可以解决这个问题吗?
Instead of having tests write directly to a file on disk (potential for concurrency issues with this model), you should use a layer of abstraction on top of the filesystem (not ioutil
). 与其让测试直接写到磁盘上的文件(此模型可能导致并发问题),
ioutil
将文件系统之上使用抽象层(而不是ioutil
)。
github.com/spf13/afero
is a great library to use for this purpose. github.com/spf13/afero
是一个很棒的库,可用于此目的。 For your test cases, you can simply pass a MemFs layer instead of the OsFs (instructions here ). 对于您的测试用例,您可以简单地传递MemFs层而不是OsFs( 此处的说明)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.