kitty/tools/completion/files_test.go

80 lines
2.3 KiB
Go

// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package completion
import (
"fmt"
"io/fs"
"os"
"path/filepath"
"reflect"
"sort"
"testing"
)
func TestCompleteFiles(t *testing.T) {
tdir := t.TempDir()
cwd, _ := os.Getwd()
if cwd != "" {
defer os.Chdir(cwd)
}
os.Chdir(tdir)
os.Create(filepath.Join(tdir, "one.txt"))
os.Create(filepath.Join(tdir, "two.txt"))
os.Mkdir(filepath.Join(tdir, "odir"), 0700)
os.Create(filepath.Join(tdir, "odir", "three.txt"))
os.Create(filepath.Join(tdir, "odir", "four.txt"))
test_candidates := func(prefix string, expected ...string) {
if expected == nil {
expected = make([]string, 0)
}
sort.Strings(expected)
actual := make([]string, 0, len(expected))
complete_files(prefix, func(completion_candidate string, abspath string, d fs.DirEntry) error {
actual = append(actual, completion_candidate)
if _, err := os.Stat(abspath); err != nil {
t.Fatalf("Abspath does not exist: %#v", abspath)
return fmt.Errorf("abspath does not exist")
}
return nil
})
sort.Strings(actual)
if !reflect.DeepEqual(expected, actual) {
t.Fatalf("Did not get expected completion candidates for prefix: %#v\nExpected: %#v\nActual: %#v", prefix, expected, actual)
}
}
test_abs_candidates := func(prefix string, expected ...string) {
e := make([]string, len(expected))
for i, x := range expected {
e[i] = filepath.Join(tdir, x)
}
test_candidates(prefix, e...)
}
test_cwd_prefix := func(prefix string, expected ...string) {
e := make([]string, len(expected))
for i, x := range expected {
e[i] = "./" + x
}
test_candidates("./"+prefix, e...)
}
test_cwd_prefix("", "one.txt", "two.txt", "odir", "odir/three.txt", "odir/four.txt")
test_cwd_prefix("t", "two.txt")
test_cwd_prefix("x")
test_abs_candidates(tdir, "one.txt", "two.txt", "odir", "odir/three.txt", "odir/four.txt")
test_abs_candidates(filepath.Join(tdir, "o"), "one.txt", "odir", "odir/three.txt", "odir/four.txt")
test_candidates("", "one.txt", "two.txt", "odir", "odir/three.txt", "odir/four.txt")
test_candidates("t", "two.txt")
test_candidates("o", "one.txt", "odir", "odir/three.txt", "odir/four.txt")
test_candidates("odir", "odir", "odir/three.txt", "odir/four.txt")
test_candidates("odir/", "odir/three.txt", "odir/four.txt")
test_candidates("odir/f", "odir/four.txt")
test_candidates("x")
}