dongli8722 2015-08-13 13:59
浏览 104
已采纳

无法在程序和单元测试中使用相同的相对路径

In my Go Project I use a function that opens a specific file and returns its content. The file is stored in another directory but still inside my project directory.

package infrastructure

func openKey() ([]byte, error) {
    if path, err := filepath.Abs("../security/key.rsa"); err != nil {
        return nil, err
    } 

    return ioutil.ReadFile(path)
}

This function works if I call it from a unit test. But if I call the same function in my program, I've this error:

2015/08/13 15:47:54 open /me/go/src/github.com/myaccount/security/key.rsa: no such file or directory

The correct absolute path of the file is:

/me/go/src/github.com/myaccount/myrepo/security/key.rsa

Both code that use the openKey function (from my program and unit test) are in the same package: infrastructure

Here is how I execute my program:

go install && ../../../../bin/myproject

And how I execute my unit tests:

go test ./...

And finally the directory structure of my project:

go/src/github.com/myaccount/myrepo/: 
- main.go
- security:
    - key.rsa // The file that I want to open
    - ...
- infrastructure
    - openFile.go // The file with the func `openKey``
    - server.go // The file with the func that call the func `openKey`
    - openFile_test.go // The unit test that calls the func `openKey`

Edit:

Here are the absolute paths of where the binary of my program is located:

/Users/me/Documents/Développement/Jean/go/bin

And where my unit tests are located:

/var/folders/tj/8ywtc7pj3rs_j0y6zzldwh5h0000gn/T/go-build221890578/github.com/myaccount/myrepo/infrastructure/_test

Any suggestion?
Thanks!

  • 写回答

2条回答 默认 最新

  • douchang8758 2015-08-13 14:27
    关注

    First, you shouldn't use the same files when running your tests than when running your application in production. Because the test files are accessible to everyone that has access to the repository, which is a security fail.

    As said in the comments, the problem is that when running your tests, the working directory is these of the source code (in fact, go copy the whole bunch into a temp directory prior to running the tests), while when you run the program for real, the working directory is the one you are running the command from, hence the wrong relative path.

    What I would advise is to use a configuration option to get a the file from which load your file (or a base directory to use with your paths). Either using an environment variable (I strongly encourage you to do that, see the 12factors manofesto for details), a configuration file, a command-line flag, etc.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制