コード例 #1
0
ファイル: async_test.go プロジェクト: Azure/go-autorest
func TestDoPollForAsynchronous_StopsPollingIfItReceivesAnInvalidOperationResource(t *testing.T) {
	r1 := newAsynchronousResponse()
	r2 := newOperationResourceResponse("busy")
	r3 := newOperationResourceResponse("busy")
	r3.Body = mocks.NewBody(operationResourceIllegal)
	r4 := newOperationResourceResponse(operationSucceeded)

	client := mocks.NewSender()
	client.AppendResponse(r1)
	client.AppendAndRepeatResponse(r2, 2)
	client.AppendAndRepeatResponse(r3, 1)
	client.AppendAndRepeatResponse(r4, 1)

	r, err := autorest.SendWithSender(client, mocks.NewRequest(),
		DoPollForAsynchronous(time.Millisecond))

	if client.Attempts() > 4 {
		t.Fatalf("azure: DoPollForAsynchronous failed to stop polling after receiving an invalid OperationResource")
	}
	if err == nil {
		t.Fatalf("azure: DoPollForAsynchronous failed to return an error after receving an invalid OperationResource")
	}

	autorest.Respond(r,
		autorest.ByClosing())
}
コード例 #2
0
ファイル: azure_test.go プロジェクト: Azure/go-autorest
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
ファイル: async_test.go プロジェクト: Azure/go-autorest
func TestDoPollForAsynchronous_ReturnsErrorForLastErrorResponse(t *testing.T) {
	// Return error code and message if error present in last response
	r1 := newAsynchronousResponse()
	r1.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation))
	r2 := newProvisioningStatusResponse("busy")
	r2.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation))
	r3 := newAsynchronousResponseWithError()
	r3.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation))

	client := mocks.NewSender()
	client.AppendResponse(r1)
	client.AppendAndRepeatResponse(r2, 2)
	client.AppendAndRepeatResponse(r3, 1)

	r, err := autorest.SendWithSender(client, mocks.NewRequest(),
		DoPollForAsynchronous(time.Millisecond))

	expected := makeLongRunningOperationErrorString("InvalidParameter", "tom-service-DISCOVERY-server-base-v1.core.local' is not a valid captured VHD blob name prefix.")
	if err.Error() != expected {
		t.Fatalf("azure: DoPollForAsynchronous failed to return an appropriate error message for an unknown error. \n expected=%q \n got=%q",
			expected, err.Error())
	}

	autorest.Respond(r,
		autorest.ByClosing())
}
コード例 #4
0
ファイル: sender_test.go プロジェクト: Azure/go-autorest
func TestDoPollForStatusCodes_CanBeCanceled(t *testing.T) {
	cancel := make(chan struct{})
	delay := 5 * time.Second

	r := mocks.NewResponse()
	mocks.SetAcceptedHeaders(r)
	client := mocks.NewSender()
	client.AppendAndRepeatResponse(r, 100)

	var wg sync.WaitGroup
	wg.Add(1)
	start := time.Now()
	go func() {
		wg.Done()
		r, _ := SendWithSender(client, mocks.NewRequest(),
			DoPollForStatusCodes(time.Millisecond, time.Millisecond, http.StatusAccepted))
		Respond(r,
			ByClosing())
	}()
	wg.Wait()
	close(cancel)
	time.Sleep(5 * time.Millisecond)
	if time.Since(start) >= delay {
		t.Fatalf("autorest: Sender#DoPollForStatusCodes failed to cancel")
	}
}
コード例 #5
0
ファイル: async_test.go プロジェクト: Azure/go-autorest
func TestDoPollForAsynchronous_CanBeCanceled(t *testing.T) {
	cancel := make(chan struct{})
	delay := 5 * time.Second

	r1 := newAsynchronousResponse()

	client := mocks.NewSender()
	client.AppendResponse(r1)
	client.AppendAndRepeatResponse(newOperationResourceResponse("Busy"), -1)

	var wg sync.WaitGroup
	wg.Add(1)
	start := time.Now()
	go func() {
		req := mocks.NewRequest()
		req.Cancel = cancel

		wg.Done()

		r, _ := autorest.SendWithSender(client, req,
			DoPollForAsynchronous(10*time.Second))
		autorest.Respond(r,
			autorest.ByClosing())
	}()
	wg.Wait()
	close(cancel)
	time.Sleep(5 * time.Millisecond)
	if time.Since(start) >= delay {
		t.Fatalf("azure: DoPollForAsynchronous failed to cancel")
	}
}
コード例 #6
0
ファイル: azure_test.go プロジェクト: Azure/go-autorest
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())
	}
}
コード例 #7
0
ファイル: async_test.go プロジェクト: Azure/go-autorest
func TestDoPollForAsynchronous_ReturnsAnUnknownErrorForFailedOperations(t *testing.T) {
	// Return unknown error if error not present in last response
	r1 := newAsynchronousResponse()
	r1.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation))
	r2 := newProvisioningStatusResponse("busy")
	r2.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation))
	r3 := newProvisioningStatusResponse(operationFailed)
	r3.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation))

	client := mocks.NewSender()
	client.AppendResponse(r1)
	client.AppendAndRepeatResponse(r2, 2)
	client.AppendAndRepeatResponse(r3, 1)

	r, err := autorest.SendWithSender(client, mocks.NewRequest(),
		DoPollForAsynchronous(time.Millisecond))

	expected := makeLongRunningOperationErrorString("Unknown", "None")
	if err.Error() != expected {
		t.Fatalf("azure: DoPollForAsynchronous failed to return an appropriate error message for an unknown error. \n expected=%q \n got=%q",
			expected, err.Error())
	}

	autorest.Respond(r,
		autorest.ByClosing())
}
コード例 #8
0
ファイル: azure_test.go プロジェクト: Azure/go-autorest
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)
	}

}
コード例 #9
0
func TestWithBearerAuthorization(t *testing.T) {
	r, err := Prepare(mocks.NewRequest(), WithBearerAuthorization("SOME-TOKEN"))
	if err != nil {
		fmt.Printf("ERROR: %v", err)
	}
	if r.Header.Get(headerAuthorization) != "Bearer SOME-TOKEN" {
		t.Errorf("autorest: WithBearerAuthorization failed to add header (%s=%s)", headerAuthorization, r.Header.Get(headerAuthorization))
	}
}
コード例 #10
0
func TestAsContentType(t *testing.T) {
	r, err := Prepare(mocks.NewRequest(), AsContentType("application/text"))
	if err != nil {
		fmt.Printf("ERROR: %v", err)
	}
	if r.Header.Get(headerContentType) != "application/text" {
		t.Errorf("autorest: AsContentType failed to add header (%s=%s)", headerContentType, r.Header.Get(headerContentType))
	}
}
コード例 #11
0
func TestAsJSON(t *testing.T) {
	r, err := Prepare(mocks.NewRequest(), AsJSON())
	if err != nil {
		fmt.Printf("ERROR: %v", err)
	}
	if r.Header.Get(headerContentType) != mimeTypeJSON {
		t.Errorf("autorest: AsJSON failed to add header (%s=%s)", headerContentType, r.Header.Get(headerContentType))
	}
}
コード例 #12
0
func TestWithUserAgent(t *testing.T) {
	r, err := Prepare(mocks.NewRequest(), WithUserAgent("User Agent Go"))
	if err != nil {
		fmt.Printf("ERROR: %v", err)
	}
	if r.Header.Get(headerUserAgent) != "User Agent Go" {
		t.Errorf("autorest: WithUserAgent failed to add header (%s=%s)", headerUserAgent, r.Header.Get(headerUserAgent))
	}
}
コード例 #13
0
ファイル: preparer_test.go プロジェクト: Azure/go-autorest
func TestAsFormURLEncoded(t *testing.T) {
	r, err := Prepare(mocks.NewRequest(), AsFormURLEncoded())
	if err != nil {
		fmt.Printf("ERROR: %v", err)
	}
	if r.Header.Get(headerContentType) != mimeTypeFormPost {
		t.Fatalf("autorest: AsFormURLEncoded failed to add header (%s=%s)", headerContentType, r.Header.Get(headerContentType))
	}
}
コード例 #14
0
func TestWithHeaderAllocatesHeaders(t *testing.T) {
	r, err := Prepare(mocks.NewRequest(), WithHeader("x-foo", "bar"))
	if err != nil {
		t.Errorf("autorest: WithHeader failed (%v)", err)
	}
	if r.Header.Get("x-foo") != "bar" {
		t.Errorf("autorest: WithHeader failed to add header (%s=%s)", "x-foo", r.Header.Get("x-foo"))
	}
}
コード例 #15
0
func TestClientSendReturnsPrepareError(t *testing.T) {
	r := mocks.NewRequest()
	s := mocks.NewSender()
	c := Client{Authorizer: mockFailingAuthorizer{}, Sender: s}

	_, err := c.Send(r)
	if err == nil {
		t.Error("autorest: Client#Send failed to return an error the Prepare error")
	}
}
コード例 #16
0
ファイル: preparer_test.go プロジェクト: Azure/go-autorest
func TestWithUserAgent(t *testing.T) {
	ua := "User Agent Go"
	r, err := Prepare(mocks.NewRequest(), WithUserAgent(ua))
	if err != nil {
		fmt.Printf("ERROR: %v", err)
	}
	if r.UserAgent() != ua || r.Header.Get(headerUserAgent) != ua {
		t.Fatalf("autorest: WithUserAgent failed to add header (%s=%s)", headerUserAgent, r.Header.Get(headerUserAgent))
	}
}
コード例 #17
0
func TestClientSendSends(t *testing.T) {
	r := mocks.NewRequest()
	s := mocks.NewSender()
	c := Client{Sender: s}

	c.Send(r)
	if s.Attempts() <= 0 {
		t.Error("autorest: Client#Send failed to invoke the Sender")
	}
}
コード例 #18
0
func TestClientDoInvokesResponseInspector(t *testing.T) {
	r := mocks.NewRequest()
	s := mocks.NewSender()
	i := &mockInspector{}
	c := Client{ResponseInspector: i.ByInspecting(), Sender: s}

	c.Do(r)
	if !i.wasInvoked {
		t.Fatal("autorest: Client#Send failed to invoke the ResponseInspector")
	}
}
コード例 #19
0
ファイル: token_test.go プロジェクト: Azure/go-autorest
func TestServicePrincipalTokenWithAuthorizationReturnsErrorIfCannotRefresh(t *testing.T) {
	spt := newServicePrincipalToken()
	s := mocks.NewSender()
	s.AppendResponse(mocks.NewResponseWithStatus("400 Bad Request", 400))
	spt.SetSender(s)

	_, err := autorest.Prepare(mocks.NewRequest(), spt.WithAuthorization())
	if err == nil {
		t.Fatal("azure: ServicePrincipalToken#WithAuthorization failed to return an error when refresh fails")
	}
}
コード例 #20
0
func TestClientSendDoesNotPollIfUnnecessary(t *testing.T) {
	r := mocks.NewRequest()
	s := mocks.NewSender()
	c := Client{Sender: s, PollingMode: PollUntilAttempts, PollingAttempts: 10}

	c.Send(r, http.StatusOK, http.StatusAccepted)
	if s.Attempts() != 1 {
		t.Errorf("autorest: Client#Send unexpectedly polled -- attempts %d",
			s.Attempts())
	}
}
コード例 #21
0
func TestClientSendInvokesInspector(t *testing.T) {
	r := mocks.NewRequest()
	s := mocks.NewSender()
	i := &mockInspector{}
	c := Client{RequestInspector: i.WithInspection(), Sender: s}

	c.Send(r)
	if !i.wasInvoked {
		t.Error("autorest: Client#Send failed to invoke the RequestInspector")
	}
}
コード例 #22
0
func TestClientSendClosesReponseBodyWhenReturningError(t *testing.T) {
	s := mocks.NewSender()
	r := mocks.NewResponseWithStatus("500 InternalServerError", http.StatusInternalServerError)
	s.SetResponse(r)
	c := Client{Sender: s}

	c.Send(mocks.NewRequest())
	if r.Body.(*mocks.Body).IsOpen() {
		t.Error("autorest: Client#Send failed to close the response body when returning an error")
	}
}
コード例 #23
0
func TestClientSendReturnsErrorWithUnexpectedStatusCode(t *testing.T) {
	r := mocks.NewRequest()
	s := mocks.NewSender()
	s.EmitStatus("500 InternalServerError", http.StatusInternalServerError)
	c := Client{Sender: s}

	_, err := c.Send(r)
	if err == nil {
		t.Error("autorest: Client#Send failed to return an error for an unexpected Status Code")
	}
}
コード例 #24
0
func TestClientSendDefaultsToUsingStatusCodeOK(t *testing.T) {
	r := mocks.NewRequest()
	s := mocks.NewSender()
	c := Client{Authorizer: mockAuthorizer{}, Sender: s}

	_, err := c.Send(r)
	if err != nil {
		t.Errorf("autorest: Client#Send returned an error for Status Code OK -- %v",
			err)
	}
}
コード例 #25
0
func TestWithNothing(t *testing.T) {
	r1 := mocks.NewRequest()
	r2, err := Prepare(r1, WithNothing())
	if err != nil {
		t.Errorf("autorest: WithNothing returned an unexpected error (%v)", err)
	}

	if !reflect.DeepEqual(r1, r2) {
		t.Error("azure: WithNothing modified the passed HTTP Request")
	}
}
コード例 #26
0
func TestWithErrorUnlessOK(t *testing.T) {
	r := mocks.NewResponse()
	r.Request = mocks.NewRequest()

	err := Respond(r,
		WithErrorUnlessOK(),
		ByClosingIfError())

	if err != nil {
		t.Errorf("autorest: WithErrorUnlessOK returned an error for OK status code (%v)", err)
	}
}
コード例 #27
0
func TestWithAuthorizer(t *testing.T) {
	r1 := mocks.NewRequest()

	na := &NullAuthorizer{}
	r2, err := Prepare(r1,
		na.WithAuthorization())
	if err != nil {
		t.Errorf("autorest: NullAuthorizer#WithAuthorization returned an unexpected error (%v)", err)
	} else if !reflect.DeepEqual(r1, r2) {
		t.Errorf("autorest: NullAuthorizer#WithAuthorization modified the request -- received %v, expected %v", r2, r1)
	}
}
コード例 #28
0
func TestClientSendDoesNotReturnErrorForExpectedStatusCode(t *testing.T) {
	r := mocks.NewRequest()
	s := mocks.NewSender()
	s.EmitStatus("500 InternalServerError", http.StatusInternalServerError)
	c := Client{Sender: s}

	_, err := c.Send(r, http.StatusInternalServerError)
	if err != nil {
		t.Errorf("autorest: Client#Send returned an error for an expected Status Code -- %v",
			err)
	}
}
コード例 #29
0
func TestClientSendPollsIfNeeded(t *testing.T) {
	r := mocks.NewRequest()
	s := mocks.NewSender()
	s.SetPollAttempts(5)
	c := Client{Sender: s, PollingMode: PollUntilAttempts, PollingAttempts: 10}

	c.Send(r, http.StatusOK, http.StatusAccepted)
	if s.Attempts() != (5 + 1) {
		t.Errorf("autorest: Client#Send failed to poll the expected number of times -- attempts %d",
			s.Attempts())
	}
}
コード例 #30
0
func TestClientDoSetsUserAgent(t *testing.T) {
	c := Client{UserAgent: "UserAgent"}
	r := mocks.NewRequest()

	c.Do(r)

	if r.Header.Get(http.CanonicalHeaderKey(headerUserAgent)) != "UserAgent" {
		t.Errorf("autorest: Client#Do failed to correctly set User-Agent header: %s=%s",
			http.CanonicalHeaderKey(headerUserAgent),
			r.Header.Get(http.CanonicalHeaderKey(headerUserAgent)))
	}
}