89 lines
2.0 KiB
Go
89 lines
2.0 KiB
Go
package runner
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
"sort"
|
|
"testing"
|
|
)
|
|
|
|
func writeTempFile(t *testing.T, dir, name, content string) string {
|
|
t.Helper()
|
|
path := filepath.Join(dir, name)
|
|
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return path
|
|
}
|
|
|
|
func TestRgListFiles(t *testing.T) {
|
|
dir := t.TempDir()
|
|
writeTempFile(t, dir, "a.txt", "foo bar\nbaz\n")
|
|
writeTempFile(t, dir, "b.txt", "no match here\n")
|
|
writeTempFile(t, dir, "c.txt", "another foo\n")
|
|
|
|
files, err := RgListFiles("foo", dir)
|
|
if err != nil {
|
|
t.Fatalf("unexpected error: %v", err)
|
|
}
|
|
if len(files) != 2 {
|
|
t.Fatalf("want 2 files, got %d: %v", len(files), files)
|
|
}
|
|
sort.Strings(files)
|
|
if filepath.Base(files[0]) != "a.txt" || filepath.Base(files[1]) != "c.txt" {
|
|
t.Errorf("unexpected files: %v", files)
|
|
}
|
|
}
|
|
|
|
func TestRgListFiles_NoMatches(t *testing.T) {
|
|
dir := t.TempDir()
|
|
writeTempFile(t, dir, "a.txt", "hello world\n")
|
|
|
|
files, err := RgListFiles("xyz_no_match", dir)
|
|
if err != nil {
|
|
t.Fatalf("unexpected error: %v", err)
|
|
}
|
|
if files != nil {
|
|
t.Errorf("want nil, got %v", files)
|
|
}
|
|
}
|
|
|
|
func TestRgListFiles_CaseInsensitive(t *testing.T) {
|
|
dir := t.TempDir()
|
|
writeTempFile(t, dir, "a.txt", "FOO bar\n")
|
|
writeTempFile(t, dir, "b.txt", "no match\n")
|
|
|
|
files, err := RgListFiles("foo", dir, "-i")
|
|
if err != nil {
|
|
t.Fatalf("unexpected error: %v", err)
|
|
}
|
|
if len(files) != 1 || filepath.Base(files[0]) != "a.txt" {
|
|
t.Errorf("want [a.txt], got %v", files)
|
|
}
|
|
}
|
|
|
|
func TestSplitLines(t *testing.T) {
|
|
tests := []struct {
|
|
input string
|
|
want []string
|
|
}{
|
|
{"", nil},
|
|
{"a\n", []string{"a"}},
|
|
{"a\nb\n", []string{"a", "b"}},
|
|
{"a\nb\nc", []string{"a", "b", "c"}},
|
|
{"\n\n", nil}, // only trailing newlines — trimmed to empty, returns nil
|
|
}
|
|
for _, tt := range tests {
|
|
got := splitLines(tt.input)
|
|
if len(got) != len(tt.want) {
|
|
t.Errorf("splitLines(%q) = %v, want %v", tt.input, got, tt.want)
|
|
continue
|
|
}
|
|
for i := range got {
|
|
if got[i] != tt.want[i] {
|
|
t.Errorf("splitLines(%q)[%d] = %q, want %q", tt.input, i, got[i], tt.want[i])
|
|
}
|
|
}
|
|
}
|
|
}
|