package liber import ( "io/ioutil" "os" "path/filepath" "strings" "testing" "git.autistici.org/ale/liber/util" ) func createTestFs(fs map[string]string) string { base, _ := ioutil.TempDir("", "test-fs-") for path, contents := range fs { path = filepath.Join(base, path) os.MkdirAll(filepath.Dir(path), 0700) ioutil.WriteFile(path, []byte(contents), 0700) } return base } func checkDbPathIntegrity(t *testing.T, db *Database) { // Files should have relative paths. for i := db.Scan(FileBucket); i.Valid(); i.Next() { var f File if err := i.Value(&f); err != nil { t.Fatal(err) } if strings.HasPrefix(f.Path, "/") { t.Errorf("file has absolute path: %v", f.Path) } } // Book cover images should have relative paths. for i := db.Scan(BookBucket); i.Valid(); i.Next() { var b Book if err := i.Value(&b); err != nil { t.Fatal(err) } if b.CoverPath != "" && strings.HasPrefix(b.CoverPath, "/") { t.Errorf("file has absolute path: %v", b.CoverPath) } } } func TestDatabase_Update(t *testing.T) { util.WalkerDefaultMinSize = 0 td, db := newTestDatabase(t) defer td.Close() // Make the test book a pdf so we don't attempt to parse it. tmpdir := createTestFs(map[string]string{ "book/Test Ebook.pdf": "foo", "book/metadata.opf": testOpf, "book/cover.jpg": "jpeg", }) defer os.RemoveAll(tmpdir) chooserCalled := false chooser := func(path string, choices []*Metadata) *Metadata { chooserCalled = true return nil } testDb := func(tag string) { // The test ebook added in newTestDatabase should not be there // any more. if _, err := db.GetBook(td.refbookid); err == nil { t.Errorf("%s: test book still in database", tag) } // Test OPF ebook should have been found by Update. if result, err := db.Search("isbn:9781939293015", 0, 1); err != nil || result.NumResults != 1 { t.Errorf("%s: new book not found in database", tag) } } // The second update should do nothing. db.Update(tmpdir, chooser) testDb("first update") db.Update(tmpdir, chooser) testDb("second update") if chooserCalled { t.Errorf("chooser function was called") } // Check that the test file is there. if _, err := db.GetFile("book/Test Ebook.pdf"); err != nil { t.Errorf("test file is not in the database") } checkDbPathIntegrity(t, db) } func TestDatabase_UpdateEpub(t *testing.T) { util.WalkerDefaultMinSize = 0 td, db := newTestDatabase(t) defer td.Close() // Read the test epub from testdata/. db.Update("testdata", nil) checkDbPathIntegrity(t, db) }