如何使Go测试与文件系统一起使用

I'm experiencing some problems testing my Go application with VsCode. This is my 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). To do this i have 2 functions the first one is to determine the filepath

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. 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. Now I am pretty lost. Any ideas how I could solve this problem?

查看全部
duan20081202
duan20081202
2019/07/31 15:21
  • testing
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复