gpt4 book ai didi

file - golang 测试临时目录

转载 作者:IT老高 更新时间:2023-10-28 13:08:52 24 4
gpt4 key购买 nike

我有一个将配置文件解析为 JSON 的简单函数。我想编写一个测试,它要么使用一些示例静态配置文件并解析它们,要么在测试期间创建示例并尝试解析它们。

这个问题并不完全需要,但这里是基本代码:

// config.go

// ...(package,imports)...

// Overall settings - corresponds to main.conf
type MainSettings struct {
// stuff
}

// Load main.conf from the specified file path
func LoadMainSettings(path string) (*MainSettings, error) {

b, err := ioutil.ReadFile(path)
if err != nil { return nil, err }

r := &MainSettings{}
err = json.Unmarshal(b, r)
if err != nil { return nil, err }

return r, nil

}

和测试:

// config_test.go

func TestLoadMainSettings(t *testing.T) {

// possibly generate some example config files,
// or use static samples packaged with the source

s, err := LoadMainSettings("conf/main.conf") // <-- what should this path be??
if err != nil { panic(err) }

// more sanity checking...

}

也就是说,我的具体问题是:

  • 是否有合适的位置存放仅适用于测试的静态 Assets (例如示例配置文件)?
  • 在测试执行期间,是否有适当的(跨平台,使用“go clean”清理)位置来写出临时文件?

(注意:我在 Linux 上运行我的大部分内容以进行登台和生产,并在 Mac 上运行本地开发人员 - 所以在实践中使用/tmp/作为测试的临时目录对我有用。但想知道是否有更好的方法。 ..)


编辑:最终使用这种方法进行测试:

f, err := ioutil.TempFile("", "testmainconf")
if err != nil { panic(err) }
defer syscall.Unlink(f.Name())
ioutil.WriteFile(f.Name(), []byte("{...sample config data...}"), 0644)

s, err := LoadMainSettings(f.Name())

但另一个让 LoadMainSettings 接受 io.Reader 而不是 string 的建议也是一个好主意。

最佳答案

从 Go 版本 1.15 开始,标准 testing 包中现在有 T.TempDir()docs explain it如下:

TempDir returns a temporary directory for the test to use. Thedirectory is automatically removed by Cleanup when the test and allits subtests complete. Each subsequent call to t.TempDir returns aunique directory; if the directory creation fails, TempDir terminatesthe test by calling Fatal.

关于file - golang 测试临时目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19081884/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com