title: golang test temp directory
body: <p>I have a simple function which parses a config file as JSON.  I want to write a test which either uses some sample static config files and parses them, or creates the samples during the test and tries to parse them.</p>
  
  <p>It's not entirely necessary to the question, but here is the basic code:</p>
  
  <pre><code>// config.go
  
  // ...(package,imports)...
  
  // Overall settings - corresponds to main.conf
  type MainSettings struct {
      // stuff
  }
  
  // Load main.conf from the specified file path
  func LoadMainSettings(path string) (*MainSettings, error) {
  
      b, err := ioutil.ReadFile(path)
      if err != nil { return nil, err }
  
      r := &amp;MainSettings{}
      err = json.Unmarshal(b, r)
      if err != nil { return nil, err }
  
      return r, nil
  
  }
  </code></pre>
  
  <p>and the test:</p>
  
  <pre><code>// config_test.go
  
  func TestLoadMainSettings(t *testing.T) {
  
      // possibly generate some example config files,
      // or use static samples packaged with the source
  
      s, err := LoadMainSettings("conf/main.conf") // &lt;-- what should this path be??
      if err != nil { panic(err) }
  
      // more sanity checking...
  
  }
  </code></pre>
  
  <hr>
  
  <p>That said, my specific questions are:</p>
  
  <ul>
  <li>Is there a proper place for static assets (like sample config files) that are only applicable to tests?</li>
  <li>During test execution is there a proper (cross platform, gets cleaned up with 'go clean') location to write out temporary files?</li>
  </ul>
  
  <p>(Note: I run most of my stuff on Linux for staging and production and Mac for local dev - so using /tmp/ as a temp dir for tests works for me in practice.  But was wondering if there's a better way...)</p>
  
  <hr>
  
  <p><strong>EDIT:</strong> Ended up using this approach for the test:</p>
  
  <pre><code>f, err := ioutil.TempFile("", "testmainconf")
  if err != nil { panic(err) }
  defer syscall.Unlink(f.Name())
  ioutil.WriteFile(f.Name(), []byte("{...sample config data...}"), 0644)
  
  s, err := LoadMainSettings(f.Name())
  </code></pre>
  
  <p>But the other suggestion of making LoadMainSettings accept an <code>io.Reader</code> instead of a <code>string</code> is also a good idea. </p>