Replace os.Setenv with testing.T.Setenv in tests

T.Setenv ensures that the environment is returned to its prior state
when the test ends. It also panics when called from a parallel test to
prevent racy test interdependencies.
This commit is contained in:
Chris Bandy 2023-04-15 10:09:47 -05:00
parent 53cccbe4f9
commit cf125a3561

View File

@ -26,7 +26,6 @@ import (
"net"
"net/http"
"net/url"
"os"
"reflect"
"strings"
"testing"
@ -205,7 +204,7 @@ func TestProxierWithNoProxyCIDR(t *testing.T) {
}
for _, test := range testCases {
os.Setenv("NO_PROXY", test.noProxy)
t.Setenv("NO_PROXY", test.noProxy)
actualDelegated := false
proxyFunc := NewProxierWithNoProxyCIDR(func(req *http.Request) (*url.URL, error) {
actualDelegated = true
@ -917,40 +916,28 @@ func TestIsProbableEOF(t *testing.T) {
}
}
func setEnv(key, value string) func() {
originalValue := os.Getenv(key)
os.Setenv(key, value)
return func() {
os.Setenv(key, originalValue)
}
}
func TestReadIdleTimeoutSeconds(t *testing.T) {
reset := setEnv("HTTP2_READ_IDLE_TIMEOUT_SECONDS", "60")
t.Setenv("HTTP2_READ_IDLE_TIMEOUT_SECONDS", "60")
if e, a := 60, readIdleTimeoutSeconds(); e != a {
t.Errorf("expected %d, got %d", e, a)
}
reset()
reset = setEnv("HTTP2_READ_IDLE_TIMEOUT_SECONDS", "illegal value")
t.Setenv("HTTP2_READ_IDLE_TIMEOUT_SECONDS", "illegal value")
if e, a := 30, readIdleTimeoutSeconds(); e != a {
t.Errorf("expected %d, got %d", e, a)
}
reset()
}
func TestPingTimeoutSeconds(t *testing.T) {
reset := setEnv("HTTP2_PING_TIMEOUT_SECONDS", "60")
t.Setenv("HTTP2_PING_TIMEOUT_SECONDS", "60")
if e, a := 60, pingTimeoutSeconds(); e != a {
t.Errorf("expected %d, got %d", e, a)
}
reset()
reset = setEnv("HTTP2_PING_TIMEOUT_SECONDS", "illegal value")
t.Setenv("HTTP2_PING_TIMEOUT_SECONDS", "illegal value")
if e, a := 15, pingTimeoutSeconds(); e != a {
t.Errorf("expected %d, got %d", e, a)
}
reset()
}
func Benchmark_ParseQuotedString(b *testing.B) {