package api import ( "encoding/json" "net/http" "net/http/httptest" "testing" "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tcs-iptv/tcs/internal/catalog" "github.com/tcs-iptv/tcs/internal/chain" "github.com/tcs-iptv/tcs/internal/model" ) func TestCatalogHandler_QueryByMA(t *testing.T) { gin.SetMode(gin.TestMode) c := chain.NewMemoryChain() // 发码 _, err := c.IssueMA(chain.RoleRegulator, chain.IssueRequest{ CCCode: "MA.156.8531.6101/WD/20260000001", ContentTwinID: "ctid-cat-svc-001", FileHash: "fh-cat-svc-001", MerkleRoot: "mr-cat-svc-001", Content: model.Content{Title: "目录库服务测试", MAType: "WD", Issuer: "测试局"}, }) require.NoError(t, err) cat := catalog.New(c) h := NewCatalogHandler(cat) r := gin.New() rg := r.Group("/api/v1") h.Register(rg) // 按 MA 码查询 w := httptest.NewRecorder() req := httptest.NewRequest("GET", "/api/v1/catalog/query-by-ma?ma_code=MA.156.8531.6101/WD/20260000001", nil) r.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) var resp struct { Code string `json:"code"` Data model.ContentQueryResult `json:"data"` } err = json.Unmarshal(w.Body.Bytes(), &resp) require.NoError(t, err) assert.Equal(t, "SUCCESS", resp.Code) assert.True(t, resp.Data.Found) assert.Equal(t, "目录库服务测试", resp.Data.Content.Title) } func TestCatalogHandler_QueryByHash(t *testing.T) { gin.SetMode(gin.TestMode) c := chain.NewMemoryChain() _, err := c.IssueMA(chain.RoleRegulator, chain.IssueRequest{ CCCode: "MA.156.8531.6101/WD/20260000002", ContentTwinID: "ctid-cat-svc-002", FileHash: "fh-cat-svc-002", MerkleRoot: "mr-cat-svc-002", Content: model.Content{Title: "Hash查询服务测试", MAType: "WD", Issuer: "测试局"}, }) require.NoError(t, err) cat := catalog.New(c) h := NewCatalogHandler(cat) r := gin.New() rg := r.Group("/api/v1") h.Register(rg) // 按 Hash 查询 w := httptest.NewRecorder() req := httptest.NewRequest("GET", "/api/v1/catalog/query-by-hash?file_hash=fh-cat-svc-002", nil) r.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) var resp struct { Code string `json:"code"` Data model.ContentQueryResult `json:"data"` } err = json.Unmarshal(w.Body.Bytes(), &resp) require.NoError(t, err) assert.True(t, resp.Data.Found) assert.Equal(t, "MA.156.8531.6101/WD/20260000002", resp.Data.Content.CCCode) // 缺少参数 w2 := httptest.NewRecorder() req2 := httptest.NewRequest("GET", "/api/v1/catalog/query-by-hash", nil) r.ServeHTTP(w2, req2) assert.Equal(t, http.StatusBadRequest, w2.Code) } func TestCatalogHandler_NotFound(t *testing.T) { gin.SetMode(gin.TestMode) c := chain.NewMemoryChain() cat := catalog.New(c) h := NewCatalogHandler(cat) r := gin.New() rg := r.Group("/api/v1") h.Register(rg) // 不存在的 MA 码 w := httptest.NewRecorder() req := httptest.NewRequest("GET", "/api/v1/catalog/query-by-ma?ma_code=nonexistent", nil) r.ServeHTTP(w, req) assert.Equal(t, http.StatusNotFound, w.Code) }