package apitest import ( "encoding/json" "fmt" "net/http" "net/http/httptest" "strconv" "strings" "testing" "git.artlef.fr/PersonalLibraryManager/internal/testutils" "github.com/stretchr/testify/assert" ) type hasId struct { ID uint `json:"id"` } func TestPostImportBookHandler_Ok(t *testing.T) { id := testPostImportBookHandler(t, "OL21177W", http.StatusOK) book := testGetBook(t, strconv.FormatUint(uint64(id), 10), 200) assert.Equal(t, "Wuthering Heights", book.Title) assert.Equal(t, "Emily Brontèˆ", book.Author) assert.Equal(t, "OL21177W", book.OpenLibraryId) } func TestPostImportBookHandler_OkAuthorKey(t *testing.T) { id := testPostImportBookHandler(t, "OL7525169M", http.StatusOK) book := testGetBook(t, strconv.FormatUint(uint64(id), 10), 200) assert.Equal(t, "Dr. Bloodmoney, or How We Got Along After the Bomb", book.Title) assert.Equal(t, "Philip K. Dick", book.Author) assert.Equal(t, "OL7525169M", book.OpenLibraryId) } func TestPostImportBookHandler_NoOLID(t *testing.T) { testPostImportBookHandler(t, "", http.StatusBadRequest) } func testPostImportBookHandler(t *testing.T, openlibraryid string, expectedCode int) uint { router := testutils.TestSetup() w := httptest.NewRecorder() token := testutils.ConnectDemoUser(router) queryJson := `{ "openlibraryid":"%s" }` queryJson = fmt.Sprintf(queryJson, openlibraryid) req, _ := http.NewRequest("POST", "/importbook", strings.NewReader(string(queryJson))) req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token)) router.ServeHTTP(w, req) assert.Equal(t, expectedCode, w.Code) if w.Code == 200 { var parsedId hasId err := json.Unmarshal(w.Body.Bytes(), &parsedId) if err != nil { t.Error(err) } return parsedId.ID } else { return 0 } }