generate: Fix testGenerateRun so that it actually works

This commit is contained in:
Sasha Koshka 2025-07-08 11:38:00 -04:00
parent a9d5bb83a2
commit c70c23d137
2 changed files with 33 additions and 6 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/generate/test

View File

@ -7,10 +7,14 @@ import "testing"
import "path/filepath" import "path/filepath"
func testGenerateRun(test *testing.T, protocol *Protocol, imports string, testCase string) { func testGenerateRun(test *testing.T, protocol *Protocol, imports string, testCase string) {
// open files // reset data directory
dir, err := os.MkdirTemp(os.TempDir(), "hopp-generate-test-*") dir := "test/generate-run"
err := os.RemoveAll(dir)
if err != nil { test.Fatal(err) } if err != nil { test.Fatal(err) }
defer os.RemoveAll(dir) err = os.MkdirAll(dir, 0750)
if err != nil { test.Fatal(err) }
// open files
sourceFile, err := os.Create(filepath.Join(dir, "protocol.go")) sourceFile, err := os.Create(filepath.Join(dir, "protocol.go"))
if err != nil { test.Fatal(err) } if err != nil { test.Fatal(err) }
defer sourceFile.Close() defer sourceFile.Close()
@ -29,15 +33,37 @@ func testGenerateRun(test *testing.T, protocol *Protocol, imports string, testCa
// build static source files // build static source files
imports = ` imports = `
import "log" import "log"
import "bytes"
import "slices"
import "git.tebibyte.media/sashakoshka/hopp/tape"
` + imports ` + imports
setup := `log.Println("*** BEGIN TEST CASE OUTPUT ***")` setup := `log.Println("*** BEGIN TEST CASE OUTPUT ***")`
teardown := `log.Println("--- END TEST CASE OUTPUT ---")` teardown := `log.Println("--- END TEST CASE OUTPUT ---")`
static := `
func testEncode(message Message, correct ...byte) {
buffer := bytes.Buffer { }
encoder := tape.NewEncoder(&buffer)
n, err := message.Encode(encoder)
if err != nil { log.Fatalf("at %d: %v\n", n, err) }
got := buffer.Bytes()
if n != len(got) {
log.Fatalln("len incorrect: %d != %d", got, correct)
}
if !slices.Equal(got, correct) {
log.Fatalln("not equal:")
}
}
`
fmt.Fprintf( fmt.Fprintf(
mainFile, "package main\n%s\nfunc main() {%s\n%s\n%s\n}\n", mainFile, "package main\n%s\nfunc main() {\n%s\n%s\n%s\n}\n%s",
imports, setup, testCase, teardown) imports, setup, testCase, teardown, static)
// build and run test // build and run test
command := exec.Command("go", "run", filepath.Join(dir, "main.go")) command := exec.Command("go", "run", "./generate/test/generate-run")
workingDirAbs, err := filepath.Abs("..")
if err != nil { test.Fatal(err) }
command.Dir = workingDirAbs
command.Env = os.Environ()
output, err := command.CombinedOutput() output, err := command.CombinedOutput()
test.Logf("output of %v:\n%s", command, output) test.Logf("output of %v:\n%s", command, output)
if err != nil { test.Fatal(err) } if err != nil { test.Fatal(err) }