diff --git a/book_test.go b/book_test.go index 6d99c0f..cc6f31e 100644 --- a/book_test.go +++ b/book_test.go @@ -1,6 +1,9 @@ package main import ( + "encoding/json" + "fmt" + "log" "net/http" "net/http/httptest" "strings" @@ -17,10 +20,36 @@ func testSetup() *gin.Engine { return setup(&c) } +type loginResponse struct { + Message string `json:"message"` + Token string `json:"token"` +} + +func connectDemoUser(router *gin.Engine) string { + loginJson := + `{ + "username": "demo", + "password":"demopw" + }` + w := httptest.NewRecorder() + req, _ := http.NewRequest("POST", "/auth/login", strings.NewReader(loginJson)) + router.ServeHTTP(w, req) + var parsedResponse loginResponse + body := w.Body.String() + err := json.Unmarshal([]byte(body), &parsedResponse) + if err != nil { + log.Fatal(err) + } + return parsedResponse.Token +} + func TestGetBooksHandler(t *testing.T) { router := testSetup() w := httptest.NewRecorder() + + token := connectDemoUser(router) req, _ := http.NewRequest("GET", "/books", nil) + req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token)) router.ServeHTTP(w, req) assert.Equal(t, 200, w.Code) @@ -87,8 +116,10 @@ func testPostBookHandler(t *testing.T, bookJson string, expectedCode int) { router := testSetup() w := httptest.NewRecorder() + token := connectDemoUser(router) req, _ := http.NewRequest("POST", "/book", strings.NewReader(string(bookJson))) + req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token)) router.ServeHTTP(w, req) assert.Equal(t, expectedCode, w.Code) diff --git a/config_test/test.toml b/config_test/test.toml index e173fa3..b1258b2 100644 --- a/config_test/test.toml +++ b/config_test/test.toml @@ -3,7 +3,7 @@ database_file_path = "file::memory:?cache=shared" # The path to the sql file to load for demo data. -demo_data_path = "" +demo_data_path = "./demodata.sql" # The port to listen on for the server. port = "8080" diff --git a/demodata.sql b/demodata.sql index 4884646..44de078 100644 --- a/demodata.sql +++ b/demodata.sql @@ -1,3 +1,4 @@ +INSERT INTO users(created_at, name, password) VALUES ('NOW', 'demo','$2a$10$7mfCBxBwIzXDU6r9az26o.zPX/r6IlNZVfU9zxSoLVtc0kRPimzba'); INSERT INTO books(created_at, title, author, rating) VALUES ('NOW', 'O dingos, o chateaux!','Jean-Patrick Manchette', 6); INSERT INTO books(created_at, title, author, rating) VALUES ('NOW', 'Le petit bleu de la côte Ouest','Jean-Patrick Manchette', 7); INSERT INTO books(created_at, title, author, rating) VALUES ('NOW', 'D''un château l''autre','Louis-Ferdinand Céline', 10);