~mna/snow unlisted

snow/pkg/codegen/codegen_build_test.go -rw-r--r-- 2.2 KiB
424066c5Martin Angers doc: v0.0.5 1 year, 6 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package codegen_test

import (
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"testing"

	"git.sr.ht/~mna/snow/pkg/codegen"
	"git.sr.ht/~mna/snow/pkg/internal/filetest"
	"git.sr.ht/~mna/snow/pkg/parser"
	"github.com/kylelemons/godebug/diff"
)

func TestBuild(t *testing.T) {
	if testing.Short() {
		t.Skip()
	}

	cwd, err := os.Getwd()
	if err != nil {
		t.Fatal(err)
	}

	baseDir := filepath.Join(cwd, "testdata")
	for _, fi := range filetest.SourceFiles(t, baseDir) {
		t.Run(fi.Name(), func(t *testing.T) {
			tdir, err := ioutil.TempDir(baseDir, "")
			if err != nil {
				t.Fatal(err)
			}
			defer os.RemoveAll(tdir)

			// parse it first, so we have the comments to see if is an  expected output
			fset, fs, err := parser.ParseFiles(filepath.Join(baseDir, fi.Name()))
			if err != nil {
				t.Fatal(err)
			}

			_, err = codegen.ExecAST(tdir, fset, fs...)
			if err != nil {
				t.Fatal(err)
			}

			rdir, err := filepath.Rel(cwd, tdir)
			if err != nil {
				t.Fatal(err)
			}
			if !strings.HasPrefix(rdir, ".") {
				rdir = "./" + rdir
			}

			bin := filepath.Join(rdir, "out")
			cc := exec.Command("go", "build", "-o", bin, rdir) //#nosec
			cc.Env = append(os.Environ(), "GO111MODULE=off")
			if out, err := cc.CombinedOutput(); err != nil {
				t.Log(string(out))
				t.Fatal(err)
			}

			// if there is an expected output comment, execute the binary and compare the output
			if len(fs) > 0 {
				var expect strings.Builder
				for _, cg := range fs[0].Comments {
					for _, c := range cg.List {
						if strings.HasPrefix(c.Text, "#=") {
							expect.WriteString(strings.TrimPrefix(c.Text, "#=") + "\n")
						}
					}
				}

				if expect.Len() > 0 {
					cc := exec.Command(bin)
					out, err := cc.CombinedOutput()
					got := string(out)
					if err != nil {
						t.Log(got)
						t.Fatal(err)
					}

					if testing.Verbose() {
						t.Logf("got exec output:\n%s\n", got)
					}
					want := expect.String()
					if patch := diff.Diff(got, want); patch != "" {
						// ignore a difference only in final newline
						want = want[:len(want)-1]
						if patch := diff.Diff(got, want); patch != "" {
							t.Fatalf("exec output diff:\n%s\n", patch)
						}
					}
				}
			}
		})
	}
}