docgrouper/main_test.go

124 lines
3.0 KiB
Go

package main
import (
"fmt"
"path/filepath"
"reflect"
"testing"
)
func TestReadFileTime(t *testing.T) {
tt := []struct {
fileName string
expectedTimestamp int
}{
{"1.txt", 3},
{"2.txt", 5},
{"3.txt", 11},
}
for _, tc := range tt {
t.Run(tc.fileName, func(t *testing.T) {
filePath := filepath.Join("testdata", tc.fileName)
timestamp, err := readFileTime(filePath)
if err != nil {
t.Fatal("error reading file time: ", err)
}
if timestamp != tc.expectedTimestamp {
t.Errorf("expected %d, got %d", tc.expectedTimestamp, timestamp)
}
})
}
}
func TestOrderFiles(t *testing.T) {
var (
expectedOrder = []int{3, 5, 11}
expectedMap = map[int][]int{
3: {1},
5: {2, 7},
11: {3, 4, 5},
}
)
fileMap, order, err := orderFiles("testdata")
if err != nil {
t.Fatal("error ordering files: ", err)
}
if !reflect.DeepEqual(order, expectedOrder) {
t.Errorf("expected %v, got %v", expectedOrder, order)
}
if !reflect.DeepEqual(fileMap, expectedMap) {
t.Errorf("expected %v, got %v", expectedMap, fileMap)
}
}
func TestFileContentsCache(t *testing.T) {
fcc := FileContentsCache{BaseDir: "testdata"}
cases := []struct {
fileNumber int
contents string
}{
{1, "foo foo foo"},
{2, "bar bar bar"},
{3, "baz baz baz"},
}
// Test initial reads.
for _, c := range cases {
t.Run(fmt.Sprintf("initial read %d", c.fileNumber), func(t *testing.T) {
got, err := fcc.GetFileContents(c.fileNumber)
if err != nil {
t.Fatal("error getting file contents: ", err)
}
if !reflect.DeepEqual(got, []string{c.contents}) {
t.Errorf("expected %q, got %q", c.contents, got)
}
})
}
// Ensure files are actually stored in cache.
for _, c := range cases {
t.Run(fmt.Sprintf("cache check %d", c.fileNumber), func(t *testing.T) {
if got, ok := fcc.cache.Load(c.fileNumber); !ok {
t.Fatalf("file %d not found in cache", c.fileNumber)
} else if !reflect.DeepEqual(got, []string{c.contents}) {
t.Fatalf("expected %q, got %q", c.contents, got)
}
})
}
// Test clear-except operation.
t.Run("clear except", func(t *testing.T) {
fcc.ClearFilesExcept([]int{1})
if _, ok := fcc.cache.Load(1); !ok {
t.Fatal("file 1 not found in cache, expected to be kept")
}
if _, ok := fcc.cache.Load(2); ok {
t.Fatal("file 2 found in cache, expected to be cleared")
}
if _, ok := fcc.cache.Load(3); ok {
t.Fatal("file 3 found in cache, expected to be cleared")
}
})
}
func TestEndToEnd(t *testing.T) {
docs, err := run([]string{"argv0", "-path", "testdata/e2e"})
want := []int{1, 6, 9, 12, 14, 18}
if err != nil {
t.Fatal("error running program: ", err)
}
if len(docs) != 1 {
t.Fatalf("expected %d documents, got %d", 1, len(docs))
}
doc := docs[0]
if doc.ID != 1 {
t.Errorf("expected ID %d, got %d", 0, doc.ID)
}
if doc.LatestTimestamp != 5 {
t.Errorf("expected latest timestamp %d, got %d", 3, doc.LatestTimestamp)
}
if !reflect.DeepEqual(doc.AssociatedFiles, want) {
t.Errorf("expected associated files %v, got %v", want, doc.AssociatedFiles)
}
}