cossacklabs / acra

Database security suite. Database proxy with field-level encryption, search through encrypted data, SQL injections prevention, intrusion detection, honeypots. Supports client-side and proxy-side ("transparent") encryption. SQL, NoSQL.
https://www.cossacklabs.com/acra/
Apache License 2.0
1.33k stars 128 forks source link

test: use `T.Setenv` to set env vars in tests #569

Closed Juneezee closed 1 year ago

Juneezee commented 1 year ago

This PR replaces os.Setenv with t.Setenv. Starting from Go 1.17, we can use t.Setenv to set environment variable in test. The environment variable is automatically restored to its original value when the test and all its subtests complete. This ensures that each test does not start with leftover environment variables from previous completed tests.

This saves us at least 2 lines (error check, and unsetting the env var) on every instance.

func TestFoo(t *testing.T) {
    // before
    key := "ENV"
    originalEnv := os.Getenv(key)

    if err := os.Setenv(key, "new value"); err != nil {
        t.Fatal(err)
    }
    defer func() {
        if err := os.Setenv(key, originalEnv); err != nil {
            t.Logf("failed to set env %s back to original value: %v", key, err)
        }
    }()

    // after
    t.Setenv(key, "new value")
}

Checklist