move tests to dedicated package

This commit is contained in:
2025-10-27 18:08:47 +01:00
parent cae46614ba
commit d407b41c9f
7 changed files with 7 additions and 7 deletions

View File

@@ -0,0 +1,66 @@
package apitest
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"git.artlef.fr/PersonalLibraryManager/internal/testutils"
"github.com/stretchr/testify/assert"
)
type fetchedBook struct {
Title string `json:"title" binding:"required,max=300"`
Author string `json:"author" binding:"max=100"`
Rating int `json:"rating"`
Read bool `json:"read"`
}
func TestGetBook_Ok(t *testing.T) {
book := testGetBook(t, "5", http.StatusOK)
assert.Equal(t,
fetchedBook{
Title: "Rigodon",
Author: "Louis-Ferdinand Céline",
Rating: 10,
Read: true,
}, book)
}
func TestGetBook_NoUserBook(t *testing.T) {
book := testGetBook(t, "18", http.StatusOK)
assert.Equal(t,
fetchedBook{
Title: "De sang-froid",
Author: "Truman Capote",
Read: false,
}, book)
}
func TestGetBook_IdNotFound(t *testing.T) {
testGetBook(t, "46544", http.StatusNotFound)
}
func TestGetBook_IdNotInt(t *testing.T) {
testGetBook(t, "wrong", http.StatusBadRequest)
}
func testGetBook(t *testing.T, id string, status int) fetchedBook {
router := testutils.TestSetup()
token := testutils.ConnectDemoUser(router)
req, _ := http.NewRequest("GET", "/book/"+id, nil)
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
var book fetchedBook
err := json.Unmarshal(w.Body.Bytes(), &book)
if err != nil {
t.Error(err)
}
assert.Equal(t, status, w.Code)
return book
}