Skip to content

Go Test Tempdir

DodaTech 1 min read

In this tutorial, you'll learn about Go Test: TempDir Cleanup. We cover key concepts, practical examples, and best practices.

Test temp directory -- Use t.TempDir() in Go tests for temporary directories that are automatically cleaned up.

The Problem

Creating temp dirs with os.MkdirTemp requires manual cleanup. t.TempDir() creates a temp directory that is automatically removed when the test completes.

Wrong

func TestWriteFile(t *testing.T) {
    dir, _ := os.MkdirTemp("", "test")
    defer os.RemoveAll(dir) // Manual cleanup
    // write file to dir
}

Output:

// Manual cleanup, easy to forget
func TestWriteFile(t *testing.T) {
    dir := t.TempDir() // Auto-cleaned!
    path := filepath.Join(dir, "test.txt")
    os.WriteFile(path, []byte("data"), 0644)
    data, _ := os.ReadFile(path)
    if string(data) != "data" {
        t.Error("unexpected content")
    }
}

Output:

// Test passes. Temp dir auto-removed.

Prevention

  • Use t.TempDir() for test temp directories
  • Automatically cleaned up after test
  • Unique per test, no name conflicts
  • Works with parallel tests
  • Also: t.Helper() for marking helper functions

Common Mistakes with test tempdir

  1. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  2. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  3. Using return to exit a function early instead of wrapping a pure value in the monad

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**What platform is t.TempDir() available?**

Go 1.15+. All platforms.

Does t.TempDir() work with t.Parallel()?

Yes. Each parallel test gets unique temp dir.

What about t.TempFile?

Not available. Use t.TempDir() and create your own files.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro