Skip to content

Commit 8723475

Browse files
committed
fix: Remove duplication in tests
1 parent a9c84ff commit 8723475

File tree

8 files changed

+84
-120
lines changed

8 files changed

+84
-120
lines changed

src/cmd/main.go

Lines changed: 1 addition & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ import (
99
"log/slog"
1010
"net/http"
1111
"os"
12-
"runtime"
1312
"time"
1413

1514
"github.com/yorukot/superfile/src/internal/common"
@@ -129,14 +128,9 @@ func spfAppAction(_ context.Context, c *cli.Command) error {
129128

130129
InitConfigFile()
131130

132-
hasTrash := true
133-
if err := InitTrash(); err != nil {
134-
hasTrash = false
135-
}
136-
137131
firstUse := checkFirstUse()
138132

139-
p := tea.NewProgram(internal.InitialModel(firstFilePanelDirs, firstUse, hasTrash),
133+
p := tea.NewProgram(internal.InitialModel(firstFilePanelDirs, firstUse, true),
140134
tea.WithAltScreen(), tea.WithMouseCellMotion())
141135
if _, err := p.Run(); err != nil {
142136
utils.PrintfAndExit("Alas, there's been an error: %v", err)
@@ -192,20 +186,6 @@ func InitConfigFile() {
192186
}
193187
}
194188

195-
// We are initializing these, but not sure if we are ever using them
196-
func InitTrash() error {
197-
// Create trash directories
198-
if runtime.GOOS != utils.OsDarwin {
199-
err := createDirectories(
200-
variable.CustomTrashDirectory,
201-
variable.CustomTrashDirectoryFiles,
202-
variable.CustomTrashDirectoryInfo,
203-
)
204-
return err
205-
}
206-
return nil
207-
}
208-
209189
// Helper functions
210190
// Create all dirs that does not already exists
211191
func createDirectories(dirs ...string) error {

src/config/fixed_variable.go

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,7 @@ var (
4646
LastDirFile = filepath.Join(SuperFileStateDir, "lastdir")
4747

4848
// Trash Directories
49-
DarwinTrashDirectory = filepath.Join(HomeDir, ".Trash")
50-
CustomTrashDirectory = filepath.Join(xdg.DataHome, "Trash")
51-
CustomTrashDirectoryFiles = filepath.Join(xdg.DataHome, "Trash", "files")
52-
CustomTrashDirectoryInfo = filepath.Join(xdg.DataHome, "Trash", "info")
49+
DarwinTrashDirectory = filepath.Join(HomeDir, ".Trash")
5350
)
5451

5552
// These variables are actually not fixed, they are sometimes updated dynamically

src/internal/common/predefined_variable.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,11 @@ const DateModifiedOption = "Date Modified"
1414
const SameRenameWarnTitle = "There is already a file or directory with that name"
1515
const SameRenameWarnContent = "This operation will override the existing file"
1616

17+
const TrashWarnTitle = "Are you sure you want to move this to trash can"
18+
const TrashWarnContent = "This operation will move file or directory to trash can."
19+
const PermanentDeleteWarnTitle = "Are you sure you want to completely delete"
20+
const PermanentDeleteWarnContent = "This operation cannot be undone and your data will be completely lost."
21+
1722
var (
1823
MinimumHeight = 24
1924
MinimumWidth = 60

src/internal/file_operations.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -145,15 +145,15 @@ func copyFile(src, dst string, srcInfo os.FileInfo) error {
145145
return nil
146146
}
147147

148-
// Move file to trash can and can auto switch macos trash can or linux trash can
149-
func trashMacOrLinux(src string) error {
148+
func moveToTrash(src string) error {
150149
var err error
151150
switch runtime.GOOS {
152151
case utils.OsDarwin:
153152
err = moveElement(src, filepath.Join(variable.DarwinTrashDirectory, filepath.Base(src)))
154153
case utils.OsWindows:
155154
err = trash_win.Throw(src)
156155
default:
156+
// TODO: We should consider moving away from this package. Its not well written.
157157
err = trash.Trash(src)
158158
}
159159
if err != nil {

src/internal/handle_file_operation_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ func TestCompressSelectedFiles(t *testing.T) {
117117
assert.Eventually(t, func() bool {
118118
_, err := os.Lstat(zipFile)
119119
return err == nil
120-
}, time.Second, 10*time.Millisecond)
120+
}, time.Second, DefaultTestTick)
121121

122122
// Assert zip file exists right after compression
123123
require.FileExists(t, zipFile, "Expected zip file does not exist after compression")
@@ -151,7 +151,7 @@ func TestCompressSelectedFiles(t *testing.T) {
151151
}
152152
}
153153
return true
154-
}, time.Second, 10*time.Millisecond, "Extraction of files failed Required - [%s]+%v",
154+
}, time.Second, DefaultTestTick, "Extraction of files failed Required - [%s]+%v",
155155
extractedDir, tt.expectedFilesAfterExtract)
156156

157157
require.NoError(t, os.RemoveAll(extractedDir))

src/internal/handle_file_operations.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ func deleteOperation(processBarModel *processbar.Model, items []string, useTrash
128128

129129
deleteFunc := os.RemoveAll
130130
if useTrash {
131-
deleteFunc = trashMacOrLinux
131+
deleteFunc = moveToTrash
132132
}
133133
for _, item := range items {
134134
err = deleteFunc(item)
@@ -167,14 +167,14 @@ func (m *model) getDeleteTriggerCmd(deletePermanent bool) tea.Cmd {
167167
return func() tea.Msg {
168168
title := "Are you sure you want to move this to trash can"
169169
content := "This operation will move file or directory to trash can."
170-
notifyModel := notify.New(true, title, content, notify.DeleteAction)
170+
action := notify.DeleteAction
171171

172172
if !m.hasTrash || isExternalDiskPath(panel.location) || deletePermanent {
173173
title = "Are you sure you want to completely delete"
174174
content = "This operation cannot be undone and your data will be completely lost."
175-
notifyModel = notify.New(true, title, content, notify.PermanentDeleteAction)
175+
action = notify.PermanentDeleteAction
176176
}
177-
return NewNotifyModalMsg(notifyModel, reqID)
177+
return NewNotifyModalMsg(notify.New(true, title, content, action), reqID)
178178
}
179179
}
180180

src/internal/model_file_operations_test.go

Lines changed: 64 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"time"
1010

1111
tea "github.com/charmbracelet/bubbletea"
12+
"github.com/rkoesters/xdg/trash"
1213
"github.com/stretchr/testify/assert"
1314
"github.com/stretchr/testify/require"
1415
variable "github.com/yorukot/superfile/src/config"
@@ -48,7 +49,7 @@ func TestCopy(t *testing.T) {
4849
assert.Eventually(t, func() bool {
4950
_, err := os.Lstat(filepath.Join(dir2, "file1.txt"))
5051
return err == nil
51-
}, time.Second, 10*time.Millisecond)
52+
}, time.Second, DefaultTestTick)
5253

5354
assert.False(t, p.getModel().copyItems.cut)
5455
assert.Equal(t, file1, p.getModel().copyItems.items[0])
@@ -57,7 +58,7 @@ func TestCopy(t *testing.T) {
5758
assert.Eventually(t, func() bool {
5859
_, err := os.Lstat(filepath.Join(dir2, "file1(1).txt"))
5960
return err == nil
60-
}, time.Second, 10*time.Millisecond)
61+
}, time.Second, DefaultTestTick)
6162
assert.FileExists(t, filepath.Join(dir2, "file1(1).txt"))
6263
//TODO: Also verify if there are only 2 items in process bar
6364
})
@@ -136,7 +137,7 @@ func TestFileRename(t *testing.T) {
136137
_, err1 := os.Stat(file1)
137138
_, err1New := os.Stat(file1New)
138139
return err1New == nil && os.IsNotExist(err1)
139-
}, time.Second, 10*time.Millisecond, "File never got renamed")
140+
}, time.Second, DefaultTestTick, "File never got renamed")
140141
})
141142

142143
t.Run("Rename confirmation for same name", func(t *testing.T) {
@@ -155,7 +156,7 @@ func TestFileRename(t *testing.T) {
155156
// This will result in async
156157
assert.Eventually(t, func() bool {
157158
return m.notifyModel.IsOpen()
158-
}, time.Second, 10*time.Millisecond, "Notify modal never opened, filepanel items : %v",
159+
}, time.Second, DefaultTestTick, "Notify modal never opened, filepanel items : %v",
159160
m.getFocusedFilePanel().element)
160161

161162
assert.Equal(t, notify.New(true,
@@ -180,7 +181,7 @@ func TestFileRename(t *testing.T) {
180181
string(f2Data) == "f3"
181182
}
182183
return err2 == nil && err3 == nil
183-
}, time.Second, 10*time.Millisecond,
184+
}, time.Second, DefaultTestTick,
184185
"Rename should be done/not done appropriately, file : %v",
185186
m.getFocusedFilePanel().element)
186187
}
@@ -190,31 +191,16 @@ func TestFileRename(t *testing.T) {
190191
})
191192
}
192193

193-
func createDirectories(dirs ...string) error {
194-
for _, dir := range dirs {
195-
if err := os.MkdirAll(dir, 0755); err != nil {
196-
return fmt.Errorf("failed to create directory %s: %w", dir, err)
197-
}
198-
}
199-
return nil
200-
}
201-
202-
func initTrash() error {
203-
return createDirectories(
204-
variable.CustomTrashDirectory,
205-
variable.CustomTrashDirectoryFiles,
206-
variable.CustomTrashDirectoryInfo,
207-
)
208-
}
209-
210-
func getTrashPath(src string) string {
211-
home, _ := os.UserHomeDir()
212-
src = filepath.Base(src)
194+
func isTrashed(fileName string) bool {
213195
switch runtime.GOOS {
214196
case utils.OsDarwin:
215-
return filepath.Join(variable.DarwinTrashDirectory, src)
197+
_, err := os.Stat(filepath.Join(variable.DarwinTrashDirectory, fileName))
198+
return err == nil
199+
case utils.OsLinux:
200+
_, err := trash.Stat(fileName)
201+
return err == nil
216202
default:
217-
return filepath.Join(home, ".local", "share", "Trash", "files", src)
203+
return false
218204
}
219205
}
220206

@@ -226,67 +212,60 @@ func TestFileDelete(t *testing.T) {
226212
setupFilesWithData(t, []byte("f1"), file1)
227213
setupFilesWithData(t, []byte("f2"), file2)
228214

229-
t.Run("move to trash", func(t *testing.T) {
230-
m := defaultTestModel(curTestDir)
231-
err := initTrash()
232-
if err == nil {
233-
m.hasTrash = true
234-
} else {
235-
fmt.Println("Unable to create trash directories.")
236-
}
237-
p := NewTestTeaProgWithEventLoop(t, m)
238-
idx := findItemIndexInPanelByLocation(m.getFocusedFilePanel(), file1)
239-
require.NotEqual(t, -1, idx, "%s should be found in panel", file1)
240-
m.getFocusedFilePanel().cursor = idx
241-
242-
p.SendKey(common.Hotkeys.DeleteItems[0])
243-
244-
assert.Eventually(t, func() bool {
245-
return m.notifyModel.IsOpen()
246-
}, time.Second, 10*time.Microsecond, "Notify model never opened")
247-
248-
p.Send(tea.KeyMsg{Type: tea.KeyRight})
249-
250-
assert.Eventually(t, func() bool {
251-
_, err1 := os.Stat(file1)
252-
trashFile := getTrashPath(file1)
253-
_, errTrash := os.Stat(trashFile)
254-
if runtime.GOOS == utils.OsWindows {
255-
return err1 != nil && os.IsNotExist(err1)
256-
}
257-
return err1 != nil && os.IsNotExist(err1) && errTrash == nil
258-
}, time.Second, 10*time.Millisecond, "File never moved to trash.")
259-
})
215+
testdata := []struct {
216+
name string
217+
filePath string
218+
permanentDelete bool
219+
}{
220+
{
221+
name: "Move to trash",
222+
filePath: file1,
223+
permanentDelete: false,
224+
},
225+
}
260226

261-
t.Run("move to trash", func(t *testing.T) {
262-
m := defaultTestModel(curTestDir)
263-
err := initTrash()
264-
if err == nil {
227+
for _, tt := range testdata {
228+
t.Run(tt.name, func(t *testing.T) {
229+
m := defaultTestModel(curTestDir)
265230
m.hasTrash = true
266-
} else {
267-
fmt.Println("Unable to create trash directories.")
268-
}
269-
p := NewTestTeaProgWithEventLoop(t, m)
270-
idx := findItemIndexInPanelByLocation(m.getFocusedFilePanel(), file2)
271-
require.NotEqual(t, -1, idx, "%s should be found in panel", file2)
272-
m.getFocusedFilePanel().cursor = idx
273-
274-
p.SendKey(common.Hotkeys.PermanentlyDeleteItems[0])
275-
276-
assert.Eventually(t, func() bool {
277-
return m.notifyModel.IsOpen()
278-
}, time.Second, 10*time.Microsecond, "Notify model never opened")
231+
p := NewTestTeaProgWithEventLoop(t, m)
232+
setFilePanelSelectedFile(t, m.getFocusedFilePanel(), tt.filePath)
233+
if tt.permanentDelete {
234+
p.SendKey(common.Hotkeys.PermanentlyDeleteItems[0])
235+
} else {
236+
p.SendKey(common.Hotkeys.DeleteItems[0])
237+
}
238+
assert.Eventually(t, m.notifyModel.IsOpen, DefaultTestTimeout,
239+
DefaultTestTick, "Notify model never opened")
240+
expectedTitle := common.TrashWarnTitle
241+
expectedAction := notify.DeleteAction
242+
if tt.permanentDelete {
243+
expectedTitle = common.PermanentDeleteWarnTitle
244+
expectedAction = notify.PermanentDeleteAction
245+
}
246+
assert.Equal(t, expectedTitle, m.notifyModel.GetTitle())
247+
assert.Equal(t, expectedAction, m.notifyModel.GetConfirmAction())
279248

280-
p.Send(tea.KeyMsg{Type: tea.KeyRight})
249+
p.Send(tea.KeyMsg{Type: tea.KeyEnter})
281250

282-
assert.Eventually(t, func() bool {
283-
_, err1 := os.Stat(file2)
284-
trashFile := getTrashPath(file2)
285-
_, errTrash := os.Stat(trashFile)
286-
if runtime.GOOS == utils.OsWindows {
287-
return err1 != nil && os.IsNotExist(err1)
251+
assert.Eventually(t, func() bool {
252+
_, err := os.Stat(tt.filePath)
253+
return err != nil && os.IsNotExist(err)
254+
}, DefaultTestTimeout, DefaultTestTick, "File never removed from original location")
255+
256+
// Window's trash is not flexible enough for the check.
257+
// Sorry windows
258+
if runtime.GOOS == utils.OsDarwin || runtime.GOOS == utils.OsLinux {
259+
assert.Equal(t, tt.permanentDelete, !isTrashed(filepath.Base(tt.filePath)),
260+
"Existence in trash status should be expected only of not permanently deleted")
288261
}
289-
return err1 != nil && os.IsNotExist(err1) && errTrash != nil && os.IsNotExist(err1)
290-
}, time.Second, 10*time.Millisecond, "File never moved to trash.")
291-
})
262+
})
263+
}
264+
}
265+
266+
func setFilePanelSelectedFile(t *testing.T, panel *filePanel, filePath string) {
267+
t.Helper()
268+
idx := findItemIndexInPanelByLocation(panel, filePath)
269+
require.NotEqual(t, -1, idx, "%s should be found in panel", filePath)
270+
panel.cursor = idx
292271
}

src/internal/test_utils.go

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@ import (
1313
"github.com/yorukot/superfile/src/internal/utils"
1414
)
1515

16+
const DefaultTestTick = 10 * time.Millisecond
17+
const DefaultTestTimeout = time.Second
18+
1619
var SampleDataBytes = []byte("This is sample") //nolint: gochecknoglobals // Effectively const
1720

1821
func setupDirectories(t *testing.T, dirs ...string) {
@@ -158,7 +161,7 @@ func verifyPathNotExistsEventually(t *testing.T, path, message string) {
158161
assert.Eventually(t, func() bool {
159162
_, err := os.Stat(path)
160163
return os.IsNotExist(err)
161-
}, time.Second, 10*time.Millisecond, message)
164+
}, time.Second, DefaultTestTick, message)
162165
}
163166

164167
// Helper function to verify expected destination files exist
@@ -169,7 +172,7 @@ func verifyDestinationFiles(t *testing.T, targetDir string, expectedDestFiles []
169172
assert.Eventually(t, func() bool {
170173
_, err := os.Stat(destPath)
171174
return err == nil
172-
}, time.Second, 10*time.Millisecond, "%s should exist in destination", expectedFile)
175+
}, time.Second, DefaultTestTick, "%s should exist in destination", expectedFile)
173176
}
174177
}
175178

0 commit comments

Comments
 (0)