1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
|
// Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package utils_test
import (
"encoding/base64"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
gc "launchpad.net/gocheck"
"launchpad.net/juju-core/utils"
)
type httpSuite struct {
Server *httptest.Server
}
var _ = gc.Suite(&httpSuite{})
type trivialResponseHandler struct{}
func (t *trivialResponseHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Greetings!\n")
}
func (s *httpSuite) SetUpSuite(c *gc.C) {
}
func (s *httpSuite) TearDownSuite(c *gc.C) {
}
func (s *httpSuite) SetUpTest(c *gc.C) {
s.Server = httptest.NewTLSServer(&trivialResponseHandler{})
}
func (s *httpSuite) TearDownTest(c *gc.C) {
if s.Server != nil {
s.Server.Close()
}
}
func (s *httpSuite) TestDefaultClientFails(c *gc.C) {
_, err := http.Get(s.Server.URL)
c.Assert(err, gc.ErrorMatches, "(.|\n)*x509: certificate signed by unknown authority")
}
func (s *httpSuite) TestValidatingClientGetter(c *gc.C) {
client1 := utils.GetValidatingHTTPClient()
client2 := utils.GetHTTPClient(utils.VerifySSLHostnames)
c.Check(client1, gc.Equals, client2)
}
func (s *httpSuite) TestNonValidatingClientGetter(c *gc.C) {
client1 := utils.GetNonValidatingHTTPClient()
client2 := utils.GetHTTPClient(utils.NoVerifySSLHostnames)
c.Check(client1, gc.Equals, client2)
}
func (s *httpSuite) TestValidatingClientFails(c *gc.C) {
client := utils.GetValidatingHTTPClient()
_, err := client.Get(s.Server.URL)
c.Assert(err, gc.ErrorMatches, "(.|\n)*x509: certificate signed by unknown authority")
}
func (s *httpSuite) TestInsecureClientSucceeds(c *gc.C) {
response, err := utils.GetNonValidatingHTTPClient().Get(s.Server.URL)
c.Assert(err, gc.IsNil)
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
c.Assert(err, gc.IsNil)
c.Check(string(body), gc.Equals, "Greetings!\n")
}
func (s *httpSuite) TestInsecureClientCached(c *gc.C) {
client1 := utils.GetNonValidatingHTTPClient()
client2 := utils.GetNonValidatingHTTPClient()
c.Check(client1, gc.Equals, client2)
}
func (s *httpSuite) TestBasicAuthHeader(c *gc.C) {
header := utils.BasicAuthHeader("eric", "sekrit")
c.Assert(len(header), gc.Equals, 1)
auth := header.Get("Authorization")
fields := strings.Fields(auth)
c.Assert(len(fields), gc.Equals, 2)
basic, encoded := fields[0], fields[1]
c.Assert(basic, gc.Equals, "Basic")
decoded, err := base64.StdEncoding.DecodeString(encoded)
c.Assert(err, gc.IsNil)
c.Assert(string(decoded), gc.Equals, "eric:sekrit")
}
|