Files

73 lines
2.2 KiB
Go
Raw Permalink Normal View History

package httpapi
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestDecodeJSONRejectsTrailingContent(t *testing.T) {
r := httptest.NewRequest(http.MethodPost, "/x", strings.NewReader(`{"name":"ok"}{"extra":true}`))
var body struct {
Name string `json:"name"`
}
err := DecodeJSON(r, &body)
if err == nil {
t.Fatal("expected trailing content error")
}
if err != errJSONTrailingContent {
t.Fatalf("unexpected error: %v", err)
}
}
func TestDecodeJSONOptionalAllowsEmptyBody(t *testing.T) {
r := httptest.NewRequest(http.MethodPost, "/x", http.NoBody)
var body struct {
Name string `json:"name"`
}
if err := DecodeJSONOptional(r, &body); err != nil {
t.Fatalf("expected empty body to be allowed, got %v", err)
}
}
func TestDecodeJSONOptionalRejectsMalformedJSON(t *testing.T) {
r := httptest.NewRequest(http.MethodPost, "/x", strings.NewReader(`{"name":`))
var body struct {
Name string `json:"name"`
}
if err := DecodeJSONOptional(r, &body); err == nil {
t.Fatal("expected malformed json error")
}
}
// SPA start-job payload includes processing_types alongside processing_type.
// DecodeJSON DisallowUnknownFields must accept both or POST /api/processing/jobs returns 400.
func TestDecodeJSONAcceptsStartJobSPAPayload(t *testing.T) {
payload := `{"raw_product_ids":["11111111-1111-1111-1111-111111111111"],"processing_type":"full","processing_types":["category","title"]}`
r := httptest.NewRequest(http.MethodPost, "/api/processing/jobs", strings.NewReader(payload))
var body startProcessingJobRequest
if err := DecodeJSON(r, &body); err != nil {
t.Fatalf("expected SPA start-job payload to decode, got %v", err)
}
if body.ProcessingType != "full" {
t.Fatalf("processing_type = %q", body.ProcessingType)
}
if len(body.RawProductIDs) != 1 || len(body.ProcessingTypes) != 2 {
t.Fatalf("unexpected body: %+v", body)
}
}
func TestDecodeJSONRejectsUnknownStartJobField(t *testing.T) {
r := httptest.NewRequest(http.MethodPost, "/x", strings.NewReader(`{"raw_product_ids":[],"processing_type":"full","unknown":true}`))
var body startProcessingJobRequest
if err := DecodeJSON(r, &body); err == nil {
t.Fatal("expected unknown field to be rejected")
}
}