示例#1
0
func (s *deviceTokenSender) Do(req *http.Request) (*http.Response, error) {
	var resp *http.Response
	if s.attempts < 1 {
		s.attempts++
		resp = mocks.NewResponseWithContent(errorDeviceTokenResponse(s.errorString))
	} else {
		resp = mocks.NewResponseWithContent(MockDeviceTokenResponse)
	}
	return resp, nil
}
示例#2
0
func TestWithErrorUnlessStatusCode_NotAnAzureError(t *testing.T) {
	body := `<html>
		<head>
			<title>IIS Error page</title>
		</head>
		<body>Some non-JSON error page</body>
	</html>`
	r := mocks.NewResponseWithContent(body)
	r.Request = mocks.NewRequest()
	r.StatusCode = http.StatusBadRequest
	r.Status = http.StatusText(r.StatusCode)

	err := autorest.Respond(r,
		WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByClosing())
	ok, _ := err.(*RequestError)
	if ok != nil {
		t.Fatalf("azure: azure.RequestError returned from malformed response: %v", err)
	}

	// the error body should still be there
	defer r.Body.Close()
	b, err := ioutil.ReadAll(r.Body)
	if err != nil {
		t.Fatal(err)
	}
	if string(b) != body {
		t.Fatalf("response body is wrong. got=%q exptected=%q", string(b), body)
	}
}
示例#3
0
func TestServicePrincipalTokenRefreshUnmarshals(t *testing.T) {
	spt := newServicePrincipalToken()

	expiresOn := strconv.Itoa(int(time.Now().Add(3600 * time.Second).Sub(expirationBase).Seconds()))
	j := newTokenJSON(expiresOn, "resource")
	resp := mocks.NewResponseWithContent(j)
	c := mocks.NewClient()
	s := autorest.DecorateSender(c,
		(func() autorest.SendDecorator {
			return func(s autorest.Sender) autorest.Sender {
				return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) {
					return resp, nil
				})
			}
		})())
	spt.SetSender(s)

	err := spt.Refresh()
	if err != nil {
		t.Errorf("azure: ServicePrincipalToken#Refresh returned an unexpected error (%v)", err)
	} else if spt.AccessToken != "accessToken" ||
		spt.ExpiresIn != "3600" ||
		spt.ExpiresOn != expiresOn ||
		spt.NotBefore != expiresOn ||
		spt.Resource != "resource" ||
		spt.Type != "Bearer" {
		t.Errorf("azure: ServicePrincipalToken#Refresh failed correctly unmarshal the JSON -- expected %v, received %v",
			j, *spt)
	}
}
示例#4
0
func TestRequestErrorString_WithError(t *testing.T) {
	j := `{
		"error": {
			"code": "InternalError",
			"message": "Conflict",
			"details": [{"code": "conflict1", "message":"error message1"}]
		}
	}`
	uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6"
	r := mocks.NewResponseWithContent(j)
	mocks.SetResponseHeader(r, HeaderRequestID, uuid)
	r.Request = mocks.NewRequest()
	r.StatusCode = http.StatusInternalServerError
	r.Status = http.StatusText(r.StatusCode)

	err := autorest.Respond(r,
		WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByClosing())

	if err == nil {
		t.Fatalf("azure: returned nil error for proper error response")
	}
	azErr, _ := err.(*RequestError)
	expected := "autorest/azure: Service returned an error. Status=500 Code=\"InternalError\" Message=\"Conflict\" Details=[{\"code\":\"conflict1\",\"message\":\"error message1\"}]"
	if expected != azErr.Error() {
		t.Fatalf("azure: send wrong RequestError.\nexpected=%v\ngot=%v", expected, azErr.Error())
	}
}
示例#5
0
func TestUpdatePollingState_ReturnsAnErrorIfOneOccurs(t *testing.T) {
	resp := mocks.NewResponseWithContent(operationResourceIllegal)
	err := updatePollingState(resp, &pollingState{})
	if err == nil {
		t.Fatalf("azure: updatePollingState failed to return an error after a JSON parsing error")
	}
}
示例#6
0
func TestWithErrorUnlessStatusCode_FoundAzureErrorWithDetails(t *testing.T) {
	j := `{
		"error": {
			"code": "InternalError",
			"message": "Azure is having trouble right now.",
			"details": [{"code": "conflict1", "message":"error message1"}, 
						{"code": "conflict2", "message":"error message2"}]
		}
	}`
	uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6"
	r := mocks.NewResponseWithContent(j)
	mocks.SetResponseHeader(r, HeaderRequestID, uuid)
	r.Request = mocks.NewRequest()
	r.StatusCode = http.StatusInternalServerError
	r.Status = http.StatusText(r.StatusCode)

	err := autorest.Respond(r,
		WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByClosing())

	if err == nil {
		t.Fatalf("azure: returned nil error for proper error response")
	}
	azErr, ok := err.(*RequestError)
	if !ok {
		t.Fatalf("azure: returned error is not azure.RequestError: %T", err)
	}

	if expected := "InternalError"; azErr.ServiceError.Code != expected {
		t.Fatalf("azure: wrong error code. expected=%q; got=%q", expected, azErr.ServiceError.Code)
	}
	if azErr.ServiceError.Message == "" {
		t.Fatalf("azure: error message is not unmarshaled properly")
	}
	b, _ := json.Marshal(*azErr.ServiceError.Details)
	if string(b) != `[{"code":"conflict1","message":"error message1"},{"code":"conflict2","message":"error message2"}]` {
		t.Fatalf("azure: error details is not unmarshaled properly")
	}

	if expected := http.StatusInternalServerError; azErr.StatusCode != expected {
		t.Fatalf("azure: got wrong StatusCode=%v Expected=%d", azErr.StatusCode, expected)
	}
	if expected := uuid; azErr.RequestID != expected {
		t.Fatalf("azure: wrong request ID in error. expected=%q; got=%q", expected, azErr.RequestID)
	}

	_ = azErr.Error()

	// the error body should still be there
	defer r.Body.Close()
	b, err = ioutil.ReadAll(r.Body)
	if err != nil {
		t.Fatal(err)
	}
	if string(b) != j {
		t.Fatalf("response body is wrong. got=%q expected=%q", string(b), j)
	}

}
示例#7
0
文件: senders.go 项目: bac/juju
// NewSenderWithValue returns a *mocks.Sender that marshals the provided object
// to JSON and sets it as the content. This function will panic if marshalling
// fails.
func NewSenderWithValue(v interface{}) *MockSender {
	content, err := json.Marshal(v)
	if err != nil {
		panic(err)
	}
	sender := &MockSender{Sender: mocks.NewSender()}
	sender.AppendResponse(mocks.NewResponseWithContent(string(content)))
	return sender
}
示例#8
0
func TestUpdatePollingState_ReturnsSuccessForSuccessfulOperationResourceState(t *testing.T) {
	resp := mocks.NewResponseWithContent(fmt.Sprintf(operationResourceFormat, operationSucceeded))
	resp.StatusCode = 42
	ps := &pollingState{responseFormat: usesOperationResponse}
	updatePollingState(resp, ps)
	if !ps.hasSucceeded() {
		t.Fatalf("azure: updatePollingState failed to return a successful pollingState for the '%s' state", operationSucceeded)
	}
}
示例#9
0
func TestUpdatePollingState_ReturnsFailedWhenProvisioningStateFieldIsAbsentForUnknownStatusCodes(t *testing.T) {
	resp := mocks.NewResponseWithContent(pollingStateEmpty)
	resp.StatusCode = 42
	ps := &pollingState{responseFormat: usesProvisioningStatus}
	updatePollingState(resp, ps)
	if !ps.hasTerminated() || ps.hasSucceeded() {
		t.Fatalf("azure: updatePollingState did not return failed when the provisionState field is absent for an unknown Status Code")
	}
}
示例#10
0
func TestUpdatePollingState_ReturnsInProgressWhenProvisioningStateFieldIsAbsentForAccepted(t *testing.T) {
	resp := mocks.NewResponseWithContent(pollingStateEmpty)
	resp.StatusCode = http.StatusAccepted
	ps := &pollingState{responseFormat: usesProvisioningStatus}
	updatePollingState(resp, ps)
	if ps.hasTerminated() {
		t.Fatalf("azure: updatePollingState returned terminated when the provisionState field is absent for Status Code Accepted")
	}
}
示例#11
0
func TestByUnmarshallingJSONEmptyInput(t *testing.T) {
	v := &mocks.T{}
	r := mocks.NewResponseWithContent(``)
	err := Respond(r,
		ByUnmarshallingJSON(v),
		ByClosing())
	if err != nil {
		t.Fatalf("autorest: ByUnmarshallingJSON failed to return nil in case of empty JSON (%v)", err)
	}
}
示例#12
0
func TestUpdatePollingState_ReturnsInProgressForAllOtherOperationResourceStates(t *testing.T) {
	s := "not a recognized state"
	resp := mocks.NewResponseWithContent(fmt.Sprintf(operationResourceFormat, s))
	resp.StatusCode = 42
	ps := &pollingState{responseFormat: usesOperationResponse}
	updatePollingState(resp, ps)
	if ps.hasTerminated() {
		t.Fatalf("azure: updatePollingState returned terminated for unknown state '%s'", s)
	}
}
func TestByUnmarhallingJSONIncludesJSONInErrors(t *testing.T) {
	v := &mocks.T{}
	j := jsonT[0 : len(jsonT)-2]
	r := mocks.NewResponseWithContent(j)
	err := Respond(r,
		ByUnmarshallingJSON(v),
		ByClosing())
	if err == nil || !strings.Contains(err.Error(), j) {
		t.Errorf("autorest: ByUnmarshallingJSON failed to return JSON in error (%v)", err)
	}
}
示例#14
0
func TestByUnmarshallingXMLIncludesXMLInErrors(t *testing.T) {
	v := &mocks.T{}
	x := xmlT[0 : len(xmlT)-2]
	r := mocks.NewResponseWithContent(x)
	err := Respond(r,
		ByUnmarshallingXML(v),
		ByClosing())
	if err == nil || !strings.Contains(err.Error(), x) {
		t.Fatalf("autorest: ByUnmarshallingXML failed to return XML in error (%v)", err)
	}
}
示例#15
0
func TestUpdatePollingState_ReturnsSuccessWhenProvisioningStateFieldIsAbsentForSuccessStatusCodes(t *testing.T) {
	for _, sc := range []int{http.StatusOK, http.StatusCreated, http.StatusNoContent} {
		resp := mocks.NewResponseWithContent(pollingStateEmpty)
		resp.StatusCode = sc
		ps := &pollingState{responseFormat: usesProvisioningStatus}
		updatePollingState(resp, ps)
		if !ps.hasSucceeded() {
			t.Fatalf("azure: updatePollingState failed to return success when the provisionState field is absent for Status Code %d", sc)
		}
	}
}
示例#16
0
func TestUpdatePollingState_ReturnsTerminatedForKnownOperationResourceStates(t *testing.T) {
	for _, state := range []string{operationSucceeded, operationCanceled, operationFailed} {
		resp := mocks.NewResponseWithContent(fmt.Sprintf(operationResourceFormat, state))
		resp.StatusCode = 42
		ps := &pollingState{responseFormat: usesOperationResponse}
		updatePollingState(resp, ps)
		if !ps.hasTerminated() {
			t.Fatalf("azure: updatePollingState failed to return a terminating pollingState for the '%s' state", state)
		}
	}
}
示例#17
0
func TestByUnmarshallingXML_HandlesReadErrors(t *testing.T) {
	v := &mocks.T{}
	r := mocks.NewResponseWithContent(xmlT)
	r.Body.(*mocks.Body).Close()

	err := Respond(r,
		ByUnmarshallingXML(v),
		ByClosing())
	if err == nil {
		t.Fatalf("autorest: ByUnmarshallingXML failed to receive / respond to read error")
	}
}
示例#18
0
文件: environ_test.go 项目: bac/juju
func (s *environSuite) TestCloudEndpointManagementURI(c *gc.C) {
	env := s.openEnviron(c)

	sender := mocks.NewSender()
	sender.AppendResponse(mocks.NewResponseWithContent("{}"))
	s.sender = azuretesting.Senders{sender}
	s.requests = nil
	env.AllInstances() // trigger a query

	c.Assert(s.requests, gc.HasLen, 1)
	c.Assert(s.requests[0].URL.Host, gc.Equals, "api.azurestack.local")
}
示例#19
0
func TestByCopying_ReturnsNestedErrors(t *testing.T) {
	r := mocks.NewResponseWithContent(jsonT)

	r.Body.Close()
	err := Respond(r,
		ByCopying(&bytes.Buffer{}),
		ByUnmarshallingJSON(&mocks.T{}),
		ByClosing())
	if err == nil {
		t.Fatalf("autorest: ByCopying failed to return the expected error")
	}
}
示例#20
0
func TestLoggingInspectorByInspecting(t *testing.T) {
	b := bytes.Buffer{}
	c := Client{}
	li := LoggingInspector{Logger: log.New(&b, "", 0)}
	c.ResponseInspector = li.ByInspecting()

	Respond(mocks.NewResponseWithContent("Content"),
		c.ByInspecting())

	if len(b.String()) <= 0 {
		t.Error("autorest: LoggingInspector#ByInspection did not record Response to the log")
	}
}
示例#21
0
文件: images_test.go 项目: bac/juju
func (s *imageutilsSuite) TestSeriesImageInvalidSKU(c *gc.C) {
	s.mockSender.AppendResponse(mocks.NewResponseWithContent(
		`[{"name": "12.04.invalid"}, {"name": "12.04.5-LTS"}]`,
	))
	image, err := imageutils.SeriesImage("precise", "released", "westus", s.client)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(image, gc.NotNil)
	c.Assert(image, jc.DeepEquals, &instances.Image{
		Id:       "Canonical:UbuntuServer:12.04.5-LTS:latest",
		Arch:     arch.AMD64,
		VirtType: "Hyper-V",
	})
}
示例#22
0
func TestByUnmarhallingJSON(t *testing.T) {
	v := &mocks.T{}
	r := mocks.NewResponseWithContent(jsonT)
	err := Respond(r,
		ByUnmarshallingJSON(v),
		ByClosing())
	if err != nil {
		t.Errorf("autorest: ByUnmarshallingJSON failed (%v)", err)
	}
	if v.Name != "Rob Pike" || v.Age != 42 {
		t.Errorf("autorest: ByUnmarshallingJSON failed to properly unmarshal")
	}
}
示例#23
0
func TestWithErrorUnlessStatusCode_FoundAzureErrorWithoutDetails(t *testing.T) {
	j := `{
		"error": {
			"code": "InternalError",
			"message": "Azure is having trouble right now."
		}
	}`
	uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6"
	r := mocks.NewResponseWithContent(j)
	mocks.SetResponseHeader(r, HeaderRequestID, uuid)
	r.Request = mocks.NewRequest()
	r.StatusCode = http.StatusInternalServerError
	r.Status = http.StatusText(r.StatusCode)

	err := autorest.Respond(r,
		WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByClosing())

	if err == nil {
		t.Fatalf("azure: returned nil error for proper error response")
	}
	azErr, ok := err.(*RequestError)
	if !ok {
		t.Fatalf("azure: returned error is not azure.RequestError: %T", err)
	}

	expected := "autorest/azure: Service returned an error. Status=500 Code=\"InternalError\" Message=\"Azure is having trouble right now.\""
	if !reflect.DeepEqual(expected, azErr.Error()) {
		t.Fatalf("azure: service error is not unmarshaled properly.\nexpected=%v\ngot=%v", expected, azErr.Error())
	}

	if expected := http.StatusInternalServerError; azErr.StatusCode != expected {
		t.Fatalf("azure: got wrong StatusCode=%d Expected=%d", azErr.StatusCode, expected)
	}
	if expected := uuid; azErr.RequestID != expected {
		t.Fatalf("azure: wrong request ID in error. expected=%q; got=%q", expected, azErr.RequestID)
	}

	_ = azErr.Error()

	// the error body should still be there
	defer r.Body.Close()
	b, err := ioutil.ReadAll(r.Body)
	if err != nil {
		t.Fatal(err)
	}
	if string(b) != j {
		t.Fatalf("response body is wrong. got=%q expected=%q", string(b), j)
	}

}
示例#24
0
func TestWithErrorUnlessStatusCode_NoAzureError(t *testing.T) {
	j := `{
			"Status":"NotFound"
		}`
	uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6"
	r := mocks.NewResponseWithContent(j)
	mocks.SetResponseHeader(r, HeaderRequestID, uuid)
	r.Request = mocks.NewRequest()
	r.StatusCode = http.StatusInternalServerError
	r.Status = http.StatusText(r.StatusCode)

	err := autorest.Respond(r,
		WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByClosing())
	if err == nil {
		t.Fatalf("azure: returned nil error for proper error response")
	}
	azErr, ok := err.(*RequestError)
	if !ok {
		t.Fatalf("azure: returned error is not azure.RequestError: %T", err)
	}

	expected := &ServiceError{
		Code:    "Unknown",
		Message: "Unknown service error",
	}

	if !reflect.DeepEqual(expected, azErr.ServiceError) {
		t.Fatalf("azure: service error is not unmarshaled properly. expected=%q\ngot=%q", expected, azErr.ServiceError)
	}

	if expected := http.StatusInternalServerError; azErr.StatusCode != expected {
		t.Fatalf("azure: got wrong StatusCode=%v Expected=%d", azErr.StatusCode, expected)
	}
	if expected := uuid; azErr.RequestID != expected {
		t.Fatalf("azure: wrong request ID in error. expected=%q; got=%q", expected, azErr.RequestID)
	}

	_ = azErr.Error()

	// the error body should still be there
	defer r.Body.Close()
	b, err := ioutil.ReadAll(r.Body)
	if err != nil {
		t.Fatal(err)
	}
	if string(b) != j {
		t.Fatalf("response body is wrong. got=%q expected=%q", string(b), j)
	}

}
示例#25
0
func TestDeviceCodeIncludesResource(t *testing.T) {
	sender := mocks.NewSender()
	sender.AppendResponse(mocks.NewResponseWithContent(MockDeviceCodeResponse))
	client := &autorest.Client{Sender: sender}

	code, err := InitiateDeviceAuth(client, TestOAuthConfig, TestClientID, TestResource)
	if err != nil {
		t.Fatalf("azure: unexpected error initiating device auth")
	}

	if code.Resource != TestResource {
		t.Fatalf("azure: InitiateDeviceAuth failed to stash the resource in the DeviceCode struct")
	}
}
示例#26
0
func TestUpdatePollingState_CopiesTheResponseBody(t *testing.T) {
	s := fmt.Sprintf(pollingStateFormat, operationSucceeded)
	resp := mocks.NewResponseWithContent(s)
	resp.StatusCode = 42
	ps := &pollingState{responseFormat: usesOperationResponse}
	updatePollingState(resp, ps)
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Fatalf("azure: updatePollingState failed to replace the http.Response Body -- Error='%v'", err)
	}
	if string(b) != s {
		t.Fatalf("azure: updatePollingState failed to copy the http.Response Body -- Expected='%s' Received='%s'", s, string(b))
	}
}
示例#27
0
func TestTeeReadCloser_PassesReadErrors(t *testing.T) {
	v := &mocks.T{}
	r := mocks.NewResponseWithContent(jsonT)

	r.Body.(*mocks.Body).Close()
	r.Body = TeeReadCloser(r.Body, &bytes.Buffer{})

	err := Respond(r,
		ByUnmarshallingJSON(v),
		ByClosing())
	if err == nil {
		t.Fatalf("autorest: TeeReadCloser failed to return the expected error")
	}
}
示例#28
0
func TestByCopying_Copies(t *testing.T) {
	r := mocks.NewResponseWithContent(jsonT)
	b := &bytes.Buffer{}

	err := Respond(r,
		ByCopying(b),
		ByUnmarshallingJSON(&mocks.T{}),
		ByClosing())
	if err != nil {
		t.Fatalf("autorest: ByCopying returned an unexpected error -- %v", err)
	}
	if b.String() != jsonT {
		t.Fatalf("autorest: ByCopying failed to copy the bytes read")
	}
}
示例#29
0
func TestLoggingInspectorByInspectingRestoresBody(t *testing.T) {
	b := bytes.Buffer{}
	c := Client{}
	r := mocks.NewResponseWithContent("Content")
	li := LoggingInspector{Logger: log.New(&b, "", 0)}
	c.ResponseInspector = li.ByInspecting()

	Respond(r,
		c.ByInspecting())

	s, _ := ioutil.ReadAll(r.Body)
	if len(s) <= 0 {
		t.Error("autorest: LoggingInspector#ByInspecting did not restore the Response body")
	}
}
示例#30
0
func TestTeeReadCloser_ClosesWrappedReader(t *testing.T) {
	v := &mocks.T{}
	r := mocks.NewResponseWithContent(jsonT)

	b := r.Body.(*mocks.Body)
	r.Body = TeeReadCloser(r.Body, &bytes.Buffer{})
	err := Respond(r,
		ByUnmarshallingJSON(v),
		ByClosing())
	if err != nil {
		t.Fatalf("autorest: TeeReadCloser returned an unexpected error -- %v", err)
	}
	if b.IsOpen() {
		t.Fatalf("autorest: TeeReadCloser failed to close the nested io.ReadCloser")
	}
}