Esempio n. 1
0
    def client(self, address):
        """
        Return a client given the address.
        """
        # Return cached client
        if address in self.clients:
            return self.clients[address]

        # Load any additional headers for this address from the config
        extra_headers = self.rest_extra_headers(address)

        # Create RestOAuthHandler that authenticates directly with
        # OAuth endpoints on the REST server
        from codalab.server.auth import RestOAuthHandler

        auth_handler = RestOAuthHandler(address, extra_headers)

        # Create JsonApiClient with a callback to get access tokens
        client = JsonApiClient(
            address,
            lambda: self._authenticate(address, auth_handler),
            extra_headers,
            self.check_version,
        )

        # Cache and return client
        self.clients[address] = client
        return client
Esempio n. 2
0
    def _create_cli(self, worksheet_uuid):
        """
        Create an instance of the CLI.

        The CLI uses JsonApiClient to communicate back to the REST API.
        This is admittedly not ideal since now the REST API is essentially
        making HTTP requests back to itself. Future potential solutions might
        include creating a subclass of JsonApiClient that can reroute HTTP
        requests directly to the appropriate Bottle view functions.
        """
        output_buffer = StringIO()
        rest_client = JsonApiClient(self._rest_url(), lambda: get_user_token())
        manager = CodaLabManager(
            temporary=True,
            config=local.config,
            clients={
                self._rest_url(): rest_client
            })
        manager.set_current_worksheet_uuid(self._rest_url(), worksheet_uuid)
        cli = bundle_cli.BundleCLI(manager, headless=True, stdout=output_buffer, stderr=output_buffer)
        return cli, output_buffer
Esempio n. 3
0
    def client(self, address):
        """
        Return a client given the address.
        """
        # Return cached client
        if address in self.clients:
            return self.clients[address]

        # Create RestOAuthHandler that authenticates directly with
        # OAuth endpoints on the REST server
        from codalab.server.auth import RestOAuthHandler
        auth_handler = RestOAuthHandler(address, None)

        # Create JsonApiClient with a callback to get access tokens
        client = JsonApiClient(
            address, lambda: self._authenticate(address, auth_handler),
            self.check_version)

        # Cache and return client
        self.clients[address] = client
        return client
Esempio n. 4
0
 def setUp(self):
     self.client = JsonApiClient('', {}, lambda: None)
Esempio n. 5
0
class JsonApiClientTest(unittest.TestCase):
    def setUp(self):
        self.client = JsonApiClient('', {}, lambda: None)

    def test_pack_params(self):
        self.assertItemsEqual(self.client._pack_params({
            'int': 2,
            'float': 2.2,
            'str': 'stringy',
            'true': True,
            'false': False,
            'list': [1, '2', 3.3, True],
            'comma': 'I,have,commas',
            'commalist': ['I,also', 'have,commas'],
        }), [
            ('int', 2),
            ('float', 2.2),
            ('str', 'stringy'),
            ('true', 1),
            ('false', 0),
            ('list', '1'),
            ('list', '2'),
            ('list', '3.3'),
            ('list', 'True'),
            ('comma', 'I,have,commas'),
            ('commalist', 'I,also'),
            ('commalist', 'have,commas'),
        ])

    def test_resource_path(self):
        self.assertEqual(self.client._get_resource_path('bundles'),
                         '/bundles')
        self.assertEqual(self.client._get_resource_path('bundles', 'abc'),
                         '/bundles/abc')

    def test_pack_document(self):
        doc = self.client._pack_document({
            'owner': JsonApiRelationship('users', '345'),
            'friend': EmptyJsonApiRelationship(),
            'id': '123',
            'name': 'hello'
        }, 'bundles')

        self.assertDictEqual(doc, {
            'data': {
                'id': '123',
                'type': 'bundles',
                'attributes': {
                    'name': 'hello'
                },
                'relationships': {
                    'owner': {
                        'data': {
                            'id': '345',
                            'type': 'users'
                        }
                    },
                    'friend': {
                        'data': None
                    }
                },
            }
        })

    def test_unpack_document(self):
        obj = self.client._unpack_document({
            'data': {
                'id': '123',
                'type': 'bundles',
                'attributes': {
                    'name': 'hello'
                },
                'relationships': {
                    'owner': {
                        'data': {
                            'id': '345',
                            'type': 'users'
                        }
                    },
                    'parent': {
                        'data': {
                            'id': '567',
                            'type': 'bundles'
                        }
                    }
                },
            },
            'included': [
                {
                    'type': 'users',
                    'id': '345',
                    'attributes': {
                        'name': 'percy',
                        'affiliation': 'stanford'
                    }
                }
            ]
        })

        self.assertDictEqual(obj, {
            'owner': JsonApiRelationship('users', '345', {
                'name': 'percy',
                'affiliation': 'stanford'
            }),
            'parent': JsonApiRelationship('bundles', '567'),
            'id': '123',
            'name': 'hello'
        })

    def test_fetch_one(self):
        class MockJsonApiClient(JsonApiClient):
            def __init__(self):
                pass

            def fetch(self, count, **kwargs):
                """
                Returns list with as many dicts as specified by |count|,
                or return a dict directly if |count| is None.
                """
                if count is None:
                    return {}
                else:
                    return [{}] * count

        client = MockJsonApiClient()
        self.assertEqual(client.fetch_one(None), {}, "fetch_one doesn't return dict directly")
        self.assertEqual(client.fetch_one(1), {}, "fetch_one doesn't extract single dict from list")
        with self.assertRaises(PreconditionViolation):
            client.fetch_one(2)
        with self.assertRaises(PreconditionViolation):
            client.fetch_one(10)
 def setUp(self):
     self.client = JsonApiClient('', {}, lambda: None)
class JsonApiClientTest(unittest.TestCase):
    def setUp(self):
        self.client = JsonApiClient('', {}, lambda: None)

    def test_pack_params(self):
        self.assertItemsEqual(
            self.client._pack_params(
                {
                    'int': 2,
                    'float': 2.2,
                    'str': 'stringy',
                    'true': True,
                    'false': False,
                    'list': [1, '2', 3.3, True],
                    'comma': 'I,have,commas',
                    'commalist': ['I,also', 'have,commas'],
                }
            ),
            [
                ('int', 2),
                ('float', 2.2),
                ('str', 'stringy'),
                ('true', 1),
                ('false', 0),
                ('list', '1'),
                ('list', '2'),
                ('list', '3.3'),
                ('list', 'True'),
                ('comma', 'I,have,commas'),
                ('commalist', 'I,also'),
                ('commalist', 'have,commas'),
            ],
        )

    def test_resource_path(self):
        self.assertEqual(self.client._get_resource_path('bundles'), '/bundles')
        self.assertEqual(self.client._get_resource_path('bundles', 'abc'), '/bundles/abc')

    def test_pack_document(self):
        doc = self.client._pack_document(
            {
                'owner': JsonApiRelationship('users', '345'),
                'friend': EmptyJsonApiRelationship(),
                'id': '123',
                'name': 'hello',
            },
            'bundles',
        )

        self.assertDictEqual(
            doc,
            {
                'data': {
                    'id': '123',
                    'type': 'bundles',
                    'attributes': {'name': 'hello'},
                    'relationships': {
                        'owner': {'data': {'id': '345', 'type': 'users'}},
                        'friend': {'data': None},
                    },
                }
            },
        )

    def test_unpack_document(self):
        obj = self.client._unpack_document(
            {
                'data': {
                    'id': '123',
                    'type': 'bundles',
                    'attributes': {'name': 'hello'},
                    'relationships': {
                        'owner': {'data': {'id': '345', 'type': 'users'}},
                        'parent': {'data': {'id': '567', 'type': 'bundles'}},
                    },
                },
                'included': [
                    {
                        'type': 'users',
                        'id': '345',
                        'attributes': {'name': 'percy', 'affiliation': 'stanford'},
                    }
                ],
            }
        )

        self.assertDictEqual(
            obj,
            {
                'owner': JsonApiRelationship(
                    'users', '345', {'name': 'percy', 'affiliation': 'stanford'}
                ),
                'parent': JsonApiRelationship('bundles', '567'),
                'id': '123',
                'name': 'hello',
            },
        )

    def test_fetch_one(self):
        class MockJsonApiClient(JsonApiClient):
            def __init__(self):
                pass

            def fetch(self, count, **kwargs):
                """
                Returns list with as many dicts as specified by |count|,
                or return a dict directly if |count| is None.
                """
                if count is None:
                    return {}
                else:
                    return [{}] * count

        client = MockJsonApiClient()
        self.assertEqual(client.fetch_one(None), {}, "fetch_one doesn't return dict directly")
        self.assertEqual(client.fetch_one(1), {}, "fetch_one doesn't extract single dict from list")
        with self.assertRaises(PreconditionViolation):
            client.fetch_one(2)
        with self.assertRaises(PreconditionViolation):
            client.fetch_one(10)