File: performance_suite_test.go

package info (click to toggle)
golang-github-onsi-ginkgo-v2 2.27.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,340 kB
  • sloc: javascript: 65; makefile: 23; sh: 14
file content (451 lines) | stat: -rw-r--r-- 13,588 bytes parent folder | download
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
package performance_test

import (
	"flag"
	"fmt"
	"math/rand"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"sync"
	"testing"
	"time"

	. "github.com/onsi/ginkgo/v2"
	"github.com/onsi/ginkgo/v2/ginkgo/internal"
	"github.com/onsi/ginkgo/v2/types"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/format"
	"github.com/onsi/gomega/gbytes"
	"github.com/onsi/gomega/gexec"
	"github.com/onsi/gomega/gmeasure"
)

var pathToGinkgo string
var DEBUG bool
var pfm PerformanceFixtureManager
var gmcm GoModCacheManager

func init() {
	flag.BoolVar(&DEBUG, "debug", false, "keep assets around after test run")
}

func TestPerformance(t *testing.T) {
	SetDefaultEventuallyTimeout(30 * time.Second)
	format.TruncatedDiff = false
	RegisterFailHandler(Fail)
	RunSpecs(t, "Performance Suite", Label("performance"))
}

var _ = SynchronizedBeforeSuite(func() []byte {
	pathToGinkgo, err := gexec.Build("../../ginkgo")
	Ω(err).ShouldNot(HaveOccurred())
	return []byte(pathToGinkgo)
}, func(computedPathToGinkgo []byte) {
	pathToGinkgo = string(computedPathToGinkgo)
})

var _ = SynchronizedAfterSuite(func() {}, func() {
	gexec.CleanupBuildArtifacts()
})

/*
GoModCacheManager sets up a new GOMODCACHE and knows how to clear it
This allows us to bust the go mod cache.
*/
type GoModCacheManager struct {
	Path         string
	OldCachePath string
}

func NewGoModCacheManager(path string) GoModCacheManager {
	err := os.MkdirAll(path, 0700)
	Ω(err).ShouldNot(HaveOccurred())
	absPath, err := filepath.Abs(path)
	Ω(err).ShouldNot(HaveOccurred())
	oldCachePath := os.Getenv("GOMODCACHE")
	os.Setenv("GOMODCACHE", absPath)
	return GoModCacheManager{
		Path:         path,
		OldCachePath: oldCachePath,
	}

}

func (m GoModCacheManager) Clear() {
	cmd := exec.Command("go", "clean", "-modcache")
	session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter)
	Ω(err).ShouldNot(HaveOccurred())
	Eventually(session).Should(gexec.Exit(0))
}

func (m GoModCacheManager) Cleanup() {
	m.Clear()
	if m.OldCachePath == "" {
		os.Unsetenv("GOMODCACHE")
	} else {
		os.Setenv("GOMODCACHE", m.OldCachePath)
	}
}

/* PerformanceFixtureManager manages fixture data */
type PerformanceFixtureManager struct {
	TmpDir string
}

func NewPerformanceFixtureManager(tmpDir string) PerformanceFixtureManager {
	err := os.MkdirAll(tmpDir, 0700)
	Ω(err).ShouldNot(HaveOccurred())
	return PerformanceFixtureManager{
		TmpDir: tmpDir,
	}
}

func (f PerformanceFixtureManager) Cleanup() {
	Ω(os.RemoveAll(f.TmpDir)).Should(Succeed())
}

func (f PerformanceFixtureManager) MountFixture(fixture string, subPackage ...string) {
	src := filepath.Join("_fixtures", fixture+"_fixture")
	dst := filepath.Join(f.TmpDir, fixture)

	if len(subPackage) > 0 {
		src = filepath.Join(src, subPackage[0])
		dst = filepath.Join(dst, subPackage[0])
	}

	f.copyIn(src, dst)
}

func (f PerformanceFixtureManager) copyIn(src string, dst string) {
	Expect(os.MkdirAll(dst, 0777)).To(Succeed())

	files, err := os.ReadDir(src)
	Expect(err).NotTo(HaveOccurred())

	for _, file := range files {
		srcPath := filepath.Join(src, file.Name())
		dstPath := filepath.Join(dst, file.Name())
		if file.IsDir() {
			f.copyIn(srcPath, dstPath)
			continue
		}

		srcContent, err := os.ReadFile(srcPath)
		Ω(err).ShouldNot(HaveOccurred())
		Ω(os.WriteFile(dstPath, srcContent, 0666)).Should(Succeed())
	}
}

func (f PerformanceFixtureManager) PathTo(pkg string, target ...string) string {
	if len(target) == 0 {
		return filepath.Join(f.TmpDir, pkg)
	}
	components := append([]string{f.TmpDir, pkg}, target...)
	return filepath.Join(components...)
}

/* GoModDownload runs go mod download for a given package */
func GoModDownload(fixture string) {
	cmd := exec.Command("go", "mod", "download")
	cmd.Dir = pfm.PathTo(fixture)
	sess, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter)
	Ω(err).ShouldNot(HaveOccurred())
	Eventually(sess).Should(gexec.Exit(0))
}

/* ScenarioSettings configures the test scenario */
type ScenarioSettings struct {
	Fixture         string
	NumSuites       int
	Recurse         bool
	ClearGoModCache bool

	ConcurrentCompilers       int
	ConcurrentRunners         int
	CompileFirstSuiteSerially bool
	GoModDownloadFirst        bool

	UseGoTestDirectly            bool
	ConcurrentGoTests            int
	GoTestCompileThenRunSerially bool
	GoTestRecurse                bool
}

func (s ScenarioSettings) Name() string {
	out := []string{s.Fixture}
	if s.UseGoTestDirectly {
		if s.GoTestCompileThenRunSerially {
			out = append(out, "go test -c; then run (serially)")
		} else if s.GoTestRecurse {
			out = append(out, "go test ./...")
		} else {
			out = append(out, "go test")
			if s.ConcurrentGoTests == 1 {
				out = append(out, "serially")
			} else {
				out = append(out, fmt.Sprintf("run concurrently [%d]", s.ConcurrentGoTests))
			}
		}
	} else {
		if s.ConcurrentCompilers == 1 {
			out = append(out, "compile serially")
		} else {
			out = append(out, fmt.Sprintf("compile concurrently [%d]", s.ConcurrentCompilers))
		}
		if s.ConcurrentRunners == 1 {
			out = append(out, "run serially")
		} else {
			out = append(out, fmt.Sprintf("run concurrently [%d]", s.ConcurrentRunners))
		}
		if s.CompileFirstSuiteSerially {
			out = append(out, "will compile first suite serially")
		}
		if s.GoModDownloadFirst {
			out = append(out, "will go mod download first")
		}
	}
	return strings.Join(out, " - ")
}

func SampleScenarios(cache gmeasure.ExperimentCache, numSamples int, cacheVersion int, runGoModDownload bool, scenarios ...ScenarioSettings) {
	// we randomize the sample set of scenarios to try to avoid any systematic effects that emerge
	// during the run (e.g. change in internet connection speed, change in computer performance)

	experiments := map[string]*gmeasure.Experiment{}
	runs := []ScenarioSettings{}
	for _, scenario := range scenarios {
		name := scenario.Name()
		if experiment := cache.Load(name, cacheVersion); experiment != nil {
			AddReportEntry(name, experiment, Offset(1), ReportEntryVisibilityFailureOrVerbose)
			continue
		}
		experiments[name] = gmeasure.NewExperiment(name)
		AddReportEntry(name, experiments[name], Offset(1), ReportEntryVisibilityFailureOrVerbose)
		for i := 0; i < numSamples; i++ {
			runs = append(runs, scenario)
		}
	}
	rand.New(rand.NewSource(GinkgoRandomSeed())).Shuffle(len(runs), func(i, j int) {
		runs[i], runs[j] = runs[j], runs[i]
	})

	if len(runs) > 0 && runGoModDownload {
		GoModDownload("performance")
	}

	for idx, run := range runs {
		fmt.Printf("%d - %s\n", idx, run.Name())
		RunScenario(experiments[run.Name()].NewStopwatch(), run, gmeasure.Annotation(fmt.Sprintf("%d", idx+1)))
	}

	for name, experiment := range experiments {
		cache.Save(name, cacheVersion, experiment)
	}
}

func AnalyzeCache(cache gmeasure.ExperimentCache) {
	headers, err := cache.List()
	Ω(err).ShouldNot(HaveOccurred())

	experiments := []*gmeasure.Experiment{}
	for _, header := range headers {
		experiments = append(experiments, cache.Load(header.Name, header.Version))
	}

	for _, measurement := range []string{"first-output", "total-runtime"} {
		stats := []gmeasure.Stats{}
		for _, experiment := range experiments {
			stats = append(stats, experiment.GetStats(measurement))
		}
		AddReportEntry(measurement, gmeasure.RankStats(gmeasure.LowerMedianIsBetter, stats...))
	}
}

func RunScenario(stopwatch *gmeasure.Stopwatch, settings ScenarioSettings, annotation gmeasure.Annotation) {
	if settings.ClearGoModCache {
		gmcm.Clear()
	}

	if settings.GoModDownloadFirst {
		GoModDownload(settings.Fixture)
		stopwatch.Record("mod-download", annotation)
	}

	if settings.UseGoTestDirectly {
		RunScenarioWithGoTest(stopwatch, settings, annotation)
	} else {
		RunScenarioWithGinkgoInternals(stopwatch, settings, annotation)
	}
}

/* CompileAndRun uses the Ginkgo CLIs internals to compile and run tests with different possible settings governing concurrency and ordering */
func RunScenarioWithGinkgoInternals(stopwatch *gmeasure.Stopwatch, settings ScenarioSettings, annotation gmeasure.Annotation) {
	cliConfig := types.NewDefaultCLIConfig()
	cliConfig.Recurse = settings.Recurse
	suiteConfig := types.NewDefaultSuiteConfig()
	reporterConfig := types.NewDefaultReporterConfig()
	reporterConfig.Succinct = true
	goFlagsConfig := types.NewDefaultGoFlagsConfig()

	suites := internal.FindSuites([]string{pfm.PathTo(settings.Fixture)}, cliConfig, true)
	Ω(suites).Should(HaveLen(settings.NumSuites))

	compile := make(chan internal.TestSuite, len(suites))
	compiled := make(chan internal.TestSuite, len(suites))
	completed := make(chan internal.TestSuite, len(suites))
	firstOutputOnce := sync.Once{}

	for compiler := 0; compiler < settings.ConcurrentCompilers; compiler++ {
		go func() {
			for suite := range compile {
				if !suite.State.Is(internal.TestSuiteStateCompiled) {
					subStopwatch := stopwatch.NewStopwatch()
					suite = internal.CompileSuite(suite, goFlagsConfig, false)
					subStopwatch.Record("compile-test: "+suite.PackageName, annotation)
					Ω(suite.CompilationError).Should(BeNil())
				}
				compiled <- suite
			}
		}()
	}

	if settings.CompileFirstSuiteSerially {
		compile <- suites[0]
		suites[0] = <-compiled
	}

	for runner := 0; runner < settings.ConcurrentRunners; runner++ {
		go func() {
			for suite := range compiled {
				firstOutputOnce.Do(func() {
					stopwatch.Record("first-output", annotation, gmeasure.Style("{{cyan}}"))
				})
				subStopwatch := stopwatch.NewStopwatch()
				suite = internal.RunCompiledSuite(suite, suiteConfig, reporterConfig, cliConfig, goFlagsConfig, []string{})
				subStopwatch.Record("run-test: "+suite.PackageName, annotation)
				Ω(suite.State).Should(Equal(internal.TestSuiteStatePassed))
				completed <- suite
			}
		}()
	}

	for _, suite := range suites {
		compile <- suite
	}

	completedSuites := []internal.TestSuite{}
	for suite := range completed {
		completedSuites = append(completedSuites, suite)
		if len(completedSuites) == len(suites) {
			close(completed)
			close(compile)
			close(compiled)
		}
	}

	stopwatch.Record("total-runtime", annotation, gmeasure.Style("{{green}}"))
	internal.Cleanup(goFlagsConfig, completedSuites...)
}

func RunScenarioWithGoTest(stopwatch *gmeasure.Stopwatch, settings ScenarioSettings, annotation gmeasure.Annotation) {
	defer func() {
		stopwatch.Record("total-runtime", annotation, gmeasure.Style("{{green}}"))
	}()

	if settings.GoTestRecurse {
		cmd := exec.Command("go", "test", "-count=1", "./...")
		cmd.Dir = pfm.PathTo(settings.Fixture)
		sess, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter)
		Ω(err).ShouldNot(HaveOccurred())
		Eventually(sess).Should(gbytes.Say(`.`)) //should say _something_ eventually!
		stopwatch.Record("first-output", annotation, gmeasure.Style("{{cyan}}"))
		Eventually(sess).Should(gexec.Exit(0))
		return
	}

	cliConfig := types.NewDefaultCLIConfig()
	cliConfig.Recurse = settings.Recurse
	suites := internal.FindSuites([]string{pfm.PathTo(settings.Fixture)}, cliConfig, true)
	Ω(suites).Should(HaveLen(settings.NumSuites))
	firstOutputOnce := sync.Once{}

	if settings.GoTestCompileThenRunSerially {
		for _, suite := range suites {
			subStopwatch := stopwatch.NewStopwatch()
			cmd := exec.Command("go", "test", "-c", "-o=out.test")
			cmd.Dir = suite.AbsPath()
			sess, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter)
			Ω(err).ShouldNot(HaveOccurred())
			Eventually(sess).Should(gexec.Exit(0))
			subStopwatch.Record("compile-test: "+suite.PackageName, annotation).Reset()

			firstOutputOnce.Do(func() {
				stopwatch.Record("first-output", annotation, gmeasure.Style("{{cyan}}"))
			})
			cmd = exec.Command("./out.test")
			cmd.Dir = suite.AbsPath()
			sess, err = gexec.Start(cmd, GinkgoWriter, GinkgoWriter)
			Ω(err).ShouldNot(HaveOccurred())
			Eventually(sess).Should(gexec.Exit(0))
			subStopwatch.Record("run-test: "+suite.PackageName, annotation)

			Ω(os.Remove(filepath.Join(suite.AbsPath(), "out.test"))).Should(Succeed())
		}
	} else {
		run := make(chan internal.TestSuite, len(suites))
		completed := make(chan internal.TestSuite, len(suites))
		for runner := 0; runner < settings.ConcurrentGoTests; runner++ {
			go func() {
				for suite := range run {
					subStopwatch := stopwatch.NewStopwatch()
					cmd := exec.Command("go", "test", "-count=1")
					cmd.Dir = suite.AbsPath()
					sess, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter)
					Ω(err).ShouldNot(HaveOccurred())
					Eventually(sess).Should(gbytes.Say(`.`)) //should say _something_ eventually!
					firstOutputOnce.Do(func() {
						stopwatch.Record("first-output", annotation, gmeasure.Style("{{cyan}}"))
					})
					Eventually(sess).Should(gexec.Exit(0))
					subStopwatch.Record("run-test: "+suite.PackageName, annotation)
					completed <- suite
				}
			}()
		}
		for _, suite := range suites {
			run <- suite
		}
		numCompleted := 0
		for _ = range completed {
			numCompleted += 1
			if numCompleted == len(suites) {
				close(completed)
				close(run)
			}
		}
	}
}

func ginkgoCommand(dir string, args ...string) *exec.Cmd {
	cmd := exec.Command(pathToGinkgo, args...)
	cmd.Dir = dir

	return cmd
}

func startGinkgo(dir string, args ...string) *gexec.Session {
	cmd := ginkgoCommand(dir, args...)
	session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter)
	Ω(err).ShouldNot(HaveOccurred())
	return session
}

func startGinkgoWithEnv(dir string, env []string, args ...string) *gexec.Session {
	cmd := ginkgoCommand(dir, args...)
	cmd.Env = append(os.Environ(), env...)
	session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter)
	Ω(err).ShouldNot(HaveOccurred())
	return session
}