package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/require" ) // Helper functions for database verification and test utilities // These functions reduce code duplication and ensure consistent database state verification // createTestLibraryWithFolder creates a test library with optional folder func createTestLibraryWithFolder(t *testing.T, ts *httptest.Server, token, name string, withFolder bool) string { libReq := map[string]interface{}{ "name": name, "type": "ebooks", } libBody, _ := json.Marshal(libReq) libHTTP, _ := http.NewRequest("POST", ts.URL+"/api/libraries", bytes.NewBuffer(libBody)) libHTTP.Header.Set("Content-Type", "application/json") libHTTP.Header.Set("Authorization", "Bearer "+token) client := &http.Client{} resp, err := client.Do(libHTTP) require.NoError(t, err) defer func(Body io.ReadCloser) { _ = Body.Close() }(resp.Body) require.Equal(t, http.StatusCreated, resp.StatusCode, "Library creation should succeed") var libResponse map[string]interface{} err = json.NewDecoder(resp.Body).Decode(&libResponse) require.NoError(t, err) libraryID := libResponse["id"].(string) // Every library a test creates must not outlive that test — delete // it on cleanup so runs leave no residue in the dev database. t.Cleanup(func() { delHTTP, _ := http.NewRequest("DELETE", fmt.Sprintf("%s/api/libraries/%s", ts.URL, libraryID), nil) delHTTP.Header.Set("Authorization", "Bearer "+token) delResp, err := client.Do(delHTTP) if err == nil { _, _ = io.Copy(io.Discard, delResp.Body) _ = delResp.Body.Close() } }) if withFolder { folderReq := map[string]interface{}{ "folder_path": "/app/uploads", } folderBody, _ := json.Marshal(folderReq) folderHTTP, _ := http.NewRequest("POST", fmt.Sprintf("%s/api/libraries/%s/folders", ts.URL, libraryID), bytes.NewBuffer(folderBody)) folderHTTP.Header.Set("Content-Type", "application/json") folderHTTP.Header.Set("Authorization", "Bearer "+token) folderResp, err := client.Do(folderHTTP) require.NoError(t, err) defer func(Body io.ReadCloser) { _ = Body.Close() }(folderResp.Body) require.Equal(t, http.StatusCreated, folderResp.StatusCode, "Folder creation should succeed") } return libraryID }