示例#1
0
func TestRequestHandlerServeHTTP(t *testing.T) {
	r, _ := http.NewRequest("", "", nil)
	w := httptest.NewRecorder()
	kernel := new(mockRequestKernel)
	collector1 := new(mockRequestContextCollector)
	collector2 := new(mockRequestContextCollector)
	handler := alma.NewRequestHandler(kernel)
	collector1.On("Collect", mock.Anything, r).Run(func(args mock.Arguments) {
		args.Get(0).(map[string]interface{})["foo"] = 1
	}).Return(nil)
	collector2.On("Collect", mock.Anything, r).Run(func(args mock.Arguments) {
		args.Get(0).(map[string]interface{})["bar"] = 2
	}).Return(nil)
	kernel.On("Handle", w, mock.Anything).Run(func(args mock.Arguments) {
		w := args.Get(0).(http.ResponseWriter)
		ctx := args.Get(1).(map[string]interface{})
		w.WriteHeader(201)
		w.Header().Set("X", "3")
		io.WriteString(w, fmt.Sprintf("%v %v", ctx["foo"].(int), ctx["bar"].(int)))
	}).Return(nil)

	handler.AddCollector(collector1)
	handler.AddCollector(collector2)
	handler.ServeHTTP(w, r)

	assert.Equal(t, 201, w.Code)
	assert.Equal(t, "1 2", w.Body.String())
	assert.Equal(t, "3", w.Header().Get("X"))
}
示例#2
0
func TestRequestHandlerServeHTTPWhenKernelReturnError(t *testing.T) {
	r, _ := http.NewRequest("", "", nil)
	w := httptest.NewRecorder()
	kernel := new(mockRequestKernel)
	handler := alma.NewRequestHandler(kernel)
	kernel.On("Handle", w, make(map[string]interface{})).Return(fmt.Errorf("foo"))

	handler.ServeHTTP(w, r)

	kernel.AssertExpectations(t)
	assert.Equal(t, 500, w.Code)
	assert.Equal(t, "foo\n", w.Body.String())
}
示例#3
0
func TestRequestHandlerServeHTTPWhenCollectorReturnError(t *testing.T) {
	r, _ := http.NewRequest("", "", nil)
	w := httptest.NewRecorder()
	collector := new(mockRequestContextCollector)
	kernel := new(mockRequestKernel)
	handler := alma.NewRequestHandler(kernel)
	collector.On("Collect", mock.Anything, r).Return(fmt.Errorf("foo"))
	collector.On("GetErrorCode").Return(400)

	handler.AddCollector(collector)
	handler.ServeHTTP(w, r)

	collector.AssertExpectations(t)
	kernel.AssertExpectations(t)
	assert.Equal(t, 400, w.Code)
	assert.Equal(t, "foo\n", w.Body.String())
}