OpenStack Compute (Nova) Client
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_client.py 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. # Copyright 2012 OpenStack Foundation
  2. # All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. # not use this file except in compliance with the License. You may obtain
  6. # a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. # License for the specific language governing permissions and limitations
  14. # under the License.
  15. import json
  16. import logging
  17. import fixtures
  18. import mock
  19. import requests
  20. import novaclient.client
  21. import novaclient.extension
  22. from novaclient.tests.unit import utils
  23. import novaclient.v2.client
  24. class ClientConnectionPoolTest(utils.TestCase):
  25. @mock.patch("novaclient.client.TCPKeepAliveAdapter")
  26. def test_get(self, mock_http_adapter):
  27. mock_http_adapter.side_effect = lambda: mock.Mock()
  28. pool = novaclient.client._ClientConnectionPool()
  29. self.assertEqual(pool.get("abc"), pool.get("abc"))
  30. self.assertNotEqual(pool.get("abc"), pool.get("def"))
  31. class ClientTest(utils.TestCase):
  32. def test_client_with_timeout(self):
  33. instance = novaclient.client.HTTPClient(user='user',
  34. password='password',
  35. projectid='project',
  36. timeout=2,
  37. auth_url="http://www.blah.com")
  38. self.assertEqual(2, instance.timeout)
  39. mock_request = mock.Mock()
  40. mock_request.return_value = requests.Response()
  41. mock_request.return_value.status_code = 200
  42. mock_request.return_value.headers = {
  43. 'x-server-management-url': 'blah.com',
  44. 'x-auth-token': 'blah',
  45. }
  46. with mock.patch('requests.request', mock_request):
  47. instance.authenticate()
  48. requests.request.assert_called_with(
  49. mock.ANY, mock.ANY, timeout=2, headers=mock.ANY,
  50. verify=mock.ANY)
  51. def test_client_reauth(self):
  52. instance = novaclient.client.HTTPClient(user='user',
  53. password='password',
  54. projectid='project',
  55. timeout=2,
  56. auth_url="http://www.blah.com")
  57. instance.auth_token = 'foobar'
  58. instance.management_url = 'http://example.com'
  59. instance.version = 'v2.0'
  60. mock_request = mock.Mock()
  61. mock_request.side_effect = novaclient.exceptions.Unauthorized(401)
  62. with mock.patch('requests.request', mock_request):
  63. try:
  64. instance.get('/servers/detail')
  65. except Exception:
  66. pass
  67. get_headers = {'X-Auth-Project-Id': 'project',
  68. 'X-Auth-Token': 'foobar',
  69. 'User-Agent': 'python-novaclient',
  70. 'Accept': 'application/json'}
  71. reauth_headers = {'Content-Type': 'application/json',
  72. 'Accept': 'application/json',
  73. 'User-Agent': 'python-novaclient'}
  74. data = {
  75. "auth": {
  76. "tenantName": "project",
  77. "passwordCredentials": {
  78. "username": "user",
  79. "password": "password"
  80. }
  81. }
  82. }
  83. expected = [mock.call('GET',
  84. 'http://example.com/servers/detail',
  85. timeout=mock.ANY,
  86. headers=get_headers,
  87. verify=mock.ANY),
  88. mock.call('POST', 'http://www.blah.com/tokens',
  89. timeout=mock.ANY,
  90. headers=reauth_headers,
  91. allow_redirects=mock.ANY,
  92. data=json.dumps(data),
  93. verify=mock.ANY)]
  94. self.assertEqual(expected, mock_request.call_args_list)
  95. @mock.patch.object(novaclient.client.HTTPClient, 'request',
  96. return_value=(200, "{'versions':[]}"))
  97. def _check_version_url(self, management_url, version_url, mock_request):
  98. projectid = '25e469aa1848471b875e68cde6531bc5'
  99. instance = novaclient.client.HTTPClient(user='user',
  100. password='password',
  101. projectid=projectid,
  102. auth_url="http://www.blah.com")
  103. instance.auth_token = 'foobar'
  104. instance.management_url = management_url % projectid
  105. instance.version = 'v2.0'
  106. # If passing None as the part of url, a client accesses the url which
  107. # doesn't include "v2/<projectid>" for getting API version info.
  108. instance.get(None)
  109. mock_request.assert_called_once_with(version_url, 'GET',
  110. headers=mock.ANY)
  111. mock_request.reset_mock()
  112. # Otherwise, a client accesses the url which includes "v2/<projectid>".
  113. instance.get('servers')
  114. url = instance.management_url + 'servers'
  115. mock_request.assert_called_once_with(url, 'GET', headers=mock.ANY)
  116. def test_client_version_url(self):
  117. self._check_version_url('http://foo.com/v2/%s', 'http://foo.com/')
  118. def test_client_version_url_with_project_name(self):
  119. self._check_version_url('http://foo.com/nova/v2/%s',
  120. 'http://foo.com/nova/')
  121. def test_get_client_class_v3(self):
  122. output = novaclient.client.get_client_class('3')
  123. self.assertEqual(output, novaclient.v2.client.Client)
  124. def test_get_client_class_v2(self):
  125. output = novaclient.client.get_client_class('2')
  126. self.assertEqual(output, novaclient.v2.client.Client)
  127. def test_get_client_class_v2_int(self):
  128. output = novaclient.client.get_client_class(2)
  129. self.assertEqual(output, novaclient.v2.client.Client)
  130. def test_get_client_class_v1_1(self):
  131. output = novaclient.client.get_client_class('1.1')
  132. self.assertEqual(output, novaclient.v2.client.Client)
  133. def test_get_client_class_unknown(self):
  134. self.assertRaises(novaclient.exceptions.UnsupportedVersion,
  135. novaclient.client.get_client_class, '0')
  136. def test_client_with_os_cache_enabled(self):
  137. cs = novaclient.v2.client.Client("user", "password", "project_id",
  138. auth_url="foo/v2", os_cache=True)
  139. self.assertEqual(True, cs.os_cache)
  140. self.assertEqual(True, cs.client.os_cache)
  141. def test_client_with_os_cache_disabled(self):
  142. cs = novaclient.v2.client.Client("user", "password", "project_id",
  143. auth_url="foo/v2", os_cache=False)
  144. self.assertEqual(False, cs.os_cache)
  145. self.assertEqual(False, cs.client.os_cache)
  146. def test_client_with_no_cache_enabled(self):
  147. cs = novaclient.v2.client.Client("user", "password", "project_id",
  148. auth_url="foo/v2", no_cache=True)
  149. self.assertEqual(False, cs.os_cache)
  150. self.assertEqual(False, cs.client.os_cache)
  151. def test_client_with_no_cache_disabled(self):
  152. cs = novaclient.v2.client.Client("user", "password", "project_id",
  153. auth_url="foo/v2", no_cache=False)
  154. self.assertEqual(True, cs.os_cache)
  155. self.assertEqual(True, cs.client.os_cache)
  156. def test_client_set_management_url_v1_1(self):
  157. cs = novaclient.v2.client.Client("user", "password", "project_id",
  158. auth_url="foo/v2")
  159. cs.set_management_url("blabla")
  160. self.assertEqual("blabla", cs.client.management_url)
  161. def test_client_get_reset_timings_v1_1(self):
  162. cs = novaclient.v2.client.Client("user", "password", "project_id",
  163. auth_url="foo/v2")
  164. self.assertEqual(0, len(cs.get_timings()))
  165. cs.client.times.append("somevalue")
  166. self.assertEqual(1, len(cs.get_timings()))
  167. self.assertEqual("somevalue", cs.get_timings()[0])
  168. cs.reset_timings()
  169. self.assertEqual(0, len(cs.get_timings()))
  170. @mock.patch('novaclient.client.HTTPClient')
  171. def test_contextmanager_v1_1(self, mock_http_client):
  172. fake_client = mock.Mock()
  173. mock_http_client.return_value = fake_client
  174. with novaclient.v2.client.Client("user", "password", "project_id",
  175. auth_url="foo/v2"):
  176. pass
  177. self.assertTrue(fake_client.open_session.called)
  178. self.assertTrue(fake_client.close_session.called)
  179. def test_get_password_simple(self):
  180. cs = novaclient.client.HTTPClient("user", "password", "", "")
  181. cs.password_func = mock.Mock()
  182. self.assertEqual("password", cs._get_password())
  183. self.assertFalse(cs.password_func.called)
  184. def test_get_password_none(self):
  185. cs = novaclient.client.HTTPClient("user", None, "", "")
  186. self.assertIsNone(cs._get_password())
  187. def test_get_password_func(self):
  188. cs = novaclient.client.HTTPClient("user", None, "", "")
  189. cs.password_func = mock.Mock(return_value="password")
  190. self.assertEqual("password", cs._get_password())
  191. cs.password_func.assert_called_once_with()
  192. cs.password_func = mock.Mock()
  193. self.assertEqual("password", cs._get_password())
  194. self.assertFalse(cs.password_func.called)
  195. def test_auth_url_rstrip_slash(self):
  196. cs = novaclient.client.HTTPClient("user", "password", "project_id",
  197. auth_url="foo/v2/")
  198. self.assertEqual("foo/v2", cs.auth_url)
  199. def test_token_and_bypass_url(self):
  200. cs = novaclient.client.HTTPClient(None, None, None,
  201. auth_token="12345",
  202. bypass_url="compute/v100/")
  203. self.assertIsNone(cs.auth_url)
  204. self.assertEqual("12345", cs.auth_token)
  205. self.assertEqual("compute/v100", cs.bypass_url)
  206. self.assertEqual("compute/v100", cs.management_url)
  207. @mock.patch("novaclient.client.requests.Session")
  208. def test_session(self, mock_session):
  209. fake_session = mock.Mock()
  210. mock_session.return_value = fake_session
  211. cs = novaclient.client.HTTPClient("user", None, "", "")
  212. cs.open_session()
  213. self.assertEqual(cs._session, fake_session)
  214. cs.close_session()
  215. self.assertIsNone(cs._session)
  216. def test_session_connection_pool(self):
  217. cs = novaclient.client.HTTPClient("user", None, "",
  218. "", connection_pool=True)
  219. cs.open_session()
  220. self.assertIsNone(cs._session)
  221. cs.close_session()
  222. self.assertIsNone(cs._session)
  223. def test_get_session(self):
  224. cs = novaclient.client.HTTPClient("user", None, "", "")
  225. self.assertIsNone(cs._get_session("http://nooooooooo.com"))
  226. @mock.patch("novaclient.client.requests.Session")
  227. def test_get_session_open_session(self, mock_session):
  228. fake_session = mock.Mock()
  229. mock_session.return_value = fake_session
  230. cs = novaclient.client.HTTPClient("user", None, "", "")
  231. cs.open_session()
  232. self.assertEqual(fake_session, cs._get_session("http://example.com"))
  233. @mock.patch("novaclient.client.requests.Session")
  234. @mock.patch("novaclient.client._ClientConnectionPool")
  235. def test_get_session_connection_pool(self, mock_pool, mock_session):
  236. service_url = "http://example.com"
  237. pool = mock.MagicMock()
  238. pool.get.return_value = "http_adapter"
  239. mock_pool.return_value = pool
  240. cs = novaclient.client.HTTPClient("user", None, "",
  241. "", connection_pool=True)
  242. cs._current_url = "http://another.com"
  243. session = cs._get_session(service_url)
  244. self.assertEqual(session, mock_session.return_value)
  245. pool.get.assert_called_once_with(service_url)
  246. mock_session().mount.assert_called_once_with(service_url,
  247. 'http_adapter')
  248. def test_init_without_connection_pool(self):
  249. cs = novaclient.client.HTTPClient("user", None, "", "")
  250. self.assertIsNone(cs._connection_pool)
  251. @mock.patch("novaclient.client._ClientConnectionPool")
  252. def test_init_with_proper_connection_pool(self, mock_pool):
  253. fake_pool = mock.Mock()
  254. mock_pool.return_value = fake_pool
  255. cs = novaclient.client.HTTPClient("user", None, "",
  256. connection_pool=True)
  257. self.assertEqual(cs._connection_pool, fake_pool)
  258. def test_log_req(self):
  259. self.logger = self.useFixture(
  260. fixtures.FakeLogger(
  261. format="%(message)s",
  262. level=logging.DEBUG,
  263. nuke_handlers=True
  264. )
  265. )
  266. cs = novaclient.client.HTTPClient("user", None, "",
  267. connection_pool=True)
  268. cs.http_log_debug = True
  269. cs.http_log_req('GET', '/foo', {'headers': {}})
  270. cs.http_log_req('GET', '/foo', {'headers':
  271. {'X-Auth-Token': 'totally_bogus'}
  272. })
  273. cs.http_log_req('GET', '/foo', {'headers':
  274. {'X-Foo': 'bar',
  275. 'X-Auth-Token': 'totally_bogus'}
  276. })
  277. cs.http_log_req('GET', '/foo', {'headers': {},
  278. 'data':
  279. '{"auth": {"passwordCredentials": '
  280. '{"password": "zhaoqin"}}}'})
  281. output = self.logger.output.split('\n')
  282. self.assertIn("REQ: curl -g -i '/foo' -X GET", output)
  283. self.assertIn(
  284. "REQ: curl -g -i '/foo' -X GET -H "
  285. '"X-Auth-Token: {SHA1}b42162b6ffdbd7c3c37b7c95b7ba9f51dda0236d"',
  286. output)
  287. self.assertIn(
  288. "REQ: curl -g -i '/foo' -X GET -H "
  289. '"X-Auth-Token: {SHA1}b42162b6ffdbd7c3c37b7c95b7ba9f51dda0236d"'
  290. ' -H "X-Foo: bar"',
  291. output)
  292. self.assertIn(
  293. "REQ: curl -g -i '/foo' -X GET -d "
  294. '\'{"auth": {"passwordCredentials": {"password":'
  295. ' "{SHA1}4fc49c6a671ce889078ff6b250f7066cf6d2ada2"}}}\'',
  296. output)
  297. def test_log_resp(self):
  298. self.logger = self.useFixture(
  299. fixtures.FakeLogger(
  300. format="%(message)s",
  301. level=logging.DEBUG,
  302. nuke_handlers=True
  303. )
  304. )
  305. cs = novaclient.client.HTTPClient("user", None, "",
  306. connection_pool=True)
  307. cs.http_log_debug = True
  308. text = ('{"access": {"token": {"id": "zhaoqin"}}}')
  309. resp = utils.TestResponse({'status_code': 200, 'headers': {},
  310. 'text': text})
  311. cs.http_log_resp(resp)
  312. output = self.logger.output.split('\n')
  313. self.assertIn('RESP: [200] {}', output)
  314. self.assertIn('RESP BODY: {"access": {"token": {"id":'
  315. ' "{SHA1}4fc49c6a671ce889078ff6b250f7066cf6d2ada2"}}}',
  316. output)