Exemple #1
0
    def test_error(self):
        expected_args = {
            'sensor': 'false',
            'address': 'my magic address'
        }
        (flexmock(requests)
            .should_receive('get')
            .with_args('http://maps.googleapis.com/maps/api/geocode/json', params=expected_args)
            .and_return(mocked_response({'status': 'ERROR'}))
        )

        with self.assertRaises(GeolocationExcetion) as expected_exception:
            geolocate('my magic address')

        self.assertEqual(expected_exception.exception.message, {'status': 'ERROR'})

        expected_args = {
            'sensor': 'false',
            'address': 'my magic address'
        }
        (flexmock(requests)
            .should_receive('get')
            .with_args('http://maps.googleapis.com/maps/api/geocode/json', params=expected_args)
            .and_return(mocked_response({'say': 'what'}, status_code=401))
        )

        with self.assertRaises(GeolocationExcetion) as expected_exception:
            geolocate('my magic address')

        self.assertEqual(expected_exception.exception.message, {'say': 'what'})
Exemple #2
0
    def test_long_poll_for_events_and_errors(self):
        client = BoxClient('my_token')

        longpoll_response = {
            'type': 'realtime_server',
            'url': 'http://2.realtime.services.box.net/subscribe?channel=12345678&stream_type=all',
            'ttl': '10',
            'max_retries': '10',
            'retry_timeout': 610
        }

        (flexmock(client)
            .should_receive('_get_long_poll_data')
            .and_return(longpoll_response)
            .times(2))

        expected_get_params = {
            'channel': ['12345678'],
            'stream_type': 'changes',
            'stream_position': 'some_stream_position',
        }

        (flexmock(requests)
            .should_receive('get')
            .with_args('http://2.realtime.services.box.net/subscribe', params=expected_get_params)
            .and_return(mocked_response({'message': 'foo'}))
            .and_return(mocked_response('some error', status_code=400))
            .times(2))

        with self.assertRaises(BoxClientException) as expect_exception:
            client.long_poll_for_events('some_stream_position', stream_type=EventFilter.CHANGES)

        self.assertEqual(400, expect_exception.exception.status_code)
        self.assertEqual('some error', expect_exception.exception.message)
    def test_get_client_with_retry(self):
        client = BoxClient("my_token")

        (
            flexmock(requests)
            .should_receive("request")
            .with_args(
                "get",
                "https://api.box.com/2.0/files/123/thumbnail.png",
                params={},
                data=None,
                headers=client.default_headers,
                stream=True,
            )
            .and_return(
                mocked_response(
                    status_code=202, headers={"Location": "http://box.com/url_to_thumbnail", "Retry-After": "1"}
                ),
                mocked_response(StringIO("Thumbnail contents")),
            )
            .one_by_one()
        )

        thumbnail = client.get_thumbnail(123, max_wait=1)
        self.assertEqual("Thumbnail contents", thumbnail.read())
    def test_long_poll_for_events_multiple_tries(self):
        client = BoxClient("my_token")

        longpoll_response = {
            "type": "realtime_server",
            "url": "http://2.realtime.services.box.net/subscribe?channel=12345678&stream_type=all",
            "ttl": "10",
            "max_retries": "10",
            "retry_timeout": 610,
        }

        (flexmock(client).should_receive("_get_long_poll_data").and_return(longpoll_response).times(5))

        (flexmock(client).should_receive("get_events").times(0))

        expected_get_params = {
            "channel": ["12345678"],
            "stream_type": "changes",
            "stream_position": "some_stream_position",
        }

        (
            flexmock(requests)
            .should_receive("get")
            .with_args("http://2.realtime.services.box.net/subscribe", params=expected_get_params)
            .and_return(mocked_response({"message": "foo"}))
            .and_return(mocked_response({"message": "foo"}))
            .and_return(mocked_response({"message": "foo"}))
            .and_return(mocked_response({"message": "foo"}))
            .and_return(mocked_response({"message": "new_message"}))
            .times(5)
        )

        position = client.long_poll_for_events("some_stream_position", stream_type=EventFilter.CHANGES)
        self.assertEqual("some_stream_position", position)
Exemple #5
0
    def test_start_authenticate_v1_fail(self):
        response = mocked_response('something_terrible', status_code=400)
        (flexmock(requests).should_receive('get').with_args(
            'https://www.box.com/api/1.0/rest?action=get_ticket&api_key=my_api_key'
        ).and_return(response))

        with self.assertRaises(
                BoxAuthenticationException) as expected_exception:
            self.assertEqual(start_authenticate_v1('my_api_key'),
                             'https://www.box.com/api/1.0/auth/golden_ticket')

        self.assertEqual('something_terrible',
                         expected_exception.exception.message)

        response = mocked_response(
            '<response><status>something_terrible</status></response>')
        (flexmock(requests).should_receive('get').with_args(
            'https://www.box.com/api/1.0/rest?action=get_ticket&api_key=my_api_key'
        ).and_return(response))

        with self.assertRaises(
                BoxAuthenticationException) as expected_exception:
            self.assertEqual(start_authenticate_v1('my_api_key'),
                             'https://www.box.com/api/1.0/auth/golden_ticket')

        self.assertEqual('something_terrible',
                         expected_exception.exception.message)
    def test_long_poll_for_events_and_errors(self):
        client = BoxClient("my_token")

        longpoll_response = {
            "type": "realtime_server",
            "url": "http://2.realtime.services.box.net/subscribe?channel=12345678&stream_type=all",
            "ttl": "10",
            "max_retries": "10",
            "retry_timeout": 610,
        }

        (flexmock(client).should_receive("_get_long_poll_data").and_return(longpoll_response).times(2))

        expected_get_params = {
            "channel": ["12345678"],
            "stream_type": "changes",
            "stream_position": "some_stream_position",
        }

        (
            flexmock(requests)
            .should_receive("get")
            .with_args("http://2.realtime.services.box.net/subscribe", params=expected_get_params)
            .and_return(mocked_response({"message": "foo"}))
            .and_return(mocked_response("some error", status_code=400))
            .times(2)
        )

        with self.assertRaises(BoxClientException) as expect_exception:
            client.long_poll_for_events("some_stream_position", stream_type=EventFilter.CHANGES)

        self.assertEqual(400, expect_exception.exception.status_code)
        self.assertEqual("some error", expect_exception.exception.message)
Exemple #7
0
    def test_handle_auth_response(self):
        _handle_auth_response(mocked_response({'code': 'bla'}))
        with self.assertRaises(BoxAuthenticationException) as expected_exception:
            _handle_auth_response(mocked_response({'error': 'some_error', 'error_description': 'foobar'}))

        self.assertEqual('foobar', expected_exception.exception.message)
        self.assertEqual('some_error', expected_exception.exception.error)
Exemple #8
0
    def test_finish_authenticate_error(self):
        response = mocked_response('something_terrible', status_code=400)
        (flexmock(requests)
            .should_receive('get')
            .with_args('https://www.box.com/api/1.0/rest', params={
                'action': 'get_auth_token',
                'api_key': 'my_api_key',
                'ticket': 'golden_ticket'
            })
            .and_return(response))

        with self.assertRaises(BoxAuthenticationException) as expected_exception:
            finish_authenticate_v1('my_api_key', 'golden_ticket')

        self.assertEqual('something_terrible', expected_exception.exception.message)

        response = mocked_response('<response><status>something_terrible</status></response>')
        (flexmock(requests)
            .should_receive('get')
            .with_args('https://www.box.com/api/1.0/rest', params={
                'action': 'get_auth_token',
                'api_key': 'my_api_key',
                'ticket': 'golden_ticket'
            })
            .and_return(response))

        with self.assertRaises(BoxAuthenticationException) as expected_exception:
            finish_authenticate_v1('my_api_key', 'golden_ticket')

        self.assertEqual('something_terrible', expected_exception.exception.message)
Exemple #9
0
    def test_finish_authenticate_error(self):
        response = mocked_response('something_terrible', status_code=400)
        (flexmock(requests).should_receive('get').with_args(
            'https://www.box.com/api/1.0/rest',
            params={
                'action': 'get_auth_token',
                'api_key': 'my_api_key',
                'ticket': 'golden_ticket'
            }).and_return(response))

        with self.assertRaises(
                BoxAuthenticationException) as expected_exception:
            finish_authenticate_v1('my_api_key', 'golden_ticket')

        self.assertEqual('something_terrible',
                         expected_exception.exception.message)

        response = mocked_response(
            '<response><status>something_terrible</status></response>')
        (flexmock(requests).should_receive('get').with_args(
            'https://www.box.com/api/1.0/rest',
            params={
                'action': 'get_auth_token',
                'api_key': 'my_api_key',
                'ticket': 'golden_ticket'
            }).and_return(response))

        with self.assertRaises(
                BoxAuthenticationException) as expected_exception:
            finish_authenticate_v1('my_api_key', 'golden_ticket')

        self.assertEqual('something_terrible',
                         expected_exception.exception.message)
Exemple #10
0
    def test_long_poll_for_events_and_errors(self):
        client = BoxClient('my_token')

        longpoll_response = {
            'type': 'realtime_server',
            'url': 'http://2.realtime.services.box.net/subscribe?channel=12345678&stream_type=all',
            'ttl': '10',
            'max_retries': '10',
            'retry_timeout': 610
        }

        (flexmock(client)
            .should_receive('_get_long_poll_data')
            .and_return(longpoll_response)
            .times(2))

        expected_get_params = {
            'channel': ['12345678'],
            'stream_type': 'changes',
            'stream_position': 'some_stream_position',
        }

        (flexmock(requests)
            .should_receive('get')
            .with_args('http://2.realtime.services.box.net/subscribe', params=expected_get_params)
            .and_return(mocked_response({'message': 'foo'}))
            .and_return(mocked_response('some error', status_code=400))
            .times(2))

        with self.assertRaises(BoxClientException) as expect_exception:
            client.long_poll_for_events('some_stream_position', stream_type=EventFilter.CHANGES)

        self.assertEqual(400, expect_exception.exception.status_code)
        self.assertEqual('some error', expect_exception.exception.message)
    def test_get_thumbnail_with_params(self):
        client = BoxClient("my_token")

        # Not available
        (
            flexmock(requests)
            .should_receive("request")
            .with_args(
                "get",
                "https://api.box.com/2.0/files/123/thumbnail.png",
                params={},
                data=None,
                headers=client.default_headers,
                stream=True,
            )
            .and_return(mocked_response(status_code=302))
            .once()
        )

        thumbnail = client.get_thumbnail(123)
        self.assertIsNone(thumbnail)

        # Already available
        (
            flexmock(requests)
            .should_receive("request")
            .with_args(
                "get",
                "https://api.box.com/2.0/files/123/thumbnail.png",
                params={},
                data=None,
                headers=client.default_headers,
                stream=True,
            )
            .and_return(mocked_response(StringIO("Thumbnail contents")))
            .once()
        )

        thumbnail = client.get_thumbnail(123)
        self.assertEqual("Thumbnail contents", thumbnail.read())

        # With size requirements
        (
            flexmock(requests)
            .should_receive("request")
            .with_args(
                "get",
                "https://api.box.com/2.0/files/123/thumbnail.png",
                params={"min_height": 1, "max_height": 2, "min_width": 3, "max_width": 4},
                data=None,
                headers=client.default_headers,
                stream=True,
            )
            .and_return(mocked_response(StringIO("Thumbnail contents")))
            .once()
        )

        thumbnail = client.get_thumbnail(123, min_height=1, max_height=2, min_width=3, max_width=4)
        self.assertEqual("Thumbnail contents", thumbnail.read())
Exemple #12
0
    def test_handle_auth_response(self):
        _handle_auth_response(mocked_response({'code': 'bla'}))
        with self.assertRaises(
                BoxAuthenticationException) as expected_exception:
            _handle_auth_response(
                mocked_response({
                    'error': 'some_error',
                    'error_description': 'foobar'
                }))

        self.assertEqual('foobar', expected_exception.exception.message)
        self.assertEqual('some_error', expected_exception.exception.error)
Exemple #13
0
    def test_refresh(self):
        # Can never refresh without all data
        for credentials in (CredentialsV2("access_token", "refresh_token",
                                          "client_id"),
                            CredentialsV2("access_token", "refresh_token",
                                          None, "client_secret"),
                            CredentialsV2("access_token", None, "client_id",
                                          "client_secret")):
            self.assertEqual(credentials.refresh(), False)

        # With callback
        flexmock(RefreshCallback).should_receive("refreshed").with_args(
            'new_access_token', 'new_refresh_token').once()
        credentials = CredentialsV2("access_token", "refresh_token", "111",
                                    "222",
                                    RefreshCallback().refreshed)
        args = {
            'client_id': '111',
            'client_secret': '222',
            'refresh_token': 'refresh_token',
            'grant_type': 'refresh_token',
        }
        (flexmock(requests).should_receive('post').with_args(
            'https://www.box.com/api/oauth2/token', args).and_return(
                mocked_response({
                    'access_token': 'new_access_token',
                    'refresh_token': 'new_refresh_token'
                })).once())

        self.assertEqual(credentials.refresh(), True)
        self.assertEqual(credentials._access_token, 'new_access_token')
        self.assertEqual(credentials._refresh_token, 'new_refresh_token')

        # Without callback
        credentials = CredentialsV2("access_token", "refresh_token", "111",
                                    "222")
        args = {
            'client_id': '111',
            'client_secret': '222',
            'refresh_token': 'refresh_token',
            'grant_type': 'refresh_token',
        }
        (flexmock(requests).should_receive('post').with_args(
            'https://www.box.com/api/oauth2/token', args).and_return(
                mocked_response({
                    'access_token': 'new_access_token',
                    'refresh_token': 'new_refresh_token'
                })).once())

        self.assertEqual(credentials.refresh(), True)
        self.assertEqual(credentials._access_token, 'new_access_token')
        self.assertEqual(credentials._refresh_token, 'new_refresh_token')
    def test_automatic_refresh(self):
        credentials = CredentialsV2("access_token", "refresh_token", "client_id", "client_secret")
        client = BoxClient(credentials)

        requests_mock = flexmock(requests)

        # The first attempt, which is denied
        (
            requests_mock.should_receive("request")
            .with_args(
                "get", "https://api.box.com/2.0/users/me", params=None, data=None, headers=client.default_headers
            )
            .and_return(mocked_response(status_code=401))
            .once()
        )

        # The call to refresh the token
        (
            requests_mock.should_receive("post")
            .with_args(
                "https://www.box.com/api/oauth2/token",
                {
                    "client_id": "client_id",
                    "client_secret": "client_secret",
                    "refresh_token": "refresh_token",
                    "grant_type": "refresh_token",
                },
            )
            .and_return(mocked_response({"access_token": "new_access_token", "refresh_token": "new_refresh_token"}))
            .once()
        )

        # The second attempt with the new access token
        (
            requests_mock.should_receive("request")
            .with_args(
                "get",
                "https://api.box.com/2.0/users/me",
                params=None,
                data=None,
                headers={"Authorization": "Bearer new_access_token"},
            )
            .and_return(mocked_response({"name": "bla"}))
            .once()
        )

        result = client.get_user_info()
        self.assertDictEqual(result, {"name": "bla"})

        self.assertEqual(credentials._access_token, "new_access_token")
        self.assertEqual(credentials._refresh_token, "new_refresh_token")
Exemple #15
0
    def test_get_thumbnail_with_params(self):
        client = BoxClient("my_token")

        # Not available
        (flexmock(requests)
            .should_receive('request')
            .with_args("get",
                       'https://api.box.com/2.0/files/123/thumbnail.png',
                       params={},
                       data=None,
                       headers=client.default_headers,
                       stream=True)
            .and_return(mocked_response(status_code=302))
            .once())

        thumbnail = client.get_thumbnail(123)
        self.assertIsNone(thumbnail)

        # Already available
        (flexmock(requests)
            .should_receive('request')
            .with_args("get",
                       'https://api.box.com/2.0/files/123/thumbnail.png',
                       params={},
                       data=None,
                       headers=client.default_headers,
                       stream=True)
            .and_return(mocked_response(StringIO("Thumbnail contents")))
            .once())

        thumbnail = client.get_thumbnail(123)
        self.assertEqual('Thumbnail contents', thumbnail.read())

        # With size requirements
        (flexmock(requests)
            .should_receive('request')
            .with_args("get",
                       'https://api.box.com/2.0/files/123/thumbnail.png',
                       params={"min_height": 1,
                               "max_height": 2,
                               "min_width": 3,
                               "max_width": 4},
                       data=None,
                       headers=client.default_headers,
                       stream=True)
            .and_return(mocked_response(StringIO("Thumbnail contents")))
            .once())

        thumbnail = client.get_thumbnail(123, min_height=1, max_height=2, min_width=3, max_width=4)
        self.assertEqual('Thumbnail contents', thumbnail.read())
Exemple #16
0
    def test_add_comment_to_comment(self):
        client = BoxClient("my_token")

        response = {"type": "comment",
                    "id": 123,
                    "item": {"id": 123,
                             "type": "comment"},
                    "message": "test"
        }

        expected_data={"item": {"type": "comment",
                                "id": 123},
                       "message": "test"
        }

        (flexmock(requests)
            .should_receive('request')
            .with_args("post",
                 "https://api.box.com/2.0/comments",
                 params=None,
                 data=json.dumps(expected_data),
                 headers=client.default_headers)
        .and_return(mocked_response(response)))

        comment = client.add_comment(123, "comment", "test")
        self.assertEquals(comment, response)
    def test_overwrite_file(self):
        client = BoxClient("my_token")

        (flexmock(client).should_receive("_check_for_errors").once())

        expected_headers = {"If-Match": "some_tag"}
        expected_headers.update(client.default_headers)

        expected_response = mocked_response({"entries": [{"id": "1"}]})
        (
            flexmock(requests)
            .should_receive("post")
            .with_args(
                "https://upload.box.com/api/2.0/files/666/content",
                {"content_modified_at": "2006-05-04T03:02:01+00:00"},
                headers=expected_headers,
                files={"file": FileObjMatcher("hello world")},
            )
            .and_return(expected_response)
            .once()
        )

        result = client.overwrite_file(
            666,
            StringIO("hello world"),
            etag="some_tag",
            content_modified_at=datetime(2006, 5, 4, 3, 2, 1, 0, tzinfo=UTC()),
        )
        self.assertEqual({"id": "1"}, result)
Exemple #18
0
    def make_client(self, method, path, params=None, data=None, headers=None, endpoint="api", result=None, **kwargs):
        """
        Makes a new test client
        """
        client = BoxClient('my_token')
        (flexmock(client)
            .should_receive('_check_for_errors')
            .once())

        if headers:
            headers = dict(headers)
            headers.update(client.default_headers)
        else:
            headers = client.default_headers

        if isinstance(data, dict):
            data = json.dumps(data)

        (flexmock(requests)
            .should_receive('request')
            .with_args(method,
                       'https://%s.box.com/2.0/%s' % (endpoint, path),
                       params=params,
                       data=data,
                       headers=headers,
                       **kwargs)
            .and_return(mocked_response(result))
            .once())

        return client
    def test_get_long_poll_data(self):
        client = BoxClient("my_token")

        expected_response = {
            "type": "realtime_server",
            "url": "http://2.realtime.services.box.net/subscribe?channel=e9de49a73f0c93a872d7&stream_type=all",
            "ttl": "10",
            "max_retries": "10",
            "retry_timeout": 610,
        }

        response = mocked_response({"chunk_size": 1, "entries": [expected_response]})

        (
            flexmock(requests)
            .should_receive("request")
            .with_args(
                "options", "https://api.box.com/2.0/events", headers=client.default_headers, data=None, params=None
            )
            .and_return(response)
            .once()
        )

        actual_response = client._get_long_poll_data()
        self.assertDictEqual(expected_response, actual_response)
    def test_add_task(self):
        client = BoxClient("my_token")
        due_at = datetime.now()

        expected_data = {
            "item": {"type": "file", "id": 123},
            "action": "review",
            "due_at": str(due_at),
            "message": "test",
        }

        response = {"type": "task", "id": 123, "action": "review", "message": "test", "due_at": str(due_at)}

        (
            flexmock(requests)
            .should_receive("request")
            .with_args(
                "post",
                "https://api.box.com/2.0/tasks",
                params=None,
                data=json.dumps(expected_data),
                headers=client.default_headers,
            )
            .and_return(mocked_response(response))
        )

        task = client.add_task(123, due_at, message="test")
        self.assertEquals(task, response)
    def test_upload_file_with_timestamps(self):
        client = BoxClient("my_token")
        response = mocked_response({"entries": [{"id": "1"}]})

        (flexmock(client).should_receive("_check_for_errors").once())
        (
            flexmock(requests)
            .should_receive("post")
            .with_args(
                "https://upload.box.com/api/2.0/files/content",
                {
                    "parent_id": "666",
                    "content_modified_at": "2007-05-04T03:02:01+00:00",
                    "content_created_at": "2006-05-04T03:02:01+00:00",
                },
                headers=client.default_headers,
                files={"hello.jpg": ("hello.jpg", FileObjMatcher("hello world"))},
            )
            .and_return(response)
            .once()
        )

        result = client.upload_file(
            "hello.jpg",
            StringIO("hello world"),
            parent=666,
            content_created_at=datetime(2006, 5, 4, 3, 2, 1, 0, tzinfo=UTC()),
            content_modified_at=datetime(2007, 5, 4, 3, 2, 1, 0, tzinfo=UTC()),
        )
        self.assertEqual({"id": "1"}, result)
Exemple #22
0
    def test_long_poll_for_events_ok(self):
        client = BoxClient('my_token')

        longpoll_response = {
            'type': 'realtime_server',
            'url': 'http://2.realtime.services.box.net/subscribe?channel=12345678&stream_type=all',
            'ttl': '10',
            'max_retries': '10',
            'retry_timeout': 610
        }

        (flexmock(client)
            .should_receive('_get_long_poll_data')
            .and_return(longpoll_response)
            .once())

        expected_get_params = {
            'channel': ['12345678'],
            'stream_type': 'changes',
            'stream_position': 'some_stream_position',
        }

        (flexmock(requests)
            .should_receive('get')
            .with_args('http://2.realtime.services.box.net/subscribe', params=expected_get_params)
            .and_return(mocked_response({'message': 'new_message'}))
            .once())

        position = client.long_poll_for_events('some_stream_position', stream_type=EventFilter.CHANGES)
        self.assertEqual('some_stream_position', position)
Exemple #23
0
    def test_send_message(self):
        client = UberClient("*****@*****.**", "12345")
        response = mocked_response("omg")
        expected_data = {
            "email": "*****@*****.**",
            "deviceOS": settings.DEVICE_OS,
            "language": "en",
            "deviceModel": settings.DEVICE_MODEL,
            "app": "client",
            "messageType": "111",
            "token": "12345",
            "version": settings.UBER_VERSION,
            "device": settings.DEVICE_NAME,
            "aaa": "bbb",
        }

        (flexmock(UberClient).should_receive("_copy_location_for_message").with_args(self.mock_location, dict).times(1))

        (
            flexmock(UberClient)
            .should_receive("_post")
            .with_args(UberClient.ENDPOINT, data=DictPartialMatcher(expected_data))
            .times(1)
            .and_return(response)
        )

        (flexmock(UberClient).should_receive("_validate_message_response").with_args(response.json()).times(1))

        params = {"aaa": "bbb"}

        self.assertEqual("omg", client._send_message("111", params, self.mock_location))
Exemple #24
0
    def test_change_task(self):
        client = BoxClient("my_token")
        due_at = datetime.now()

        expected_data = {"action": "review",
                         "due_at": str(due_at),
                         "message": "changed"
        }

        response = {"type": "task",
                    "id": 123,
                    "action": "review",
                    "message": "changed",
                    "due_at": str(due_at)
        }

        (flexmock(requests)
            .should_receive('request')
            .with_args("put",
                 "https://api.box.com/2.0/tasks/123",
                 params=None,
                 data=json.dumps(expected_data),
                 headers=client.default_headers)
        .and_return(mocked_response(response)))

        changed = client.change_task(123, due_at, message="changed")
        self.assertEquals(changed, response)
Exemple #25
0
    def test_update_assignment(self):
        client = BoxClient("my_token")

        response = {"type": "task_assignment",
                    "id": 123,
                    "message": "All good !!!",
                    "resolution_state": "completed",
                    "assigned_to": {"type": "user",
                                    "id": 123,
                                    "login": "******"},
                    "item": {"type": "task",
                             "id": 123}
        }

        expected_data = {"resolution_state": "completed",
                         "message": "All good !!!"}

        (flexmock(requests)
            .should_receive('request')
            .with_args("put",
                 "https://api.box.com/2.0/task_assignments/123",
                 params=None,
                 data=json.dumps(expected_data),
                 headers=client.default_headers)
        .and_return(mocked_response(response)))

        changed = client.update_assignment(123, "completed", "All good !!!")
        self.assertEquals(changed, response)
Exemple #26
0
    def test_send_message(self):
        client = UberClient('*****@*****.**', '12345')
        response = mocked_response('omg')
        expected_data = {
            'email': '*****@*****.**',
            'deviceOS': settings.DEVICE_OS,
            'language': 'en',
            'deviceModel': settings.DEVICE_MODEL,
            'app': 'client',
            'messageType': '111',
            'token': '12345',
            'version': settings.UBER_VERSION,
            'device': settings.DEVICE_NAME,
            'aaa': 'bbb',
        }

        (flexmock(UberClient).should_receive(
            '_copy_location_for_message').with_args(self.mock_location,
                                                    dict).times(1))

        (flexmock(UberClient).should_receive('_post').with_args(
            UberClient.ENDPOINT, data=DictPartialMatcher(expected_data)).times(
                1).and_return(response))

        (flexmock(UberClient).should_receive(
            '_validate_message_response').with_args(response.json()).times(1))

        params = {'aaa': 'bbb'}

        self.assertEqual(
            'omg', client._send_message('111', params, self.mock_location))
Exemple #27
0
    def make_client(self, method, path, params=None, data=None, headers=None, endpoint="api", result=None, **kwargs):
        """
        Makes a new test client
        """
        client = BoxClient('my_token')
        (flexmock(client)
            .should_receive('_check_for_errors')
            .once())

        if headers:
            headers = dict(headers)
            headers.update(client.default_headers)
        else:
            headers = client.default_headers

        if isinstance(data, dict):
            data = json.dumps(data)

        (flexmock(requests)
            .should_receive('request')
            .with_args(method,
                       'https://%s.box.com/2.0/%s' % (endpoint, path),
                       params=params,
                       data=data,
                       headers=headers,
                       **kwargs)
            .and_return(mocked_response(result))
            .once())

        return client
Exemple #28
0
    def test_long_poll_for_events_ok(self):
        client = BoxClient('my_token')

        longpoll_response = {
            'type': 'realtime_server',
            'url': 'http://2.realtime.services.box.net/subscribe?channel=12345678&stream_type=all',
            'ttl': '10',
            'max_retries': '10',
            'retry_timeout': 610
        }

        (flexmock(client)
            .should_receive('_get_long_poll_data')
            .and_return(longpoll_response)
            .once())

        expected_get_params = {
            'channel': ['12345678'],
            'stream_type': 'changes',
            'stream_position': 'some_stream_position',
        }

        (flexmock(requests)
            .should_receive('get')
            .with_args('http://2.realtime.services.box.net/subscribe', params=expected_get_params)
            .and_return(mocked_response({'message': 'new_message'}))
            .once())

        position = client.long_poll_for_events('some_stream_position', stream_type=EventFilter.CHANGES)
        self.assertEqual('some_stream_position', position)
Exemple #29
0
    def test_add_assignment(self):
        client = BoxClient("my_token")

        response = {"type": "task_assignment",
                    "id": 123,
                    "assigned_to": {"type": "user",
                                    "id": 123,
                                    "login": "******"},
                    "item": {"type": "task",
                             "id": 123}
        }

        expected_data = {"task": {"id": 123,
                                  "type": "task"},
                         "assign_to": {"id": 123,
                                       "login": "******"}
        }

        (flexmock(requests)
            .should_receive('request')
            .with_args("post",
                 "https://api.box.com/2.0/task_assignments",
                 params=None,
                 data=json.dumps(expected_data),
                 headers=client.default_headers)
        .and_return(mocked_response(response)))

        assignment = client.assign_task(123, user_id=123, login="******")
        self.assertEquals(assignment, response)
Exemple #30
0
    def test_http_error_handling(self):
        (flexmock(self._client._session).should_receive("post").and_return(mocked_response("error!", 401)).times(1))

        with self.assertRaises(UberException) as expected_exception:
            self._client._post("http://www.test.org", {"nobody": "cares"})

        self.assertEqual(expected_exception.exception.error_code, 401)
        self.assertEqual(expected_exception.exception.description, "error!")
Exemple #31
0
    def test_automatic_refresh(self):
        credentials = CredentialsV2("access_token", "refresh_token", "client_id", "client_secret")
        client = BoxClient(credentials)

        requests_mock = flexmock(requests)

        # The first attempt, which is denied
        (requests_mock
            .should_receive('request')
            .with_args("get",
                       'https://api.box.com/2.0/users/me',
                       params=None,
                       data=None,
                       headers=client.default_headers)
            .and_return(mocked_response(status_code=401))
            .once())

        # The call to refresh the token
        (requests_mock
            .should_receive('post')
            .with_args('https://www.box.com/api/oauth2/token', {
                'client_id': 'client_id',
                'client_secret': 'client_secret',
                'refresh_token': 'refresh_token',
                'grant_type': 'refresh_token',
            })
            .and_return(mocked_response({"access_token": "new_access_token",
                                         "refresh_token": "new_refresh_token"}))\
            .once())

        # The second attempt with the new access token
        (requests_mock
            .should_receive('request')
            .with_args("get",
                       'https://api.box.com/2.0/users/me',
                       params=None,
                       data=None,
                       headers={"Authorization": "Bearer new_access_token"})
            .and_return(mocked_response({'name': 'bla'}))
            .once())

        result = client.get_user_info()
        self.assertDictEqual(result, {'name': 'bla'})

        self.assertEqual(credentials._access_token, "new_access_token")
        self.assertEqual(credentials._refresh_token, "new_refresh_token")
Exemple #32
0
    def test_start_authenticate_v1(self):
        response = mocked_response('<response><status>get_ticket_ok</status><ticket>golden_ticket</ticket></response>')
        (flexmock(requests)
            .should_receive('get')
            .with_args('https://www.box.com/api/1.0/rest?action=get_ticket&api_key=my_api_key')
            .and_return(response))

        self.assertEqual(start_authenticate_v1('my_api_key'), 'https://www.box.com/api/1.0/auth/golden_ticket')
Exemple #33
0
    def test_automatic_refresh(self):
        credentials = CredentialsV2("access_token", "refresh_token", "client_id", "client_secret")
        client = BoxClient(credentials)

        requests_mock = flexmock(requests)

        # The first attempt, which is denied
        requests_mock \
            .should_receive('request') \
            .with_args("get",
                       'https://api.box.com/2.0/users/me',
                       params=None,
                       data=None,
                       headers=client.default_headers) \
            .and_return(mocked_response(status_code=401)) \
            .once()

        # The call to refresh the token
        requests_mock \
            .should_receive('post')\
            .with_args('https://www.box.com/api/oauth2/token', {
                'client_id': 'client_id',
                'client_secret': 'client_secret',
                'refresh_token': 'refresh_token',
                'grant_type': 'refresh_token',
            })\
            .and_return(mocked_response({"access_token": "new_access_token",
                                         "refresh_token": "new_refresh_token"}))\
            .once()

        # The second attempt with the new access token
        requests_mock \
            .should_receive('request') \
            .with_args("get",
                       'https://api.box.com/2.0/users/me',
                       params=None,
                       data=None,
                       headers={"Authorization": "Bearer new_access_token"}) \
            .and_return(mocked_response({'name': 'bla'})) \
            .once()

        result = client.get_user_info()
        self.assertDictEqual(result, {'name': 'bla'})

        self.assertEqual(credentials._access_token, "new_access_token")
        self.assertEqual(credentials._refresh_token, "new_refresh_token")
Exemple #34
0
    def test_refresh(self):
        # Can never refresh without all data
        for credentials in (CredentialsV2("access_token", "refresh_token", "client_id"),
                            CredentialsV2("access_token", "refresh_token", None, "client_secret"),
                            CredentialsV2("access_token", None, "client_id", "client_secret")):
            self.assertEqual(credentials.refresh(), False)

        # With callback
        flexmock(RefreshCallback).should_receive("refreshed").with_args('new_access_token', 'new_refresh_token').once()
        credentials = CredentialsV2("access_token", "refresh_token", "111", "222", RefreshCallback().refreshed)
        args = {
            'client_id': '111',
            'client_secret': '222',
            'refresh_token': 'refresh_token',
            'grant_type': 'refresh_token',
        }
        (flexmock(requests)
            .should_receive('post')
            .with_args('https://www.box.com/api/oauth2/token', args)
            .and_return(mocked_response({'access_token': 'new_access_token',
                                         'refresh_token': 'new_refresh_token'}))
            .once())

        self.assertEqual(credentials.refresh(), True)
        self.assertEqual(credentials._access_token, 'new_access_token')
        self.assertEqual(credentials._refresh_token, 'new_refresh_token')

        # Without callback
        credentials = CredentialsV2("access_token", "refresh_token", "111", "222")
        args = {
            'client_id': '111',
            'client_secret': '222',
            'refresh_token': 'refresh_token',
            'grant_type': 'refresh_token',
        }
        (flexmock(requests)
            .should_receive('post')
            .with_args('https://www.box.com/api/oauth2/token', args)
            .and_return(mocked_response({'access_token': 'new_access_token',
                                         'refresh_token': 'new_refresh_token'}))
            .once())

        self.assertEqual(credentials.refresh(), True)
        self.assertEqual(credentials._access_token, 'new_access_token')
        self.assertEqual(credentials._refresh_token, 'new_refresh_token')
Exemple #35
0
    def test_http_error_handling(self):
        (flexmock(self._client._session).should_receive('post').and_return(
            mocked_response('error!', 401)).times(1))

        with self.assertRaises(UberException) as expected_exception:
            self._client._post('http://www.test.org', {'nobody': 'cares'})

        self.assertEqual(expected_exception.exception.error_code, 401)
        self.assertEqual(expected_exception.exception.description, 'error!')
Exemple #36
0
    def test_message_error_handling(self):
        error_data = {"messageType": "Error", "description": "something bad", "errorCode": 12345}

        (flexmock(self._client._session).should_receive("post").and_return(mocked_response(error_data)).times(1))

        with self.assertRaises(UberException) as expected_exception:
            self._client._send_message("crap")

        self.assertEqual(expected_exception.exception.description, "something bad")
        self.assertEqual(expected_exception.exception.error_code, 12345)
Exemple #37
0
    def test_start_authenticate_v1(self):
        response = mocked_response(
            '<response><status>get_ticket_ok</status><ticket>golden_ticket</ticket></response>'
        )
        (flexmock(requests).should_receive('get').with_args(
            'https://www.box.com/api/1.0/rest?action=get_ticket&api_key=my_api_key'
        ).and_return(response))

        self.assertEqual(start_authenticate_v1('my_api_key'),
                         'https://www.box.com/api/1.0/auth/golden_ticket')
Exemple #38
0
    def test_get_client_with_retry(self):
        client = BoxClient("my_token")



        (flexmock(requests)
            .should_receive('request')
            .with_args("get",
                       'https://api.box.com/2.0/files/123/thumbnail.png',
                       params={},
                       data=None,
                       headers=client.default_headers,
                       stream=True)
            .and_return(mocked_response(status_code=202, headers={"Location": "http://box.com/url_to_thumbnail", "Retry-After": "1"}),
                        mocked_response(StringIO("Thumbnail contents")))
            .one_by_one())

        thumbnail = client.get_thumbnail(123, max_wait=1)
        self.assertEqual('Thumbnail contents', thumbnail.read())
Exemple #39
0
    def test_geolocation_multiple_results(self):
        expected_args = {
            'sensor': 'false',
            'address': 'my magic address'
        }

        expected_results = {
            'status': 'OK',
            'results': [{
                'address_components': 'lol1',
                'some_field': 'some_field1',
                'geometry': {
                    'location': {
                        'lat': 1,
                        'lng': 2,
                    }
                }

            },
            {
                'address_components': 'lol2',
                'some_field': 'some_field2',
                'geometry': {
                    'location': {
                        'lat': 3,
                        'lng': 4,
                    }
                }

            }]

        }
        (flexmock(requests)
            .should_receive('get')
            .with_args('http://maps.googleapis.com/maps/api/geocode/json', params=expected_args)
            .and_return(mocked_response(expected_results))
        )

        results = geolocate('my magic address')
        self.assertEqual(results, [
            {
                'address_components': 'lol1',
                'some_field': 'some_field1',
                'geometry': {'location': {'lat': 1, 'lng': 2}},
                'latitude': 1,
                'longitude': 2,
            },
            {
                'address_components': 'lol2',
                'some_field': 'some_field2',
                'geometry': {'location': {'lat': 3, 'lng': 4}},
                'latitude': 3,
                'longitude': 4,
            }
        ])
Exemple #40
0
    def test_post(self):
        data = {'a': 'b'}

        (flexmock(self._client._session)
         .should_receive('post')
         .with_args('http://www.boo.org', json.dumps(data), headers=self._client._headers)
         .and_return(mocked_response({'aaa': 'bbb'}))
         .times(1)
        )

        self.assertEqual(self._client._post('http://www.boo.org', data=data).json(), {'aaa': 'bbb'})
Exemple #41
0
    def test_post(self):
        data = {'a': 'b'}

        (flexmock(self._client._session)
         .should_receive('post')
         .with_args('http://www.boo.org', json.dumps(data), headers=self._client._headers)
         .and_return(mocked_response({'aaa': 'bbb'}))
         .times(1)
        )

        self.assertEqual(self._client._post('http://www.boo.org', data=data).json(), {'aaa': 'bbb'})
Exemple #42
0
    def test_http_error_handling(self):
        (flexmock(self._client._session)
         .should_receive('post')
         .and_return(mocked_response('error!', 401))
         .times(1)
        )

        with self.assertRaises(UberException) as expected_exception:
            self._client._post('http://www.test.org', {'nobody': 'cares'})

        self.assertEqual(expected_exception.exception.error_code, 401)
        self.assertEqual(expected_exception.exception.description, 'error!')
Exemple #43
0
    def test_post(self):
        data = {"a": "b"}

        (
            flexmock(self._client._session)
            .should_receive("post")
            .with_args("http://www.boo.org", json.dumps(data), headers=self._client._headers)
            .and_return(mocked_response({"aaa": "bbb"}))
            .times(1)
        )

        self.assertEqual(self._client._post("http://www.boo.org", data=data).json(), {"aaa": "bbb"})
Exemple #44
0
    def test_handle_error(self):
        client = BoxClient('my_token')

        self.assertIsNone(client._check_for_errors(mocked_response()))

        with self.assertRaises(ItemAlreadyExists) as expected_exception:
            client._check_for_errors(mocked_response('something terrible', status_code=CONFLICT))
        self.assertEqual(CONFLICT, expected_exception.exception.status_code)
        self.assertEqual('something terrible', expected_exception.exception.message)

        with self.assertRaises(ItemDoesNotExist) as expected_exception:
            client._check_for_errors(mocked_response('something terrible', status_code=NOT_FOUND))
        self.assertEqual(NOT_FOUND, expected_exception.exception.status_code)
        self.assertEqual('something terrible', expected_exception.exception.message)

        with self.assertRaises(PreconditionFailed) as expected_exception:
            client._check_for_errors(mocked_response('something terrible', status_code=PRECONDITION_FAILED))
        self.assertEqual(PRECONDITION_FAILED, expected_exception.exception.status_code)
        self.assertEqual('something terrible', expected_exception.exception.message)

        with self.assertRaises(BoxAccountUnauthorized) as expected_exception:
            client._check_for_errors(mocked_response('something terrible', status_code=UNAUTHORIZED))
        self.assertEqual(UNAUTHORIZED, expected_exception.exception.status_code)
        self.assertEqual('something terrible', expected_exception.exception.message)

        # unknown code
        with self.assertRaises(BoxClientException) as expected_exception:
            client._check_for_errors(mocked_response('something terrible', status_code=599))
        self.assertEqual(599, expected_exception.exception.status_code)
        self.assertEqual('something terrible', expected_exception.exception.message)
Exemple #45
0
    def test_handle_error(self):
        client = BoxClient('my_token')

        self.assertIsNone(client._check_for_errors(mocked_response()))

        with self.assertRaises(ItemAlreadyExists) as expected_exception:
            client._check_for_errors(mocked_response('something terrible', status_code=CONFLICT))
        self.assertEqual(CONFLICT, expected_exception.exception.status_code)
        self.assertEqual('something terrible', expected_exception.exception.message)

        with self.assertRaises(ItemDoesNotExist) as expected_exception:
            client._check_for_errors(mocked_response('something terrible', status_code=NOT_FOUND))
        self.assertEqual(NOT_FOUND, expected_exception.exception.status_code)
        self.assertEqual('something terrible', expected_exception.exception.message)

        with self.assertRaises(PreconditionFailed) as expected_exception:
            client._check_for_errors(mocked_response('something terrible', status_code=PRECONDITION_FAILED))
        self.assertEqual(PRECONDITION_FAILED, expected_exception.exception.status_code)
        self.assertEqual('something terrible', expected_exception.exception.message)

        with self.assertRaises(BoxAccountUnauthorized) as expected_exception:
            client._check_for_errors(mocked_response('something terrible', status_code=UNAUTHORIZED))
        self.assertEqual(UNAUTHORIZED, expected_exception.exception.status_code)
        self.assertEqual('something terrible', expected_exception.exception.message)

        # unknown code
        with self.assertRaises(BoxClientException) as expected_exception:
            client._check_for_errors(mocked_response('something terrible', status_code=599))
        self.assertEqual(599, expected_exception.exception.status_code)
        self.assertEqual('something terrible', expected_exception.exception.message)
Exemple #46
0
    def test_delete_assignment(self):
        client = BoxClient("my_token")

        (flexmock(requests)
            .should_receive('request')
            .with_args("delete",
                 "https://api.box.com/2.0/task_assignments/123",
                 params=None,
                 data=None,
                 headers=client.default_headers)
        .and_return(mocked_response(status_code=204)))

        self.assertIsNone(client.delete_assignment(123))
Exemple #47
0
    def test_bounds(self):
        expected_args = {
            'sensor': 'false',
            'address': 'my magic address',
            'bounds': '1,2|3,4'
        }
        (flexmock(requests)
            .should_receive('get')
            .with_args('http://maps.googleapis.com/maps/api/geocode/json', params=expected_args)
            .and_return(mocked_response({'status': 'ZERO_RESULTS'}))
        )

        geolocate('my magic address', bounds=[GPSLocation(1, 2), GPSLocation(3, 4)])
Exemple #48
0
    def test_components(self):
        expected_args = {
            'sensor': 'false',
            'address': 'my magic address',
            'components': 'country:US|administrative_area:SF'
        }
        (flexmock(requests)
            .should_receive('get')
            .with_args('http://maps.googleapis.com/maps/api/geocode/json', params=expected_args)
            .and_return(mocked_response({'status': 'ZERO_RESULTS'}))
        )

        results = geolocate('my magic address', country='US', administrative_area='SF')
Exemple #49
0
    def test_geolocation_no_results(self):
        expected_args = {
            'sensor': 'false',
            'address': 'my magic address'
        }
        (flexmock(requests)
            .should_receive('get')
            .with_args('http://maps.googleapis.com/maps/api/geocode/json', params=expected_args)
            .and_return(mocked_response({'status': 'ZERO_RESULTS'}))
        )

        results = geolocate('my magic address')
        self.assertEqual(results, [])
Exemple #50
0
    def test_file_get_tasks(self):
        client = BoxClient("my_token")

        response = { "total_count": 0, "entries": [] }

        (flexmock(requests)
            .should_receive('request')
            .with_args("get",
                       'https://api.box.com/2.0/files/123/tasks',
                       params=None,
                       data=None,
                       headers=client.default_headers)
        .and_return(mocked_response(response)))

        tasks = client.get_file_tasks(123)
        self.assertEquals(tasks, response)
Exemple #51
0
    def test_message_error_handling(self):
        error_data = {
            'messageType': 'Error',
            'description': 'something bad',
            'errorCode': 12345,
        }

        (flexmock(self._client._session).should_receive('post').and_return(
            mocked_response(error_data)).times(1))

        with self.assertRaises(UberException) as expected_exception:
            self._client._send_message('crap')

        self.assertEqual(expected_exception.exception.description,
                         'something bad')
        self.assertEqual(expected_exception.exception.error_code, 12345)
Exemple #52
0
    def test_get_thumbnail(self):
        client = BoxClient("my_token")

        # Delayed without wait allowed
        (flexmock(requests)
            .should_receive('request')
            .with_args("get",
                       'https://api.box.com/2.0/files/123/thumbnail.png',
                       params={},
                       data=None,
                       headers=client.default_headers,
                       stream=True)
            .and_return(mocked_response(status_code=202, headers={"Location": "http://box.com", "Retry-After": "5"}))
            .once())

        thumbnail = client.get_thumbnail(123)
        self.assertIsNone(thumbnail)
Exemple #53
0
    def test_get_assignment_information(self):
        client = BoxClient("my_token")

        response = {"type": "task_assignment",
                    "id": 123
        }

        (flexmock(requests)
            .should_receive('request')
            .with_args("get",
                 "https://api.box.com/2.0/task_assignments/123",
                 params=None,
                 data=None,
                 headers=client.default_headers)
        .and_return(mocked_response(response)))

        assignment = client.get_assignment(123)
        self.assertEquals(assignment, response)
Exemple #54
0
    def test_upload_file_with_parent_as_dict(self):
        client = BoxClient('my_token')
        (flexmock(client)
            .should_receive('_check_for_errors')
            .once())

        response = mocked_response({'entries': [{'id': '1'}]})
        (flexmock(requests)
            .should_receive('post')
            .with_args('https://upload.box.com/api/2.0/files/content',
                       {'parent_id': '666'},
                       headers=client.default_headers,
                       files={'hello.jpg': ('hello.jpg', FileObjMatcher('hello world'))})
            .and_return(response)
            .once())

        result = client.upload_file('hello.jpg', StringIO('hello world'), parent={'id': 666})
        self.assertEqual({'id': '1'}, result)