title: Load data files across different tests in Golang
body: <p>I have a directory structure like:</p>
  
  <pre><code>./gen/items/items.go
  ./gen/items/items_test.go
  ./gen/items/data/items.xml
  ./engine/action/actions_test.go
  </code></pre>
  
  <p>In <code>items.go</code> I have a method which is supposed to run once, and populate some data structure with the items loaded from <code>items.xml</code>. I do this with an absolute path, which works when the code is running in <code>items_test.go</code>, as I assume the current working directory in go test is the package root of the current tested package.</p>
  
  <pre class="lang-golang prettyprint-override"><code>itemsXMLPath := "./data/items.xml"
  absPath, err := path.Abs(itemsXMLPath)
  if err != nil {
      ...
  }
  bytes, err := ioutil.ReadFile(absPath)
  </code></pre>
  
  <p>You can see here why the absolute path <code>./data/items.xml</code> works fine from the <code>gen/items</code> dir.</p>
  
  <p>If I run tests in <code>actions_tests.go</code>, it tries to use the relative path from <code>action</code> and fails because there isn't a <code>data</code> dir in <code>action</code>.</p>
  
  <p><strong>When I call my loadFromXML method in <code>items.go</code>, I want it to always use the relative path from the <code>items</code> dir, which will search the data dir below.</strong></p>
  
  <p>I assumed since the calling code is in <code>items.go</code>, 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).</p>
  
  <p>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).</p>
  
  <p>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!</p>