filepicker_test.go

 1package filepicker
 2
 3import (
 4	"fmt"
 5	"io/fs"
 6	"path/filepath"
 7	"strings"
 8	"testing"
 9	"testing/fstest"
10
11	tea "github.com/charmbracelet/bubbletea/v2"
12	"github.com/charmbracelet/crush/internal/tui/util"
13	"github.com/stretchr/testify/assert"
14	"github.com/stretchr/testify/require"
15)
16
17var pngMagicNumberData = []byte("\x89PNG\x0D\x0A\x1A\x0A")
18
19func makePathCanonical(p string) string {
20	return strings.ReplaceAll(p, "/", string(filepath.Separator))
21}
22
23func TestOnPasteMockFSWithValidPath(t *testing.T) {
24	var mockedFSPath string
25	resolveTestFS := func(fsysPath string) fs.FS {
26		mockedFSPath = fsysPath
27		return fstest.MapFS{
28			"image1.png": &fstest.MapFile{
29				Data: pngMagicNumberData,
30			},
31			"image2.png": &fstest.MapFile{
32				Data: []byte("fake png content"),
33			},
34		}
35	}
36
37	// Test with the first file
38	cmd := onPaste(resolveTestFS, makePathCanonical("/home/testuser/images/image1.png"))
39	msg := cmd()
40
41	assert.Equal(t, makePathCanonical("/home/testuser/images"), mockedFSPath)
42	filePickedMsg, ok := msg.(FilePickedMsg)
43	require.True(t, ok)
44	require.NotNil(t, filePickedMsg)
45	assert.Equal(t, "image1.png", filePickedMsg.Attachment.FileName)
46	assert.Equal(t, "image/png", filePickedMsg.Attachment.MimeType)
47}
48
49func TestOnPasteMockFSWithInvalidPath(t *testing.T) {
50	var mockedFSPath string
51	resolveTestFS := func(fsysPath string) fs.FS {
52		mockedFSPath = fsysPath
53		return fstest.MapFS{
54			"image1.png": &fstest.MapFile{
55				Data: pngMagicNumberData,
56			},
57			"image2.png": &fstest.MapFile{
58				Data: []byte("fake png content"),
59			},
60		}
61	}
62
63	// Test with the first file
64	cmd, ok := onPaste(resolveTestFS, makePathCanonical("/home/testuser/images/nonexistent.png"))().(tea.Cmd)
65	require.True(t, ok)
66
67	msg := cmd()
68
69	assert.Equal(t, makePathCanonical("/home/testuser/images"), mockedFSPath)
70	fmt.Printf("TYPE: %T\n", msg)
71	infoErrMsg, ok := msg.(util.InfoMsg)
72	require.True(t, ok)
73	require.NotNil(t, infoErrMsg)
74
75	assert.Equal(t, util.InfoMsg{
76		Type: util.InfoTypeError,
77		Msg:  "unable to read the image: error getting file info: open nonexistent.png: file does not exist, " + makePathCanonical("/home/testuser/images/nonexistent.png"),
78	}, infoErrMsg)
79}