github.com/jghiloni/cli@v6.28.1-0.20170628223758-0ce05fe032a2+incompatible/api/uaa/auth_test.go (about)

     1  package uaa_test
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  
     7  	. "code.cloudfoundry.org/cli/api/uaa"
     8  	"code.cloudfoundry.org/cli/integration/helpers"
     9  	. "github.com/onsi/ginkgo"
    10  	. "github.com/onsi/gomega"
    11  	. "github.com/onsi/gomega/ghttp"
    12  )
    13  
    14  var _ = Describe("Auth", func() {
    15  	var (
    16  		client *Client
    17  	)
    18  
    19  	BeforeEach(func() {
    20  		client = NewTestUAAClientAndStore()
    21  	})
    22  
    23  	Describe("Authenticate", func() {
    24  		Context("when no errors occur", func() {
    25  			var (
    26  				username string
    27  				password string
    28  			)
    29  
    30  			BeforeEach(func() {
    31  				response := `{
    32  						"access_token":"some-access-token",
    33  						"refresh_token":"some-refresh-token"
    34  					}`
    35  				username = helpers.RandomUsername()
    36  				password = helpers.RandomPassword()
    37  				server.AppendHandlers(
    38  					CombineHandlers(
    39  						VerifyRequest(http.MethodPost, "/oauth/token"),
    40  						VerifyHeaderKV("Content-Type", "application/x-www-form-urlencoded"),
    41  						VerifyHeaderKV("Authorization", "Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ="),
    42  						VerifyBody([]byte(fmt.Sprintf("grant_type=password&password=%s&username=%s", password, username))),
    43  						RespondWith(http.StatusOK, response),
    44  					))
    45  			})
    46  
    47  			It("authenticates with the credentials provided", func() {
    48  				accessToken, refreshToken, err := client.Authenticate(username, password)
    49  				Expect(err).NotTo(HaveOccurred())
    50  
    51  				Expect(accessToken).To(Equal("some-access-token"))
    52  				Expect(refreshToken).To(Equal("some-refresh-token"))
    53  			})
    54  		})
    55  
    56  		Context("when an error occurs", func() {
    57  			var response string
    58  
    59  			BeforeEach(func() {
    60  				response = `{
    61  						"error": "some-error",
    62  						"error_description": "some-description"
    63  					}`
    64  				server.AppendHandlers(
    65  					CombineHandlers(
    66  						VerifyRequest(http.MethodPost, "/oauth/token"),
    67  						RespondWith(http.StatusTeapot, response),
    68  					))
    69  			})
    70  
    71  			It("returns the error", func() {
    72  				_, _, err := client.Authenticate("us3r", "pa55")
    73  				Expect(err).To(MatchError(RawHTTPStatusError{
    74  					StatusCode:  http.StatusTeapot,
    75  					RawResponse: []byte(response),
    76  				}))
    77  			})
    78  		})
    79  	})
    80  })