func ExampleSendWithSender() { client := mocks.NewSender() client.EmitStatus("202 Accepted", http.StatusAccepted) logger := log.New(os.Stdout, "autorest: ", 0) na := NullAuthorizer{} req, _ := Prepare(&http.Request{}, AsGet(), WithBaseURL("https://microsoft.com/a/b/c/"), na.WithAuthorization()) r, _ := SendWithSender(client, req, WithLogging(logger), DoErrorIfStatusCode(http.StatusAccepted), DoCloseIfError(), DoRetryForAttempts(5, time.Duration(0))) Respond(r, ByClosing()) // Output: // autorest: Sending GET https://microsoft.com/a/b/c/ // autorest: GET https://microsoft.com/a/b/c/ received 202 Accepted // autorest: Sending GET https://microsoft.com/a/b/c/ // autorest: GET https://microsoft.com/a/b/c/ received 202 Accepted // autorest: Sending GET https://microsoft.com/a/b/c/ // autorest: GET https://microsoft.com/a/b/c/ received 202 Accepted // autorest: Sending GET https://microsoft.com/a/b/c/ // autorest: GET https://microsoft.com/a/b/c/ received 202 Accepted // autorest: Sending GET https://microsoft.com/a/b/c/ // autorest: GET https://microsoft.com/a/b/c/ received 202 Accepted }
func TestClientPollAsNeededPollsForDuration(t *testing.T) { c := Client{} c.PollingMode = PollUntilDuration c.PollingDuration = 10 * time.Millisecond s := mocks.NewSender() s.EmitStatus("202 Accepted", http.StatusAccepted) c.Sender = s r := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) mocks.SetAcceptedHeaders(r) s.SetResponse(r) d1 := 10 * time.Millisecond start := time.Now() resp, _ := c.PollAsNeeded(r) d2 := time.Now().Sub(start) if d2 < d1 { t.Errorf("autorest: Client#PollAsNeeded did not poll for the expected duration -- expected %v, actual %v", d1.Seconds(), d2.Seconds()) } Respond(resp, ByClosing()) }
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.NewSender() 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) } }
func (s *environSuite) TestAllInstancesResourceGroupNotFound(c *gc.C) { env := s.openEnviron(c) sender := mocks.NewSender() sender.EmitStatus("resource group not found", http.StatusNotFound) s.sender = azuretesting.Senders{sender} _, err := env.AllInstances() c.Assert(err, jc.ErrorIsNil) }
func (s *environSuite) TestStopInstancesNotFound(c *gc.C) { env := s.openEnviron(c) sender := mocks.NewSender() sender.EmitStatus("vm not found", http.StatusNotFound) s.sender = azuretesting.Senders{sender, sender, sender} err := env.StopInstances("a", "b") c.Assert(err, jc.ErrorIsNil) }
// 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.EmitContent(string(content)) return sender }
func TestServicePrincipalTokenSetSender(t *testing.T) { spt := newServicePrincipalToken() var s autorest.Sender s = mocks.NewSender() spt.SetSender(s) if !reflect.DeepEqual(s, spt.sender) { t.Error("azure: ServicePrincipalToken#SetSender did not set the sender") } }
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") } }
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") } }
func TestClientSenderReturnsSetSender(t *testing.T) { c := Client{} s := mocks.NewSender() c.Sender = s if c.sender() != s { t.Error("autorest: Client#sender failed to return set Sender") } }
func TestClientDoInvokesSender(t *testing.T) { c := Client{} s := mocks.NewSender() c.Sender = s c.Do(&http.Request{}) if s.Attempts() != 1 { t.Error("autorest: Client#Do failed to invoke the Sender") } }
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") } }
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()) } }
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") } }
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) } }
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") } }
func TestServicePrincipalTokenRefreshReturnsErrorIfNotOk(t *testing.T) { spt := newServicePrincipalToken() c := mocks.NewSender() c.EmitStatus("401 NotAuthorized", 401) spt.SetSender(c) err := spt.Refresh() if err == nil { t.Error("azure: Failed to return an when receiving a status code other than HTTP 200") } }
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()) } }
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) } }
func (s *environSuite) testLocationManagementURI(c *gc.C, location, host string) { env := s.openEnviron(c, testing.Attrs{"location": location}) sender := mocks.NewSender() sender.EmitContent("{}") 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, host) }
func TestClientSendSetsAuthorization(t *testing.T) { r := mocks.NewRequest() s := mocks.NewSender() c := Client{Authorizer: mockAuthorizer{}, Sender: s} c.Send(r) if len(r.Header.Get(http.CanonicalHeaderKey(headerAuthorization))) <= 0 { t.Errorf("autorest: Client#Send failed to set Authorization header -- %s=%s", http.CanonicalHeaderKey(headerAuthorization), r.Header.Get(http.CanonicalHeaderKey(headerAuthorization))) } }
func TestServicePrincipalTokenRefreshPropagatesErrors(t *testing.T) { spt := newServicePrincipalToken() c := mocks.NewSender() c.EmitErrors(1) spt.SetSender(c) err := spt.Refresh() if err == nil { t.Error("azure: Failed to propagate the request error") } }
func (s *environSuite) TestCloudEndpointManagementURI(c *gc.C) { env := s.openEnviron(c) sender := mocks.NewSender() sender.EmitContent("{}") 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") }
func TestDecorateForPollingCloseBodyOnEachAttempt(t *testing.T) { client := mocks.NewSender() resp := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) mocks.SetAcceptedHeaders(resp) client.SetResponse(resp) req, _ := NewPollingRequest(resp, NullAuthorizer{}) resp, _ = PollForAttempts(client, req, time.Duration(0), 5) if resp.Body.(*mocks.Body).CloseAttempts() < 5 { t.Errorf("autorest: decorateForPolling failed to close the response Body between requests -- expected %v, received %v", 5, resp.Body.(*mocks.Body).CloseAttempts()) } }
func TestPollingLeavesFinalBodyOpen(t *testing.T) { client := mocks.NewSender() client.EmitStatus("500 InternalServerError", http.StatusInternalServerError) resp := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) mocks.SetAcceptedHeaders(resp) req, _ := NewPollingRequest(resp, NullAuthorizer{}) resp, _ = PollForAttempts(client, req, time.Duration(0), 1) if !resp.Body.(*mocks.Body).IsOpen() { t.Error("autorest: Polling unexpectedly closed the response body") } }
func TestDoErrorUnlessStatusCode(t *testing.T) { client := mocks.NewSender() client.EmitStatus("400 BadRequest", http.StatusBadRequest) r, err := SendWithSender(client, mocks.NewRequest(), DoErrorUnlessStatusCode(http.StatusAccepted), DoCloseIfError()) if err == nil { t.Error("autorest: DoErrorUnlessStatusCode failed to emit an error for an unknown status code") } Respond(r, ByClosing()) }
func TestDoErrorUnlessStatusCodeIgnoresStatusCodes(t *testing.T) { client := mocks.NewSender() client.EmitStatus("202 Accepted", http.StatusAccepted) r, err := SendWithSender(client, mocks.NewRequest(), DoErrorUnlessStatusCode(http.StatusAccepted), DoCloseIfError()) if err != nil { t.Error("autorest: DoErrorUnlessStatusCode emitted an error for a knonwn status code") } Respond(r, ByClosing()) }
func TestPollingReturnsDefaultsToAcceptedStatusCode(t *testing.T) { client := mocks.NewSender() resp := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) mocks.SetAcceptedHeaders(resp) client.SetResponse(resp) req, _ := NewPollingRequest(resp, NullAuthorizer{}) resp, err := PollForAttempts(client, req, time.Duration(0), 1) if err == nil { t.Error("autorest: Polling failed to default to HTTP 202") } }
func TestPollingReturnsNoErrorForUnexpectedStatusCode(t *testing.T) { client := mocks.NewSender() client.EmitStatus("500 InternalServerError", http.StatusInternalServerError) resp := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) mocks.SetAcceptedHeaders(resp) req, _ := NewPollingRequest(resp, NullAuthorizer{}) resp, err := PollForAttempts(client, req, time.Duration(0), 1, http.StatusAccepted) if err != nil { t.Error("autorest: Polling emitted error for unknown status code") } }
func TestDoErrorIfStatusCodeIgnoresStatusCodes(t *testing.T) { client := mocks.NewSender() client.EmitStatus("202 Accepted", http.StatusAccepted) r, err := SendWithSender(client, mocks.NewRequest(), DoErrorIfStatusCode(http.StatusBadRequest), DoCloseIfError()) if err != nil { t.Error("autorest: DoErrorIfStatusCode failed to ignore a status code") } Respond(r, ByClosing()) }