go - 如何使 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”作为参数,但这会使测试一起停止工作。现在我很迷茫。有什么想法可以解决这个问题吗?
解决方案
与其让测试直接写入磁盘上的文件(此模型可能存在并发问题),不如在文件系统之上使用抽象层(不是ioutil
)。
github.com/spf13/afero
是用于此目的的一个很好的库。对于您的测试用例,您可以简单地传递 MemFs 层而不是 OsFs(此处的说明)。
推荐阅读
- python - Django:如何从表中的每一行中选择列及其最大值和最小值的值?
- html - Bootstrap hamburger menu mobile - 点击后会出现然后消失
- .net - 无法使用 LocalHost 调试 Web 应用程序
- python - 如何使用 lopps 找到给定值的一对搜寻值?
- python - python上所有可能的重复组合和排列
- html - Bootstrap 模态表单发布两次 Django
- r - 引导 poLCA - Rstudio 版本 3.6.1
- timestamp - 如何在 Vega 图表的 x 轴上显示 dateTime 值,时间间隔为 5 分钟
- maven - scss 文件更改未注册
- css - 使用 CSS 变量(CSS 自定义属性)时,为什么设置语法和获取语法不同?