package httpapi import ( "database/sql" "database/sql/driver" "encoding/json" "github.com/gin-gonic/gin" "net/http/httptest" "testing" ) func TestReleaseListingProductScope(t *testing.T) { for _, filtered := range []bool{false, true} { t.Run(map[bool]string{false: "all", true: "filtered"}[filtered], func(t *testing.T) { where := "" countArgs := []any{} listArgs := []any{20, 20} url := "/api/v1/releases?page=2" if filtered { where = " WHERE r.product_id=?" countArgs = []any{int64(7)} listArgs = []any{int64(7), 20, 20} url += "&product_id=7" } d := &dashboardDB{t: t, queries: []dashboardQuery{ {sql: "SELECT COUNT(*) FROM product_releases r JOIN products p ON p.id=r.product_id" + where, args: countArgs, rows: [][]driver.Value{{int64(21)}}}, {sql: "SELECT r.id,r.version,r.sha256,r.size_bytes,r.published,p.id,p.name,p.code FROM product_releases r JOIN products p ON p.id=r.product_id" + where + " ORDER BY r.id DESC LIMIT ? OFFSET ?", args: listArgs, rows: [][]driver.Value{{int64(9), "1.2.0", "hash", int64(100), true, int64(7), "产品甲", "product-a"}}}, }} db := sql.OpenDB(d) defer db.Close() w := httptest.NewRecorder() c, _ := gin.CreateTestContext(w) c.Request = httptest.NewRequest("GET", url, nil) (&BusinessAPI{db: db}).listReleases(c) var body struct { Data []struct { ProductID uint64 `json:"product_id"` Name string `json:"product_name"` Code string `json:"product_code"` } Meta struct { Total int Page int } } if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &body) != nil || len(body.Data) != 1 || body.Data[0].ProductID != 7 || body.Data[0].Name != "产品甲" || body.Data[0].Code != "product-a" || body.Meta.Total != 21 || body.Meta.Page != 2 || len(d.queries) != 0 { t.Fatalf("unexpected response %d %s", w.Code, w.Body) } }) } } func TestReleaseListingInvalidProduct(t *testing.T) { for _, id := range []string{"0", "bad", "-1"} { w := httptest.NewRecorder() c, _ := gin.CreateTestContext(w) c.Request = httptest.NewRequest("GET", "/api/v1/releases?product_id="+id, nil) (&BusinessAPI{}).listReleases(c) c.Writer.WriteHeaderNow() if w.Code != 400 { t.Fatalf("invalid product %s: %d", id, w.Code) } } }