git/intake/main
internal/sheet/store_test.go
88 lines2 KB last change raw · history
package sheet

import (
	"os"
	"path/filepath"
	"strings"
	"testing"
)

// The saved sheet is what makes a review resumable, so it has to survive being
// written and read back exactly.
func TestStoreRoundTrips(t *testing.T) {
	dir := t.TempDir()
	s := Store{Dir: filepath.Join(dir, "review")}
	album := filepath.Join(dir, "staging", "Boards of Canada - Geogaddi")
	before := sample()

	if _, ok, err := s.Load(album); err != nil || ok {
		t.Fatalf("an album with no saved sheet should report none: %v %v", ok, err)
	}
	path, err := s.Save(album, Render(before))
	if err != nil {
		t.Fatal(err)
	}
	if !strings.HasPrefix(filepath.Base(path), "boards-of-canada-geogaddi-") {
		t.Errorf("the stored name %q is not readable", filepath.Base(path))
	}
	text, ok, err := s.Load(album)
	if err != nil || !ok {
		t.Fatalf("Load: %v %v", ok, err)
	}
	got, err := Parse(text, before)
	if err != nil {
		t.Fatal(err)
	}
	if got.ChangedFrom(before).Any() || len(got.Tracks) != len(before.Tracks) {
		t.Errorf("the round trip changed the sheet: %+v", got)
	}

	s.Delete(album)
	if _, ok, _ := s.Load(album); ok {
		t.Error("Delete left the sheet behind")
	}
}

// Two albums with the same folder name in different places must not share a
// saved sheet.
func TestStoreKeepsSameNamedAlbumsApart(t *testing.T) {
	dir := t.TempDir()
	s := Store{Dir: dir}
	a := filepath.Join(dir, "one", "Boards of Canada - Geogaddi")
	b := filepath.Join(dir, "two", "Boards of Canada - Geogaddi")
	if s.Path(a) == s.Path(b) {
		t.Fatalf("both albums map to %s", s.Path(a))
	}
	if _, err := s.Save(a, "album:  One\n"); err != nil {
		t.Fatal(err)
	}
	if _, err := s.Save(b, "album:  Two\n"); err != nil {
		t.Fatal(err)
	}
	ta, _, _ := s.Load(a)
	tb, _, _ := s.Load(b)
	if !strings.Contains(ta, "One") || !strings.Contains(tb, "Two") {
		t.Errorf("the two sheets got mixed up: %q and %q", ta, tb)
	}
}

// A store with nowhere to write is not an error: a configuration without a state
// directory simply has no resumable reviews.
func TestStoreWithNoDirectory(t *testing.T) {
	s := Store{}
	if _, err := s.Save("/x", "y"); err != nil {
		t.Errorf("Save: %v", err)
	}
	if _, ok, err := s.Load("/x"); err != nil || ok {
		t.Errorf("Load: %v %v", ok, err)
	}
	s.Delete("/x")
	if p := s.Path("/x"); !strings.HasPrefix(p, "x-") || !strings.HasSuffix(p, ".txt") {
		t.Errorf("Path = %q", p)
	}
	// Nothing was created anywhere.
	if _, err := os.Stat(filepath.Join(os.TempDir(), "review")); err == nil {
		t.Error("a store with no directory wrote something")
	}
}