How to use FindCaller method of integration_test Package

Best Ginkgo code snippet using integration_test.FindCaller

profiling_test.go

Source:profiling_test.go Github

copy

Full Screen

...17	Caller  string18	CumStat float6419}20type ProfileLines []ProfileLine21func (lines ProfileLines) FindCaller(caller string) ProfileLine {22	for _, line := range lines {23		if strings.Contains(line.Caller, caller) {24			return line25		}26	}27	Fail(fmt.Sprintf("Could not find caller %s among profile lines %+v.", caller, lines), 1)28	return ProfileLine{}29}30var PROFILE_RE = regexp.MustCompile(`[\d\.]+[MBms]*\s*[\d\.]+\%\s*[\d\.]+\%\s*([\d\.]+[MBnms]*)\s*[\d\.]+\%\s*(.*)`)31func ParseProfile(binary string, path string) ProfileLines {32	cmd := exec.Command("go", "tool", "pprof", "-cum", "-top", binary, path)33	output, err := cmd.CombinedOutput()34	GinkgoWriter.Printf("Profile for: %s\n%s\n", path, string(output))35	ExpectWithOffset(1, err).ShouldNot(HaveOccurred())36	out := ProfileLines{}37	idx := 038	for _, line := range strings.Split(string(output), "\n") {39		matches := PROFILE_RE.FindStringSubmatch(line)40		if matches == nil {41			continue42		}43		cumStatEntry := matches[1]44		var cumStat float6445		if strings.Contains(cumStatEntry, "MB") {46			var err error47			cumStat, err = strconv.ParseFloat(strings.TrimRight(cumStatEntry, "MB"), 64)48			ExpectWithOffset(1, err).ShouldNot(HaveOccurred())49		} else {50			duration, err := time.ParseDuration(cumStatEntry)51			ExpectWithOffset(1, err).ShouldNot(HaveOccurred())52			cumStat = float64(duration.Milliseconds())53		}54		out = append(out, ProfileLine{55			Index:   idx,56			Caller:  matches[2],57			CumStat: cumStat,58		})59		idx += 160	}61	return out62}63var _ = Describe("Profiling Specs", func() {64	Describe("Measuring code coverage", func() {65		BeforeEach(func() {66			fm.MountFixture("coverage")67		})68		processCoverageProfile := func(path string) string {69			profileOutput, err := exec.Command("go", "tool", "cover", fmt.Sprintf("-func=%s", path)).CombinedOutput()70			ExpectWithOffset(1, err).ShouldNot(HaveOccurred())71			return string(profileOutput)72		}73		Context("when running a single package in series or in parallel with -cover", func() {74			It("emits the coverage pecentage and generates a cover profile", func() {75				seriesSession := startGinkgo(fm.PathTo("coverage"), "--no-color", "-cover")76				Eventually(seriesSession).Should(gexec.Exit(0))77				Ω(seriesSession.Out).Should(gbytes.Say(`coverage: 80\.0% of statements`))78				seriesCoverage := processCoverageProfile(fm.PathTo("coverage", "coverprofile.out"))79				fm.RemoveFile("coverage", "coverprofile.out")80				parallelSession := startGinkgo(fm.PathTo("coverage"), "--no-color", "--procs=2", "-cover")81				Eventually(parallelSession).Should(gexec.Exit(0))82				Ω(parallelSession.Out).Should(gbytes.Say(`coverage: 80\.0% of statements`))83				parallelCoverage := processCoverageProfile(fm.PathTo("coverage", "coverprofile.out"))84				Ω(parallelCoverage).Should(Equal(seriesCoverage))85			})86		})87		Context("with -coverpkg", func() {88			It("computes coverage of the passed-in additional packages", func() {89				coverPkgFlag := fmt.Sprintf("-coverpkg=%s,%s", fm.PackageNameFor("coverage"), fm.PackageNameFor("coverage/external_coverage"))90				seriesSession := startGinkgo(fm.PathTo("coverage"), coverPkgFlag)91				Eventually(seriesSession).Should(gexec.Exit(0))92				Ω(seriesSession.Out).Should(gbytes.Say("coverage: 71.4% of statements in"))93				seriesCoverage := processCoverageProfile(fm.PathTo("coverage", "coverprofile.out"))94				fm.RemoveFile("coverage", "coverprofile.out")95				parallelSession := startGinkgo(fm.PathTo("coverage"), "--no-color", "--procs=2", coverPkgFlag)96				Eventually(parallelSession).Should(gexec.Exit(0))97				Ω(parallelSession.Out).Should(gbytes.Say(`coverage: 71\.4% of statements`))98				parallelCoverage := processCoverageProfile(fm.PathTo("coverage", "coverprofile.out"))99				Ω(parallelCoverage).Should(Equal(seriesCoverage))100			})101		})102		Context("with a custom profile name", func() {103			It("generates cover profiles with the specified name", func() {104				session := startGinkgo(fm.PathTo("coverage"), "--no-color", "-coverprofile=myprofile.out")105				Eventually(session).Should(gexec.Exit(0))106				Ω(session.Out).Should(gbytes.Say(`coverage: 80\.0% of statements`))107				Ω(fm.PathTo("coverage", "myprofile.out")).Should(BeAnExistingFile())108				Ω(fm.PathTo("coverage", "coverprofile.out")).ShouldNot(BeAnExistingFile())109			})110		})111		Context("when multiple suites are tested", func() {112			BeforeEach(func() {113				fm.MountFixture("combined_coverage")114			})115			It("generates a single cover profile", func() {116				session := startGinkgo(fm.PathTo("combined_coverage"), "--no-color", "--cover", "-r", "--procs=2", "--covermode=atomic")117				Eventually(session).Should(gexec.Exit(0))118				Ω(fm.PathTo("combined_coverage", "coverprofile.out")).Should(BeAnExistingFile())119				Ω(fm.PathTo("combined_coverage", "first_package/coverprofile.out")).ShouldNot(BeAnExistingFile())120				Ω(fm.PathTo("combined_coverage", "second_package/coverprofile.out")).ShouldNot(BeAnExistingFile())121				Ω(fm.PathTo("combined_coverage", "third_package/coverprofile.out")).ShouldNot(BeAnExistingFile())122				Ω(session.Out).Should(gbytes.Say(`coverage: 80\.0% of statements`))123				Ω(session.Out).Should(gbytes.Say(`coverage: 100\.0% of statements`))124				Ω(session.Out).Should(gbytes.Say(`coverage: \[no statements\]`))125				By("ensuring there is only one 'mode:' line")126				re := regexp.MustCompile(`mode: atomic`)127				content := fm.ContentOf("combined_coverage", "coverprofile.out")128				matches := re.FindAllStringIndex(content, -1)129				Ω(len(matches)).Should(Equal(1))130				By("emitting a composite coverage score")131				Ω(session.Out).Should(gbytes.Say(`composite coverage: 90\.0% of statements`))132			})133			Context("when -keep-separate-coverprofiles is set", func() {134				It("generates separate coverprofiles", Label("slow"), func() {135					session := startGinkgo(fm.PathTo("combined_coverage"), "--no-color", "--cover", "-r", "--procs=2", "--keep-separate-coverprofiles")136					Eventually(session).Should(gexec.Exit(0))137					Ω(fm.PathTo("combined_coverage", "coverprofile.out")).ShouldNot(BeAnExistingFile())138					Ω(fm.PathTo("combined_coverage", "first_package/coverprofile.out")).Should(BeAnExistingFile())139					Ω(fm.PathTo("combined_coverage", "second_package/coverprofile.out")).Should(BeAnExistingFile())140					Ω(fm.PathTo("combined_coverage", "third_package/coverprofile.out")).Should(BeAnExistingFile())141				})142			})143		})144		Context("when -output-dir is set", func() {145			BeforeEach(func() {146				fm.MountFixture("combined_coverage")147			})148			It("puts the cover profile in -output-dir", func() {149				session := startGinkgo(fm.PathTo("combined_coverage"), "--no-color", "--cover", "-r", "--procs=2", "--output-dir=./output")150				Eventually(session).Should(gexec.Exit(0))151				Ω(fm.PathTo("combined_coverage", "output/coverprofile.out")).Should(BeAnExistingFile())152				By("emitting a composite coverage score")153				Ω(session.Out).Should(gbytes.Say(`composite coverage: 90\.0% of statements`))154			})155			Context("when -keep-separate-coverprofiles is set", func() {156				It("puts namespaced coverprofiels in the -output-dir", func() {157					session := startGinkgo(fm.PathTo("combined_coverage"), "--no-color", "--cover", "-r", "--procs=2", "--output-dir=./output", "--keep-separate-coverprofiles")158					Eventually(session).Should(gexec.Exit(0))159					Ω(fm.PathTo("combined_coverage", "output/coverprofile.out")).ShouldNot(BeAnExistingFile())160					Ω(fm.PathTo("combined_coverage", "output/first_package_coverprofile.out")).Should(BeAnExistingFile())161					Ω(fm.PathTo("combined_coverage", "output/second_package_coverprofile.out")).Should(BeAnExistingFile())162				})163			})164		})165	})166	Describe("measuring cpu, memory, block, and mutex profiles", func() {167		BeforeEach(func() {168			fm.MountFixture("profile")169		})170		DescribeTable("profile behavior",171			func(pathToBinary func(string) string, pathToProfile func(string, string) string, args ...string) {172				args = append([]string{"--no-color", "-r", "--cpuprofile=cpu.out", "--memprofile=mem.out", "--blockprofile=block.out", "--mutexprofile=mutex.out"}, args...)173				session := startGinkgo(fm.PathTo("profile"), args...)174				Eventually(session).Should(gexec.Exit(0))175				// Verify that the binaries have been preserved and the profiles were generated176				for _, pkg := range []string{"slow_memory_hog", "block_contest", "lock_contest"} {177					Ω(pathToBinary(pkg)).Should(BeAnExistingFile())178					for _, profile := range []string{"cpu.out", "mem.out", "block.out", "mutex.out"} {179						Ω(pathToProfile(pkg, profile)).Should(BeAnExistingFile())180					}181				}182				cpuProfile := ParseProfile(pathToBinary("slow_memory_hog"), pathToProfile("slow_memory_hog", "cpu.out"))183				// The CPUProfile for the slow_memory_hog test should list the slow_memory_hog.SomethingExpensive functions as one of the most time-consuming functions184				// we can't assert on time as that will vary from machine to machine, however we _can_ assert that the slow_memory_hog.SomethingExpensive185				// function has a low index186				Ω(cpuProfile.FindCaller("slow_memory_hog.SomethingExpensive").Index).Should(BeNumerically("<=", 10))187				memProfile := ParseProfile(pathToBinary("slow_memory_hog"), pathToProfile("slow_memory_hog", "mem.out"))188				// The MemProifle for the slow_memory_hog test should list the slow_memory_hog.SomethingExpensive functions as one of the most memory-consuming functions189				// Assrting on the amount of memory consumed should be stable across tests as the function always builds a large array of this size190				Ω(memProfile.FindCaller("slow_memory_hog.SomethingExpensive").CumStat).Should(BeNumerically(">=", 200))191				blockProfile := ParseProfile(pathToBinary("block_contest"), pathToProfile("block_contest", "block.out"))192				// The BlockProfile for the block_contest test should list two channel-reading functions:193				// block_contest.ReadTheChannel is called 10 times and takes ~5ms per call194				// block_contest.SlowReadTheChannel is called once and teakes ~500ms per call195				// Asserting that both times are within a range should be stable across tests196				// Note: these numbers are adjusted slightly to tolerate variance during test runs197				Ω(blockProfile.FindCaller("block_contest.ReadTheChannel").CumStat).Should(BeNumerically(">=", 45))198				Ω(blockProfile.FindCaller("block_contest.ReadTheChannel").CumStat).Should(BeNumerically("<", 500))199				Ω(blockProfile.FindCaller("block_contest.SlowReadTheChannel").CumStat).Should(BeNumerically(">=", 450))200				mutexProfile := ParseProfile(pathToBinary("lock_contest"), pathToProfile("lock_contest", "mutex.out"))201				// The MutexProfile for the lock_contest test should list two functions that wait on a lock.202				// Unfortunately go doesn't seem to capture the names of the functions - so they're listed here as203				// lock_contest_test.glob..func1.1 is called 10 times and takes ~5ms per call204				// lock_contest_test.glob..func2.1 is called once and teakes ~500ms per call205				// Asserting that both times are within a range should be stable across tests.  The function names should be as well206				// but that might become a source of failure in the future207				// Note: these numbers are adjusted slightly to tolerate variance during test runs208				Ω(mutexProfile.FindCaller("lock_contest_test.glob..func1.1").CumStat).Should(BeNumerically(">=", 45))209				Ω(mutexProfile.FindCaller("lock_contest_test.glob..func1.1").CumStat).Should(BeNumerically("<", 500))210				Ω(mutexProfile.FindCaller("lock_contest_test.glob..func2.1").CumStat).Should(BeNumerically(">=", 450))211			},212			Entry("when running in series",213				func(pkg string) string { return fm.PathTo("profile", pkg+"/"+pkg+".test") },214				func(pkg string, profile string) string { return fm.PathTo("profile", pkg+"/"+profile) },215			),216			Entry("when running in parallel",217				func(pkg string) string { return fm.PathTo("profile", pkg+"/"+pkg+".test") },218				func(pkg string, profile string) string { return fm.PathTo("profile", pkg+"/"+profile) },219				"--procs=3",220			),221			Entry("when --output-dir is set", Label("slow"),222				func(pkg string) string { return fm.PathTo("profile", "profiles/"+pkg+".test") },223				func(pkg string, profile string) string { return fm.PathTo("profile", "profiles/"+pkg+"_"+profile) },224				"--procs=3", "--output-dir=./profiles",...

Full Screen

Full Screen

FindCaller

Using AI Code Generation

copy

Full Screen

1func TestFindCaller(t *testing.T) {2    caller := FindCaller()3    fmt.Println(caller)4}5func TestFindCaller(t *testing.T) {6    caller := FindCaller()7    fmt.Println(caller)8}9func TestFindCaller(t *testing.T) {10    caller := FindCaller()11    fmt.Println(caller)12}13func FindCaller() string {14    _, file, _, _ := runtime.Caller(1)15}16The solution is to create a package for the FindCaller() method and then import the package in the files you want to use the method in. Here is the code for the new package:17import (18func FindCaller() string {19    _, file, _, _ := runtime.Caller(1)20}21Then, you can import the findcaller package in your files and call the FindCaller() method:22import (23func main() {24    caller := findcaller.FindCaller()25    fmt.Println(caller)26}27import (28func main() {29    caller := findcaller.FindCaller()30    fmt.Println(caller)31}32import (

Full Screen

Full Screen

FindCaller

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	fileName := integration_test.FindCaller()4	fmt.Println(fileName)5	file := xlsx.NewFile()6	sheet, err := file.AddSheet("Sheet1")7	if err != nil {8		fmt.Printf(err.Error())9	}10	row := sheet.AddRow()11	cell := row.AddCell()12	err = file.Save(fileName + ".xlsx")13	if err != nil {14		fmt.Printf(err.Error())15	}16	xlFile, err := excelize.OpenFile(fileName + ".xlsx")17	if err != nil {18		fmt.Println(err)19	}20	cell, err = xlFile.GetCellValue("Sheet1", "A1")21	if err != nil {22		fmt.Println(err)23	}24	fmt.Println(cell)25	rows, err := xlFile.GetRows("Sheet1")26	for _, row := range rows {27		for _, colCell := range row {28			fmt.Print(colCell, "\t")29		}30		fmt.Println()31	}32	err = os.Remove(fileName + ".xlsx")33	if err != nil {34		log.Fatal(err)35	}36}37import (38func main() {39	fileName := integration_test.FindCaller()40	fmt.Println(fileName)41	file := xlsx.NewFile()42	sheet, err := file.AddSheet("Sheet1")43	if err != nil {44		fmt.Printf(err.Error())45	}46	row := sheet.AddRow()47	cell := row.AddCell()48	err = file.Save(fileName + ".xlsx")

Full Screen

Full Screen

FindCaller

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	fmt.Println(integration_test.FindCaller())4}5import (6func FindCaller() string {7	pc, file, line, ok := runtime.Caller(1)8	if !ok {9		return "runtime.Caller() failed"10	}11	f := runtime.FuncForPC(pc)12	file = strings.TrimPrefix(file, "/home/username/go/src/")13	return fmt.Sprintf("%s:%d %s", file, line, f.Name())14}

Full Screen

Full Screen

FindCaller

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	fmt.Println("Hello World")4	integration_test.FindCaller()5}6import (7func main() {8	fmt.Println("Hello World")9	integration_test.FindCaller()10}11import (12func FindCaller() {13	pc, file, line, ok := runtime.Caller(1)14	if ok {15		fmt.Printf("Caller is %v16", runtime.FuncForPC(pc).Name())17		fmt.Printf("File is %v18		fmt.Printf("Line is %v19	}20}

Full Screen

Full Screen

FindCaller

Using AI Code Generation

copy

Full Screen

1import "testing"2func TestFindCaller(t *testing.T) {3    t.Run("FindCaller Test", func(t *testing.T) {4        t.Helper()5        t.Log("TestFindCaller")6        t.Log(FindCaller(t))7    })8}9import "testing"10func TestFindCaller(t *testing.T) {11    t.Run("FindCaller Test", func(t *testing.T) {12        t.Helper()13        t.Log("TestFindCaller")14        t.Log(FindCaller(t))15    })16}17import "testing"18func TestFindCaller(t *testing.T) {19    t.Run("FindCaller Test", func(t *testing.T) {20        t.Helper()21        t.Log("TestFindCaller")22        t.Log(FindCaller(t))23    })24}25import "testing"26func TestFindCaller(t *testing.T) {27    t.Run("FindCaller Test", func(t *testing.T) {28        t.Helper()29        t.Log("TestFindCaller")30        t.Log(FindCaller(t))31    })32}33import "testing"34func TestFindCaller(t *testing.T) {35    t.Run("FindCaller Test", func(t *testing.T) {36        t.Helper()37        t.Log("TestFindCaller")38        t.Log(FindCaller(t))39    })40}41import "testing"42func TestFindCaller(t *testing.T) {43    t.Run("FindCaller Test", func(t *testing.T) {44        t.Helper()45        t.Log("TestFindCaller")46        t.Log(FindCaller(t))47    })48}49import "testing"50func TestFindCaller(t *testing.T) {51    t.Run("FindCaller Test", func(t *testing.T) {52        t.Helper()53        t.Log("TestFindCaller")54        t.Log(FindCaller(t))55    })

Full Screen

Full Screen

FindCaller

Using AI Code Generation

copy

Full Screen

1func TestFindCaller(t *testing.T) {2    caller := integration_test.FindCaller()3    if caller != "integration_test" {4        t.Error("Expected caller to be integration_test but got ", caller)5    }6}7--- PASS: TestFindCaller (0.00s)8--- PASS: TestFindCaller (0.00s)9--- PASS: TestFindCaller (0.00s)10--- PASS: TestFindCaller (

Full Screen

Full Screen

FindCaller

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	fmt.Println("Hello, playground")4	integration_test.FindCaller()5}6import (7func FindCaller() {8	_, file, line, ok := runtime.Caller(0)9	if ok {10		fmt.Println(file, line)11	}12}13Your name to display (optional):14Your name to display (optional):15Your name to display (optional):

Full Screen

Full Screen

FindCaller

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	fmt.Println("Hello, playground")4	integration_test.FindCaller()5}6import (7func main() {8	fmt.Println("Hello, playground")9	integration_test.FindCaller()10}

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