Skip to content

Commit

Permalink
tests: add a fuzz test for the publish handler
Browse files Browse the repository at this point in the history
  • Loading branch information
dunglas committed Nov 23, 2022
1 parent d9844e5 commit 4705102
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 3 deletions.
8 changes: 5 additions & 3 deletions handler.go
Expand Up @@ -176,9 +176,11 @@ func (h *Hub) listenShutdown() <-chan struct{} {
c.Write(zap.Error(err))
}
}
if err := h.metricsServer.Shutdown(context.Background()); err != nil {
if c := h.logger.Check(zap.ErrorLevel, "Unexpected error during metrics server shutdown"); c != nil {
c.Write(zap.Error(err))
if h.metricsServer != nil {
if err := h.metricsServer.Shutdown(context.Background()); err != nil {
if c := h.logger.Check(zap.ErrorLevel, "Unexpected error during metrics server shutdown"); c != nil {
c.Write(zap.Error(err))
}
}
}
if c := h.logger.Check(zap.InfoLevel, "My Baby Shot Me Down"); c != nil {
Expand Down
49 changes: 49 additions & 0 deletions publish_test.go
Expand Up @@ -308,3 +308,52 @@ func TestPublishWithErrorInTransport(t *testing.T) {
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, "id", string(body))
}

func FuzzPublish(f *testing.F) {
hub := createDummy()
authorizationHeader := "Bearer " + createDummyAuthorizedJWT(hub, rolePublisher, []string{"*"})

testCases := [][]interface{}{
{"https://localhost/foo/bar", "baz", "", "", "", "", ""},
{"https://localhost/foo/baz", "bat", "id", "data", "on", "22", "mytype"},
}

for _, tc := range testCases {
f.Add(tc...)
}

f.Fuzz(func(t *testing.T, topic1, topic2, id, data, private, retry, typ string) {
form := url.Values{}
form.Add("topic", topic1)
form.Add("topic", topic2)
form.Add("id", id)
form.Add("data", data)
form.Add("private", private)
form.Add("retry", retry)
form.Add("type", typ)

req := httptest.NewRequest(http.MethodPost, defaultHubURL, strings.NewReader(form.Encode()))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Authorization", authorizationHeader)

w := httptest.NewRecorder()
hub.PublishHandler(w, req)

resp := w.Result()
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)

if resp.StatusCode == http.StatusBadRequest {
return
}

assert.Equal(t, http.StatusOK, resp.StatusCode)
if id == "" {
assert.NotEqual(t, "", string(body))

return
}

assert.Equal(t, id, string(body))
})
}

0 comments on commit 4705102

Please sign in to comment.