blob: f8bbd9541cce58ed86e3439b131a0e913fcb2362 [file] [log] [blame]
Samuel A. Falvo IIfd78c302013-06-25 16:35:32 -07001package gophercloud
2
3import (
4 "testing"
Samuel A. Falvo II5d0d74c2013-06-25 17:23:18 -07005 "net/http"
6 "io/ioutil"
7 "strings"
Samuel A. Falvo IIfd78c302013-06-25 16:35:32 -07008)
9
Samuel A. Falvo II5d0d74c2013-06-25 17:23:18 -070010
11type testTransport struct {
12 called int
13 response string
14}
15
16func (t *testTransport) RoundTrip(req *http.Request) (rsp *http.Response, err error) {
17 t.called++;
18
19 headers := make(http.Header)
20 headers.Add("Content-Type", "application/xml; charset=UTF-8")
21
22 body := ioutil.NopCloser(strings.NewReader(t.response))
23
24 rsp = &http.Response{
25 Status: "200 OK",
26 StatusCode: 200,
27 Proto: "HTTP/1.1",
28 ProtoMajor: 1,
29 ProtoMinor: 1,
30 Header: headers,
31 Body: body,
32 ContentLength: -1,
33 TransferEncoding: nil,
34 Close: true,
35 Trailer: nil,
36 Request: req,
37 }
38 return
39}
40
Samuel A. Falvo IIfd78c302013-06-25 16:35:32 -070041func TestAuthProvider(t *testing.T) {
42 c := TestContext()
Samuel A. Falvo II5d0d74c2013-06-25 17:23:18 -070043 tt := &testTransport{}
44 c.UseCustomClient(&http.Client{
45 Transport: tt,
46 })
Samuel A. Falvo IIfd78c302013-06-25 16:35:32 -070047
48 _, err := c.Authenticate("", AuthOptions{})
49 if err == nil {
50 t.Error("Expected error for empty provider string")
51 return
52 }
53 _, err = c.Authenticate("unknown-provider", AuthOptions{Username: "u", Password: "p"})
54 if err == nil {
55 t.Error("Expected error for unknown service provider")
56 return
57 }
58
Samuel A. Falvo II5d0d74c2013-06-25 17:23:18 -070059 err = c.RegisterProvider("provider", &Provider{AuthEndpoint: "/"})
Samuel A. Falvo IIfd78c302013-06-25 16:35:32 -070060 if err != nil {
61 t.Error(err)
62 return
63 }
64 _, err = c.Authenticate("provider", AuthOptions{Username: "u", Password: "p"})
65 if err != nil {
66 t.Error(err)
67 return
68 }
Samuel A. Falvo II5d0d74c2013-06-25 17:23:18 -070069 if tt.called != 1 {
70 t.Error("Expected transport to be called once.")
71 return
72 }
Samuel A. Falvo IIfd78c302013-06-25 16:35:32 -070073}
74
75func TestUserNameAndPassword(t *testing.T) {
76 c := TestContext()
Samuel A. Falvo II5d0d74c2013-06-25 17:23:18 -070077 c.RegisterProvider("provider", &Provider{AuthEndpoint: "/"})
Samuel A. Falvo IIfd78c302013-06-25 16:35:32 -070078
79 auths := []AuthOptions{
80 AuthOptions{},
81 AuthOptions{Username: "u"},
82 AuthOptions{Password: "p"},
83 }
84 for i, auth := range auths {
85 _, err := c.Authenticate("provider", auth)
86 if err == nil {
87 t.Error("Expected error from missing credentials (%d)", i)
88 return
89 }
90 }
91
92 _, err := c.Authenticate("provider", AuthOptions{Username: "u", Password: "p"})
93 if err != nil {
94 t.Error(err)
95 return
96 }
97}