예제 #1
0
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
}
예제 #2
0
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())
}
예제 #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.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)
	}
}
예제 #4
0
파일: environ_test.go 프로젝트: makyo/juju
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)
}
예제 #5
0
파일: environ_test.go 프로젝트: makyo/juju
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)
}
예제 #6
0
파일: senders.go 프로젝트: imoapps/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.EmitContent(string(content))
	return sender
}
예제 #7
0
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")
	}
}
예제 #8
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")
	}
}
예제 #9
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")
	}
}
예제 #10
0
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")
	}
}
예제 #11
0
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")
	}
}
예제 #12
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")
	}
}
예제 #13
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())
	}
}
예제 #14
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")
	}
}
예제 #15
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)
	}
}
예제 #16
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")
	}
}
예제 #17
0
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")
	}
}
예제 #18
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())
	}
}
예제 #19
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)
	}
}
예제 #20
0
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)
}
예제 #21
0
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)))
	}
}
예제 #22
0
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")
	}
}
예제 #23
0
파일: environ_test.go 프로젝트: makyo/juju
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")
}
예제 #24
0
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())
	}
}
예제 #25
0
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")
	}
}
예제 #26
0
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())
}
예제 #27
0
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())
}
예제 #28
0
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")
	}
}
예제 #29
0
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")
	}
}
예제 #30
0
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())
}