golang test temp directory
Just to compare vs. what you have with ioutil.TempDir
, here's what things look like with io.Reader
:
// Load main.conf from the specified file path
func LoadMainSettings(src io.Reader) (*MainSettings, error) {
b, err := ioutil.ReadAll(src)
if err != nil { return nil, err }
r := &MainSettings{}
err = json.Unmarshal(b, r)
if err != nil { return nil, err }
return r, nil
}
Specifically, we change the argument from a path
string to a src
io.Reader
instance, and we replace the ioutil.ReadFile
with an ioutil.ReadAll
.
The test case that you've written then ends up being a bit shorter precisely because we can dispense with file operations:
s, err := LoadMainSettings(strings.NewReader("{...sample config data...}"))
You could use ioutil.TempDir or TempFile from the same package.
Since Go version 1.15 there is now T.TempDir()
in the standard testing
package. The docs explain it as follows:
TempDir returns a temporary directory for the test to use. The directory is automatically removed by Cleanup when the test and all its subtests complete. Each subsequent call to t.TempDir returns a unique directory; if the directory creation fails, TempDir terminates the test by calling Fatal.