我有一个简单的函数,它将配置文件解析为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
}
Run Code Online (Sandbox Code Playgroud)
和测试:
// 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...
}
Run Code Online (Sandbox Code Playgroud)
那就是说,我的具体问题是:
(注意:我在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())
Run Code Online (Sandbox Code Playgroud)
但另一个让LoadMainSettings接受io.Reader
而不是a string
的建议也是一个好主意.
只是为了与你所拥有ioutil.TempDir
的东西进行比较,这里的内容是io.Reader
:
// Load main.conf from the specified file path
func LoadMainSettings(src io.Reader) (*MainSettings, error) {
b, err := ioutil.ReadAll(src)
if err != nil { return nil, err }
r := &MainSettings{}
err = json.Unmarshal(b, r)
if err != nil { return nil, err }
return r, nil
}
Run Code Online (Sandbox Code Playgroud)
具体来说,我们改变从参数path
字符串的src
io.Reader
实例,我们在更换ioutil.ReadFile
用ioutil.ReadAll
.
您编写的测试用例最后会缩短一点,因为我们可以免除文件操作:
s, err := LoadMainSettings(strings.NewReader("{...sample config data...}"))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11537 次 |
最近记录: |