Running tests in Go - Time & Space Complexity
When running tests in Go, it's important to know how the time needed grows as tests increase.
We want to see how the total test time changes when we add more tests.
Analyze the time complexity of the following code snippet.
func TestAll(t *testing.T) {
for i := 0; i < len(testCases); i++ {
i := i // capture loop variable
t.Run(testCases[i].name, func(t *testing.T) {
result := SomeFunction(testCases[i].input)
if result != testCases[i].expected {
t.Errorf("got %v, want %v", result, testCases[i].expected)
}
})
}
}
This code runs a series of tests, one for each case in the testCases list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each test case and running a test.
- How many times: Once for each test case in the list.
Each test case adds one more test to run, so the total time grows as the number of tests grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Runs 10 tests |
| 100 | Runs 100 tests |
| 1000 | Runs 1000 tests |
Pattern observation: The total work grows directly with the number of tests.
Time Complexity: O(n)
This means the total test time grows in a straight line as you add more tests.
[X] Wrong: "Running more tests doesn't affect total time much because tests run fast."
[OK] Correct: Even if each test is quick, adding many tests adds up, so total time grows with the number of tests.
Understanding how test time grows helps you write efficient tests and manage testing time well in real projects.
"What if each test case itself runs a loop over data? How would the time complexity change?"