(This question is not about the playground per se, one commenter requested a playground, which is why I provided one. This question is about the testing feature of Go.)
I'm getting the time like this in a unit test: time.Now()
Here is some code showing how I get the time using time.Now():
package main
import (
"log"
"testing"
"time"
)
// LastIndex returns the index of the last instance of x in list, or
// -1 if x is not present. The loop condition has a fault that
// causes some tests to fail. Change it to i >= 0 to see them pass.
func LastIndex(list []int, x int) int {
for i := len(list) - 1; i > 0; i-- {
if list[i] == x {
return i
}
}
return -1
}
func TestLastIndex(t *testing.T) {
tests := []struct {
list []int
x int
want int
mytime time.Time
}{
{list: []int{1}, x: 1, want: 0, mytime: time.Now()},
{list: []int{1, 1}, x: 1, want: 1, mytime: time.Now()},
{list: []int{2, 1}, x: 2, want: 0, mytime: time.Now()},
{list: []int{1, 2, 1, 1}, x: 2, want: 1, mytime: time.Now()},
{list: []int{1, 1, 1, 2, 2, 1}, x: 3, want: -1, mytime: time.Now()},
{list: []int{3, 1, 2, 2, 1, 1}, x: 3, want: 0, mytime: time.Now()},
}
for _, tt := range tests {
log.Println("Running test, mytime:", tt.mytime)
if got := LastIndex(tt.list, tt.x); got != tt.want {
t.Errorf("LastIndex(%v, %v) = %v, want %v", tt.list, tt.x, got, tt.want)
}
}
}
Despite calling the test several times, with a few seconds between, the "mytime" returned is exactly the same. Why is this?
(output redacted because some people misunderstand the question)
It seems a lot of you misunderstand the question completely. I'll state it like this again to make it easier to know what I mean:
- Execute the test and note the output times.
- Go grab a coffee.
- Execute the test again, and look at the times.
The times in step 1 and step 3 are the same.
Update: What seems to be a probable cause; the times given back by time.Now() is always going to be the time of code compilation, or something similar. Anyone can confirm this?