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

fix: simplify identifying caller #61

Merged
merged 2 commits into from
May 22, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 10 additions & 42 deletions snaps/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@ package snaps
import (
"errors"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"unicode"
"unicode/utf8"

"github.com/gkampitakis/ciinfo"
)
Expand Down Expand Up @@ -75,60 +74,29 @@ func baseCaller(skip int) string {
var (
pc uintptr
file, prevFile string
ok bool
)

for i := skip + 1; ; i++ {
prevFile = file
pc, file, _, _ = runtime.Caller(i)
pc, file, _, ok = runtime.Caller(i)
if !ok {
return prevFile
}

f := runtime.FuncForPC(pc)
if f == nil {
break
return prevFile
}

funcName := f.Name()
if funcName == "testing.tRunner" {
break
if f.Name() == "testing.tRunner" {
return prevFile
}

// special case handling test runners
// tested with testify/suite, packagestest and testcase
segments := strings.Split(funcName, ".")
for _, segment := range segments {
if !isTest(segment, "Test") {
continue
}

// packagestest is same as tRunner where we step one caller further
// so we need to return the prevFile in testcase and testify/suite we return the current file
// e.g. funcName golang.org/x/tools/go/packages/packagestest.TestAll.func1
if strings.Contains(funcName, "packagestest") {
// return only the Function Name
// e.g. "go-snaps-testing-suite/src/issues.(*ExampleTestSuite).TestExampleSnapshot"
// will return TestExampleSnapshot
return prevFile
}

if strings.HasSuffix(filepath.Base(file), "_test.go") {
return file
}
}

return prevFile
}

// Stolen from the `go test` tool
//
// isTest tells whether name looks like a test
// It is a Test (say) if there is a character after Test that is not a lower-case letter
func isTest(name, prefix string) bool {
if !strings.HasPrefix(name, prefix) {
return false
}
if len(name) == len(prefix) { // "Test" is ok
return true
}
r, _ := utf8.DecodeRuneInString(name[len(prefix):])
return !unicode.IsLower(r)
}

// shouldUpdateSingle returns if a single should be updated or not
Expand Down