douxing8323 2012-12-13 06:14
浏览 53
已采纳

Go中的资源文件

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条回答 默认 最新

  • duanrao3371 2012-12-13 08:22
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习残差模块模型
  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)