I have a directory structure like:
./gen/items/items.go
./gen/items/items_test.go
./gen/items/data/items.xml
./engine/action/actions_test.go
In items.go I have a method which is supposed to run once, and populate some data structure with the items loaded from items.xml. I do this with an absolute path, which works when the code is running in items_test.go, as I assume the current working directory in go test is the package root of the current tested package.
itemsXMLPath := "./data/items.xml"
absPath, err := path.Abs(itemsXMLPath)
if err != nil {
...
}
bytes, err := ioutil.ReadFile(absPath)
You can see here why the absolute path ./data/items.xml works fine from the gen/items dir.
If I run tests in actions_tests.go, it tries to use the relative path from action and fails because there isn't a data dir in action.
When I call my loadFromXML method in items.go, I want it to always use the relative path from the items dir, which will search the data dir below.
I assumed since the calling code is in items.go, the path will go from there, but it seems it uses the working directory of the test runner or the go runner (if I run main.go).
Is there a way to ensure whether used in a test run, or from a main run, the xml load function uses a relative path from a consistent directory in the repo (e.g., how would I consistently find package root dir when ran from MAIN or a test).
I'm sure there is a way to achieve this without duplicating the test data, or without passing in a relative path to the loadFromXML function, which must be adjusted based on where the method is being called!