How to use PathTo method of performance_test Package

Best Ginkgo code snippet using performance_test.PathTo

performance_suite_test.go

Source:performance_suite_test.go Github

copy

Full Screen

...35var _ = SynchronizedBeforeSuite(func() []byte {36	pathToGinkgo, err := gexec.Build("../../ginkgo")37	Ω(err).ShouldNot(HaveOccurred())38	return []byte(pathToGinkgo)39}, func(computedPathToGinkgo []byte) {40	pathToGinkgo = string(computedPathToGinkgo)41})42var _ = SynchronizedAfterSuite(func() {}, func() {43	gexec.CleanupBuildArtifacts()44})45/*46	GoModCacheManager sets up a new GOMODCACHE and knows how to clear it47	This allows us to bust the go mod cache.48*/49type GoModCacheManager struct {50	Path         string51	OldCachePath string52}53func NewGoModCacheManager(path string) GoModCacheManager {54	err := os.MkdirAll(path, 0700)55	Ω(err).ShouldNot(HaveOccurred())56	absPath, err := filepath.Abs(path)57	Ω(err).ShouldNot(HaveOccurred())58	oldCachePath := os.Getenv("GOMODCACHE")59	os.Setenv("GOMODCACHE", absPath)60	return GoModCacheManager{61		Path:         path,62		OldCachePath: oldCachePath,63	}64}65func (m GoModCacheManager) Clear() {66	cmd := exec.Command("go", "clean", "-modcache")67	session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter)68	Ω(err).ShouldNot(HaveOccurred())69	Eventually(session).Should(gexec.Exit(0))70}71func (m GoModCacheManager) Cleanup() {72	m.Clear()73	if m.OldCachePath == "" {74		os.Unsetenv("GOMODCACHE")75	} else {76		os.Setenv("GOMODCACHE", m.OldCachePath)77	}78}79/* PerformanceFixtureManager manages fixture data */80type PerformanceFixtureManager struct {81	TmpDir string82}83func NewPerformanceFixtureManager(tmpDir string) PerformanceFixtureManager {84	err := os.MkdirAll(tmpDir, 0700)85	Ω(err).ShouldNot(HaveOccurred())86	return PerformanceFixtureManager{87		TmpDir: tmpDir,88	}89}90func (f PerformanceFixtureManager) Cleanup() {91	Ω(os.RemoveAll(f.TmpDir)).Should(Succeed())92}93func (f PerformanceFixtureManager) MountFixture(fixture string, subPackage ...string) {94	src := filepath.Join("_fixtures", fixture+"_fixture")95	dst := filepath.Join(f.TmpDir, fixture)96	if len(subPackage) > 0 {97		src = filepath.Join(src, subPackage[0])98		dst = filepath.Join(dst, subPackage[0])99	}100	f.copyIn(src, dst)101}102func (f PerformanceFixtureManager) copyIn(src string, dst string) {103	Expect(os.MkdirAll(dst, 0777)).To(Succeed())104	files, err := os.ReadDir(src)105	Expect(err).NotTo(HaveOccurred())106	for _, file := range files {107		srcPath := filepath.Join(src, file.Name())108		dstPath := filepath.Join(dst, file.Name())109		if file.IsDir() {110			f.copyIn(srcPath, dstPath)111			continue112		}113		srcContent, err := os.ReadFile(srcPath)114		Ω(err).ShouldNot(HaveOccurred())115		Ω(os.WriteFile(dstPath, srcContent, 0666)).Should(Succeed())116	}117}118func (f PerformanceFixtureManager) PathTo(pkg string, target ...string) string {119	if len(target) == 0 {120		return filepath.Join(f.TmpDir, pkg)121	}122	components := append([]string{f.TmpDir, pkg}, target...)123	return filepath.Join(components...)124}125/* GoModDownload runs go mod download for a given package */126func GoModDownload(fixture string) {127	cmd := exec.Command("go", "mod", "download")128	cmd.Dir = pfm.PathTo(fixture)129	sess, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter)130	Ω(err).ShouldNot(HaveOccurred())131	Eventually(sess).Should(gexec.Exit(0))132}133/* ScenarioSettings configures the test scenario */134type ScenarioSettings struct {135	Fixture         string136	NumSuites       int137	Recurse         bool138	ClearGoModCache bool139	ConcurrentCompilers       int140	ConcurrentRunners         int141	CompileFirstSuiteSerially bool142	GoModDownloadFirst        bool143	UseGoTestDirectly            bool144	ConcurrentGoTests            int145	GoTestCompileThenRunSerially bool146	GoTestRecurse                bool147}148func (s ScenarioSettings) Name() string {149	out := []string{s.Fixture}150	if s.UseGoTestDirectly {151		if s.GoTestCompileThenRunSerially {152			out = append(out, "go test -c; then run (serially)")153		} else if s.GoTestRecurse {154			out = append(out, "go test ./...")155		} else {156			out = append(out, "go test")157			if s.ConcurrentGoTests == 1 {158				out = append(out, "serially")159			} else {160				out = append(out, fmt.Sprintf("run concurrently [%d]", s.ConcurrentGoTests))161			}162		}163	} else {164		if s.ConcurrentCompilers == 1 {165			out = append(out, "compile serially")166		} else {167			out = append(out, fmt.Sprintf("compile concurrently [%d]", s.ConcurrentCompilers))168		}169		if s.ConcurrentRunners == 1 {170			out = append(out, "run serially")171		} else {172			out = append(out, fmt.Sprintf("run concurrently [%d]", s.ConcurrentRunners))173		}174		if s.CompileFirstSuiteSerially {175			out = append(out, "will compile first suite serially")176		}177		if s.GoModDownloadFirst {178			out = append(out, "will go mod download first")179		}180	}181	return strings.Join(out, " - ")182}183func SampleScenarios(cache gmeasure.ExperimentCache, numSamples int, cacheVersion int, runGoModDownload bool, scenarios ...ScenarioSettings) {184	// we randomize the sample set of scenarios to try to avoid any systematic effects that emerge185	// during the run (e.g. change in internet connection speed, change in computer performance)186	experiments := map[string]*gmeasure.Experiment{}187	runs := []ScenarioSettings{}188	for _, scenario := range scenarios {189		name := scenario.Name()190		if experiment := cache.Load(name, cacheVersion); experiment != nil {191			AddReportEntry(name, experiment, Offset(1), ReportEntryVisibilityFailureOrVerbose)192			continue193		}194		experiments[name] = gmeasure.NewExperiment(name)195		AddReportEntry(name, experiments[name], Offset(1), ReportEntryVisibilityFailureOrVerbose)196		for i := 0; i < numSamples; i++ {197			runs = append(runs, scenario)198		}199	}200	rand.New(rand.NewSource(GinkgoRandomSeed())).Shuffle(len(runs), func(i, j int) {201		runs[i], runs[j] = runs[j], runs[i]202	})203	if len(runs) > 0 && runGoModDownload {204		GoModDownload("performance")205	}206	for idx, run := range runs {207		fmt.Printf("%d - %s\n", idx, run.Name())208		RunScenario(experiments[run.Name()].NewStopwatch(), run, gmeasure.Annotation(fmt.Sprintf("%d", idx+1)))209	}210	for name, experiment := range experiments {211		cache.Save(name, cacheVersion, experiment)212	}213}214func AnalyzeCache(cache gmeasure.ExperimentCache) {215	headers, err := cache.List()216	Ω(err).ShouldNot(HaveOccurred())217	experiments := []*gmeasure.Experiment{}218	for _, header := range headers {219		experiments = append(experiments, cache.Load(header.Name, header.Version))220	}221	for _, measurement := range []string{"first-output", "total-runtime"} {222		stats := []gmeasure.Stats{}223		for _, experiment := range experiments {224			stats = append(stats, experiment.GetStats(measurement))225		}226		AddReportEntry(measurement, gmeasure.RankStats(gmeasure.LowerMedianIsBetter, stats...))227	}228}229func RunScenario(stopwatch *gmeasure.Stopwatch, settings ScenarioSettings, annotation gmeasure.Annotation) {230	if settings.ClearGoModCache {231		gmcm.Clear()232	}233	if settings.GoModDownloadFirst {234		GoModDownload(settings.Fixture)235		stopwatch.Record("mod-download", annotation)236	}237	if settings.UseGoTestDirectly {238		RunScenarioWithGoTest(stopwatch, settings, annotation)239	} else {240		RunScenarioWithGinkgoInternals(stopwatch, settings, annotation)241	}242}243/* CompileAndRun uses the Ginkgo CLIs internals to compile and run tests with different possible settings governing concurrency and ordering */244func RunScenarioWithGinkgoInternals(stopwatch *gmeasure.Stopwatch, settings ScenarioSettings, annotation gmeasure.Annotation) {245	cliConfig := types.NewDefaultCLIConfig()246	cliConfig.Recurse = settings.Recurse247	suiteConfig := types.NewDefaultSuiteConfig()248	reporterConfig := types.NewDefaultReporterConfig()249	reporterConfig.Succinct = true250	goFlagsConfig := types.NewDefaultGoFlagsConfig()251	suites := internal.FindSuites([]string{pfm.PathTo(settings.Fixture)}, cliConfig, true)252	Ω(suites).Should(HaveLen(settings.NumSuites))253	compile := make(chan internal.TestSuite, len(suites))254	compiled := make(chan internal.TestSuite, len(suites))255	completed := make(chan internal.TestSuite, len(suites))256	firstOutputOnce := sync.Once{}257	for compiler := 0; compiler < settings.ConcurrentCompilers; compiler++ {258		go func() {259			for suite := range compile {260				if !suite.State.Is(internal.TestSuiteStateCompiled) {261					subStopwatch := stopwatch.NewStopwatch()262					suite = internal.CompileSuite(suite, goFlagsConfig)263					subStopwatch.Record("compile-test: "+suite.PackageName, annotation)264					Ω(suite.CompilationError).Should(BeNil())265				}266				compiled <- suite267			}268		}()269	}270	if settings.CompileFirstSuiteSerially {271		compile <- suites[0]272		suites[0] = <-compiled273	}274	for runner := 0; runner < settings.ConcurrentRunners; runner++ {275		go func() {276			for suite := range compiled {277				firstOutputOnce.Do(func() {278					stopwatch.Record("first-output", annotation, gmeasure.Style("{{cyan}}"))279				})280				subStopwatch := stopwatch.NewStopwatch()281				suite = internal.RunCompiledSuite(suite, suiteConfig, reporterConfig, cliConfig, goFlagsConfig, []string{})282				subStopwatch.Record("run-test: "+suite.PackageName, annotation)283				Ω(suite.State).Should(Equal(internal.TestSuiteStatePassed))284				completed <- suite285			}286		}()287	}288	for _, suite := range suites {289		compile <- suite290	}291	completedSuites := []internal.TestSuite{}292	for suite := range completed {293		completedSuites = append(completedSuites, suite)294		if len(completedSuites) == len(suites) {295			close(completed)296			close(compile)297			close(compiled)298		}299	}300	stopwatch.Record("total-runtime", annotation, gmeasure.Style("{{green}}"))301	internal.Cleanup(goFlagsConfig, completedSuites...)302}303func RunScenarioWithGoTest(stopwatch *gmeasure.Stopwatch, settings ScenarioSettings, annotation gmeasure.Annotation) {304	defer func() {305		stopwatch.Record("total-runtime", annotation, gmeasure.Style("{{green}}"))306	}()307	if settings.GoTestRecurse {308		cmd := exec.Command("go", "test", "-count=1", "./...")309		cmd.Dir = pfm.PathTo(settings.Fixture)310		sess, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter)311		Ω(err).ShouldNot(HaveOccurred())312		Eventually(sess).Should(gbytes.Say(`.`)) //should say _something_ eventually!313		stopwatch.Record("first-output", annotation, gmeasure.Style("{{cyan}}"))314		Eventually(sess).Should(gexec.Exit(0))315		return316	}317	cliConfig := types.NewDefaultCLIConfig()318	cliConfig.Recurse = settings.Recurse319	suites := internal.FindSuites([]string{pfm.PathTo(settings.Fixture)}, cliConfig, true)320	Ω(suites).Should(HaveLen(settings.NumSuites))321	firstOutputOnce := sync.Once{}322	if settings.GoTestCompileThenRunSerially {323		for _, suite := range suites {324			subStopwatch := stopwatch.NewStopwatch()325			cmd := exec.Command("go", "test", "-c", "-o=out.test")326			cmd.Dir = suite.AbsPath()327			sess, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter)328			Ω(err).ShouldNot(HaveOccurred())329			Eventually(sess).Should(gexec.Exit(0))330			subStopwatch.Record("compile-test: "+suite.PackageName, annotation).Reset()331			firstOutputOnce.Do(func() {332				stopwatch.Record("first-output", annotation, gmeasure.Style("{{cyan}}"))333			})...

Full Screen

Full Screen

large_suite_test.go

Source:large_suite_test.go Github

copy

Full Screen

...31		if !DEBUG {32			DeferCleanup(pfm.Cleanup)33		}34		pfm.MountFixture("large_suite")35		session := startGinkgo(pfm.PathTo("large_suite"), "build")36		Eventually(session).Should(gexec.Exit(0))37		Expect(pfm.PathTo("large_suite", "large_suite.test")).To(BeAnExistingFile())38	})39	var nameFor = func(nodes int, protocol string, interceptor string) string {40		if nodes == 1 {41			return "serial"42		}43		return "parallel" + "-" + protocol + "-" + interceptor44	}45	DescribeTable("scenarios",46		func(nodes int, protocol string, interceptor string) {47			var experiment *gmeasure.Experiment48			name := nameFor(nodes, protocol, interceptor)49			if REGENERATE_BENCHMARK {50				experiment = gmeasure.NewExperiment(name + "-benchmark")51			} else {52				benchmark := cache.Load(name+"-benchmark", BENCHMARK_VERSION)53				Ω(benchmark).ShouldNot(BeNil())54				runtimes = append(runtimes, benchmark.GetStats("runtime"))55				experiment = gmeasure.NewExperiment(name)56			}57			AddReportEntry(experiment.Name, experiment)58			env := []string{}59			if nodes > 1 {60				env = append(env, "GINKGO_PARALLEL_PROTOCOL="+protocol)61			}62			experiment.SampleDuration("runtime", func(idx int) {63				fmt.Printf("Running %s %d/%d\n", name, idx+1, N)64				session := startGinkgoWithEnv(65					pfm.PathTo("large_suite"),66					env,67					fmt.Sprintf("--procs=%d", nodes),68					fmt.Sprintf("--output-interceptor-mode=%s", interceptor),69					"large_suite.test",70				)71				Eventually(session).Should(gexec.Exit(0))72			}, gmeasure.SamplingConfig{N: N})73			runtimes = append(runtimes, experiment.GetStats("runtime"))74			fmt.Printf("Profiling %s\n", name)75			session := startGinkgoWithEnv(76				pfm.PathTo("large_suite"),77				env,78				fmt.Sprintf("--procs=%d", nodes),79				fmt.Sprintf("--output-interceptor-mode=%s", interceptor),80				"--cpuprofile=CPU.profile",81				"--blockprofile=BLOCK.profile",82				"large_suite.test",83			)84			Eventually(session).Should(gexec.Exit(0))85			if REGENERATE_BENCHMARK {86				cache.Save(experiment.Name, BENCHMARK_VERSION, experiment)87			}88		},89		nameFor,90		Entry(nil, 1, "", ""),...

Full Screen

Full Screen

PathTo

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	vm := otto.New()4	vm.Run(`var performance_test = require("./performance_test.js");`)5	result, err := vm.Call("performance_test.PathTo", nil, "1", "3")6	if err != nil {7		fmt.Println("An error occurred while calling the function:", err)8	}9	fmt.Println("Result of the function:", result)10}

Full Screen

Full Screen

PathTo

Using AI Code Generation

copy

Full Screen

1import (2type Node struct {3}4type performance_test struct {5}6func (p *performance_test) PathTo() {7	dist := make([][]float64, len(p.grid))8	for i := range dist {9		dist[i] = make([]float64, len(p.grid[0]))10		for j := range dist[i] {11			dist[i][j] = math.Inf(1)12		}13	}14	parent := make([][]Node, len(p.grid))15	for i := range parent {16		parent[i] = make([]Node, len(p.grid[0]))17		for j := range parent[i] {18			parent[i][j] = Node{-1, -1}19		}20	}21	state := make([][]int, len(p.grid))22	for i := range state {23		state[i] = make([]int, len(p.grid[0]))24		for j := range state[i] {25		}26	}27	curr_dist := make([][]float64, len(p.grid))28	for i := range curr_dist {

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful