Tests should be completely isolated from each other and clean up after themselves to prevent interference. 1. **Use testing utilities properly**: Leverage the standard library's testing helpers correctly.
Tests should be completely isolated from each other and clean up after themselves to prevent interference.
// GOOD: Let t.TempDir() handle directory creation and cleanup
td := t.TempDir()
// BAD: Don't call os.MkdirAll() after t.TempDir()
td := t.TempDir()
os.MkdirAll(td, 0755) // Unnecessary - directory already exists with proper permissions
// GOOD: Save and restore global state
p := tfversion.Prerelease
v := tfversion.Version
defer func() {
tfversion.Prerelease = p
tfversion.Version = v
}()
// GOOD: Sort keys or values before assertion when using maps
// Instead of directly asserting on map values which may be in random order
sortedKeys := make([]string, 0, len(someMap))
for k := range someMap {
sortedKeys = append(sortedKeys, k)
}
sort.Strings(sortedKeys)
// Verify no resources remain after test
if provider.ResourceCount() > 0 {
t.Fatalf("should have deleted all resources on completion but left %v",
provider.ResourceString())
}
Properly isolated tests lead to more reliable test suites, easier debugging, and prevent issues where test results depend on execution order.
Enter the URL of a public GitHub repository