func (s *instanceSuite) TestInstanceClosePorts(c *gc.C) { inst := s.getInstance(c) sender := mocks.NewSender() notFoundSender := mocks.NewSender() notFoundSender.AppendResponse(mocks.NewResponseWithStatus( "rule not found", http.StatusNotFound, )) s.sender = azuretesting.Senders{sender, notFoundSender} err := inst.ClosePorts("0", []jujunetwork.PortRange{{ Protocol: "tcp", FromPort: 1000, ToPort: 1000, }, { Protocol: "udp", FromPort: 1000, ToPort: 2000, }}) c.Assert(err, jc.ErrorIsNil) c.Assert(s.requests, gc.HasLen, 2) c.Assert(s.requests[0].Method, gc.Equals, "DELETE") c.Assert(s.requests[0].URL.Path, gc.Equals, securityRulePath("machine-0-tcp-1000")) c.Assert(s.requests[1].Method, gc.Equals, "DELETE") c.Assert(s.requests[1].URL.Path, gc.Equals, securityRulePath("machine-0-udp-1000-2000")) }
func (s *environSuite) TestStopInstancesNotFound(c *gc.C) { env := s.openEnviron(c) sender0 := mocks.NewSender() sender0.AppendResponse(mocks.NewResponseWithStatus( "vm not found", http.StatusNotFound, )) sender1 := mocks.NewSender() sender1.AppendResponse(mocks.NewResponseWithStatus( "vm not found", http.StatusNotFound, )) s.sender = azuretesting.Senders{sender0, sender1} err := env.StopInstances("a", "b") c.Assert(err, jc.ErrorIsNil) }
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.Fatalf("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.Fatalf("azure: ServicePrincipalToken#Refresh failed correctly unmarshal the JSON -- expected %v, received %v", j, *spt) } }
func TestServicePrincipalTokenRefreshUsesPOST(t *testing.T) { spt := newServicePrincipalToken() body := mocks.NewBody("") resp := mocks.NewResponseWithBodyAndStatus(body, 200, "OK") 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) { if r.Method != "POST" { t.Fatalf("azure: ServicePrincipalToken#Refresh did not correctly set HTTP method -- expected %v, received %v", "POST", r.Method) } return resp, nil }) } })()) spt.SetSender(s) spt.Refresh() if body.IsOpen() { t.Fatalf("the response was not closed!") } }
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") } }
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 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 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()) }
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()) }
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()) }
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") } }
func oauthConfigSender() autorest.Sender { sender := mocks.NewSender() resp := mocks.NewResponseWithStatus("", http.StatusUnauthorized) mocks.SetResponseHeaderValues(resp, "WWW-Authenticate", []string{ `authorization_uri="https://testing.invalid/` + fakeTenantId + `"`, }) sender.AppendResponse(resp) return sender }
// 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 }
func TestDeviceCodeReturnsErrorIfSendingFails(t *testing.T) { sender := mocks.NewSender() sender.SetError(fmt.Errorf("this is an error")) client := &autorest.Client{Sender: sender} _, err := InitiateDeviceAuth(client, TestOAuthConfig, TestClientID, TestResource) if err == nil || !strings.Contains(err.Error(), errCodeSendingFails) { t.Fatalf("azure: failed to get correct error expected(%s) actual(%s)", errCodeSendingFails, err.Error()) } }
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 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 (*DiscoverySuite) TestDiscoverAuthorizationURIUnexpectedStatusCode(c *gc.C) { sender := mocks.NewSender() resp := mocks.NewResponseWithStatus("", http.StatusNotFound) sender.AppendResponse(resp) client := subscriptions.NewClient() client.Sender = sender _, err := azureauth.DiscoverAuthorizationURI(client, "subscription_id") c.Assert(err, gc.ErrorMatches, "expected unauthorized error response, got 404: .*") }
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 (*DiscoverySuite) TestDiscoverAuthorizationURIMissingHeader(c *gc.C) { sender := mocks.NewSender() resp := mocks.NewResponseWithStatus("", http.StatusUnauthorized) sender.AppendResponse(resp) client := subscriptions.NewClient() client.Sender = sender _, err := azureauth.DiscoverAuthorizationURI(client, "subscription_id") c.Assert(err, gc.ErrorMatches, `WWW-Authenticate header not found`) }
func TestDeviceTokenReturnsErrorIfSendingFails(t *testing.T) { sender := mocks.NewSender() sender.SetError(fmt.Errorf("this is an error")) client := &autorest.Client{Sender: sender} _, err := WaitForUserCompletion(client, deviceCode()) if err == nil || !strings.Contains(err.Error(), errTokenSendingFails) { t.Fatalf("azure: failed to get correct error expected(%s) actual(%s)", errTokenSendingFails, err.Error()) } }
func TestServicePrincipalTokenSetSender(t *testing.T) { spt := newServicePrincipalToken() var s autorest.Sender s = mocks.NewSender() spt.SetSender(s) if !reflect.DeepEqual(s, spt.sender) { t.Fatal("azure: ServicePrincipalToken#SetSender did not set the sender") } }
func (s *environSuite) TestAllInstancesResourceGroupNotFound(c *gc.C) { env := s.openEnviron(c) sender := mocks.NewSender() sender.AppendResponse(mocks.NewResponseWithStatus( "resource group not found", http.StatusNotFound, )) s.sender = azuretesting.Senders{sender} _, err := env.AllInstances() c.Assert(err, jc.ErrorIsNil) }
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 TestClientDoDoesNotSendIfPrepareFails(t *testing.T) { c := Client{} s := mocks.NewSender() c.Authorizer = mockFailingAuthorizer{} c.Sender = s c.Do(&http.Request{}) if s.Attempts() > 0 { t.Fatal("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 (s *environSuite) TestStopInstancesDeploymentNotFound(c *gc.C) { env := s.openEnviron(c) cancelSender := mocks.NewSender() cancelSender.AppendResponse(mocks.NewResponseWithStatus( "deployment not found", http.StatusNotFound, )) s.sender = azuretesting.Senders{cancelSender} err := env.StopInstances("machine-0") c.Assert(err, jc.ErrorIsNil) }
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 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 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") } }