Esempio n. 1
0
func (s *handlerSuite) TestServeDebugStatus(c *gc.C) {
	httpHandler := newHTTPHandler(&debugstatus.Handler{
		Check: func() map[string]debugstatus.CheckResult {
			return debugstatus.Check(debugstatus.ServerStartTime)
		},
	})
	httptesting.AssertJSONCall(c, httptesting.JSONCallParams{
		Handler: httpHandler,
		URL:     "/debug/status",
		ExpectBody: httptesting.BodyAsserter(func(c *gc.C, body json.RawMessage) {
			var result map[string]debugstatus.CheckResult
			err := json.Unmarshal(body, &result)
			c.Assert(err, gc.IsNil)
			for k, v := range result {
				v.Duration = 0
				result[k] = v
			}
			c.Assert(result, jc.DeepEquals, map[string]debugstatus.CheckResult{
				"server_started": {
					Name:   "Server started",
					Value:  debugstatus.StartTime.String(),
					Passed: true,
				},
			})
		}),
	})
}
Esempio n. 2
0
func (s *handlerSuite) TestServeTraceEvents(c *gc.C) {
	httpHandler := newHTTPHandler(&debugstatus.Handler{
		CheckTraceAllowed: func(req *http.Request) (bool, error) {
			if req.Header.Get("Authorization") == "" {
				return false, errUnauthorized
			}
			return false, nil
		},
	})
	authHeader := make(http.Header)
	authHeader.Set("Authorization", "let me in")
	for i, path := range debugTracePaths {
		c.Logf("%d. %s", i, path)
		httptesting.AssertJSONCall(c, httptesting.JSONCallParams{
			Handler:      httpHandler,
			URL:          path,
			ExpectStatus: http.StatusUnauthorized,
			ExpectBody: httprequest.RemoteError{
				Code:    "unauthorized",
				Message: "you shall not pass!",
			},
		})
		rr := httptesting.DoRequest(c, httptesting.DoRequestParams{
			Handler: httpHandler,
			URL:     path,
			Header:  authHeader,
		})
		c.Assert(rr.Code, gc.Equals, http.StatusOK)
	}
}
Esempio n. 3
0
func (s *handlerSuite) TestServeDebugStatusWithNilCheck(c *gc.C) {
	httpHandler := newHTTPHandler(&debugstatus.Handler{})
	httptesting.AssertJSONCall(c, httptesting.JSONCallParams{
		Handler:    httpHandler,
		URL:        "/debug/status",
		ExpectBody: map[string]debugstatus.CheckResult{},
	})
}
Esempio n. 4
0
func (*requestsSuite) TestAssertJSONCallWithHostedURL(c *gc.C) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte(fmt.Sprintf("%q", "ok "+req.URL.Path)))
	}))
	defer srv.Close()
	httptesting.AssertJSONCall(c, httptesting.JSONCallParams{
		URL:        srv.URL + "/foo",
		ExpectBody: "ok /foo",
	})
}
Esempio n. 5
0
func (*requestsSuite) TestAssertJSONCall(c *gc.C) {
	for i, test := range assertJSONCallTests {
		c.Logf("test %d: %s", i, test.about)
		params := test.params

		// A missing status is assumed to be http.StatusOK.
		status := params.ExpectStatus
		if status == 0 {
			status = http.StatusOK
		}

		// Create the HTTP handler for this test.
		params.Handler = makeHandler(c, status, "application/json")

		// Populate the expected body parameter.
		expectBody := handlerResponse{
			URL:    params.URL,
			Method: params.Method,
			Header: params.Header,
		}

		// A missing method is assumed to be "GET".
		if expectBody.Method == "" {
			expectBody.Method = "GET"
		}
		expectBody.Header = make(http.Header)
		if params.JSONBody != nil {
			expectBody.Header.Set("Content-Type", "application/json")
		}
		for k, v := range params.Header {
			expectBody.Header[k] = v
		}
		if params.JSONBody != nil {
			data, err := json.Marshal(params.JSONBody)
			c.Assert(err, jc.ErrorIsNil)
			expectBody.Body = string(data)
			params.Body = bytes.NewReader(data)
		} else if params.Body != nil {
			// Handle the request body parameter.
			body, err := ioutil.ReadAll(params.Body)
			c.Assert(err, jc.ErrorIsNil)
			expectBody.Body = string(body)
			params.Body = bytes.NewReader(body)
		}

		// Handle basic HTTP authentication.
		if params.Username != "" || params.Password != "" {
			expectBody.Auth = true
		}
		params.ExpectBody = expectBody
		httptesting.AssertJSONCall(c, params)
	}
}
Esempio n. 6
0
func (s *registrationSuite) testInvalidRequest(c *gc.C, requestBody, errorMessage, errorCode string, statusCode int) {
	httptesting.AssertJSONCall(c, httptesting.JSONCallParams{
		Do:           utils.GetNonValidatingHTTPClient().Do,
		URL:          s.registrationURL(c),
		Method:       "POST",
		Body:         strings.NewReader(requestBody),
		ExpectStatus: statusCode,
		ExpectBody: &params.ErrorResult{
			Error: &params.Error{Message: errorMessage, Code: errorCode},
		},
	})
}
Esempio n. 7
0
func (s *handlerSuite) TestDebugEventsForbiddenWhenNotConfigured(c *gc.C) {
	httpHandler := newHTTPHandler(&debugstatus.Handler{})
	httptesting.AssertJSONCall(c, httptesting.JSONCallParams{
		Handler:      httpHandler,
		URL:          "/debug/events",
		ExpectStatus: http.StatusForbidden,
		ExpectBody: httprequest.RemoteError{
			Code:    "forbidden",
			Message: "no trace access configured",
		},
	})
}
Esempio n. 8
0
func (s *registrationSuite) TestRegisterInvalidMethod(c *gc.C) {
	httptesting.AssertJSONCall(c, httptesting.JSONCallParams{
		Do:           utils.GetNonValidatingHTTPClient().Do,
		URL:          s.registrationURL(c),
		Method:       "GET",
		ExpectStatus: http.StatusMethodNotAllowed,
		ExpectBody: &params.ErrorResult{
			Error: &params.Error{
				Message: `unsupported method: "GET"`,
				Code:    params.CodeMethodNotAllowed,
			},
		},
	})
}
Esempio n. 9
0
func (s *handlerSuite) TestServeDebugInfo(c *gc.C) {
	version := debugstatus.Version{
		GitCommit: "some-git-status",
		Version:   "a-version",
	}
	httpHandler := newHTTPHandler(&debugstatus.Handler{
		Version: version,
	})
	httptesting.AssertJSONCall(c, httptesting.JSONCallParams{
		Handler:      httpHandler,
		URL:          "/debug/info",
		ExpectStatus: http.StatusOK,
		ExpectBody:   version,
	})
}
Esempio n. 10
0
func (*handlerSuite) TestHandlersWithTypeThatImplementsIOCloser(c *gc.C) {
	var v closeHandlersType
	handlers := errorMapper.Handlers(func(httprequest.Params) (*closeHandlersType, error) {
		return &v, nil
	})
	router := httprouter.New()
	for _, h := range handlers {
		router.Handle(h.Method, h.Path, h.Handle)
	}
	httptesting.AssertJSONCall(c, httptesting.JSONCallParams{
		URL:     "/m1/99",
		Handler: router,
	})
	c.Assert(v.closed, gc.Equals, true)
	c.Assert(v.p, gc.Equals, 99)
}
Esempio n. 11
0
func (*handlerSuite) TestHandlersFuncReturningError(c *gc.C) {
	handlers := errorMapper.Handlers(func(httprequest.Params) (*testHandlers, error) {
		return nil, errgo.WithCausef(errgo.New("failure"), errUnauth, "something")
	})
	router := httprouter.New()
	for _, h := range handlers {
		router.Handle(h.Method, h.Path, h.Handle)
	}
	httptesting.AssertJSONCall(c, httptesting.JSONCallParams{
		URL:          "/m1/p",
		Handler:      router,
		ExpectStatus: http.StatusUnauthorized,
		ExpectBody: &httprequest.RemoteError{
			Message: "something: failure",
			Code:    "unauthorized",
		},
	})
}
Esempio n. 12
0
func (*requestsSuite) TestAssertJSONCallWithBodyAsserter(c *gc.C) {
	called := false
	params := httptesting.JSONCallParams{
		URL:     "/",
		Handler: makeHandler(c, http.StatusOK, "application/json"),
		ExpectBody: httptesting.BodyAsserter(func(c1 *gc.C, body json.RawMessage) {
			c.Assert(c1, gc.Equals, c)
			c.Assert(string(body), jc.JSONEquals, handlerResponse{
				URL:    "/",
				Method: "GET",
				Header: make(http.Header),
			})
			called = true
		}),
	}
	httptesting.AssertJSONCall(c, params)
	c.Assert(called, gc.Equals, true)
}
Esempio n. 13
0
func (*handlerSuite) TestHandlers(c *gc.C) {
	handleVal := testHandlers{
		c: c,
	}
	f := func(p httprequest.Params) (*testHandlers, error) {
		handleVal.p = p
		return &handleVal, nil
	}
	handlers := errorMapper.Handlers(f)
	handlers1 := make([]httprequest.Handler, len(handlers))
	copy(handlers1, handlers)
	for i := range handlers1 {
		handlers1[i].Handle = nil
	}
	expectHandlers := []httprequest.Handler{{
		Method: "GET",
		Path:   "/m1/:p",
	}, {
		Method: "GET",
		Path:   "/m2/:p",
	}, {
		Method: "GET",
		Path:   "/m3/:p",
	}, {
		Method: "POST",
		Path:   "/m3/:p",
	}}
	c.Assert(handlers1, jc.DeepEquals, expectHandlers)
	c.Assert(handlersTests, gc.HasLen, len(expectHandlers))

	router := httprouter.New()
	for _, h := range handlers {
		c.Logf("adding %s %s", h.Method, h.Path)
		router.Handle(h.Method, h.Path, h.Handle)
	}
	for i, test := range handlersTests {
		c.Logf("test %d: %s", i, test.calledMethod)
		handleVal.calledMethod = ""
		test.callParams.Handler = router
		httptesting.AssertJSONCall(c, test.callParams)
		c.Assert(handleVal.calledMethod, gc.Equals, test.calledMethod)
	}
}