首页 > 解决方案 > 如何使 Go 测试与文件系统一起工作

问题描述

我在使用 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”作为参数,但这会使测试一起停止工作。现在我很迷茫。有什么想法可以解决这个问题吗?

标签: gotestingvisual-studio-code

解决方案


与其让测试直接写入磁盘上的文件(此模型可能存在并发问题),不如在文件系统之上使用抽象层(不是ioutil)。

github.com/spf13/afero是用于此目的的一个很好的库。对于您的测试用例,您可以简单地传递 MemFs 层而不是 OsFs(此处的说明)。


推荐阅读