23

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.

It's not entirely necessary to the question, but here is the basic 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 := &MainSettings{}
    err = json.Unmarshal(b, r)
    if err != nil { return nil, err }

    return r, nil

}

and the test:

// 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") // <-- what should this path be??
    if err != nil { panic(err) }

    // more sanity checking...

}

That said, my specific questions are:

  • Is there a proper place for static assets (like sample config files) that are only applicable to tests?
  • During test execution is there a proper (cross platform, gets cleaned up with 'go clean') location to write out temporary files?

(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...)


EDIT: Ended up using this approach for the test:

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())

But the other suggestion of making LoadMainSettings accept an io.Reader instead of a string is also a good idea.

5
  • 2
    Can you write your test so it uses an io.Reader directly? If so, then your test case won't need to depend on the file system, as your tests can use strings.NewReader to provide the appropriate test content in the test itself.
    – dyoo
    Commented Sep 29, 2013 at 18:57
  • Hm - that's an interesting idea... Slightly more cumbersome for the caller but otherwise, yes, that would work in this case. Commented Sep 29, 2013 at 19:01
  • 1
    It shouldn't be more cumbersome for the caller. A file is an io.Reader already.
    – Tyler
    Commented Sep 30, 2013 at 2:04
  • True - but a string is not, but I get your point. I agree it's a good idea. Commented Sep 30, 2013 at 3:51
  • 1
    just for the record, if using a func with a path parameter is more convenient, one can write a public function with a path parameter, and call a private func from within it with an io.Reader (with the file opened). Then test only the internal func. The other is just a wrapper, all it does is compiler "tested".
    – zupa
    Commented May 22, 2014 at 11:54

5 Answers 5

38

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.

14

You could use ioutil.TempDir or TempFile from the same package.

1
  • Cool - yes, that's what I ended up doing. Commented Sep 30, 2013 at 3:52
10

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...}"))
3
  • Right, makes sense on that - for the test. It also means the caller in the main program would be doing: f, err := os.Open("conf/main.conf"); /*check for file open error*/ defer f.close(); s, err := LoadMainSettings(f); If configs are always read from files, and I have several different types (LoadSomeOtherSettings(), LoadYetAnotherConfig(), etc.), I think this approach may not be the best way. Unless I'm missing something... Commented Sep 30, 2013 at 5:11
  • one other thing: I guess I'm comparing this to my experience with Java where you usually have an output directory created as part of the JUnit test suite execution and it often contains not only the results of the tests but a temp dir where test related items can go. And you know that when the "clean" is run on the build it will all go away. Makes things simple. Was just wondering if there was some corresponding concept on this that existed in go - but as I'm seeing (and you're pointing out) it's probably better to just approach the problem differently. Commented Sep 30, 2013 at 5:39
  • Yup. Temporary files are also fine. You see them in the 'testdata' subdirectory of packages such as golang.org/src/pkg/net/testdata. So no hard-and-fast rule here: sometimes it makes sense to have your test data in files, and sometimes it makes sense to embed them in tests. As in Java (where you see java.io.InputStream and java.io.Reader everywhere), you'll see that the majority of Go code works with generic io.Reader, so I just wanted to make sure that it was documented as an approach to your question somewhere. :P
    – dyoo
    Commented Sep 30, 2013 at 6:12
0

You can do this too:

uniqueTempDir, err := os.MkdirTemp(os.TempDir(), "*-myOptionalSuffix")
if err != nil {
    return err
}
0

You can do this:

go env -w GOTMPDIR="C:\Users<user>\go\tmp"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.