sync_test.go 1.59 KB
Newer Older
ale's avatar
ale committed
1 2 3 4 5 6 7 8 9 10 11 12
package liber

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"os"
	"strconv"
	"testing"
)

ale's avatar
ale committed
13
func newTestSyncHttpServer(db *Database, updir string) *httptest.Server {
14
	localsrv := &syncServer{db, NewRWFileStorage(updir, 2)}
ale's avatar
ale committed
15 16 17 18 19 20 21 22 23 24 25 26

	mux := http.NewServeMux()
	mux.HandleFunc("/api/sync/upload", localsrv.handleSyncUpload)
	mux.HandleFunc("/api/sync/diff", localsrv.handleDiffRequest)

	return httptest.NewServer(mux)
}

func TestSync_Sync(t *testing.T) {
	// Create a temporary directory to store uploads.
	updir, _ := ioutil.TempDir("", "ebook-upload-")
	defer os.RemoveAll(updir)
27
	clientStorage := NewFileStorage(updir)
ale's avatar
ale committed
28 29 30 31 32 33 34 35

	td, db := newTestDatabase(t)
	defer td.Close()

	td2, db2 := newTestDatabase(t)
	defer td2.Close()

	for i := 0; i < 10; i++ {
ale's avatar
ale committed
36
		bookid := NewID()
ale's avatar
ale committed
37
		db.PutBook(&Book{
ale's avatar
ale committed
38
			Id: bookid,
ale's avatar
ale committed
39 40 41 42 43 44
			Metadata: &Metadata{
				Title:   fmt.Sprintf("Book #%d", i+1),
				Creator: []string{"Random Author"},
				ISBN:    []string{strconv.Itoa(i + 1)},
			},
		})
ale's avatar
ale committed
45
		db.PutFile(testEpubFile(updir, bookid))
ale's avatar
ale committed
46 47 48
	}

	// Run a sync from db to db2.
ale's avatar
ale committed
49
	srv := newTestSyncHttpServer(db2, updir)
ale's avatar
ale committed
50 51 52
	defer srv.Close()

	cl := NewRemoteServer(srv.URL)
53
	if err := db.Sync(clientStorage, cl); err != nil {
ale's avatar
ale committed
54 55 56 57 58 59 60 61
		t.Fatalf("Sync(): %v", err)
	}

	// Ensure that books are present in db2.
	for i := 0; i < 10; i++ {
		metatmpl := &Metadata{
			ISBN: []string{strconv.Itoa(i + 1)},
		}
ale's avatar
ale committed
62
		if _, err := db2.Find(metatmpl.Uniques()); err != nil {
ale's avatar
ale committed
63 64 65
			t.Errorf("Book %d missing from db2: %v", i+1, err)
		}
	}
66 67 68 69 70

	// Calling Sync again should not result in errors.
	if err := db.Sync(clientStorage, cl); err != nil {
		t.Fatalf("Sync(): %v", err)
	}
ale's avatar
ale committed
71
}