예제 #1
0
    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)
예제 #2
0
    def test_authenticate_with_project(self):
        """A client is authenticated with a project."""
        response = mock.MagicMock(status_code=200)
        response.json.side_effect = [
            {
                "metadata": {
                    "auth": "untrusted",
                    "api_extensions": ["projects"],
                }
            },
            {
                "metadata": {
                    "type": "client",
                    "fingerprint": "eaf55b72fc23aa516d709271df9b0116064bf8cfa009cf34c67c33ad32c2320c",
                }
            },
            {
                "metadata": {
                    "auth": "trusted",
                    "environment": {"project": "test-proj"},
                }
            },
        ]
        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, project="test-proj")

        an_client.authenticate("test-password")

        self.assertTrue(an_client.trusted)
        self.assertEqual(an_client.host_info["environment"]["project"], "test-proj")
예제 #3
0
    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)
예제 #4
0
    def test_create(self):
        """Client creation sets default API endpoint."""
        expected = 'http+unix://%2Fvar%2Flib%2Flxd%2Funix.socket/1.0'

        an_client = client.Client()

        self.assertEqual(expected, an_client.api._api_endpoint)
예제 #5
0
 def test_resources_raises_conn_failed_exception(self):
     a_client = client.Client()
     a_client.host_info["api_extensions"] = ["resources"]
     response = mock.MagicMock(status_code=400)
     self.get.return_value = response
     with self.assertRaises(exceptions.ClientConnectionFailed):
         a_client.resources
예제 #6
0
    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)
예제 #7
0
    def test_authenticate(self):
        """A client is authenticated."""
        response = mock.MagicMock(status_code=200)
        response.json.side_effect = [
            {
                "metadata": {
                    "auth": "untrusted"
                }
            },
            {
                "metadata": {
                    "type":
                    "client",
                    "fingerprint":
                    "eaf55b72fc23aa516d709271df9b0116064bf8cfa009cf34c67c33ad32c2320c",
                }
            },
            {
                "metadata": {
                    "auth": "trusted"
                }
            },
        ]
        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)

        an_client.authenticate("test-password")

        self.assertTrue(an_client.trusted)
예제 #8
0
 def test_server_clustered_false_no_info(self):
     """Client.server_clustered is False if the info is not available in metadata."""
     response = mock.MagicMock(status_code=200)
     response.json.return_value = {"metadata": {"environment": {}}}
     self.get.return_value = response
     a_client = client.Client()
     self.assertFalse(a_client.server_clustered)
예제 #9
0
    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)
예제 #10
0
    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)
예제 #11
0
    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)
예제 #12
0
 def test_resources_uses_cache(self):
     a_client = client.Client()
     a_client._resource_cache = {"cpu": {}}
     # Client.__init__ calls get, reset the mock before trying
     # resources to confirm it wasn't called.
     self.get.called = False
     self.assertIn("cpu", a_client.resources)
     self.assertFalse(self.get.called)
예제 #13
0
 def test_assert_has_api_extension(self):
     a_client = client.Client()
     a_client.host_info = {"api_extensions": ["one", "two"]}
     with self.assertRaises(exceptions.LXDAPIExtensionNotAvailable) as c:
         self.assertFalse(a_client.assert_has_api_extension("three"))
     self.assertIn("three", str(c.exception))
     a_client.assert_has_api_extension("one")
     a_client.assert_has_api_extension("two")
예제 #14
0
    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)
예제 #15
0
    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)
예제 #16
0
    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)
예제 #17
0
    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")
예제 #18
0
    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
        an_client = client.Client()

        an_client.events(websocket_client=WebsocketClient)

        WebsocketClient.assert_called_once_with('ws+unix:///lxd/unix.socket')
예제 #19
0
    def test_create_endpoint_unixsocket(self):
        """Test with unix socket endpoint."""
        endpoint = "/tmp/unix.socket"
        expected = "http+unix://%2Ftmp%2Funix.socket/1.0"

        with mock.patch("os.path.exists") as mock_exists:
            mock_exists.return_value = True
            a_client = client.Client(endpoint)

        self.assertEqual(expected, a_client.api._api_endpoint)
예제 #20
0
    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)
예제 #21
0
 def test_resources(self):
     a_client = client.Client()
     a_client.host_info["api_extensions"] = ["resources"]
     response = mock.MagicMock(status_code=200)
     response.json.return_value = {
         "metadata": {
             "cpu": {},
         }
     }
     self.get.return_value = response
     self.assertIn("cpu", a_client.resources)
예제 #22
0
파일: test_client.py 프로젝트: pstch/pylxd
 def test_resources(self):
     a_client = client.Client()
     a_client.host_info['api_extensions'] = ['resources']
     response = mock.MagicMock(status_code=200)
     response.json.return_value = {
         'metadata': {
             'cpu': {},
         }
     }
     self.get.return_value = response
     self.assertIn('cpu', a_client.resources)
예제 #23
0
    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",
                                                ssl_options=None)
예제 #24
0
 def test_server_clustered_true(self):
     """Client.server_clustered is True if clustered."""
     response = mock.MagicMock(status_code=200)
     response.json.return_value = {
         "metadata": {
             "environment": {
                 "server_clustered": True
             }
         }
     }
     self.get.return_value = response
     a_client = client.Client()
     self.assertTrue(a_client.server_clustered)
예제 #25
0
    def test_authenticate_project_not_supported(self):
        """A client raises an error if projects are not supported."""
        response = mock.MagicMock(status_code=200)
        response.json.return_value = {
            "metadata": {
                "auth": "untrusted",
                "api_extensions": [],
            }
        }
        self.get.return_value = response

        with pytest.raises(exceptions.ClientConnectionFailed):
            client.Client("https://lxd", project="test-proj")
예제 #26
0
    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
예제 #27
0
    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",
                                  cert=client.DEFAULT_CERTS)

        an_client.events(websocket_client=WebsocketClient)
        ssl_options = {
            "certfile": client.DEFAULT_CERTS.cert,
            "keyfile": client.DEFAULT_CERTS.key,
        }
        WebsocketClient.assert_called_once_with("wss://lxd.local",
                                                ssl_options=ssl_options)
예제 #28
0
    def func_wrapper(self, server, *args, **kwargs):
        s = self.config[server]
        ws_client = client.Client(endpoint=s.get("endpoint"),
                                  cert=s.get("cert"),
                                  verify=s.get("verify"))
        ev_client = ws_client.events(_WebsocketClient)
        ssl_options = {
            "keyfile": s.get("keyfile"),
            "certfile": s.get("certfile"),
        }

        ev_client.ssl_options = ssl_options
        ev_client.connect()
        kwargs.update({
            "ev_client": ev_client,
            "ws_client": ws_client,
        })
        res = func(self, server, *args, **kwargs)
        ev_client.close_connection()
        return res
예제 #29
0
    def test_create_endpoint_with_project(self):
        """Explicitly set the client endpoint."""
        response = mock.MagicMock(status_code=200)
        response.json.side_effect = [
            {
                "metadata": {
                    "auth": "untrusted",
                    "api_extensions": ["projects"],
                }
            },
        ]
        self.get.return_value = response

        endpoint = "/tmp/unix.socket"
        expected = "http+unix://%2Ftmp%2Funix.socket/1.0"

        with mock.patch("os.path.exists") as mock_exists:
            mock_exists.return_value = True
            a_client = client.Client(endpoint=endpoint, project="prj")

        self.assertEqual(a_client.api._api_endpoint, expected)
        self.assertEqual(a_client.api._project, "prj")
예제 #30
0
    def test_authenticate_project_not_supported_but_default(self):
        """
        A client doesn't raise an error if projects are not supported and the
        default one is requested.
        """
        response = mock.MagicMock(status_code=200)
        response.json.side_effect = [
            {
                "metadata": {
                    "auth": "untrusted",
                    "api_extensions": [],
                }
            },
            {
                "metadata": {
                    "type":
                    "client",
                    "fingerprint":
                    "eaf55b72fc23aa516d709271df9b0116064bf8cfa009cf34c67c33ad32c2320c",
                }
            },
            {
                "metadata": {
                    "auth": "trusted",
                    "environment": {},
                }
            },
        ]
        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, project="default")

        an_client.authenticate("test-password")

        self.assertTrue(an_client.trusted)