Python oauth2client.client 模块,OAuth2Credentials() 实例源码

我们从Python开源项目中,提取了以下44个代码示例,用于说明如何使用oauth2client.client.OAuth2Credentials()

项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def test_refresh_failure(self):
        """
        Failure to refresh the access token should be treated as auth error.
        """

        def raise_invalid_grant(*args, **kwargs):
            raise AccessTokenRefreshError()

        with mock.patch('sndlatr.models.get_credentials') as getter, \
            self.notify_mock() as notify:
            cred = mock.MagicMock(spec=OAuth2Credentials)
            getter.return_value = cred
            cred.refresh.side_effect = raise_invalid_grant

            job = self.create_job(error_cnt=self.JOB_MAX_RETRIES)
            resp = self._post_send(job)
            self.assertEquals(resp.status_int, 200)
            notify.assert_called_with(job, 'auth')
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def setUp(self):
        access_token = 'foo'
        client_id = 'some_client_id'
        client_secret = 'cOuDdkfjxxnv+'
        refresh_token = '1/0/a.df219fjls0'
        token_expiry = datetime.datetime.utcnow()
        user_agent = 'refresh_checker/1.0'

        self.credentials = OAuth2Credentials(
            access_token, client_id, client_secret,
            refresh_token, token_expiry, GOOGLE_TOKEN_URI,
            user_agent)

        self.key_name = 'id'
        self.key_value = '1'
        self.property_name = 'credentials'
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def setUp(self):
        access_token = 'foo'
        client_id = 'some_client_id'
        client_secret = 'cOuDdkfjxxnv+'
        refresh_token = '1/0/a.df219fjls0'
        token_expiry = datetime.datetime.utcnow()
        user_agent = 'refresh_checker/1.0'
        self.credentials = client.OAuth2Credentials(
            access_token, client_id, client_secret,
            refresh_token, token_expiry, oauth2client.GOOGLE_TOKEN_URI,
            user_agent, revoke_uri=oauth2client.GOOGLE_REVOKE_URI,
            scopes='foo', token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI)

        # Provoke a failure if @_helpers.positional is not respected.
        self.old_positional_enforcement = (
            _helpers.positional_parameters_enforcement)
        _helpers.positional_parameters_enforcement = (
            _helpers.POSITIONAL_EXCEPTION)
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def test_get_access_token_with_http(self, expires_in, refresh_mock):
        credentials = client.OAuth2Credentials(None, None, None, None,
                                               None, None, None)
        # Make sure access_token_expired returns True
        credentials.invalid = True
        # Specify a token so we can use it in the response.
        credentials.access_token = 'ya29-s3kr3t'

        http_obj = object()
        token_info = credentials.get_access_token(http_obj)
        self.assertIsInstance(token_info, client.AccessTokenInfo)
        self.assertEqual(token_info.access_token,
                         credentials.access_token)
        self.assertEqual(token_info.expires_in,
                         expires_in.return_value)

        expires_in.assert_called_once_with()
        refresh_mock.assert_called_once_with(http_obj)
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
def setUp(self):
        access_token = 'foo'
        client_id = 'some_client_id'
        client_secret = 'cOuDdkfjxxnv+'
        refresh_token = '1/0/a.df219fjls0'
        token_expiry = datetime.datetime.utcnow()
        user_agent = 'refresh_checker/1.0'

        self.credentials = OAuth2Credentials(
            access_token, client_id, client_secret,
            refresh_token, token_expiry, GOOGLE_TOKEN_URI,
            user_agent)

        self.key_name = 'id'
        self.key_value = '1'
        self.property_name = 'credentials'
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
def setUp(self):
        access_token = 'foo'
        client_id = 'some_client_id'
        client_secret = 'cOuDdkfjxxnv+'
        refresh_token = '1/0/a.df219fjls0'
        token_expiry = datetime.datetime.utcnow()
        user_agent = 'refresh_checker/1.0'
        self.credentials = client.OAuth2Credentials(
            access_token, client_id, client_secret,
            refresh_token, token_expiry, oauth2client.GOOGLE_TOKEN_URI,
            user_agent, revoke_uri=oauth2client.GOOGLE_REVOKE_URI,
            scopes='foo', token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI)

        # Provoke a failure if @_helpers.positional is not respected.
        self.old_positional_enforcement = (
            _helpers.positional_parameters_enforcement)
        _helpers.positional_parameters_enforcement = (
            _helpers.POSITIONAL_EXCEPTION)
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
def test_get_access_token_with_http(self, expires_in, refresh_mock):
        credentials = client.OAuth2Credentials(None, None, None, None,
                                               None, None, None)
        # Make sure access_token_expired returns True
        credentials.invalid = True
        # Specify a token so we can use it in the response.
        credentials.access_token = 'ya29-s3kr3t'

        http_obj = object()
        token_info = credentials.get_access_token(http_obj)
        self.assertIsInstance(token_info, client.AccessTokenInfo)
        self.assertEqual(token_info.access_token,
                         credentials.access_token)
        self.assertEqual(token_info.expires_in,
                         expires_in.return_value)

        expires_in.assert_called_once_with()
        refresh_mock.assert_called_once_with(http_obj)
项目:gee-gateway    作者:openforis    | 项目源码 | 文件源码
def initialize(ee_account='', ee_key_path='', ee_user_token=''):
    try:
        if ee_user_token:
            credentials = OAuth2Credentials(ee_user_token, None, None, None, None, None, None)
            ee.InitializeThread(credentials)
        elif ee_account and ee_key_path:
            credentials = ServiceAccountCredentials.from_p12_keyfile(
                service_account_email=ee_account,
                filename=ee_key_path,
                private_key_password='notasecret',
                scopes=ee.oauth.SCOPE + ' https://www.googleapis.com/auth/drive')
            ee.Initialize(credentials)
        else:
            ee.Initialize()
    except (EEException, TypeError):
        pass
项目:forseti-security    作者:GoogleCloudPlatform    | 项目源码 | 文件源码
def _set_ua_and_scopes(credentials):
    """Set custom Forseti user agent and add cloud scopes on credential object.

    Args:
        credentials (client.OAuth2Credentials): The credentials object used to
            authenticate all http requests.

    Returns:
        client.OAuth2Credentials: The credentials object with the user agent
            attribute set or updated.
    """
    if isinstance(credentials, client.OAuth2Credentials):
        user_agent = credentials.user_agent
        if (not user_agent or
                forseti_security.__package_name__ not in user_agent):

            credentials.user_agent = (
                'Python-httplib2/{} (gzip), {}/{}'.format(
                    httplib2.__version__,
                    forseti_security.__package_name__,
                    forseti_security.__version__))
        if (isinstance(credentials, client.GoogleCredentials) and
                credentials.create_scoped_required()):
            credentials = credentials.create_scoped(list(CLOUD_SCOPES))
    return credentials
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def test_get_and_set_with_json_credentials_stored(self):
        access_token = 'foo'
        client_id = 'some_client_id'
        client_secret = 'cOuDdkfjxxnv+'
        refresh_token = '1/0/a.df219fjls0'
        token_expiry = datetime.datetime.utcnow()
        user_agent = 'refresh_checker/1.0'

        credentials = client.OAuth2Credentials(
            access_token, client_id, client_secret,
            refresh_token, token_expiry, oauth2client.GOOGLE_TOKEN_URI,
            user_agent)

        # Setting autospec on a mock with an iterable side_effect is
        # currently broken (http://bugs.python.org/issue17826), so instead
        # we patch twice.
        with mock.patch.object(keyring, 'get_password',
                               return_value=None,
                               autospec=True) as get_password:
            with mock.patch.object(keyring, 'set_password',
                                   return_value=None,
                                   autospec=True) as set_password:
                store = keyring_storage.Storage('my_unit_test', 'me')
                self.assertEquals(None, store.get())

                store.put(credentials)

                set_password.assert_called_once_with(
                    'my_unit_test', 'me', credentials.to_json())
                get_password.assert_called_once_with('my_unit_test', 'me')

        with mock.patch.object(keyring, 'get_password',
                               return_value=credentials.to_json(),
                               autospec=True) as get_password:
            restored = store.get()
            self.assertEqual('foo', restored.access_token)
            self.assertEqual('some_client_id', restored.client_id)
            get_password.assert_called_once_with('my_unit_test', 'me')
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()

        access_token = 'foo'
        client_id = 'some_client_id'
        client_secret = 'cOuDdkfjxxnv+'
        refresh_token = '1/0/a.df219fjls0'
        token_expiry = datetime.datetime.utcnow()
        user_agent = 'refresh_checker/1.0'
        self.credentials = client.OAuth2Credentials(
            access_token, client_id, client_secret,
            refresh_token, token_expiry, oauth2client.GOOGLE_TOKEN_URI,
            user_agent)
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def _create_test_credentials(expiration=None):
    access_token = 'foo'
    client_secret = 'cOuDdkfjxxnv+'
    refresh_token = '1/0/a.df219fjls0'
    token_expiry = expiration or (
        datetime.datetime.utcnow() + datetime.timedelta(seconds=3600))
    token_uri = 'https://www.google.com/accounts/o8/oauth2/token'
    user_agent = 'refresh_checker/1.0'

    credentials = client.OAuth2Credentials(
        access_token, 'test-client-id', client_secret,
        refresh_token, token_expiry, token_uri,
        user_agent)
    return credentials
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def test_recursive_authorize(self):
        # Tests that OAuth2Credentials doesn't introduce new method
        # constraints. Formerly, OAuth2Credentials.authorize monkeypatched the
        # request method of the passed in HTTP object with a wrapper annotated
        # with @_helpers.positional(1). Since the original method has no such
        # annotation, that meant that the wrapper was violating the contract of
        # the original method by adding a new requirement to it. And in fact
        # the wrapper itself doesn't even respect that requirement. So before
        # the removal of the annotation, this test would fail.
        token_response = {'access_token': '1/3w', 'expires_in': 3600}
        encoded_response = json.dumps(token_response).encode('utf-8')
        http = http_mock.HttpMock(data=encoded_response)
        http = self.credentials.authorize(http)
        http = self.credentials.authorize(http)
        transport.request(http, 'http://example.com')
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def test_to_from_json(self):
        json = self.credentials.to_json()
        instance = client.OAuth2Credentials.from_json(json)
        self.assertEqual(client.OAuth2Credentials, type(instance))
        instance.token_expiry = None
        self.credentials.token_expiry = None

        self.assertEqual(instance.__dict__, self.credentials.__dict__)
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def test_from_json_token_expiry(self):
        data = json.loads(self.credentials.to_json())
        data['token_expiry'] = None
        instance = client.OAuth2Credentials.from_json(json.dumps(data))
        self.assertIsInstance(instance, client.OAuth2Credentials)
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def test_unicode_header_checks(self):
        access_token = u'foo'
        client_id = u'some_client_id'
        client_secret = u'cOuDdkfjxxnv+'
        refresh_token = u'1/0/a.df219fjls0'
        token_expiry = str(datetime.datetime.utcnow())
        token_uri = str(oauth2client.GOOGLE_TOKEN_URI)
        revoke_uri = str(oauth2client.GOOGLE_REVOKE_URI)
        user_agent = u'refresh_checker/1.0'
        credentials = client.OAuth2Credentials(
            access_token, client_id, client_secret, refresh_token,
            token_expiry, token_uri, user_agent, revoke_uri=revoke_uri)

        # First, test that we correctly encode basic objects, making sure
        # to include a bytes object. Note that oauth2client will normalize
        # everything to bytes, no matter what python version we're in.
        http = credentials.authorize(http_mock.HttpMock())
        headers = {u'foo': 3, b'bar': True, 'baz': b'abc'}
        cleaned_headers = {b'foo': b'3', b'bar': b'True', b'baz': b'abc'}
        transport.request(
            http, u'http://example.com', method=u'GET', headers=headers)
        for k, v in cleaned_headers.items():
            self.assertTrue(k in http.headers)
            self.assertEqual(v, http.headers[k])

        # Next, test that we do fail on unicode.
        unicode_str = six.unichr(40960) + 'abcd'
        with self.assertRaises(client.NonAsciiHeaderError):
            transport.request(
                http, u'http://example.com', method=u'GET',
                headers={u'foo': unicode_str})
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def test_no_unicode_in_request_params(self):
        access_token = u'foo'
        client_id = u'some_client_id'
        client_secret = u'cOuDdkfjxxnv+'
        refresh_token = u'1/0/a.df219fjls0'
        token_expiry = str(datetime.datetime.utcnow())
        token_uri = str(oauth2client.GOOGLE_TOKEN_URI)
        revoke_uri = str(oauth2client.GOOGLE_REVOKE_URI)
        user_agent = u'refresh_checker/1.0'
        credentials = client.OAuth2Credentials(
            access_token, client_id, client_secret, refresh_token,
            token_expiry, token_uri, user_agent, revoke_uri=revoke_uri)

        http = http_mock.HttpMock()
        http = credentials.authorize(http)
        transport.request(
            http, u'http://example.com', method=u'GET',
            headers={u'foo': u'bar'})
        for k, v in six.iteritems(http.headers):
            self.assertIsInstance(k, six.binary_type)
            self.assertIsInstance(v, six.binary_type)

        # Test again with unicode strings that can't simply be converted
        # to ASCII.
        with self.assertRaises(client.NonAsciiHeaderError):
            transport.request(
                http, u'http://example.com', method=u'GET',
                headers={u'foo': u'\N{COMET}'})

        self.credentials.token_response = 'foobar'
        instance = client.OAuth2Credentials.from_json(
            self.credentials.to_json())
        self.assertEqual('foobar', instance.token_response)
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def test__expires_in_no_expiry(self):
        credentials = client.OAuth2Credentials(None, None, None, None,
                                               None, None, None)
        self.assertIsNone(credentials.token_expiry)
        self.assertIsNone(credentials._expires_in())
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def test__expires_in_expired(self, utcnow):
        credentials = client.OAuth2Credentials(None, None, None, None,
                                               None, None, None)
        credentials.token_expiry = datetime.datetime.utcnow()
        now = credentials.token_expiry + datetime.timedelta(seconds=1)
        self.assertLess(credentials.token_expiry, now)
        utcnow.return_value = now
        self.assertEqual(credentials._expires_in(), 0)
        utcnow.assert_called_once_with()
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def test__expires_in_not_expired(self, utcnow):
        credentials = client.OAuth2Credentials(None, None, None, None,
                                               None, None, None)
        credentials.token_expiry = datetime.datetime.utcnow()
        seconds = 1234
        now = credentials.token_expiry - datetime.timedelta(seconds=seconds)
        self.assertLess(now, credentials.token_expiry)
        utcnow.return_value = now
        self.assertEqual(credentials._expires_in(), seconds)
        utcnow.assert_called_once_with()
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def _do_refresh_request_test_helper(self, response, content,
                                        error_msg, logger, gen_body,
                                        gen_headers, store=None):
        token_uri = 'http://token_uri'
        credentials = client.OAuth2Credentials(None, None, None, None,
                                               None, token_uri, None)
        credentials.store = store
        http = http_mock.HttpMock(headers=response, data=content)

        with self.assertRaises(
                client.HttpAccessTokenRefreshError) as exc_manager:
            credentials._do_refresh_request(http)

        self.assertEqual(exc_manager.exception.args, (error_msg,))
        self.assertEqual(exc_manager.exception.status, response.status)

        # Verify mocks.
        self.assertEqual(http.requests, 1)
        self.assertEqual(http.uri, token_uri)
        self.assertEqual(http.method, 'POST')
        self.assertEqual(http.body, gen_body.return_value)
        self.assertEqual(http.headers, gen_headers.return_value)

        call1 = mock.call('Refreshing access_token')
        failure_template = 'Failed to retrieve access token: %s'
        call2 = mock.call(failure_template, content)
        self.assertEqual(logger.info.mock_calls, [call1, call2])
        if store is not None:
            store.locked_put.assert_called_once_with(credentials)
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def _do_revoke_test_helper(self, response, content,
                               error_msg, logger, store=None):
        credentials = client.OAuth2Credentials(
            None, None, None, None, None, None, None,
            revoke_uri=oauth2client.GOOGLE_REVOKE_URI)
        credentials.store = store

        http = http_mock.HttpMock(headers=response, data=content)
        token = u's3kr3tz'

        if response.status == http_client.OK:
            self.assertFalse(credentials.invalid)
            self.assertIsNone(credentials._do_revoke(http, token))
            self.assertTrue(credentials.invalid)
            if store is not None:
                store.delete.assert_called_once_with()
        else:
            self.assertFalse(credentials.invalid)
            with self.assertRaises(client.TokenRevokeError) as exc_manager:
                credentials._do_revoke(http, token)
            # Make sure invalid was not flipped on.
            self.assertFalse(credentials.invalid)
            self.assertEqual(exc_manager.exception.args, (error_msg,))
            if store is not None:
                store.delete.assert_not_called()

        revoke_uri = oauth2client.GOOGLE_REVOKE_URI + '?token=' + token

        # Verify mocks.
        self.assertEqual(http.requests, 1)
        self.assertEqual(http.uri, revoke_uri)
        self.assertEqual(http.method, 'GET')
        self.assertIsNone(http.body)
        self.assertIsNone(http.headers)

        logger.info.assert_called_once_with('Revoking token')
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def _do_retrieve_scopes_test_helper(self, response, content,
                                        error_msg, logger, scopes=None):
        credentials = client.OAuth2Credentials(
            None, None, None, None, None, None, None,
            token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI)
        http = http_mock.HttpMock(headers=response, data=content)
        token = u's3kr3tz'

        if response.status == http_client.OK:
            self.assertEqual(credentials.scopes, set())
            self.assertIsNone(
                credentials._do_retrieve_scopes(http, token))
            self.assertEqual(credentials.scopes, scopes)
        else:
            self.assertEqual(credentials.scopes, set())
            with self.assertRaises(client.Error) as exc_manager:
                credentials._do_retrieve_scopes(http, token)
            # Make sure scopes were not changed.
            self.assertEqual(credentials.scopes, set())
            self.assertEqual(exc_manager.exception.args, (error_msg,))

        token_uri = _helpers.update_query_params(
            oauth2client.GOOGLE_TOKEN_INFO_URI,
            {'fields': 'scope', 'access_token': token})

        # Verify mocks.
        self.assertEqual(http.requests, 1)
        assertUrisEqual(self, token_uri, http.uri)
        self.assertEqual(http.method, 'GET')
        self.assertIsNone(http.body)
        self.assertIsNone(http.headers)
        logger.info.assert_called_once_with('Refreshing scopes')
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def _create_test_credentials(self, client_id='some_client_id',
                                 expiration=None):
        access_token = 'foo'
        client_secret = 'cOuDdkfjxxnv+'
        refresh_token = '1/0/a.df219fjls0'
        token_expiry = expiration or datetime.datetime.utcnow()
        token_uri = 'https://www.google.com/accounts/o8/oauth2/token'
        user_agent = 'refresh_checker/1.0'

        credentials = client.OAuth2Credentials(
            access_token, client_id, client_secret,
            refresh_token, token_expiry, token_uri,
            user_agent)
        return credentials
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
def test_get_and_set_with_json_credentials_stored(self):
        access_token = 'foo'
        client_id = 'some_client_id'
        client_secret = 'cOuDdkfjxxnv+'
        refresh_token = '1/0/a.df219fjls0'
        token_expiry = datetime.datetime.utcnow()
        user_agent = 'refresh_checker/1.0'

        credentials = client.OAuth2Credentials(
            access_token, client_id, client_secret,
            refresh_token, token_expiry, oauth2client.GOOGLE_TOKEN_URI,
            user_agent)

        # Setting autospec on a mock with an iterable side_effect is
        # currently broken (http://bugs.python.org/issue17826), so instead
        # we patch twice.
        with mock.patch.object(keyring, 'get_password',
                               return_value=None,
                               autospec=True) as get_password:
            with mock.patch.object(keyring, 'set_password',
                                   return_value=None,
                                   autospec=True) as set_password:
                store = keyring_storage.Storage('my_unit_test', 'me')
                self.assertEquals(None, store.get())

                store.put(credentials)

                set_password.assert_called_once_with(
                    'my_unit_test', 'me', credentials.to_json())
                get_password.assert_called_once_with('my_unit_test', 'me')

        with mock.patch.object(keyring, 'get_password',
                               return_value=credentials.to_json(),
                               autospec=True) as get_password:
            restored = store.get()
            self.assertEqual('foo', restored.access_token)
            self.assertEqual('some_client_id', restored.client_id)
            get_password.assert_called_once_with('my_unit_test', 'me')
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()

        access_token = 'foo'
        client_id = 'some_client_id'
        client_secret = 'cOuDdkfjxxnv+'
        refresh_token = '1/0/a.df219fjls0'
        token_expiry = datetime.datetime.utcnow()
        user_agent = 'refresh_checker/1.0'
        self.credentials = client.OAuth2Credentials(
            access_token, client_id, client_secret,
            refresh_token, token_expiry, oauth2client.GOOGLE_TOKEN_URI,
            user_agent)
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
def _create_test_credentials(expiration=None):
    access_token = 'foo'
    client_secret = 'cOuDdkfjxxnv+'
    refresh_token = '1/0/a.df219fjls0'
    token_expiry = expiration or (
        datetime.datetime.utcnow() + datetime.timedelta(seconds=3600))
    token_uri = 'https://www.google.com/accounts/o8/oauth2/token'
    user_agent = 'refresh_checker/1.0'

    credentials = client.OAuth2Credentials(
        access_token, 'test-client-id', client_secret,
        refresh_token, token_expiry, token_uri,
        user_agent)
    return credentials
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
def test_recursive_authorize(self):
        # Tests that OAuth2Credentials doesn't introduce new method
        # constraints. Formerly, OAuth2Credentials.authorize monkeypatched the
        # request method of the passed in HTTP object with a wrapper annotated
        # with @_helpers.positional(1). Since the original method has no such
        # annotation, that meant that the wrapper was violating the contract of
        # the original method by adding a new requirement to it. And in fact
        # the wrapper itself doesn't even respect that requirement. So before
        # the removal of the annotation, this test would fail.
        token_response = {'access_token': '1/3w', 'expires_in': 3600}
        encoded_response = json.dumps(token_response).encode('utf-8')
        http = http_mock.HttpMock(data=encoded_response)
        http = self.credentials.authorize(http)
        http = self.credentials.authorize(http)
        transport.request(http, 'http://example.com')
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
def test_to_from_json(self):
        json = self.credentials.to_json()
        instance = client.OAuth2Credentials.from_json(json)
        self.assertEqual(client.OAuth2Credentials, type(instance))
        instance.token_expiry = None
        self.credentials.token_expiry = None

        self.assertEqual(instance.__dict__, self.credentials.__dict__)
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
def test_from_json_token_expiry(self):
        data = json.loads(self.credentials.to_json())
        data['token_expiry'] = None
        instance = client.OAuth2Credentials.from_json(json.dumps(data))
        self.assertIsInstance(instance, client.OAuth2Credentials)
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
def test_unicode_header_checks(self):
        access_token = u'foo'
        client_id = u'some_client_id'
        client_secret = u'cOuDdkfjxxnv+'
        refresh_token = u'1/0/a.df219fjls0'
        token_expiry = str(datetime.datetime.utcnow())
        token_uri = str(oauth2client.GOOGLE_TOKEN_URI)
        revoke_uri = str(oauth2client.GOOGLE_REVOKE_URI)
        user_agent = u'refresh_checker/1.0'
        credentials = client.OAuth2Credentials(
            access_token, client_id, client_secret, refresh_token,
            token_expiry, token_uri, user_agent, revoke_uri=revoke_uri)

        # First, test that we correctly encode basic objects, making sure
        # to include a bytes object. Note that oauth2client will normalize
        # everything to bytes, no matter what python version we're in.
        http = credentials.authorize(http_mock.HttpMock())
        headers = {u'foo': 3, b'bar': True, 'baz': b'abc'}
        cleaned_headers = {b'foo': b'3', b'bar': b'True', b'baz': b'abc'}
        transport.request(
            http, u'http://example.com', method=u'GET', headers=headers)
        for k, v in cleaned_headers.items():
            self.assertTrue(k in http.headers)
            self.assertEqual(v, http.headers[k])

        # Next, test that we do fail on unicode.
        unicode_str = six.unichr(40960) + 'abcd'
        with self.assertRaises(client.NonAsciiHeaderError):
            transport.request(
                http, u'http://example.com', method=u'GET',
                headers={u'foo': unicode_str})
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
def test_no_unicode_in_request_params(self):
        access_token = u'foo'
        client_id = u'some_client_id'
        client_secret = u'cOuDdkfjxxnv+'
        refresh_token = u'1/0/a.df219fjls0'
        token_expiry = str(datetime.datetime.utcnow())
        token_uri = str(oauth2client.GOOGLE_TOKEN_URI)
        revoke_uri = str(oauth2client.GOOGLE_REVOKE_URI)
        user_agent = u'refresh_checker/1.0'
        credentials = client.OAuth2Credentials(
            access_token, client_id, client_secret, refresh_token,
            token_expiry, token_uri, user_agent, revoke_uri=revoke_uri)

        http = http_mock.HttpMock()
        http = credentials.authorize(http)
        transport.request(
            http, u'http://example.com', method=u'GET',
            headers={u'foo': u'bar'})
        for k, v in six.iteritems(http.headers):
            self.assertIsInstance(k, six.binary_type)
            self.assertIsInstance(v, six.binary_type)

        # Test again with unicode strings that can't simply be converted
        # to ASCII.
        with self.assertRaises(client.NonAsciiHeaderError):
            transport.request(
                http, u'http://example.com', method=u'GET',
                headers={u'foo': u'\N{COMET}'})

        self.credentials.token_response = 'foobar'
        instance = client.OAuth2Credentials.from_json(
            self.credentials.to_json())
        self.assertEqual('foobar', instance.token_response)
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
def test__expires_in_no_expiry(self):
        credentials = client.OAuth2Credentials(None, None, None, None,
                                               None, None, None)
        self.assertIsNone(credentials.token_expiry)
        self.assertIsNone(credentials._expires_in())
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
def test__expires_in_expired(self, utcnow):
        credentials = client.OAuth2Credentials(None, None, None, None,
                                               None, None, None)
        credentials.token_expiry = datetime.datetime.utcnow()
        now = credentials.token_expiry + datetime.timedelta(seconds=1)
        self.assertLess(credentials.token_expiry, now)
        utcnow.return_value = now
        self.assertEqual(credentials._expires_in(), 0)
        utcnow.assert_called_once_with()
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
def test__expires_in_not_expired(self, utcnow):
        credentials = client.OAuth2Credentials(None, None, None, None,
                                               None, None, None)
        credentials.token_expiry = datetime.datetime.utcnow()
        seconds = 1234
        now = credentials.token_expiry - datetime.timedelta(seconds=seconds)
        self.assertLess(now, credentials.token_expiry)
        utcnow.return_value = now
        self.assertEqual(credentials._expires_in(), seconds)
        utcnow.assert_called_once_with()
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
def _do_refresh_request_test_helper(self, response, content,
                                        error_msg, logger, gen_body,
                                        gen_headers, store=None):
        token_uri = 'http://token_uri'
        credentials = client.OAuth2Credentials(None, None, None, None,
                                               None, token_uri, None)
        credentials.store = store
        http = http_mock.HttpMock(headers=response, data=content)

        with self.assertRaises(
                client.HttpAccessTokenRefreshError) as exc_manager:
            credentials._do_refresh_request(http)

        self.assertEqual(exc_manager.exception.args, (error_msg,))
        self.assertEqual(exc_manager.exception.status, response.status)

        # Verify mocks.
        self.assertEqual(http.requests, 1)
        self.assertEqual(http.uri, token_uri)
        self.assertEqual(http.method, 'POST')
        self.assertEqual(http.body, gen_body.return_value)
        self.assertEqual(http.headers, gen_headers.return_value)

        call1 = mock.call('Refreshing access_token')
        failure_template = 'Failed to retrieve access token: %s'
        call2 = mock.call(failure_template, content)
        self.assertEqual(logger.info.mock_calls, [call1, call2])
        if store is not None:
            store.locked_put.assert_called_once_with(credentials)
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
def _do_revoke_test_helper(self, response, content,
                               error_msg, logger, store=None):
        credentials = client.OAuth2Credentials(
            None, None, None, None, None, None, None,
            revoke_uri=oauth2client.GOOGLE_REVOKE_URI)
        credentials.store = store

        http = http_mock.HttpMock(headers=response, data=content)
        token = u's3kr3tz'

        if response.status == http_client.OK:
            self.assertFalse(credentials.invalid)
            self.assertIsNone(credentials._do_revoke(http, token))
            self.assertTrue(credentials.invalid)
            if store is not None:
                store.delete.assert_called_once_with()
        else:
            self.assertFalse(credentials.invalid)
            with self.assertRaises(client.TokenRevokeError) as exc_manager:
                credentials._do_revoke(http, token)
            # Make sure invalid was not flipped on.
            self.assertFalse(credentials.invalid)
            self.assertEqual(exc_manager.exception.args, (error_msg,))
            if store is not None:
                store.delete.assert_not_called()

        revoke_uri = oauth2client.GOOGLE_REVOKE_URI + '?token=' + token

        # Verify mocks.
        self.assertEqual(http.requests, 1)
        self.assertEqual(http.uri, revoke_uri)
        self.assertEqual(http.method, 'GET')
        self.assertIsNone(http.body)
        self.assertIsNone(http.headers)

        logger.info.assert_called_once_with('Revoking token')
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
def _do_retrieve_scopes_test_helper(self, response, content,
                                        error_msg, logger, scopes=None):
        credentials = client.OAuth2Credentials(
            None, None, None, None, None, None, None,
            token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI)
        http = http_mock.HttpMock(headers=response, data=content)
        token = u's3kr3tz'

        if response.status == http_client.OK:
            self.assertEqual(credentials.scopes, set())
            self.assertIsNone(
                credentials._do_retrieve_scopes(http, token))
            self.assertEqual(credentials.scopes, scopes)
        else:
            self.assertEqual(credentials.scopes, set())
            with self.assertRaises(client.Error) as exc_manager:
                credentials._do_retrieve_scopes(http, token)
            # Make sure scopes were not changed.
            self.assertEqual(credentials.scopes, set())
            self.assertEqual(exc_manager.exception.args, (error_msg,))

        token_uri = _helpers.update_query_params(
            oauth2client.GOOGLE_TOKEN_INFO_URI,
            {'fields': 'scope', 'access_token': token})

        # Verify mocks.
        self.assertEqual(http.requests, 1)
        assertUrisEqual(self, token_uri, http.uri)
        self.assertEqual(http.method, 'GET')
        self.assertIsNone(http.body)
        self.assertIsNone(http.headers)
        logger.info.assert_called_once_with('Refreshing scopes')
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
def _create_test_credentials(self, client_id='some_client_id',
                                 expiration=None):
        access_token = 'foo'
        client_secret = 'cOuDdkfjxxnv+'
        refresh_token = '1/0/a.df219fjls0'
        token_expiry = expiration or datetime.datetime.utcnow()
        token_uri = 'https://www.google.com/accounts/o8/oauth2/token'
        user_agent = 'refresh_checker/1.0'

        credentials = client.OAuth2Credentials(
            access_token, client_id, client_secret,
            refresh_token, token_expiry, token_uri,
            user_agent)
        return credentials
项目:forseti-security    作者:GoogleCloudPlatform    | 项目源码 | 文件源码
def get_test_credential(self):
        access_token = 'foo'
        client_id = 'some_client_id'
        client_secret = 'cOuDdkfjxxnv+'
        refresh_token = '1/0/a.df219fjls0'
        token_expiry = datetime.datetime.utcnow()
        user_agent = ''
        return client.OAuth2Credentials(
            access_token, client_id, client_secret,
            refresh_token, token_expiry, oauth2client.GOOGLE_TOKEN_URI,
            user_agent, revoke_uri=oauth2client.GOOGLE_REVOKE_URI,
            scopes='foo', token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI)
项目:forseti-security    作者:GoogleCloudPlatform    | 项目源码 | 文件源码
def _create_service_api(credentials, service_name, version, developer_key=None,
                        cache_discovery=False):
    """Builds and returns a cloud API service object.

    Args:
        credentials (OAuth2Credentials): Credentials that will be used to
            authenticate the API calls.
        service_name (str): The name of the API.
        version (str): The version of the API to use.
        developer_key (str): The api key to use to determine the project
            associated with the API call, most API services do not require
            this to be set.
        cache_discovery (bool): Whether or not to cache the discovery doc.

    Returns:
        object: A Resource object with methods for interacting with the service.
    """
    # The default logging of the discovery obj is very noisy in recent versions.
    # Lower the default logging level of just this module to WARNING unless
    # debug is enabled.
    if LOGGER.getEffectiveLevel() > logging.DEBUG:
        logging.getLogger(discovery.__name__).setLevel(logging.WARNING)

    discovery_kwargs = {
        'serviceName': service_name,
        'version': version,
        'developerKey': developer_key,
        'credentials': credentials}
    if SUPPORT_DISCOVERY_CACHE:
        discovery_kwargs['cache_discovery'] = cache_discovery
    return discovery.build(**discovery_kwargs)
项目:Tobo-Cogs    作者:Tobotimus    | 项目源码 | 文件源码
def __init__(self, credentials: client.OAuth2Credentials):
        self.credentials = credentials
        self.session = ClientSession()
项目:ddpclient    作者:insiight    | 项目源码 | 文件源码
def setUp(self):
        self.client = Client(OAuth2Credentials('token', 'clientid', 'secret',
                                               'rtoken', datetime.datetime(
                                                   2038, 1, 1), 'uri', 'ua'))
项目:ddpclient    作者:insiight    | 项目源码 | 文件源码
def setUp(self):
        self.client = Client(OAuth2Credentials('token', 'clientid', 'secret',
                                               'rtoken', datetime.datetime(
                                                   2038, 1, 1), 'uri', 'ua'))
        self.selector = UserListSelector()