package apitest import ( "fmt" "net/http" "net/http/httptest" "strings" "testing" "git.artlef.fr/PersonalLibraryManager/internal/testutils" "github.com/stretchr/testify/assert" ) func TestPutBookUpdate_NewReadOk(t *testing.T) { payload := `{ "read": true }` testPutUserBooksHandler(t, payload, "21", http.StatusOK) } func TestPutUserBooksHandler_UpdateRating(t *testing.T) { payload := `{ "rating": 5 }` bookId := "17" testPutUserBooksHandler(t, payload, bookId, http.StatusOK) book := testGetBook(t, bookId, http.StatusOK) assert.Equal(t, 5, book.Rating) assert.Equal(t, true, book.Read) } func TestPutUserBooksHandler_RateNewBookMakeItRead(t *testing.T) { payload := `{ "rating": 7 }` bookId := "18" testPutUserBooksHandler(t, payload, bookId, http.StatusOK) book := testGetBook(t, bookId, http.StatusOK) assert.Equal(t, 7, book.Rating) assert.Equal(t, true, book.Read) } func TestPutUserBooksHandler_RatingTypeWrong(t *testing.T) { payload := `{ "rating": "bad" }` bookId := "18" testPutUserBooksHandler(t, payload, bookId, http.StatusInternalServerError) } func TestPutUserBooksHandler_RatingMin(t *testing.T) { payload := `{ "rating": -3 }` bookId := "18" testPutUserBooksHandler(t, payload, bookId, http.StatusBadRequest) } func TestPutUserBooksHandler_RatingMax(t *testing.T) { payload := `{ "rating": 15 }` bookId := "18" testPutUserBooksHandler(t, payload, bookId, http.StatusBadRequest) } func TestPutUserBooksHandler_BadBookId(t *testing.T) { payload := `{ "rating": 15 }` bookId := "18574" testPutUserBooksHandler(t, payload, bookId, http.StatusNotFound) } func testPutUserBooksHandler(t *testing.T, payload string, bookId string, expectedCode int) { router := testutils.TestSetup() token := testutils.ConnectDemoUser(router) req, _ := http.NewRequest("PUT", "/book/"+bookId, strings.NewReader(payload)) req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token)) w := httptest.NewRecorder() router.ServeHTTP(w, req) assert.Equal(t, expectedCode, w.Code) }