Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bug: use CallerFrames to find the filename instead of traversing program counter #40

Open
karngyan opened this issue Jun 8, 2022 · 0 comments · May be fixed by #41
Open

bug: use CallerFrames to find the filename instead of traversing program counter #40

karngyan opened this issue Jun 8, 2022 · 0 comments · May be fixed by #41

Comments

@karngyan
Copy link

karngyan commented Jun 8, 2022

Regarding findFileName

Go runtime docs discourage traversing PC or FuncForPC on any returned PCs as they can't account for inlining or return program counter adjustment.

This sometimes returns the wrong file name.

Something like this would be a better alternative:

func findFileName() (*string, error) {
	pc := make([]uintptr, 100)
	count := runtime.Callers(0, pc)
	frames := runtime.CallersFrames(pc[:count])
	var lastFrame *runtime.Frame
	var testFrame *runtime.Frame

	for {
		frame, more := frames.Next()
		if !more {
			break
		}

		if isTestRunnerFrame(&frame) {
			testFrame = &frame
			break
		}
		lastFrame = &frame
	}

	if !isTestRunnerFrame(testFrame) {
		return nil, fmt.Errorf("approvals: could not find the test method")
	}

	return &lastFrame.File, nil
}

func isTestRunnerFrame(f *runtime.Frame) bool {
	return f != nil && f.Function == "testing.tRunner" || f.Function == "testing.runExample"
}

What do you think?

@karngyan karngyan changed the title Use CallerFrames to find the filename instead of traversing program counter bug: use CallerFrames to find the filename instead of traversing program counter Jun 8, 2022
@karngyan karngyan linked a pull request Jun 8, 2022 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant