本文整理汇总了Python中oauth2client.gce.AppAssertionCredentials类的典型用法代码示例。如果您正苦于以下问题:Python AppAssertionCredentials类的具体用法?Python AppAssertionCredentials怎么用?Python AppAssertionCredentials使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了AppAssertionCredentials类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_fail_refresh
def test_fail_refresh(self):
m = mox.Mox()
httplib2_response = m.CreateMock(object)
httplib2_response.status = 400
httplib2_request = m.CreateMock(object)
httplib2_request.__call__(
('http://metadata.google.internal/0.1/meta-data/service-accounts/'
'default/acquire'
'?scope=http%3A%2F%2Fexample.com%2Fa%20http%3A%2F%2Fexample.com%2Fb'
)).AndReturn((httplib2_response, '{"accessToken": "this-is-a-token"}'))
m.ReplayAll()
c = AppAssertionCredentials(scope=['http://example.com/a',
'http://example.com/b'])
try:
c._refresh(httplib2_request)
self.fail('Should have raised exception on 400')
except AccessTokenRefreshError:
pass
m.UnsetStubs()
m.VerifyAll()
示例2: test_to_from_json
def test_to_from_json(self):
c = AppAssertionCredentials(scope=['http://example.com/a',
'http://example.com/b'])
json = c.to_json()
c2 = Credentials.new_from_json(json)
self.assertEqual(c.access_token, c2.access_token)
示例3: test_to_json_and_from_json
def test_to_json_and_from_json(self):
credentials = AppAssertionCredentials(
scope=['http://example.com/a', 'http://example.com/b'])
json = credentials.to_json()
credentials_from_json = Credentials.new_from_json(json)
self.assertEqual(credentials.access_token,
credentials_from_json.access_token)
示例4: main
def main():
# Define three parameters--color, size, count--each time you run the script"
parser = argparse.ArgumentParser(description="Write a labeled custom metric.")
parser.add_argument("--color", required=True)
parser.add_argument("--size", required=True)
parser.add_argument("--count", required=True)
args = parser.parse_args()
# Assign some values that will be used repeatedly.
project_id = GetProjectId()
now_rfc3339 = GetNowRfc3339()
# Create a cloudmonitoring service object. Use OAuth2 credentials.
credentials = AppAssertionCredentials(
scope="https://www.googleapis.com/auth/monitoring")
http = credentials.authorize(httplib2.Http())
service = build(serviceName="cloudmonitoring", version="v2beta2", http=http)
try:
print "Labels: color: %s, size: %s." % (args.color, args.size)
print "Creating custom metric..."
CreateCustomMetric(service, project_id)
time.sleep(2)
print "Writing new data to custom metric timeseries..."
WriteCustomMetric(service, project_id, now_rfc3339,
args.color, args.size, args.count)
print "Reading data from custom metric timeseries..."
ReadCustomMetric(service, project_id, now_rfc3339, args.color, args.size)
except Exception as e:
print "Failed to complete operations on custom metric: exception=%s" % e
示例5: test_get_access_token
def test_get_access_token(self):
m = mox.Mox()
httplib2_response = m.CreateMock(object)
httplib2_response.status = 200
httplib2_request = m.CreateMock(object)
httplib2_request.__call__(
('http://metadata.google.internal/0.1/meta-data/service-accounts/'
'default/acquire?scope=dummy_scope'
)).AndReturn((httplib2_response, '{"accessToken": "this-is-a-token"}'))
m.ReplayAll()
credentials = AppAssertionCredentials(['dummy_scope'])
http = httplib2.Http()
http.request = httplib2_request
token = credentials.get_access_token(http=http)
self.assertEqual('this-is-a-token', token.access_token)
self.assertEqual(None, token.expires_in)
m.UnsetStubs()
m.VerifyAll()
示例6: test_get_access_token
def test_get_access_token(self):
http = mock.MagicMock()
http.request = mock.MagicMock(
return_value=(mock.Mock(status=200),
'{"accessToken": "this-is-a-token"}'))
credentials = AppAssertionCredentials(['dummy_scope'])
token = credentials.get_access_token(http=http)
self.assertEqual('this-is-a-token', token.access_token)
self.assertEqual(None, token.expires_in)
http.request.assert_called_exactly_once_with(
'http://metadata.google.internal/0.1/meta-data/service-accounts/'
'default/acquire?scope=dummy_scope')
示例7: main
def main():
project_id = GetProjectId()
# Create a cloudmonitoring service to call. Use OAuth2 credentials.
credentials = AppAssertionCredentials(
scope="https://www.googleapis.com/auth/monitoring")
http = credentials.authorize(httplib2.Http())
service = build(serviceName="cloudmonitoring", version="v2beta2", http=http)
# Set up the write request.
now = GetNowRfc3339()
desc = {"project": project_id,
"metric": CUSTOM_METRIC_NAME}
point = {"start": now,
"end": now,
"doubleValue": os.getpid()}
print "Writing %d at %s" % (point["doubleValue"], now)
# Write a new data point.
try:
write_request = service.timeseries().write(
project=project_id,
body={"timeseries": [{"timeseriesDesc": desc, "point": point}]})
_ = write_request.execute() # Ignore the response.
except Exception as e:
print "Failed to write custom metric data: exception=%s" % e
raise # propagate exception
# Read all data points from the time series.
# When a custom metric is created, it may take a few seconds
# to propagate throughout the system. Retry a few times.
print "Reading data from custom metric timeseries..."
read_request = service.timeseries().list(
project=project_id,
metric=CUSTOM_METRIC_NAME,
youngest=now)
start = time.time()
while True:
try:
read_response = read_request.execute()
for point in read_response["timeseries"][0]["points"]:
print " %s: %s" % (point["end"], point["doubleValue"])
break
except Exception as e:
if time.time() < start + 20:
print "Failed to read custom metric data, retrying..."
time.sleep(3)
else:
print "Failed to read custom metric data, aborting: exception=%s" % e
raise # propagate exception
示例8: test_good_refresh
def test_good_refresh(self):
http = mock.MagicMock()
http.request = mock.MagicMock(
return_value=(mock.Mock(status=200),
'{"accessToken": "this-is-a-token"}'))
c = AppAssertionCredentials(scope=['http://example.com/a',
'http://example.com/b'])
self.assertEquals(None, c.access_token)
c.refresh(http)
self.assertEquals('this-is-a-token', c.access_token)
http.request.assert_called_exactly_once_with(
'http://metadata.google.internal/0.1/meta-data/service-accounts/'
'default/acquire'
'?scope=http%3A%2F%2Fexample.com%2Fa%20http%3A%2F%2Fexample.com%2Fb')
示例9: test_refresh_failure_400
def test_refresh_failure_400(self):
http = mock.MagicMock()
content = '{}'
http.request = mock.MagicMock(
return_value=(mock.Mock(status=400), content))
credentials = AppAssertionCredentials(
scope=['http://example.com/a', 'http://example.com/b'])
exception_caught = None
try:
credentials.refresh(http)
except AccessTokenRefreshError as exc:
exception_caught = exc
self.assertNotEqual(exception_caught, None)
self.assertEqual(str(exception_caught), content)
示例10: main
def main(argv):
# Parse the command-line flags.
flags = parser.parse_args(argv[1:])
# Obtain service account credentials from virtual machine environment.
credentials = AppAssertionCredentials(['https://www.googleapis.com/auth/datastore'])
# Create an httplib2.Http object to handle our HTTP requests and authorize
# it with our good Credentials.
http = httplib2.Http()
http = credentials.authorize(http)
# Construct the service object for the interacting with the Compute Engine
# API.
service = discovery.build(API_NAME, API_VERSION, http=http)
for (title, year, peak) in DATA:
commit(service.datasets(), title, year, peak)
示例11: test_refresh_failure_404
def test_refresh_failure_404(self):
http = mock.MagicMock()
content = '{}'
http.request = mock.MagicMock(
return_value=(mock.Mock(status=404), content))
credentials = AppAssertionCredentials(
scope=['http://example.com/a', 'http://example.com/b'])
exception_caught = None
try:
credentials.refresh(http)
except AccessTokenRefreshError as exc:
exception_caught = exc
self.assertNotEqual(exception_caught, None)
expanded_content = content + (' This can occur if a VM was created'
' with no service account or scopes.')
self.assertEqual(str(exception_caught), expanded_content)
示例12: _refresh_success_helper
def _refresh_success_helper(self, bytes_response=False):
access_token = u'this-is-a-token'
return_val = json.dumps({u'accessToken': access_token})
if bytes_response:
return_val = _to_bytes(return_val)
http = mock.MagicMock()
http.request = mock.MagicMock(
return_value=(mock.Mock(status=200), return_val))
scopes = ['http://example.com/a', 'http://example.com/b']
credentials = AppAssertionCredentials(scope=scopes)
self.assertEquals(None, credentials.access_token)
credentials.refresh(http)
self.assertEquals(access_token, credentials.access_token)
base_metadata_uri = ('http://metadata.google.internal/0.1/meta-data/'
'service-accounts/default/acquire')
escaped_scopes = urllib.parse.quote(' '.join(scopes), safe='')
request_uri = base_metadata_uri + '?scope=' + escaped_scopes
http.request.assert_called_once_with(request_uri)
示例13: test_good_refresh
def test_good_refresh(self):
m = mox.Mox()
httplib2_response = m.CreateMock(object)
httplib2_response.status = 200
httplib2_request = m.CreateMock(object)
httplib2_request.__call__(
('http://metadata.google.internal/0.1/meta-data/service-accounts/'
'default/acquire'
'?scope=http%3A%2F%2Fexample.com%2Fa%20http%3A%2F%2Fexample.com%2Fb'
)).AndReturn((httplib2_response, '{"accessToken": "this-is-a-token"}'))
m.ReplayAll()
c = AppAssertionCredentials(scope=['http://example.com/a',
'http://example.com/b'])
c._refresh(httplib2_request)
self.assertEquals('this-is-a-token', c.access_token)
m.UnsetStubs()
m.VerifyAll()
示例14: test_create_scoped
def test_create_scoped(self):
credentials = AppAssertionCredentials([])
new_credentials = credentials.create_scoped(['dummy_scope'])
self.assertNotEqual(credentials, new_credentials)
self.assertTrue(isinstance(new_credentials, AppAssertionCredentials))
self.assertEqual('dummy_scope', new_credentials.scope)
示例15: test_create_scoped_required_with_scopes
def test_create_scoped_required_with_scopes(self):
credentials = AppAssertionCredentials(['dummy_scope'])
self.assertFalse(credentials.create_scoped_required())