lundi 30 juillet 2018

Use relative path in init function cannot be found in test

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.

Aucun commentaire:

Enregistrer un commentaire