Statistics
| Branch: | Tag: | Revision:

root / test / ganeti.http_unittest.py @ 26d3fd2f

History | View | Annotate | Download (14.6 kB)

1 a0638838 Oleksiy Mishchenko
#!/usr/bin/python
2 a0638838 Oleksiy Mishchenko
#
3 a0638838 Oleksiy Mishchenko
4 a0638838 Oleksiy Mishchenko
# Copyright (C) 2007, 2008 Google Inc.
5 a0638838 Oleksiy Mishchenko
#
6 a0638838 Oleksiy Mishchenko
# This program is free software; you can redistribute it and/or modify
7 a0638838 Oleksiy Mishchenko
# it under the terms of the GNU General Public License as published by
8 a0638838 Oleksiy Mishchenko
# the Free Software Foundation; either version 2 of the License, or
9 a0638838 Oleksiy Mishchenko
# (at your option) any later version.
10 a0638838 Oleksiy Mishchenko
#
11 a0638838 Oleksiy Mishchenko
# This program is distributed in the hope that it will be useful, but
12 a0638838 Oleksiy Mishchenko
# WITHOUT ANY WARRANTY; without even the implied warranty of
13 a0638838 Oleksiy Mishchenko
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 a0638838 Oleksiy Mishchenko
# General Public License for more details.
15 a0638838 Oleksiy Mishchenko
#
16 a0638838 Oleksiy Mishchenko
# You should have received a copy of the GNU General Public License
17 a0638838 Oleksiy Mishchenko
# along with this program; if not, write to the Free Software
18 a0638838 Oleksiy Mishchenko
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 a0638838 Oleksiy Mishchenko
# 02110-1301, USA.
20 a0638838 Oleksiy Mishchenko
21 a0638838 Oleksiy Mishchenko
22 a0638838 Oleksiy Mishchenko
"""Script for unittesting the http module"""
23 a0638838 Oleksiy Mishchenko
24 a0638838 Oleksiy Mishchenko
25 a0638838 Oleksiy Mishchenko
import os
26 a0638838 Oleksiy Mishchenko
import unittest
27 a0638838 Oleksiy Mishchenko
import time
28 a8950eb7 Michael Hanselmann
import tempfile
29 a0638838 Oleksiy Mishchenko
30 a0638838 Oleksiy Mishchenko
from ganeti import http
31 a0638838 Oleksiy Mishchenko
32 f30ca1e6 Michael Hanselmann
import ganeti.http.server
33 f30ca1e6 Michael Hanselmann
import ganeti.http.client
34 bf9bd8dd Michael Hanselmann
import ganeti.http.auth
35 a0638838 Oleksiy Mishchenko
36 25231ec5 Michael Hanselmann
import testutils
37 25231ec5 Michael Hanselmann
38 f30ca1e6 Michael Hanselmann
39 f30ca1e6 Michael Hanselmann
class TestStartLines(unittest.TestCase):
40 f30ca1e6 Michael Hanselmann
  """Test cases for start line classes"""
41 f30ca1e6 Michael Hanselmann
42 f30ca1e6 Michael Hanselmann
  def testClientToServerStartLine(self):
43 f30ca1e6 Michael Hanselmann
    """Test client to server start line (HTTP request)"""
44 f30ca1e6 Michael Hanselmann
    start_line = http.HttpClientToServerStartLine("GET", "/", "HTTP/1.1")
45 f30ca1e6 Michael Hanselmann
    self.assertEqual(str(start_line), "GET / HTTP/1.1")
46 f30ca1e6 Michael Hanselmann
47 f30ca1e6 Michael Hanselmann
  def testServerToClientStartLine(self):
48 f30ca1e6 Michael Hanselmann
    """Test server to client start line (HTTP response)"""
49 f30ca1e6 Michael Hanselmann
    start_line = http.HttpServerToClientStartLine("HTTP/1.1", 200, "OK")
50 f30ca1e6 Michael Hanselmann
    self.assertEqual(str(start_line), "HTTP/1.1 200 OK")
51 f30ca1e6 Michael Hanselmann
52 f30ca1e6 Michael Hanselmann
53 f30ca1e6 Michael Hanselmann
class TestMisc(unittest.TestCase):
54 f30ca1e6 Michael Hanselmann
  """Miscellaneous tests"""
55 f30ca1e6 Michael Hanselmann
56 f30ca1e6 Michael Hanselmann
  def _TestDateTimeHeader(self, gmnow, expected):
57 f30ca1e6 Michael Hanselmann
    self.assertEqual(http.server._DateTimeHeader(gmnow=gmnow), expected)
58 f30ca1e6 Michael Hanselmann
59 f30ca1e6 Michael Hanselmann
  def testDateTimeHeader(self):
60 f30ca1e6 Michael Hanselmann
    """Test ganeti.http._DateTimeHeader"""
61 f30ca1e6 Michael Hanselmann
    self._TestDateTimeHeader((2008, 1, 2, 3, 4, 5, 3, 0, 0),
62 f30ca1e6 Michael Hanselmann
                             "Thu, 02 Jan 2008 03:04:05 GMT")
63 f30ca1e6 Michael Hanselmann
    self._TestDateTimeHeader((2008, 1, 1, 0, 0, 0, 0, 0, 0),
64 f30ca1e6 Michael Hanselmann
                             "Mon, 01 Jan 2008 00:00:00 GMT")
65 f30ca1e6 Michael Hanselmann
    self._TestDateTimeHeader((2008, 12, 31, 0, 0, 0, 0, 0, 0),
66 f30ca1e6 Michael Hanselmann
                             "Mon, 31 Dec 2008 00:00:00 GMT")
67 f30ca1e6 Michael Hanselmann
    self._TestDateTimeHeader((2008, 12, 31, 23, 59, 59, 0, 0, 0),
68 f30ca1e6 Michael Hanselmann
                             "Mon, 31 Dec 2008 23:59:59 GMT")
69 f30ca1e6 Michael Hanselmann
    self._TestDateTimeHeader((2008, 12, 31, 0, 0, 0, 6, 0, 0),
70 f30ca1e6 Michael Hanselmann
                             "Sun, 31 Dec 2008 00:00:00 GMT")
71 f30ca1e6 Michael Hanselmann
72 f30ca1e6 Michael Hanselmann
  def testHttpServerRequest(self):
73 f30ca1e6 Michael Hanselmann
    """Test ganeti.http.server._HttpServerRequest"""
74 a8950eb7 Michael Hanselmann
    server_request = http.server._HttpServerRequest("GET", "/", None, None)
75 f30ca1e6 Michael Hanselmann
76 f30ca1e6 Michael Hanselmann
    # These are expected by users of the HTTP server
77 f30ca1e6 Michael Hanselmann
    self.assert_(hasattr(server_request, "request_method"))
78 f30ca1e6 Michael Hanselmann
    self.assert_(hasattr(server_request, "request_path"))
79 f30ca1e6 Michael Hanselmann
    self.assert_(hasattr(server_request, "request_headers"))
80 f30ca1e6 Michael Hanselmann
    self.assert_(hasattr(server_request, "request_body"))
81 f30ca1e6 Michael Hanselmann
    self.assert_(isinstance(server_request.resp_headers, dict))
82 68fa9caf Michael Hanselmann
    self.assert_(hasattr(server_request, "private"))
83 f30ca1e6 Michael Hanselmann
84 f30ca1e6 Michael Hanselmann
  def testServerSizeLimits(self):
85 f30ca1e6 Michael Hanselmann
    """Test HTTP server size limits"""
86 f30ca1e6 Michael Hanselmann
    message_reader_class = http.server._HttpClientToServerMessageReader
87 f30ca1e6 Michael Hanselmann
    self.assert_(message_reader_class.START_LINE_LENGTH_MAX > 0)
88 f30ca1e6 Michael Hanselmann
    self.assert_(message_reader_class.HEADER_LENGTH_MAX > 0)
89 f30ca1e6 Michael Hanselmann
90 a8950eb7 Michael Hanselmann
  def testFormatAuthHeader(self):
91 a8950eb7 Michael Hanselmann
    self.assertEqual(http.auth._FormatAuthHeader("Basic", {}),
92 a8950eb7 Michael Hanselmann
                     "Basic")
93 a8950eb7 Michael Hanselmann
    self.assertEqual(http.auth._FormatAuthHeader("Basic", { "foo": "bar", }),
94 a8950eb7 Michael Hanselmann
                     "Basic foo=bar")
95 a8950eb7 Michael Hanselmann
    self.assertEqual(http.auth._FormatAuthHeader("Basic", { "foo": "", }),
96 a8950eb7 Michael Hanselmann
                     "Basic foo=\"\"")
97 a8950eb7 Michael Hanselmann
    self.assertEqual(http.auth._FormatAuthHeader("Basic", { "foo": "x,y", }),
98 a8950eb7 Michael Hanselmann
                     "Basic foo=\"x,y\"")
99 a8950eb7 Michael Hanselmann
    params = {
100 a8950eb7 Michael Hanselmann
      "foo": "x,y",
101 a8950eb7 Michael Hanselmann
      "realm": "secure",
102 a8950eb7 Michael Hanselmann
      }
103 a8950eb7 Michael Hanselmann
    # It's a dict whose order isn't guaranteed, hence checking a list
104 a8950eb7 Michael Hanselmann
    self.assert_(http.auth._FormatAuthHeader("Digest", params) in
105 a8950eb7 Michael Hanselmann
                 ("Digest foo=\"x,y\" realm=secure",
106 a8950eb7 Michael Hanselmann
                  "Digest realm=secure foo=\"x,y\""))
107 a8950eb7 Michael Hanselmann
108 a0638838 Oleksiy Mishchenko
109 bf9bd8dd Michael Hanselmann
class _FakeRequestAuth(http.auth.HttpServerRequestAuthentication):
110 a8950eb7 Michael Hanselmann
  def __init__(self, realm, authreq, authenticate_fn):
111 bf9bd8dd Michael Hanselmann
    http.auth.HttpServerRequestAuthentication.__init__(self)
112 bf9bd8dd Michael Hanselmann
113 bf9bd8dd Michael Hanselmann
    self.realm = realm
114 a8950eb7 Michael Hanselmann
    self.authreq = authreq
115 a8950eb7 Michael Hanselmann
    self.authenticate_fn = authenticate_fn
116 a8950eb7 Michael Hanselmann
117 a8950eb7 Michael Hanselmann
  def AuthenticationRequired(self, req):
118 a8950eb7 Michael Hanselmann
    return self.authreq
119 bf9bd8dd Michael Hanselmann
120 bf9bd8dd Michael Hanselmann
  def GetAuthRealm(self, req):
121 bf9bd8dd Michael Hanselmann
    return self.realm
122 bf9bd8dd Michael Hanselmann
123 a8950eb7 Michael Hanselmann
  def Authenticate(self, *args):
124 a8950eb7 Michael Hanselmann
    if self.authenticate_fn:
125 a8950eb7 Michael Hanselmann
      return self.authenticate_fn(*args)
126 a8950eb7 Michael Hanselmann
    raise NotImplementedError()
127 a8950eb7 Michael Hanselmann
128 bf9bd8dd Michael Hanselmann
129 bf9bd8dd Michael Hanselmann
class TestAuth(unittest.TestCase):
130 bf9bd8dd Michael Hanselmann
  """Authentication tests"""
131 bf9bd8dd Michael Hanselmann
132 bf9bd8dd Michael Hanselmann
  hsra = http.auth.HttpServerRequestAuthentication
133 bf9bd8dd Michael Hanselmann
134 bf9bd8dd Michael Hanselmann
  def testConstants(self):
135 a8950eb7 Michael Hanselmann
    for scheme in [self.hsra._CLEARTEXT_SCHEME, self.hsra._HA1_SCHEME]:
136 a8950eb7 Michael Hanselmann
      self.assertEqual(scheme, scheme.upper())
137 a8950eb7 Michael Hanselmann
      self.assert_(scheme.startswith("{"))
138 a8950eb7 Michael Hanselmann
      self.assert_(scheme.endswith("}"))
139 bf9bd8dd Michael Hanselmann
140 bf9bd8dd Michael Hanselmann
  def _testVerifyBasicAuthPassword(self, realm, user, password, expected):
141 a8950eb7 Michael Hanselmann
    ra = _FakeRequestAuth(realm, False, None)
142 bf9bd8dd Michael Hanselmann
143 bf9bd8dd Michael Hanselmann
    return ra.VerifyBasicAuthPassword(None, user, password, expected)
144 bf9bd8dd Michael Hanselmann
145 bf9bd8dd Michael Hanselmann
  def testVerifyBasicAuthPassword(self):
146 bf9bd8dd Michael Hanselmann
    tvbap = self._testVerifyBasicAuthPassword
147 bf9bd8dd Michael Hanselmann
148 bf9bd8dd Michael Hanselmann
    good_pws = ["pw", "pw{", "pw}", "pw{}", "pw{x}y", "}pw",
149 bf9bd8dd Michael Hanselmann
                "0", "123", "foo...:xyz", "TeST"]
150 bf9bd8dd Michael Hanselmann
151 bf9bd8dd Michael Hanselmann
    for pw in good_pws:
152 bf9bd8dd Michael Hanselmann
      # Try cleartext passwords
153 bf9bd8dd Michael Hanselmann
      self.assert_(tvbap("abc", "user", pw, pw))
154 bf9bd8dd Michael Hanselmann
      self.assert_(tvbap("abc", "user", pw, "{cleartext}" + pw))
155 bf9bd8dd Michael Hanselmann
      self.assert_(tvbap("abc", "user", pw, "{ClearText}" + pw))
156 bf9bd8dd Michael Hanselmann
      self.assert_(tvbap("abc", "user", pw, "{CLEARTEXT}" + pw))
157 bf9bd8dd Michael Hanselmann
158 bf9bd8dd Michael Hanselmann
      # Try with invalid password
159 bf9bd8dd Michael Hanselmann
      self.failIf(tvbap("abc", "user", pw, "something"))
160 bf9bd8dd Michael Hanselmann
161 bf9bd8dd Michael Hanselmann
      # Try with invalid scheme
162 bf9bd8dd Michael Hanselmann
      self.failIf(tvbap("abc", "user", pw, "{000}" + pw))
163 bf9bd8dd Michael Hanselmann
      self.failIf(tvbap("abc", "user", pw, "{unk}" + pw))
164 bf9bd8dd Michael Hanselmann
      self.failIf(tvbap("abc", "user", pw, "{Unk}" + pw))
165 bf9bd8dd Michael Hanselmann
      self.failIf(tvbap("abc", "user", pw, "{UNK}" + pw))
166 bf9bd8dd Michael Hanselmann
167 bf9bd8dd Michael Hanselmann
    # Try with invalid scheme format
168 bf9bd8dd Michael Hanselmann
    self.failIf(tvbap("abc", "user", "pw", "{something"))
169 bf9bd8dd Michael Hanselmann
170 bf9bd8dd Michael Hanselmann
    # Hash is MD5("user:This is only a test:pw")
171 bf9bd8dd Michael Hanselmann
    self.assert_(tvbap("This is only a test", "user", "pw",
172 bf9bd8dd Michael Hanselmann
                       "{ha1}92ea58ae804481498c257b2f65561a17"))
173 bf9bd8dd Michael Hanselmann
    self.assert_(tvbap("This is only a test", "user", "pw",
174 bf9bd8dd Michael Hanselmann
                       "{HA1}92ea58ae804481498c257b2f65561a17"))
175 bf9bd8dd Michael Hanselmann
176 23ccba04 Michael Hanselmann
    self.failUnlessRaises(AssertionError, tvbap, None, "user", "pw",
177 23ccba04 Michael Hanselmann
                          "{HA1}92ea58ae804481498c257b2f65561a17")
178 bf9bd8dd Michael Hanselmann
    self.failIf(tvbap("Admin area", "user", "pw",
179 bf9bd8dd Michael Hanselmann
                      "{HA1}92ea58ae804481498c257b2f65561a17"))
180 bf9bd8dd Michael Hanselmann
    self.failIf(tvbap("This is only a test", "someone", "pw",
181 bf9bd8dd Michael Hanselmann
                      "{HA1}92ea58ae804481498c257b2f65561a17"))
182 bf9bd8dd Michael Hanselmann
    self.failIf(tvbap("This is only a test", "user", "something",
183 bf9bd8dd Michael Hanselmann
                      "{HA1}92ea58ae804481498c257b2f65561a17"))
184 bf9bd8dd Michael Hanselmann
185 bf9bd8dd Michael Hanselmann
186 a8950eb7 Michael Hanselmann
class _SimpleAuthenticator:
187 a8950eb7 Michael Hanselmann
  def __init__(self, user, password):
188 a8950eb7 Michael Hanselmann
    self.user = user
189 a8950eb7 Michael Hanselmann
    self.password = password
190 a8950eb7 Michael Hanselmann
    self.called = False
191 a8950eb7 Michael Hanselmann
192 a8950eb7 Michael Hanselmann
  def __call__(self, req, user, password):
193 a8950eb7 Michael Hanselmann
    self.called = True
194 a8950eb7 Michael Hanselmann
    return self.user == user and self.password == password
195 a8950eb7 Michael Hanselmann
196 a8950eb7 Michael Hanselmann
197 a8950eb7 Michael Hanselmann
class TestHttpServerRequestAuthentication(unittest.TestCase):
198 a8950eb7 Michael Hanselmann
  def testNoAuth(self):
199 a8950eb7 Michael Hanselmann
    req = http.server._HttpServerRequest("GET", "/", None, None)
200 a8950eb7 Michael Hanselmann
    _FakeRequestAuth("area1", False, None).PreHandleRequest(req)
201 a8950eb7 Michael Hanselmann
202 a8950eb7 Michael Hanselmann
  def testNoRealm(self):
203 a8950eb7 Michael Hanselmann
    headers = { http.HTTP_AUTHORIZATION: "", }
204 a8950eb7 Michael Hanselmann
    req = http.server._HttpServerRequest("GET", "/", headers, None)
205 a8950eb7 Michael Hanselmann
    ra = _FakeRequestAuth(None, False, None)
206 a8950eb7 Michael Hanselmann
    self.assertRaises(AssertionError, ra.PreHandleRequest, req)
207 a8950eb7 Michael Hanselmann
208 a8950eb7 Michael Hanselmann
  def testNoScheme(self):
209 a8950eb7 Michael Hanselmann
    headers = { http.HTTP_AUTHORIZATION: "", }
210 a8950eb7 Michael Hanselmann
    req = http.server._HttpServerRequest("GET", "/", headers, None)
211 a8950eb7 Michael Hanselmann
    ra = _FakeRequestAuth("area1", False, None)
212 a8950eb7 Michael Hanselmann
    self.assertRaises(http.HttpUnauthorized, ra.PreHandleRequest, req)
213 a8950eb7 Michael Hanselmann
214 a8950eb7 Michael Hanselmann
  def testUnknownScheme(self):
215 a8950eb7 Michael Hanselmann
    headers = { http.HTTP_AUTHORIZATION: "NewStyleAuth abc", }
216 a8950eb7 Michael Hanselmann
    req = http.server._HttpServerRequest("GET", "/", headers, None)
217 a8950eb7 Michael Hanselmann
    ra = _FakeRequestAuth("area1", False, None)
218 a8950eb7 Michael Hanselmann
    self.assertRaises(http.HttpUnauthorized, ra.PreHandleRequest, req)
219 a8950eb7 Michael Hanselmann
220 a8950eb7 Michael Hanselmann
  def testInvalidBase64(self):
221 a8950eb7 Michael Hanselmann
    headers = { http.HTTP_AUTHORIZATION: "Basic x_=_", }
222 a8950eb7 Michael Hanselmann
    req = http.server._HttpServerRequest("GET", "/", headers, None)
223 a8950eb7 Michael Hanselmann
    ra = _FakeRequestAuth("area1", False, None)
224 a8950eb7 Michael Hanselmann
    self.assertRaises(http.HttpUnauthorized, ra.PreHandleRequest, req)
225 a8950eb7 Michael Hanselmann
226 a8950eb7 Michael Hanselmann
  def testAuthForPublicResource(self):
227 a8950eb7 Michael Hanselmann
    headers = {
228 a8950eb7 Michael Hanselmann
      http.HTTP_AUTHORIZATION: "Basic %s" % ("foo".encode("base64").strip(), ),
229 a8950eb7 Michael Hanselmann
      }
230 a8950eb7 Michael Hanselmann
    req = http.server._HttpServerRequest("GET", "/", headers, None)
231 a8950eb7 Michael Hanselmann
    ra = _FakeRequestAuth("area1", False, None)
232 a8950eb7 Michael Hanselmann
    self.assertRaises(http.HttpUnauthorized, ra.PreHandleRequest, req)
233 a8950eb7 Michael Hanselmann
234 a8950eb7 Michael Hanselmann
  def testAuthForPublicResource(self):
235 a8950eb7 Michael Hanselmann
    headers = {
236 a8950eb7 Michael Hanselmann
      http.HTTP_AUTHORIZATION:
237 a8950eb7 Michael Hanselmann
        "Basic %s" % ("foo:bar".encode("base64").strip(), ),
238 a8950eb7 Michael Hanselmann
      }
239 a8950eb7 Michael Hanselmann
    req = http.server._HttpServerRequest("GET", "/", headers, None)
240 a8950eb7 Michael Hanselmann
    ac = _SimpleAuthenticator("foo", "bar")
241 a8950eb7 Michael Hanselmann
    ra = _FakeRequestAuth("area1", False, ac)
242 a8950eb7 Michael Hanselmann
    ra.PreHandleRequest(req)
243 a8950eb7 Michael Hanselmann
244 a8950eb7 Michael Hanselmann
    req = http.server._HttpServerRequest("GET", "/", headers, None)
245 a8950eb7 Michael Hanselmann
    ac = _SimpleAuthenticator("something", "else")
246 a8950eb7 Michael Hanselmann
    ra = _FakeRequestAuth("area1", False, ac)
247 a8950eb7 Michael Hanselmann
    self.assertRaises(http.HttpUnauthorized, ra.PreHandleRequest, req)
248 a8950eb7 Michael Hanselmann
249 a8950eb7 Michael Hanselmann
  def testInvalidRequestHeader(self):
250 a8950eb7 Michael Hanselmann
    checks = {
251 a8950eb7 Michael Hanselmann
      http.HttpUnauthorized: ["", "\t", "-", ".", "@", "<", ">", "Digest",
252 a8950eb7 Michael Hanselmann
                              "basic %s" % "foobar".encode("base64").strip()],
253 a8950eb7 Michael Hanselmann
      http.HttpBadRequest: ["Basic"],
254 a8950eb7 Michael Hanselmann
      }
255 a8950eb7 Michael Hanselmann
256 a8950eb7 Michael Hanselmann
    for exc, headers in checks.items():
257 a8950eb7 Michael Hanselmann
      for i in headers:
258 a8950eb7 Michael Hanselmann
        headers = { http.HTTP_AUTHORIZATION: i, }
259 a8950eb7 Michael Hanselmann
        req = http.server._HttpServerRequest("GET", "/", headers, None)
260 a8950eb7 Michael Hanselmann
        ra = _FakeRequestAuth("area1", False, None)
261 a8950eb7 Michael Hanselmann
        self.assertRaises(exc, ra.PreHandleRequest, req)
262 a8950eb7 Michael Hanselmann
263 a8950eb7 Michael Hanselmann
  def testBasicAuth(self):
264 a8950eb7 Michael Hanselmann
    for user in ["", "joe", "user name with spaces"]:
265 a8950eb7 Michael Hanselmann
      for pw in ["", "-", ":", "foobar", "Foo Bar Baz", "@@@", "###",
266 a8950eb7 Michael Hanselmann
                 "foo:bar:baz"]:
267 a8950eb7 Michael Hanselmann
        for wrong_pw in [True, False]:
268 a8950eb7 Michael Hanselmann
          basic_auth = "%s:%s" % (user, pw)
269 a8950eb7 Michael Hanselmann
          if wrong_pw:
270 a8950eb7 Michael Hanselmann
            basic_auth += "WRONG"
271 a8950eb7 Michael Hanselmann
          headers = {
272 a8950eb7 Michael Hanselmann
              http.HTTP_AUTHORIZATION:
273 a8950eb7 Michael Hanselmann
                "Basic %s" % (basic_auth.encode("base64").strip(), ),
274 a8950eb7 Michael Hanselmann
            }
275 a8950eb7 Michael Hanselmann
          req = http.server._HttpServerRequest("GET", "/", headers, None)
276 a8950eb7 Michael Hanselmann
277 a8950eb7 Michael Hanselmann
          ac = _SimpleAuthenticator(user, pw)
278 a8950eb7 Michael Hanselmann
          self.assertFalse(ac.called)
279 a8950eb7 Michael Hanselmann
          ra = _FakeRequestAuth("area1", True, ac)
280 a8950eb7 Michael Hanselmann
          if wrong_pw:
281 a8950eb7 Michael Hanselmann
            try:
282 a8950eb7 Michael Hanselmann
              ra.PreHandleRequest(req)
283 a8950eb7 Michael Hanselmann
            except http.HttpUnauthorized, err:
284 a8950eb7 Michael Hanselmann
              www_auth = err.headers[http.HTTP_WWW_AUTHENTICATE]
285 a8950eb7 Michael Hanselmann
              self.assert_(www_auth.startswith(http.auth.HTTP_BASIC_AUTH))
286 a8950eb7 Michael Hanselmann
            else:
287 a8950eb7 Michael Hanselmann
              self.fail("Didn't raise HttpUnauthorized")
288 a8950eb7 Michael Hanselmann
          else:
289 a8950eb7 Michael Hanselmann
            ra.PreHandleRequest(req)
290 a8950eb7 Michael Hanselmann
          self.assert_(ac.called)
291 a8950eb7 Michael Hanselmann
292 a8950eb7 Michael Hanselmann
293 a8950eb7 Michael Hanselmann
class TestReadPasswordFile(testutils.GanetiTestCase):
294 a8950eb7 Michael Hanselmann
  def setUp(self):
295 a8950eb7 Michael Hanselmann
    testutils.GanetiTestCase.setUp(self)
296 a8950eb7 Michael Hanselmann
297 a8950eb7 Michael Hanselmann
    self.tmpfile = tempfile.NamedTemporaryFile()
298 a8950eb7 Michael Hanselmann
299 a8950eb7 Michael Hanselmann
  def testSimple(self):
300 a8950eb7 Michael Hanselmann
    self.tmpfile.write("user1 password")
301 a8950eb7 Michael Hanselmann
    self.tmpfile.flush()
302 a8950eb7 Michael Hanselmann
303 a8950eb7 Michael Hanselmann
    users = http.auth.ReadPasswordFile(self.tmpfile.name)
304 a8950eb7 Michael Hanselmann
    self.assertEqual(len(users), 1)
305 a8950eb7 Michael Hanselmann
    self.assertEqual(users["user1"].password, "password")
306 a8950eb7 Michael Hanselmann
    self.assertEqual(len(users["user1"].options), 0)
307 a8950eb7 Michael Hanselmann
308 a8950eb7 Michael Hanselmann
  def testOptions(self):
309 a8950eb7 Michael Hanselmann
    self.tmpfile.write("# Passwords\n")
310 a8950eb7 Michael Hanselmann
    self.tmpfile.write("user1 password\n")
311 a8950eb7 Michael Hanselmann
    self.tmpfile.write("\n")
312 a8950eb7 Michael Hanselmann
    self.tmpfile.write("# Comment\n")
313 a8950eb7 Michael Hanselmann
    self.tmpfile.write("user2 pw write,read\n")
314 a8950eb7 Michael Hanselmann
    self.tmpfile.write("   \t# Another comment\n")
315 a8950eb7 Michael Hanselmann
    self.tmpfile.write("invalidline\n")
316 a8950eb7 Michael Hanselmann
    self.tmpfile.flush()
317 a8950eb7 Michael Hanselmann
318 a8950eb7 Michael Hanselmann
    users = http.auth.ReadPasswordFile(self.tmpfile.name)
319 a8950eb7 Michael Hanselmann
    self.assertEqual(len(users), 2)
320 a8950eb7 Michael Hanselmann
    self.assertEqual(users["user1"].password, "password")
321 a8950eb7 Michael Hanselmann
    self.assertEqual(len(users["user1"].options), 0)
322 a8950eb7 Michael Hanselmann
323 a8950eb7 Michael Hanselmann
    self.assertEqual(users["user2"].password, "pw")
324 a8950eb7 Michael Hanselmann
    self.assertEqual(users["user2"].options, ["write", "read"])
325 a8950eb7 Michael Hanselmann
326 a8950eb7 Michael Hanselmann
327 33231500 Michael Hanselmann
class TestClientRequest(unittest.TestCase):
328 33231500 Michael Hanselmann
  def testRepr(self):
329 33231500 Michael Hanselmann
    cr = http.client.HttpClientRequest("localhost", 1234, "GET", "/version",
330 33231500 Michael Hanselmann
                                       headers=[], post_data="Hello World")
331 33231500 Michael Hanselmann
    self.assert_(repr(cr).startswith("<"))
332 33231500 Michael Hanselmann
333 33231500 Michael Hanselmann
  def testNoHeaders(self):
334 33231500 Michael Hanselmann
    cr = http.client.HttpClientRequest("localhost", 1234, "GET", "/version",
335 33231500 Michael Hanselmann
                                       headers=None)
336 33231500 Michael Hanselmann
    self.assert_(isinstance(cr.headers, list))
337 33231500 Michael Hanselmann
    self.assertEqual(cr.headers, [])
338 33231500 Michael Hanselmann
    self.assertEqual(cr.url, "https://localhost:1234/version")
339 33231500 Michael Hanselmann
340 33231500 Michael Hanselmann
  def testOldStyleHeaders(self):
341 33231500 Michael Hanselmann
    headers = {
342 33231500 Michael Hanselmann
      "Content-type": "text/plain",
343 33231500 Michael Hanselmann
      "Accept": "text/html",
344 33231500 Michael Hanselmann
      }
345 33231500 Michael Hanselmann
    cr = http.client.HttpClientRequest("localhost", 16481, "GET", "/vg_list",
346 33231500 Michael Hanselmann
                                       headers=headers)
347 33231500 Michael Hanselmann
    self.assert_(isinstance(cr.headers, list))
348 33231500 Michael Hanselmann
    self.assertEqual(sorted(cr.headers), [
349 33231500 Michael Hanselmann
      "Accept: text/html",
350 33231500 Michael Hanselmann
      "Content-type: text/plain",
351 33231500 Michael Hanselmann
      ])
352 33231500 Michael Hanselmann
    self.assertEqual(cr.url, "https://localhost:16481/vg_list")
353 33231500 Michael Hanselmann
354 33231500 Michael Hanselmann
  def testNewStyleHeaders(self):
355 33231500 Michael Hanselmann
    headers = [
356 33231500 Michael Hanselmann
      "Accept: text/html",
357 33231500 Michael Hanselmann
      "Content-type: text/plain; charset=ascii",
358 33231500 Michael Hanselmann
      "Server: httpd 1.0",
359 33231500 Michael Hanselmann
      ]
360 33231500 Michael Hanselmann
    cr = http.client.HttpClientRequest("localhost", 1234, "GET", "/version",
361 33231500 Michael Hanselmann
                                       headers=headers)
362 33231500 Michael Hanselmann
    self.assert_(isinstance(cr.headers, list))
363 33231500 Michael Hanselmann
    self.assertEqual(sorted(cr.headers), sorted(headers))
364 33231500 Michael Hanselmann
    self.assertEqual(cr.url, "https://localhost:1234/version")
365 33231500 Michael Hanselmann
366 33231500 Michael Hanselmann
  def testPostData(self):
367 33231500 Michael Hanselmann
    cr = http.client.HttpClientRequest("localhost", 1234, "GET", "/version",
368 33231500 Michael Hanselmann
                                       post_data="Hello World")
369 33231500 Michael Hanselmann
    self.assertEqual(cr.post_data, "Hello World")
370 33231500 Michael Hanselmann
371 33231500 Michael Hanselmann
  def testNoPostData(self):
372 33231500 Michael Hanselmann
    cr = http.client.HttpClientRequest("localhost", 1234, "GET", "/version")
373 33231500 Michael Hanselmann
    self.assertEqual(cr.post_data, "")
374 33231500 Michael Hanselmann
375 33231500 Michael Hanselmann
  def testIdentity(self):
376 33231500 Michael Hanselmann
    # These should all use different connections, hence also have a different
377 33231500 Michael Hanselmann
    # identity
378 33231500 Michael Hanselmann
    cr1 = http.client.HttpClientRequest("localhost", 1234, "GET", "/version")
379 33231500 Michael Hanselmann
    cr2 = http.client.HttpClientRequest("localhost", 9999, "GET", "/version")
380 33231500 Michael Hanselmann
    cr3 = http.client.HttpClientRequest("node1", 1234, "GET", "/version")
381 33231500 Michael Hanselmann
    cr4 = http.client.HttpClientRequest("node1", 9999, "GET", "/version")
382 33231500 Michael Hanselmann
383 33231500 Michael Hanselmann
    self.assertEqual(len(set([cr1.identity, cr2.identity,
384 33231500 Michael Hanselmann
                              cr3.identity, cr4.identity])), 4)
385 33231500 Michael Hanselmann
386 33231500 Michael Hanselmann
    # But this one should have the same
387 33231500 Michael Hanselmann
    cr1vglist = http.client.HttpClientRequest("localhost", 1234,
388 33231500 Michael Hanselmann
                                              "GET", "/vg_list")
389 33231500 Michael Hanselmann
    self.assertEqual(cr1.identity, cr1vglist.identity)
390 33231500 Michael Hanselmann
391 33231500 Michael Hanselmann
392 33231500 Michael Hanselmann
class TestClient(unittest.TestCase):
393 33231500 Michael Hanselmann
  def test(self):
394 33231500 Michael Hanselmann
    pool = http.client.HttpClientPool(None)
395 33231500 Michael Hanselmann
    self.assertFalse(pool._pool)
396 33231500 Michael Hanselmann
397 33231500 Michael Hanselmann
398 a0638838 Oleksiy Mishchenko
if __name__ == '__main__':
399 25231ec5 Michael Hanselmann
  testutils.GanetiTestProgram()