Exemplo n.º 1
0
func TestWrapPanic(t *testing.T) {
	var buf bytes.Buffer
	reqlog.SetLogger(stdlog.New(&buf, "", 0))

	mux := goji.NewMux()

	mux.HandleFunc(pat.New("/safe"), func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusNoContent)
	})
	mux.HandleFunc(pat.New("/panic"), func(w http.ResponseWriter, r *http.Request) {
		panic("hi there!")
	})

	mux.UseC(respond.WrapPanicC)

	req, err := http.NewRequest("FOO", "/safe", nil)
	if err != nil {
		t.Fatal(err)
	}

	rr := httptest.NewRecorder()
	mux.ServeHTTP(rr, req)

	if err := apptest.AssertStatus(rr, http.StatusNoContent); err != nil {
		t.Error(err)
	}

	buf.Reset()
	rr = httptest.NewRecorder()
	req.URL.Path = "/panic"
	mux.ServeHTTP(rr, req)

	if err := apptest.AssertStatus(rr, http.StatusInternalServerError); err != nil {
		t.Error(err)
	}

	t.Log(rr.Body.String())
	uerr, err := usererrors.UnmarshalJSON(rr.Body.Bytes())
	if err != nil {
		t.Fatal(err)
	}

	_, ok := uerr.(usererrors.InternalFailure)
	if !ok {
		t.Errorf("expected an InternalFailure but got %#v", uerr)
	}

	t.Log(buf.String())
}
Exemplo n.º 2
0
func TestWrapC(t *testing.T) {
	var buf bytes.Buffer
	logger := log.New(&buf, "", 0)
	reqlog.SetLogger(logger)

	var setOK bool

	bare := goji.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		setOK = reqlog.SetContext(ctx, "hey", "oh")
		w.Write([]byte("foo"))
	})
	wrapped := reqlog.WrapC(bare)

	req, err := http.NewRequest("FOO", "/bar", nil)
	if err != nil {
		t.Fatal(err)
	}

	wrapped.ServeHTTPC(context.Background(), httptest.NewRecorder(), req)
	logged := buf.String()
	t.Log(logged)
	if !strings.Contains(logged, `http_status=200`) {
		t.Errorf("Expected http_status in line %s", logged)
	}
	if !strings.Contains(logged, `hey="oh"`) {
		t.Errorf("Expected to say hey oh in line %s", logged)
	}
	if !setOK {
		t.Error("SetContext should have set successfully.")
	}

	setOK = true
	buf.Reset()

	bare.ServeHTTPC(context.Background(), httptest.NewRecorder(), req)
	if buf.Len() != 0 {
		t.Errorf("Nothing should have been logged but got %s", buf.String())
	}
	if setOK {
		t.Errorf("SetContext should not have set successfully.")
	}

}