|
5 | 5 | package pytest
|
6 | 6 |
|
7 | 7 | import (
|
| 8 | + "bytes" |
8 | 9 | "io"
|
9 | 10 | "os"
|
10 | 11 | "path"
|
| 12 | + "path/filepath" |
11 | 13 | "strings"
|
12 | 14 | "testing"
|
13 | 15 |
|
14 | 16 | "github.com/go-python/gpython/compile"
|
15 | 17 | "github.com/go-python/gpython/py"
|
| 18 | + "github.com/google/go-cmp/cmp" |
16 | 19 |
|
17 | 20 | _ "github.com/go-python/gpython/stdlib"
|
18 | 21 | )
|
@@ -126,3 +129,57 @@ func RunBenchmarks(b *testing.B, testDir string) {
|
126 | 129 | })
|
127 | 130 | }
|
128 | 131 | }
|
| 132 | + |
| 133 | +// RunScript runs the provided path to a script. |
| 134 | +// RunScript captures the stdout and stderr while executing the script |
| 135 | +// and compares it to a golden file: |
| 136 | +// RunScript("./testdata/foo.py") |
| 137 | +// will compare the output with "./testdata/foo_golden.txt". |
| 138 | +func RunScript(t *testing.T, fname string) { |
| 139 | + opts := py.DefaultContextOpts() |
| 140 | + opts.SysArgs = []string{fname} |
| 141 | + ctx := py.NewContext(opts) |
| 142 | + defer ctx.Close() |
| 143 | + |
| 144 | + sys := ctx.Store().MustGetModule("sys") |
| 145 | + tmp, err := os.MkdirTemp("", "gpython-pytest-") |
| 146 | + if err != nil { |
| 147 | + t.Fatal(err) |
| 148 | + } |
| 149 | + defer os.RemoveAll(tmp) |
| 150 | + |
| 151 | + out, err := os.Create(filepath.Join(tmp, "combined")) |
| 152 | + if err != nil { |
| 153 | + t.Fatalf("could not create stdout/stderr: %+v", err) |
| 154 | + } |
| 155 | + defer out.Close() |
| 156 | + |
| 157 | + sys.Globals["stdout"] = &py.File{File: out, FileMode: py.FileWrite} |
| 158 | + sys.Globals["stderr"] = &py.File{File: out, FileMode: py.FileWrite} |
| 159 | + |
| 160 | + _, err = py.RunFile(ctx, fname, py.CompileOpts{}, nil) |
| 161 | + if err != nil { |
| 162 | + t.Fatalf("could not run script %q: %+v", fname, err) |
| 163 | + } |
| 164 | + |
| 165 | + err = out.Close() |
| 166 | + if err != nil { |
| 167 | + t.Fatalf("could not close stdout/stderr: %+v", err) |
| 168 | + } |
| 169 | + |
| 170 | + got, err := os.ReadFile(out.Name()) |
| 171 | + if err != nil { |
| 172 | + t.Fatalf("could not read script output: %+v", err) |
| 173 | + } |
| 174 | + |
| 175 | + ref := fname[:len(fname)-len(".py")] + "_golden.txt" |
| 176 | + want, err := os.ReadFile(ref) |
| 177 | + if err != nil { |
| 178 | + t.Fatalf("could not read golden output %q: %+v", ref, err) |
| 179 | + } |
| 180 | + |
| 181 | + diff := cmp.Diff(string(want), string(got)) |
| 182 | + if !bytes.Equal(got, want) { |
| 183 | + t.Fatalf("output differ: -- (-ref +got)\n%s", diff) |
| 184 | + } |
| 185 | +} |
0 commit comments