/usr/lib/python2.7/dist-packages/pylxd/tests/test_client.py is in python-pylxd 2.2.6-0ubuntu1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 | # Copyright (c) 2016 Canonical Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import json
import os
import os.path
import unittest
import mock
import requests
import requests_unixsocket
from pylxd import client, exceptions
from pylxd.tests.testing import requires_ws4py
class TestClient(unittest.TestCase):
"""Tests for pylxd.client.Client."""
def setUp(self):
self.get_patcher = mock.patch('pylxd.client._APINode.get')
self.get = self.get_patcher.start()
self.post_patcher = mock.patch('pylxd.client._APINode.post')
self.post = self.post_patcher.start()
response = mock.MagicMock(status_code=200)
response.json.return_value = {'metadata': {
'auth': 'trusted',
'environment': {'storage': 'zfs'},
}}
self.get.return_value = response
post_response = mock.MagicMock(status_code=200)
self.post.return_value = post_response
def tearDown(self):
self.get_patcher.stop()
self.post_patcher.stop()
@mock.patch('os.path.exists')
def test_create(self, _path_exists):
"""Client creation sets default API endpoint."""
_path_exists.return_value = False
expected = 'http+unix://%2Fvar%2Flib%2Flxd%2Funix.socket/1.0'
an_client = client.Client()
self.assertEqual(expected, an_client.api._api_endpoint)
@mock.patch('os.path.exists')
@mock.patch('os.environ')
def test_create_with_snap_lxd(self, _environ, _path_exists):
# """Client creation sets default API endpoint."""
_path_exists.return_value = True
expected = ('http+unix://%2Fvar%2Fsnap%2Flxd%2F'
'common%2Flxd%2Funix.socket/1.0')
an_client = client.Client()
self.assertEqual(expected, an_client.api._api_endpoint)
def test_create_LXD_DIR(self):
"""When LXD_DIR is set, use it in the client."""
os.environ['LXD_DIR'] = '/lxd'
expected = 'http+unix://%2Flxd%2Funix.socket/1.0'
an_client = client.Client()
self.assertEqual(expected, an_client.api._api_endpoint)
def test_create_endpoint(self):
"""Explicitly set the client endpoint."""
endpoint = 'http://lxd'
expected = 'http://lxd/1.0'
an_client = client.Client(endpoint=endpoint)
self.assertEqual(expected, an_client.api._api_endpoint)
def test_create_endpoint_unixsocket(self):
"""Test with unix socket endpoint."""
endpoint = '/tmp/unix.socket'
expected = 'http+unix://%2Ftmp%2Funix.socket/1.0'
real_isfile = os.path.isfile
os.path.isfile = lambda x: True
an_client = client.Client(endpoint)
os.path.isfile = real_isfile
self.assertEqual(expected, an_client.api._api_endpoint)
def test_connection_404(self):
"""If the endpoint 404s, an exception is raised."""
response = mock.MagicMock(status_code=404)
self.get.return_value = response
self.assertRaises(exceptions.ClientConnectionFailed, client.Client)
def test_connection_failed(self):
"""If the connection fails, an exception is raised."""
def raise_exception():
raise requests.exceptions.ConnectionError()
self.get.side_effect = raise_exception
self.get.return_value = None
self.assertRaises(exceptions.ClientConnectionFailed, client.Client)
def test_connection_untrusted(self):
"""Client.trusted is False when certs are untrusted."""
response = mock.MagicMock(status_code=200)
response.json.return_value = {'metadata': {'auth': 'untrusted'}}
self.get.return_value = response
an_client = client.Client()
self.assertFalse(an_client.trusted)
def test_connection_trusted(self):
"""Client.trusted is True when certs are untrusted."""
response = mock.MagicMock(status_code=200)
response.json.return_value = {'metadata': {'auth': 'trusted'}}
self.get.return_value = response
an_client = client.Client()
self.assertTrue(an_client.trusted)
def test_authenticate(self):
"""A client is authenticated."""
response = mock.MagicMock(status_code=200)
response.json.return_value = {'metadata': {'auth': 'untrusted'}}
self.get.return_value = response
certs = (
os.path.join(os.path.dirname(__file__), 'lxd.crt'),
os.path.join(os.path.dirname(__file__), 'lxd.key'))
an_client = client.Client('https://lxd', cert=certs)
get_count = []
def _get(*args, **kwargs):
if len(get_count) == 0:
get_count.append(None)
return {'metadata': {
'type': 'client',
'fingerprint': 'eaf55b72fc23aa516d709271df9b0116064bf8cfa009cf34c67c33ad32c2320c', # NOQA
}}
else:
return {'metadata': {'auth': 'trusted'}}
response = mock.MagicMock(status_code=200)
response.json.side_effect = _get
self.get.return_value = response
an_client.authenticate('test-password')
self.assertTrue(an_client.trusted)
def test_authenticate_already_authenticated(self):
"""If the client is already authenticated, nothing happens."""
an_client = client.Client()
an_client.authenticate('test-password')
self.assertTrue(an_client.trusted)
def test_host_info(self):
"""Perform a host query."""
an_client = client.Client()
self.assertEqual('zfs', an_client.host_info['environment']['storage'])
@requires_ws4py
def test_events(self):
"""The default websocket client is returned."""
an_client = client.Client()
ws_client = an_client.events()
self.assertEqual('/1.0/events', ws_client.resource)
def test_events_no_ws4py(self):
"""No ws4py will result in a ValueError."""
from pylxd import client
old_installed = client._ws4py_installed
client._ws4py_installed = False
def cleanup():
client._ws4py_installed = old_installed
self.addCleanup(cleanup)
an_client = client.Client()
self.assertRaises(ValueError, an_client.events)
client._ws4py_installed
@requires_ws4py
def test_events_unix_socket(self):
"""A unix socket compatible websocket client is returned."""
websocket_client = mock.Mock(resource=None)
WebsocketClient = mock.Mock()
WebsocketClient.return_value = websocket_client
os.environ['LXD_DIR'] = '/lxd'
an_client = client.Client()
an_client.events(websocket_client=WebsocketClient)
WebsocketClient.assert_called_once_with('ws+unix:///lxd/unix.socket')
@requires_ws4py
def test_events_htt(self):
"""An http compatible websocket client is returned."""
websocket_client = mock.Mock(resource=None)
WebsocketClient = mock.Mock()
WebsocketClient.return_value = websocket_client
an_client = client.Client('http://lxd.local')
an_client.events(websocket_client=WebsocketClient)
WebsocketClient.assert_called_once_with('ws://lxd.local')
@requires_ws4py
def test_events_https(self):
"""An https compatible websocket client is returned."""
websocket_client = mock.Mock(resource=None)
WebsocketClient = mock.Mock()
WebsocketClient.return_value = websocket_client
an_client = client.Client('https://lxd.local')
an_client.events(websocket_client=WebsocketClient)
WebsocketClient.assert_called_once_with('wss://lxd.local')
class TestAPINode(unittest.TestCase):
"""Tests for pylxd.client._APINode."""
def test_getattr(self):
"""API Nodes can use object notation for nesting."""
node = client._APINode('http://test.com')
new_node = node.test
self.assertEqual(
'http://test.com/test', new_node._api_endpoint)
def test_getitem(self):
"""API Nodes can use dict notation for nesting."""
node = client._APINode('http://test.com')
new_node = node['test']
self.assertEqual(
'http://test.com/test', new_node._api_endpoint)
def test_session_http(self):
"""HTTP nodes return the default requests session."""
node = client._APINode('http://test.com')
self.assertIsInstance(node.session, requests.Session)
def test_session_unix_socket(self):
"""HTTP nodes return a requests_unixsocket session."""
node = client._APINode('http+unix://test.com')
self.assertIsInstance(node.session, requests_unixsocket.Session)
@mock.patch('pylxd.client.requests.Session')
def test_get(self, Session):
"""Perform a session get."""
response = mock.Mock(**{
'status_code': 200,
'json.return_value': {'type': 'sync'},
})
session = mock.Mock(**{'get.return_value': response})
Session.return_value = session
node = client._APINode('http://test.com')
node.get()
session.get.assert_called_once_with('http://test.com', timeout=None)
@mock.patch('pylxd.client.requests.Session')
def test_post(self, Session):
"""Perform a session post."""
response = mock.Mock(**{
'status_code': 200,
'json.return_value': {'type': 'sync'},
})
session = mock.Mock(**{'post.return_value': response})
Session.return_value = session
node = client._APINode('http://test.com')
node.post()
session.post.assert_called_once_with('http://test.com', timeout=None)
@mock.patch('pylxd.client.requests.Session')
def test_post_200_not_sync(self, Session):
"""A status code of 200 with async request raises an exception."""
response = mock.Mock(**{
'status_code': 200,
'json.return_value': {'type': 'async'},
})
session = mock.Mock(**{'post.return_value': response})
Session.return_value = session
node = client._APINode('http://test.com')
self.assertRaises(
exceptions.LXDAPIException,
node.post)
@mock.patch('pylxd.client.requests.Session')
def test_post_missing_type_200(self, Session):
"""A missing response type raises an exception."""
response = mock.Mock(**{
'status_code': 200,
'json.return_value': {},
})
session = mock.Mock(**{'post.return_value': response})
Session.return_value = session
node = client._APINode('http://test.com')
self.assertRaises(
exceptions.LXDAPIException,
node.post)
@mock.patch('pylxd.client.requests.Session')
def test_put(self, Session):
"""Perform a session put."""
response = mock.Mock(**{
'status_code': 200,
'json.return_value': {'type': 'sync'},
})
session = mock.Mock(**{'put.return_value': response})
Session.return_value = session
node = client._APINode('http://test.com')
node.put()
session.put.assert_called_once_with('http://test.com', timeout=None)
@mock.patch('pylxd.client.requests.Session')
def test_delete(self, Session):
"""Perform a session delete."""
response = mock.Mock(**{
'status_code': 200,
'json.return_value': {'type': 'sync'},
})
session = mock.Mock(**{'delete.return_value': response})
Session.return_value = session
node = client._APINode('http://test.com')
node.delete()
session.delete.assert_called_once_with('http://test.com', timeout=None)
class TestWebsocketClient(unittest.TestCase):
"""Tests for pylxd.client.WebsocketClient."""
@requires_ws4py
def test_handshake_ok(self):
"""A `message` attribute of an empty list is created."""
ws_client = client._WebsocketClient('ws://an/fake/path')
ws_client.handshake_ok()
self.assertEqual([], ws_client.messages)
@requires_ws4py
def test_received_message(self):
"""A json dict is added to the messages attribute."""
message = mock.Mock(data=json.dumps({'test': 'data'}).encode('utf-8'))
ws_client = client._WebsocketClient('ws://an/fake/path')
ws_client.handshake_ok()
ws_client.received_message(message)
self.assertEqual({'test': 'data'}, ws_client.messages[0])
|