Skip to content

Commit

Permalink
test: use t.Setenv to set env vars in tests (bluenviron#2722)
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
Juneezee authored Nov 20, 2023
1 parent dee7176 commit f335fc6
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 15 deletions.
18 changes: 6 additions & 12 deletions internal/conf/conf_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
4 changes: 1 addition & 3 deletions internal/conf/env/env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package env

import (
"encoding/json"
"os"
"testing"
"time"

Expand Down Expand Up @@ -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
Expand Down

0 comments on commit f335fc6

Please sign in to comment.