68 lines
1.4 KiB
Go
Raw Normal View History

2024-06-29 19:40:14 +00:00
package main_test
import (
"os"
"os/exec"
"testing"
"git.akyoto.dev/cli/q/src/build"
"git.akyoto.dev/go/assert"
)
func TestExamples(t *testing.T) {
var examples = []struct {
Name string
ExpectedOutput string
ExpectedExitCode int
}{
{"hello", "", 25},
{"write", "ELF", 0},
}
for _, example := range examples {
example := example
t.Run(example.Name, func(t *testing.T) {
runExample(t, example.Name, example.ExpectedOutput, example.ExpectedExitCode)
})
}
}
// runExample builds and runs the example to check if the output matches the expected output.
func runExample(t *testing.T, name string, expectedOutput string, expectedExitCode int) {
b := build.New("examples/" + name)
assert.True(t, len(b.Executable()) > 0)
defer os.Remove(b.Executable())
t.Run("Compile", func(t *testing.T) {
result, err := b.Run()
assert.Nil(t, err)
err = result.Write(b.Executable())
assert.Nil(t, err)
stat, err := os.Stat(b.Executable())
assert.Nil(t, err)
assert.True(t, stat.Size() > 0)
})
t.Run("Output", func(t *testing.T) {
cmd := exec.Command(b.Executable())
output, err := cmd.Output()
exitCode := 0
if err != nil {
exitError, ok := err.(*exec.ExitError)
if !ok {
t.Fatal(exitError)
}
exitCode = exitError.ExitCode()
}
assert.Equal(t, exitCode, expectedExitCode)
assert.DeepEqual(t, string(output), expectedOutput)
})
}