简体   繁体   English

Go中的资源文件

[英]Resources files in Go

I've got some binary files that are required to run some _test cases. 我有一些运行一些_test案例所需的二进制文件。

Currently the relative paths to these files are hardcoded into the tests, which I don't like since the tests break if you change anything in the folder hierarchy and make the tests fragile. 目前,这些文件的相对路径被硬编码到测试中,我不喜欢,因为如果您更改文件夹层次结构中的任何内容并使测试变得脆弱,测试就会中断。

Is there a preferred best practice for handling this, and resource files in general? 是否有一个首选的最佳实践来处理这个和资源文件?

The testing resource name may be hard coded but the path doesn't have to be. 测试资源名称可以是硬编码的,但路径不一定是。

(09:13) jnml@fsc-r550:~/src/tmp/SO/13854048$ ls -a
.  ..  a_test.go
(09:13) jnml@fsc-r550:~/src/tmp/SO/13854048$ cat a_test.go 
package foo

import (
        "testing"
        "io/ioutil"
)

func Test(t *testing.T) {
        b, err := ioutil.ReadFile("foo")
        if err != nil {
                t.Fatal(err)
        }

        t.Logf("resource content is: %s", b)
}
(09:13) jnml@fsc-r550:~/src/tmp/SO/13854048$ go test -v
=== RUN Test
--- FAIL: Test (0.00 seconds)
a_test.go:11:         open foo: no such file or directory
FAIL
exit status 1
FAIL        tmp/SO/13854048        0.005s
(09:14) jnml@fsc-r550:~/src/tmp/SO/13854048$

Correct, no such resource (yet). 正确,没有这样的资源(还)。 Let's create it. 让我们创造它。

(09:14) jnml@fsc-r550:~/src/tmp/SO/13854048$ echo blah > foo
(09:14) jnml@fsc-r550:~/src/tmp/SO/13854048$ go test -v
=== RUN Test
--- PASS: Test (0.00 seconds)
a_test.go:14:         resource content is: blah
PASS
ok          tmp/SO/13854048        0.007s
(09:14) jnml@fsc-r550:~/src/tmp/SO/13854048$ cd
(09:14) jnml@fsc-r550:~$ go test -v tmp/SO/13854048
=== RUN Test
--- PASS: Test (0.00 seconds)
a_test.go:14:         resource content is: blah
PASS
ok          tmp/SO/13854048        0.005s
(09:14) jnml@fsc-r550:~$ 

Note (in the last run above) that the cwd is correct even when go test is invoked from elsewhere. 注意(在上面的上一次运行中)即使从其他地方调用go test ,cwd也是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM