github.com/moby/docker@v26.1.3+incompatible/integration/container/container_test.go (about) 1 package container // import "github.com/docker/docker/integration/container" 2 3 import ( 4 "net/http" 5 "testing" 6 7 "github.com/docker/docker/testutil" 8 "github.com/docker/docker/testutil/request" 9 "gotest.tools/v3/assert" 10 is "gotest.tools/v3/assert/cmp" 11 ) 12 13 // TestContainerInvalidJSON tests that POST endpoints that expect a body return 14 // the correct error when sending invalid JSON requests. 15 func TestContainerInvalidJSON(t *testing.T) { 16 ctx := setupTest(t) 17 18 // POST endpoints that accept / expect a JSON body; 19 endpoints := []string{ 20 "/commit", 21 "/containers/create", 22 "/containers/foobar/exec", 23 "/containers/foobar/update", 24 "/exec/foobar/start", 25 } 26 27 for _, ep := range endpoints { 28 ep := ep 29 t.Run(ep[1:], func(t *testing.T) { 30 t.Parallel() 31 32 t.Run("invalid content type", func(t *testing.T) { 33 ctx := testutil.StartSpan(ctx, t) 34 res, body, err := request.Post(ctx, ep, request.RawString("{}"), request.ContentType("text/plain")) 35 assert.NilError(t, err) 36 assert.Check(t, is.Equal(res.StatusCode, http.StatusBadRequest)) 37 38 buf, err := request.ReadBody(body) 39 assert.NilError(t, err) 40 assert.Check(t, is.Contains(string(buf), "unsupported Content-Type header (text/plain): must be 'application/json'")) 41 }) 42 43 t.Run("invalid JSON", func(t *testing.T) { 44 ctx := testutil.StartSpan(ctx, t) 45 res, body, err := request.Post(ctx, ep, request.RawString("{invalid json"), request.JSON) 46 assert.NilError(t, err) 47 assert.Check(t, is.Equal(res.StatusCode, http.StatusBadRequest)) 48 49 buf, err := request.ReadBody(body) 50 assert.NilError(t, err) 51 assert.Check(t, is.Contains(string(buf), "invalid JSON: invalid character 'i' looking for beginning of object key string")) 52 }) 53 54 t.Run("extra content after JSON", func(t *testing.T) { 55 ctx := testutil.StartSpan(ctx, t) 56 res, body, err := request.Post(ctx, ep, request.RawString(`{} trailing content`), request.JSON) 57 assert.NilError(t, err) 58 assert.Check(t, is.Equal(res.StatusCode, http.StatusBadRequest)) 59 60 buf, err := request.ReadBody(body) 61 assert.NilError(t, err) 62 assert.Check(t, is.Contains(string(buf), "unexpected content after JSON")) 63 }) 64 65 t.Run("empty body", func(t *testing.T) { 66 ctx := testutil.StartSpan(ctx, t) 67 // empty body should not produce an 500 internal server error, or 68 // any 5XX error (this is assuming the request does not produce 69 // an internal server error for another reason, but it shouldn't) 70 res, _, err := request.Post(ctx, ep, request.RawString(``), request.JSON) 71 assert.NilError(t, err) 72 assert.Check(t, res.StatusCode < http.StatusInternalServerError) 73 }) 74 }) 75 } 76 }