Skip to content

Commit

Permalink
Added mock mode status code override #89
Browse files Browse the repository at this point in the history
setting a header with ‘wiretap-status-code’ and a status code, will automatically override any status code set by the OpenAPI spec when running in mock mode.

Only works for successful mocks, any errors/failed mock requests will return the extsing error codes.
  • Loading branch information
daveshanley committed May 2, 2024
1 parent 1ff3950 commit 3483053
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
5 changes: 5 additions & 0 deletions mock/mock_engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,11 @@ func (rme *ResponseMockEngine) runWorkflow(request *http.Request) ([]byte, int,
), 200, err
}

// check for wiretap-status-code in header and override the code, regardless of what was found in the spec.
if statusCode := request.Header.Get("wiretap-status-code"); statusCode != "" {
c, _ = strconv.Atoi(statusCode)
}

return mock, c, nil
}

Expand Down
45 changes: 45 additions & 0 deletions mock/mock_engine_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1232,3 +1232,48 @@ paths:
assert.Equal(t, "1", items[0])

}

// https://github.com/pb33f/wiretap/issues/89
func TestNewMockEngine_OverrideStatusCode_Issue89(t *testing.T) {

spec := `openapi: 3.1.0
paths:
/test:
get:
responses:
'200':
content:
application/json:
schema:
$ref: '#/components/schemas/Thing'
components:
schemas:
Thing:
type: object
properties:
name:
type: string
description:
type: string
`

d, _ := libopenapi.NewDocument([]byte(spec))
doc, _ := d.BuildV3Model()

me := NewMockEngine(&doc.Model, false)

request, _ := http.NewRequest(http.MethodGet, "https://api.pb33f.io/test", nil)
request.Header.Set("wiretap-status-code", "418")

b, status, err := me.GenerateResponse(request)

assert.NoError(t, err)
assert.Equal(t, 418, status)

var decoded map[string]any
_ = json.Unmarshal(b, &decoded)

assert.NotEmpty(t, decoded["name"])
assert.NotEmpty(t, decoded["description"])

}

0 comments on commit 3483053

Please sign in to comment.