fix tests

This commit is contained in:
2025-10-04 00:05:49 +02:00
parent 6e189d2ff0
commit 884d674765
3 changed files with 33 additions and 1 deletions

View File

@@ -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)

View File

@@ -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"

View File

@@ -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);