notexOPENOverview
Notex/Languages/Working with Temporary Directories
05.07LESSON 07 OF 29 · 1 MIN READ

Working with Temporary Directories

Always free to read

If your test uses temporary files, use the t.TempDir method. It creates a new temporary directory every time it is invoked and returns the full path of the directory. It also registers a handler with Cleanup to delete the directory and its contents when the test completes. Example 6-2 demonstrates its usage:

Example 6-2. Using t.TempDir

// createFile is a helper function called from multiple tests
func createFile(t *testing.T) string {
    t.Helper()
    tempDir := t.TempDir()

    f, err := os.CreateTemp(tempDir, "tempFile")
    if err != nil {
        t.Fatal("error creating temp file", err)
    }
    defer f.Close()
    // write some data to f
    f.Write([]byte("Hello"))
    return f.Name()
}

func TestFileProcessing(t *testing.T) {
    fName := createFile(t)
    // do testing, don't worry about cleanup
}

You can find this example in the examples/tempdir directory or on the Go playground.

Progress is saved on this device.
KEEP EXPLORING

One note leads to another.

Back to the library →
⌕
Search across the entire library ⌘ K