diff --git a/filestore_fs_test.go b/filestore_fs_test.go index 8e1fc81..c473e44 100644 --- a/filestore_fs_test.go +++ b/filestore_fs_test.go @@ -14,4 +14,13 @@ func TestFSFileStore(t *testing.T) { } RunFilestoreTest(s, t) + persistentDir := t.TempDir() + newFunc := func() gpaste.FileStore { + s, err := gpaste.NewFSFileStore(persistentDir) + if err != nil { + t.Fatalf("Error creating store: %s", err) + } + return s + } + RunPersistentFilestoreTest(newFunc, t) } diff --git a/filestore_test.go b/filestore_test.go index 7395a43..aef18c6 100644 --- a/filestore_test.go +++ b/filestore_test.go @@ -3,9 +3,12 @@ package gpaste_test import ( "bytes" "io" + "strings" "testing" + "time" "git.t-juice.club/torjus/gpaste" + "github.com/google/go-cmp/cmp" "github.com/google/uuid" ) @@ -74,3 +77,81 @@ func RunFilestoreTest(s gpaste.FileStore, t *testing.T) { } }) } + +func RunPersistentFilestoreTest(newStoreFunc func() gpaste.FileStore, t *testing.T) { + s := newStoreFunc() + + files := []struct { + File *gpaste.File + ExpectedData string + }{ + { + File: &gpaste.File{ + ID: uuid.NewString(), + OriginalFilename: "testfile.txt", + MaxViews: 5, + ExpiresOn: time.Now().Add(10 * time.Minute), + Body: io.NopCloser(strings.NewReader("cocks!")), + }, + ExpectedData: "cocks!", + }, + { + File: &gpaste.File{ + ID: uuid.NewString(), + OriginalFilename: "testfile2.txt", + MaxViews: 5, + ExpiresOn: time.Now().Add(10 * time.Minute), + Body: io.NopCloser(strings.NewReader("derps!")), + }, + ExpectedData: "derps!", + }, + } + + for _, f := range files { + err := s.Store(f.File) + if err != nil { + t.Fatalf("Error storing file: %s", err) + } + } + for _, f := range files { + retrieved, err := s.Get(f.File.ID) + if err != nil { + t.Fatalf("Unable to retrieve file: %s", err) + } + + ignoreBody := cmp.FilterPath(func(p cmp.Path) bool { return p.String() == "Body" }, cmp.Ignore()) + if !cmp.Equal(retrieved, f.File, ignoreBody) { + t.Errorf("Mismatch: %s", cmp.Diff(retrieved, f.File)) + } + buf := new(strings.Builder) + if _, err := io.Copy(buf, retrieved.Body); err != nil { + t.Fatalf("Error reading from body: %s", err) + } + retrieved.Body.Close() + if buf.String() != f.ExpectedData { + t.Fatalf("Data does not match. %s", cmp.Diff(buf.String(), f.ExpectedData)) + } + } + + // Reopen store, and fetch again + s = newStoreFunc() + for _, f := range files { + retrieved, err := s.Get(f.File.ID) + if err != nil { + t.Fatalf("Unable to retrieve file: %s", err) + } + + ignoreBody := cmp.FilterPath(func(p cmp.Path) bool { return p.String() == "Body" }, cmp.Ignore()) + if !cmp.Equal(retrieved, f.File, ignoreBody) { + t.Errorf("Mismatch: %s", cmp.Diff(retrieved, f.File)) + } + buf := new(strings.Builder) + if _, err := io.Copy(buf, retrieved.Body); err != nil { + t.Fatalf("Error reading from body: %s", err) + } + retrieved.Body.Close() + if buf.String() != f.ExpectedData { + t.Fatalf("Data does not match. %s", cmp.Diff(buf.String(), f.ExpectedData)) + } + } +}