test: use t.Setenv to set env vars in tests (#2722)

This commit replaces `os.Setenv` with `t.Setenv` in tests. The
environment variable is automatically restored to its original value
when the test and all its subtests complete.

Reference: https://pkg.go.dev/testing#T.Setenv

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
This commit is contained in:
Eng Zer Jun 2023-11-21 00:34:56 +08:00 committed by GitHub
parent dee7176cb0
commit f335fc67f9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 7 additions and 15 deletions

View File

@ -113,20 +113,16 @@ func TestConfFromFile(t *testing.T) {
func TestConfFromFileAndEnv(t *testing.T) {
// global parameter
os.Setenv("RTSP_PROTOCOLS", "tcp")
defer os.Unsetenv("RTSP_PROTOCOLS")
t.Setenv("RTSP_PROTOCOLS", "tcp")
// path parameter
os.Setenv("MTX_PATHS_CAM1_SOURCE", "rtsp://testing")
defer os.Unsetenv("MTX_PATHS_CAM1_SOURCE")
t.Setenv("MTX_PATHS_CAM1_SOURCE", "rtsp://testing")
// deprecated global parameter
os.Setenv("MTX_RTMPDISABLE", "yes")
defer os.Unsetenv("MTX_RTMPDISABLE")
t.Setenv("MTX_RTMPDISABLE", "yes")
// deprecated path parameter
os.Setenv("MTX_PATHS_CAM2_DISABLEPUBLISHEROVERRIDE", "yes")
defer os.Unsetenv("MTX_PATHS_CAM2_DISABLEPUBLISHEROVERRIDE")
t.Setenv("MTX_PATHS_CAM2_DISABLEPUBLISHEROVERRIDE", "yes")
tmpf, err := writeTempFile([]byte("{}"))
require.NoError(t, err)
@ -149,8 +145,7 @@ func TestConfFromFileAndEnv(t *testing.T) {
}
func TestConfFromEnvOnly(t *testing.T) {
os.Setenv("MTX_PATHS_CAM1_SOURCE", "rtsp://testing")
defer os.Unsetenv("MTX_PATHS_CAM1_SOURCE")
t.Setenv("MTX_PATHS_CAM1_SOURCE", "rtsp://testing")
conf, confPath, err := Load("", nil)
require.NoError(t, err)
@ -179,8 +174,7 @@ func TestConfEncryption(t *testing.T) {
return base64.StdEncoding.EncodeToString(encrypted)
}()
os.Setenv("RTSP_CONFKEY", key)
defer os.Unsetenv("RTSP_CONFKEY")
t.Setenv("RTSP_CONFKEY", key)
tmpf, err := writeTempFile([]byte(encryptedConf))
require.NoError(t, err)

View File

@ -2,7 +2,6 @@ package env
import (
"encoding/json"
"os"
"testing"
"time"
@ -127,8 +126,7 @@ func TestLoad(t *testing.T) {
}
for key, val := range env {
os.Setenv(key, val)
defer os.Unsetenv(key)
t.Setenv(key, val)
}
var s testStruct