gkampitakis/go-snaps

[Bug]: Snap filename is reported wrongly

Closed this issue · 2 comments

Description

For code https://github.com/stdedos/junit2html/blob/927e5218bb0ff447cd5390a7190a34db5a1b4b9a/tests/file_based_test.go#L94-L97, it seems that go-snaps will print the wrong snapshot path:

=== RUN   TestSnapshots/my_first_test
    file_based_test.go:85: 
        	Error Trace:	~/p/junit2html/tests/file_based_test.go:85
        	            				~/go/pkg/mod/golang.org/toolchain@v0.0.1-go1.22.4.linux-amd64/src/runtime/panic.go:770
        	            				~/p/junit2html/pkg/parse/parse.go:117
        	            				~/p/junit2html/pkg/parse/parse.go:92
        	            				~/p/junit2html/pkg/cmd/cmd.go:40
        	            				~/p/junit2html/tests/file_based_test.go:89
        	            				~/p/junit2html/pkg/utils/utils.go:25
        	            				~/p/junit2html/tests/file_based_test.go:82
        	Error:      	Expected nil, but got: &fmt.wrapError{msg:"error probing file: EOF", err:(*errors.errorString)(0x8a9a30)}
        	Test:       	TestSnapshots/my_first_test
        	Messages:   	Panic: error probing file: EOF
    file_based_test.go:97: 
        - Snapshot - 172
        + Received   + 0
        
        ...
        
        at ../my_first_test/__snapshots__/result.html.snap:2
        
    --- FAIL: TestSnapshots/my_first_test (0.00s)

(forget about the failing test)

The at ../ path is clearly wrong - as the and the path have the same parent folder.

The issue is at

go-snaps/snaps/snapshot.go

Lines 256 to 274 in c578aa7

func snapshotPath(c *config) (string, string) {
// skips current func, the wrapper match* and the exported Match* func
callerPath := baseCaller(3)
dir := c.snapsDir
if !filepath.IsAbs(dir) {
dir = filepath.Join(filepath.Dir(callerPath), c.snapsDir)
}
filename := c.filename
if filename == "" {
base := filepath.Base(callerPath)
filename = strings.TrimSuffix(base, filepath.Ext(base))
}
snapPath := filepath.Join(dir, filename+snapsExt)
snapPathRel, _ := filepath.Rel(callerPath, snapPath)
return snapPath, snapPathRel
}
, and specifically in snapPathRel, _ := filepath.Rel(callerPath, snapPath).

callerPath is used "interchangeably" as a filename and a directory. It seems that in snapPathRel, _ := filepath.Rel(callerPath, snapPath) it was forgotten that it is a filename.

Apart from the necessary filepath.Dir(callerPath), I'd also suggest renaming this to callerFilename, highlighting its correct contents

Steps to Reproduce

Run https://github.com/stdedos/junit2html/blob/927e5218bb0ff447cd5390a7190a34db5a1b4b9a/tests/file_based_test.go test

Expected Behavior

No response

Hey 👋 , thanks for reporting this issue. Will try and have a look at it asap.

Indeed I can reproduce the issue, and looking into it probably never worked correct. Not sure how I missed that. Will issue a pr later today fixing this. Again thank you for reporting this with clear steps on how to reproduce and the fix.