From 16f27f1529bf01047bd06c28e2b2f545a321e604 Mon Sep 17 00:00:00 2001 From: Tronje Krop Date: Wed, 6 Mar 2024 12:56:49 +0100 Subject: [PATCH] chore: update deps (#74) Signed-off-by: Tronje Krop --- cmd/mock/main_test.go | 52 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 cmd/mock/main_test.go diff --git a/cmd/mock/main_test.go b/cmd/mock/main_test.go new file mode 100644 index 0000000..3e9100f --- /dev/null +++ b/cmd/mock/main_test.go @@ -0,0 +1,52 @@ +package main + +import ( + "errors" + "os" + "os/exec" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/tkrop/go-testing/test" +) + +type MainParams struct { + args []string + expectExitCode int +} + +var testMainParams = map[string]MainParams{ + "no mock to generate": { + args: []string{"mock"}, + expectExitCode: 0, + }, +} + +func TestMain(t *testing.T) { + test.Map(t, testMainParams). + Run(func(t test.Test, param MainParams) { + // Switch to execute main function in separate process. + if name := os.Getenv("TEST"); name != "" { + // Ensure only expected test is running. + if name == t.Name() { + os.Args = param.args + main() + assert.Fail(t, "os-exit not called") + } + // Skip other test. + return + } + + // Call the main function in a separate process. + cmd := exec.Command(os.Args[0], "-test.run=TestMain") + cmd.Env = append(os.Environ(), "TEST="+t.Name()) + if err := cmd.Run(); err != nil || param.expectExitCode != 0 { + errExit := &exec.ExitError{} + if errors.As(err, &errExit) { + assert.Equal(t, param.expectExitCode, errExit.ExitCode()) + } else { + assert.Fail(t, "unexpected error", err) + } + } + }) +}