英文:
Resources files in Go
问题
我有一些二进制文件,这些文件是运行一些_test
测试用例所需的。
目前,这些文件的相对路径被硬编码到测试中,我不喜欢这样做,因为如果在文件夹层次结构中更改任何内容,测试就会中断,使得测试变得脆弱。
有没有处理这个问题的首选最佳实践,以及一般资源文件的处理方式?
英文:
I've got some binary files that are required to run some _test
cases.
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?
答案1
得分: 5
测试资源名称可能是硬编码的,但路径不必如此。
(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$
正确,没有这样的资源(尚未创建)。让我们创建它。
(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:~$
注意(上面的最后一次运行),即使从其他地方调用go test
,当前工作目录也是正确的。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论