file - golang 测试临时目录

标签 file testing go

我有一个将配置文件解析为 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. The directory is automatically removed by Cleanup when the test and all its subtests complete. Each subsequent call to t.TempDir returns a unique directory; if the directory creation fails, TempDir terminates the test by calling Fatal.

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

相关文章:

go - 如何理解golang文档?

objective-c - 从文件中读取数据

java - 传递要捕获的异常类型

c++ - 多次调用单个测试 - Google 测试

android - 运行测试时如何更改 android.permission 设置

validation - 验证结构的惯用方法

google-app-engine - 使用 golang 调试 App 引擎——一定有更好的方法吗?

c - 即使文件不存在,fopen也会返回非空指针

file - 如何 'cut' 为空?

c - 如何将文本添加到c语言的结束文件文本中