在测试中找不到在init函数中使用相对路径

在测试中找不到在init函数中使用相对路径

问题描述:

I'm running into an annoying problem when using relative path in the init function which cannot be found by the unit test.

Say I have a project structured like:

.
├── conf
│   └── blacklist
├── filter
│   ├── filter.go
│   └── filter_test.go

And in the init function of filter.go, I try to load the blacklist by using relative path conf/blacklist to avoid loading it multiple times. Since the default working directory is exactly the project root directory, it works well with compiled binary. However filter_test.go will panic by panic: open conf/blacklist: no such file or directory, becasue go test always uses the package directory as the working directory.

I also referred this solution, which could dynamically build the relative path to find the config file. It did work well until I add the covermode=set flag and try to do some coverage testing. It seems that the covermode would rewrite and generate some middle packages like _obj, which makes the dynamical relative path not working any more.

Has anyone run into the same problem before? I'm still new to golang for a couple of months. Any suggestions will be appreciated.

在init函数中使用相对路径时,我遇到了一个烦人的问题,而单元测试无法找到相对路径 。 p>

说我有一个结构如下的项目: p>

 。
├──conf 
│└──黑名单
├  ──filter 
│├──filter.go 
│└──filter_test.go 
  code>  pre> 
 
 

并在 init code>函数中 filter.go code>中,我尝试通过使用相对路径 conf / blacklist code>加载黑名单,以避免多次加载。 由于默认工作目录正是项目根目录 目录,它与已编译的二进制文件很好地兼容。 但是 filter_test.go code>会被 panic恐慌:打开conf / blacklist:没有这样的文件或目录 code>,因为go test始终将软件包目录用作工作目录。 / p>

我还引用了此解决方案,该解决方案可以动态构建相对路径来查找 配置文件。 在我添加 covermode = set code>标志并尝试进行一些覆盖率测试之前,它确实运行良好。 似乎 covermode code>将重写并生成一些中间包,例如 _obj code>,这使得动态相对路径不再起作用。 p>

以前有人遇到过同样的问题吗? 我刚接触golang有几个月了。 任何建议将不胜感激。 p> div>

A simple solution is to run tests using something like SRC_ROOT=$PWD go test and then inside the test that want to access files use os.Getenv("SRC_ROOT").