dgryski / semgrep-go

Go rules for semgrep and go-ruleguard
MIT License
457 stars 37 forks source link

ruleguard: suggest t.Setenv in test cases #50

Closed dnwe closed 2 years ago

dnwe commented 2 years ago

Where an existing testcase has a pattern of:

os.Setenv("KEY", "VALUE")
defer os.Unsetenv("KEY")

Suggest replacement of:

t.Setenv("KEY")

As this will handle the defer for you and will restore the previous value, rather than unsetting it. It will also ensure a compile time error is raised if the test has been marked as t.Parallel (which would be unsafe).

dnwe commented 2 years ago

Note: this only catches the specific Unsetenv pattern. There may also be patterns where the user has stored the previous value themselves and added a defer to restore it. That pattern would be harder to autofix, but we could add a catcher for it.

    original := os.Getenv(k)
    os.Setenv(k, v)
    defer func(k, v string) {
        os.Setenv(k, v)
    }(k, original)