package main import ( "bytes" "fmt" "os" "os/exec" "path/filepath" "runtime" "testing" ) var ( testDir = "testdata" goldenFile = "config.yaml.golden" outFile = "config.yaml" binName = "dkl-dir2config" ) /* Build and run the code with default parameters and testdata */ func TestMain(m *testing.M) { fmt.Println("Building...") if runtime.GOOS == "windows" { binName += ".exe" } build := exec.Command("go", "build", "-o", filepath.Join(testDir, binName)) if err := build.Run(); err != nil { fmt.Fprintf(os.Stderr, "Cannot build : %v", err) os.Exit(1) } fmt.Println("Running Tests...") result := m.Run() fmt.Println("Cleaning Up ... ") os.Remove(binName) os.Exit(result) } func TestRunMain(t *testing.T) { err := os.Chdir(testDir) if err != nil { t.Fatal(err) } t.Run("RunWithNoArgument", func(t *testing.T) { cmd := exec.Command("./" + binName) if err := cmd.Run(); err != nil { t.Fatal(err) } }) t.Run("CompareOutputs", func(t *testing.T) { cmd := exec.Command("./"+binName, "-out", outFile) if err := cmd.Run(); err != nil { t.Fatal(err) } output, err := os.ReadFile(outFile) if err != nil { t.Fatal(err) } expected, err := os.ReadFile(goldenFile) if err != nil { t.Fatal(err) } if ret := bytes.Compare(output, expected); ret != 0 { t.Fatalf("Output (%v) of length %d is different than expected (%v) of length %d", outFile, len(output), goldenFile, len(expected)) } }) }