Possible issue with testing code
slonoed-uber opened this issue · comments
slonoed-uber commented
Test tables section https://github.com/uber-go/guide/blob/master/style.md#test-tables has this code
for _, tt := range tests {
t.Run(tt.give, func(t *testing.T) {
host, port, err := net.SplitHostPort(tt.give)
require.NoError(t, err)
assert.Equal(t, tt.wantHost, host)
assert.Equal(t, tt.wantPort, port)
})
}
It reused tt
across loops. While it would work in this particular example it may lead to issues when running in parallel because all runs will receive last item of tests
slice.
Possible fix is to create a variable to use in closure.
for _, tt := range tests {
tt := tt
t.Run(tt.give, func(t *testing.T) {
host, port, err := net.SplitHostPort(tt.give)
require.NoError(t, err)
assert.Equal(t, tt.wantHost, host)
assert.Equal(t, tt.wantPort, port)
})
}
Abhinav Gupta commented
Hey there! Yes, that would be a problem if we had a t.Parallel
inside the test like so:
for _, tt := range tests {
t.Run(tt.give, func(t *testing.T) {
t.Parallel()
// ...
})
}
In that case, the tt := tt
would be required. However, without it, we do not need this.
That said, it's completely reasonable for that section to advise use of tt := tt
for the case when t.Parallel is being used.