Skip to content
Snippets Groups Projects
web_test.go 2.08 KiB
Newer Older
ale's avatar
ale committed
package liber

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

type testHttpServer struct {
	tmpdir string
	td     *testDatabase
	db     *Database
}

func (ts *testHttpServer) Close() {
	ts.td.Close()
	os.RemoveAll(ts.tmpdir)
}

func newTestHttpServer(t *testing.T) (*testHttpServer, *httptest.Server) {
	var ts testHttpServer

	*htdocsDir = "./htdocs"

	ts.tmpdir, _ = ioutil.TempDir("", "tmp-storage-")
	ts.td, ts.db = newTestDatabase(t)

	tempStorage := NewRWFileStorage(ts.tmpdir, 2)
ale's avatar
ale committed
	server := NewHttpServer(ts.db, tempStorage, tempStorage, ":1234")
	return &ts, httptest.NewServer(server.Handler)
}

func readTestResponseData(resp *http.Response, t *testing.T) string {
	data, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	if err != nil {
		t.Fatalf("Read response: %v", err)
	}
	return string(data)
}

func TestWeb_Home(t *testing.T) {
	ts, srv := newTestHttpServer(t)
	defer srv.Close()
	defer ts.Close()

	resp, err := http.Get(srv.URL)
	if err != nil {
		t.Fatal(err)
	}
	if resp.StatusCode != 200 {
		t.Fatalf("Bad HTTP response: %s\n%s", resp.Status, readTestResponseData(resp, t))
	}
}

func TestWeb_Search(t *testing.T) {
	ts, srv := newTestHttpServer(t)
	defer srv.Close()
	defer ts.Close()

	resp, err := http.Get(srv.URL + "/search?q=jules")
	if err != nil {
		t.Fatal(err)
	}
	if resp.StatusCode != 200 {
		t.Fatalf("Bad HTTP response: %s\n%s", resp.Status, readTestResponseData(resp, t))
	}
	data := readTestResponseData(resp, t)
ale's avatar
ale committed
	if !strings.Contains(data, "Twenty Thousand Leagues") {
ale's avatar
ale committed
		t.Fatalf("Response does not contain book title:\n%s", data)
	}
}

func TestWeb_ShowBook(t *testing.T) {
	ts, srv := newTestHttpServer(t)
	defer srv.Close()
	defer ts.Close()

	resp, err := http.Get(fmt.Sprintf("%s/book/%d", srv.URL, ts.td.refbookid))
	if err != nil {
		t.Fatal(err)
	}
	if resp.StatusCode != 200 {
		t.Fatalf("Bad HTTP response: %s\n%s", resp.Status, readTestResponseData(resp, t))
	}
	data := readTestResponseData(resp, t)
ale's avatar
ale committed
	if !strings.Contains(data, "Twenty Thousand Leagues") {
ale's avatar
ale committed
		t.Fatalf("Response does not contain book title:\n%s", data)
	}
}