-
-
Notifications
You must be signed in to change notification settings - Fork 163
/
helper_test.go
213 lines (190 loc) · 5.67 KB
/
helper_test.go
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package playwright_test
import (
"bytes"
"image"
"log"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
_ "image/png"
"github.com/orisano/pixelmatch"
"github.com/playwright-community/playwright-go"
)
// global variables, can be used in any tests
var (
pw *playwright.Playwright
browser playwright.Browser
context playwright.BrowserContext
page playwright.Page
expect playwright.PlaywrightAssertions
headless = os.Getenv("HEADFUL") == ""
isChromium bool
isFirefox bool
isWebKit bool
browserName = getBrowserName()
browserType playwright.BrowserType
)
// default context options for most tests
var DEFAULT_CONTEXT_OPTIONS = playwright.BrowserNewContextOptions{
AcceptDownloads: playwright.Bool(true),
HasTouch: playwright.Bool(true),
}
// TestMain is used to setup and teardown the tests
func TestMain(m *testing.M) {
BeforeAll()
code := m.Run()
AfterAll()
os.Exit(code)
}
// BeforeAll prepares the environment, including
// - start Playwright driver
// - launch browser depends on BROWSER env
// - init web-first assertions, alias as `expect`
func BeforeAll() {
var err error
pw, err = playwright.Run()
if err != nil {
log.Fatalf("could not start Playwright: %v", err)
}
if browserName == "chromium" || browserName == "" {
browserType = pw.Chromium
} else if browserName == "firefox" {
browserType = pw.Firefox
} else if browserName == "webkit" {
browserType = pw.WebKit
}
// launch browser, headless or not depending on HEADFUL env
browser, err = browserType.Launch(playwright.BrowserTypeLaunchOptions{
Headless: playwright.Bool(headless),
})
if err != nil {
log.Fatalf("could not launch: %v", err)
}
// init web-first assertions with 1s timeout instead of default 5s
expect = playwright.NewPlaywrightAssertions(1000)
isChromium = browserName == "chromium" || browserName == ""
isFirefox = browserName == "firefox"
isWebKit = browserName == "webkit"
// for playwright-go tests
server = newTestServer()
utils = &testUtils{}
}
// AfterAll does cleanup, e.g. stop playwright driver
func AfterAll() {
if server != nil {
server.testServer.Close()
}
if err := pw.Stop(); err != nil {
log.Fatalf("could not start Playwright: %v", err)
}
}
// BeforeEach creates a new context and page for each test,
// so each test has isolated environment. Usage:
//
// Func TestFoo(t *testing.T) {
// BeforeEach(t)
// // your test code
// }
func BeforeEach(t *testing.T, contextOptions ...playwright.BrowserNewContextOptions) {
t.Helper()
opt := DEFAULT_CONTEXT_OPTIONS
if len(contextOptions) == 1 {
opt = contextOptions[0]
}
context, page = newBrowserContextAndPage(t, opt)
t.Cleanup(func() {
server.AfterEach()
})
}
func getBrowserName() string {
browserName, hasEnv := os.LookupEnv("BROWSER")
if hasEnv {
return browserName
}
return "chromium"
}
func newBrowserContextAndPage(t *testing.T, options playwright.BrowserNewContextOptions) (playwright.BrowserContext, playwright.Page) {
t.Helper()
context, err := browser.NewContext(options)
if err != nil {
t.Fatalf("could not create new context: %v", err)
}
t.Cleanup(func() {
if err := context.Close(); err != nil {
t.Errorf("could not close context: %v", err)
}
})
page, err := context.NewPage()
if err != nil {
t.Fatalf("could not create new page: %v", err)
}
return context, page
}
// AssertToBeGolden compares the given image with a golden file and asserts that they are equal.
//
// Notes:
// - Golden files are stored in the "*-snapshots" directory in the same directory as the test file. e.g. "page_test.go" lead to "page-snapshots".
// - If the golden file does not exist, creates the golden file with the given image.
// - If the UPDATE_SNAPSHOTS environment variable is set, updates the golden file with the given image.
// - Use `pixelmatch.MatchOptions` to configure the pixelmatch algorithm.
func AssertToBeGolden(t *testing.T, img []byte, filename string, matchOptions ...pixelmatch.MatchOption) {
t.Helper()
actual, _, err := image.Decode(bytes.NewReader(img))
if err != nil {
t.Errorf("could not decode actual image: %v", err)
}
_, srcFile, _, _ := runtime.Caller(1)
goldenDir := strings.Replace(srcFile, "_test.go", "-snapshots", 1)
goldenPath := filepath.Join(goldenDir, getGoldenFilename(filename))
if os.Getenv("UPDATE_SNAPSHOTS") != "" {
if err := writeGoldenFile(goldenPath, img); err != nil {
t.Errorf("could not write golden file: %v", err)
} else {
t.Logf("updated golden file: %s", goldenPath)
}
return
}
goldenRaw, err := os.ReadFile(goldenPath)
if err != nil {
// create golden file if it does not exist
if os.IsNotExist(err) {
if err := writeGoldenFile(goldenPath, img); err != nil {
t.Errorf("could not write golden file: %v", err)
} else {
t.Logf("created golden file: %s", goldenPath)
}
return
}
t.Errorf("could not read golden file: %v", err)
}
golden, _, err := image.Decode(bytes.NewReader(goldenRaw))
if err != nil {
t.Errorf("could not decode golden: %v", err)
}
if actual.Bounds().Size() != golden.Bounds().Size() {
t.Errorf("actual and golden have different sizes: %v != %v", actual.Bounds().Size(), golden.Bounds().Size())
}
diff, err := pixelmatch.MatchPixel(actual, golden, matchOptions...)
if err != nil {
t.Errorf("could not match pixel: %v", err)
}
if diff > 0 {
t.Errorf("diff: %v", diff)
}
}
func writeGoldenFile(path string, data []byte) error {
dir := filepath.Dir(path)
_, err := os.Stat(dir)
if os.IsNotExist(err) {
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
}
return os.WriteFile(path, data, 0o644)
}
func getGoldenFilename(name string) string {
ext := filepath.Ext(name)
return strings.TrimSuffix(name, ext) + "-" + browserName + ext
}