desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Test that __getitem__() gets mocked in Dummy.
In this test, _Verify() succeeds.'
| def testMockGetItem_ExpectedGetItem_Success(self):
| dummy = mox.MockObject(TestClass)
dummy['X'].AndReturn('value')
dummy._Replay()
self.assertEqual(dummy['X'], 'value')
dummy._Verify()
|
'Test that __getitem__() gets mocked in Dummy.
In this test, _Verify() fails.'
| def testMockGetItem_ExpectedGetItem_NoSuccess(self):
| dummy = mox.MockObject(TestClass)
dummy['X'].AndReturn('value')
dummy._Replay()
self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify)
|
'Test that __getitem__() gets mocked in Dummy.'
| def testMockGetItem_ExpectedNoGetItem_NoSuccess(self):
| dummy = mox.MockObject(TestClass)
dummy._Replay()
def call():
return dummy['X']
self.assertRaises(mox.UnexpectedMethodCallError, call)
|
'Test that __getitem__() fails if other parameters are expected.'
| def testMockGetItem_ExpectedGetItem_NonmatchingParameters(self):
| dummy = mox.MockObject(TestClass)
dummy['X'].AndReturn('value')
dummy._Replay()
def call():
return dummy['wrong']
self.assertRaises(mox.UnexpectedMethodCallError, call)
dummy._Verify()
|
'Test that __iter__() gets mocked in Dummy.
In this test, _Verify() succeeds.'
| def testMockIter_ExpectedIter_Success(self):
| dummy = mox.MockObject(TestClass)
iter(dummy).AndReturn(iter(['X', 'Y']))
dummy._Replay()
self.assertEqual([x for x in dummy], ['X', 'Y'])
dummy._Verify()
|
'Test that __contains__ gets mocked in Dummy.
In this test, _Verify() succeeds.'
| def testMockContains_ExpectedContains_Success(self):
| dummy = mox.MockObject(TestClass)
dummy.__contains__('X').AndReturn(True)
dummy._Replay()
self.failUnless(('X' in dummy))
dummy._Verify()
|
'Test that __contains__() gets mocked in Dummy.
In this test, _Verify() fails.'
| def testMockContains_ExpectedContains_NoSuccess(self):
| dummy = mox.MockObject(TestClass)
dummy.__contains__('X').AndReturn('True')
dummy._Replay()
self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify)
|
'Test that __contains__ fails if other parameters are expected.'
| def testMockContains_ExpectedContains_NonmatchingParameter(self):
| dummy = mox.MockObject(TestClass)
dummy.__contains__('X').AndReturn(True)
dummy._Replay()
def call():
return ('Y' in dummy)
self.assertRaises(mox.UnexpectedMethodCallError, call)
dummy._Verify()
|
'Test that __iter__() gets mocked in Dummy.
In this test, _Verify() fails.'
| def testMockIter_ExpectedIter_NoSuccess(self):
| dummy = mox.MockObject(TestClass)
iter(dummy).AndReturn(iter(['X', 'Y']))
dummy._Replay()
self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify)
|
'Test that __iter__() gets mocked in Dummy.'
| def testMockIter_ExpectedNoIter_NoSuccess(self):
| dummy = mox.MockObject(TestClass)
dummy._Replay()
def call():
return [x for x in dummy]
self.assertRaises(mox.UnexpectedMethodCallError, call)
|
'Test that __iter__() gets mocked in Dummy using getitem.'
| def testMockIter_ExpectedGetItem_Success(self):
| dummy = mox.MockObject(SubscribtableNonIterableClass)
dummy[0].AndReturn('a')
dummy[1].AndReturn('b')
dummy[2].AndRaise(IndexError)
dummy._Replay()
self.assertEquals(['a', 'b'], [x for x in dummy])
dummy._Verify()
|
'Test that __iter__() gets mocked in Dummy using getitem.'
| def testMockIter_ExpectedNoGetItem_NoSuccess(self):
| dummy = mox.MockObject(SubscribtableNonIterableClass)
dummy._Replay()
function = (lambda : [x for x in dummy])
self.assertRaises(mox.UnexpectedMethodCallError, function)
|
'Mox should create a mock object.'
| def testCreateObject(self):
| mock_obj = self.mox.CreateMock(TestClass)
|
'Mox should replay and verify all objects it created.'
| def testVerifyObjectWithCompleteReplay(self):
| mock_obj = self.mox.CreateMock(TestClass)
mock_obj.ValidCall()
mock_obj.ValidCallWithArgs(mox.IsA(TestClass))
self.mox.ReplayAll()
mock_obj.ValidCall()
mock_obj.ValidCallWithArgs(TestClass('some_value'))
self.mox.VerifyAll()
|
'Mox should raise an exception if a mock didn\'t replay completely.'
| def testVerifyObjectWithIncompleteReplay(self):
| mock_obj = self.mox.CreateMock(TestClass)
mock_obj.ValidCall()
self.mox.ReplayAll()
self.assertRaises(mox.ExpectedMethodCallsError, self.mox.VerifyAll)
|
'Test the whole work flow.'
| def testEntireWorkflow(self):
| mock_obj = self.mox.CreateMock(TestClass)
mock_obj.ValidCall().AndReturn('yes')
self.mox.ReplayAll()
ret_val = mock_obj.ValidCall()
self.assertEquals('yes', ret_val)
self.mox.VerifyAll()
|
'Test recording calls to a callable object works.'
| def testCallableObject(self):
| mock_obj = self.mox.CreateMock(CallableClass)
mock_obj('foo').AndReturn('qux')
self.mox.ReplayAll()
ret_val = mock_obj('foo')
self.assertEquals('qux', ret_val)
self.mox.VerifyAll()
|
'Test recording calls to an object inheriting from a callable object.'
| def testInheritedCallableObject(self):
| mock_obj = self.mox.CreateMock(InheritsFromCallable)
mock_obj('foo').AndReturn('qux')
self.mox.ReplayAll()
ret_val = mock_obj('foo')
self.assertEquals('qux', ret_val)
self.mox.VerifyAll()
|
'Test that you cannot call a non-callable object.'
| def testCallOnNonCallableObject(self):
| mock_obj = self.mox.CreateMock(TestClass)
self.assertRaises(TypeError, mock_obj)
|
'Test verifying calls to a callable object works.'
| def testCallableObjectWithBadCall(self):
| mock_obj = self.mox.CreateMock(CallableClass)
mock_obj('foo').AndReturn('qux')
self.mox.ReplayAll()
self.assertRaises(mox.UnexpectedMethodCallError, mock_obj, 'ZOOBAZ')
|
'Test that using one unordered group works.'
| def testUnorderedGroup(self):
| mock_obj = self.mox.CreateMockAnything()
mock_obj.Method(1).InAnyOrder()
mock_obj.Method(2).InAnyOrder()
self.mox.ReplayAll()
mock_obj.Method(2)
mock_obj.Method(1)
self.mox.VerifyAll()
|
'Unordered groups should work in the context of ordered calls.'
| def testUnorderedGroupsInline(self):
| mock_obj = self.mox.CreateMockAnything()
mock_obj.Open()
mock_obj.Method(1).InAnyOrder()
mock_obj.Method(2).InAnyOrder()
mock_obj.Close()
self.mox.ReplayAll()
mock_obj.Open()
mock_obj.Method(2)
mock_obj.Method(1)
mock_obj.Close()
self.mox.VerifyAll()
|
'Multiple unoreded groups should work.'
| def testMultipleUnorderdGroups(self):
| mock_obj = self.mox.CreateMockAnything()
mock_obj.Method(1).InAnyOrder()
mock_obj.Method(2).InAnyOrder()
mock_obj.Foo().InAnyOrder('group2')
mock_obj.Bar().InAnyOrder('group2')
self.mox.ReplayAll()
mock_obj.Method(2)
mock_obj.Method(1)
mock_obj.Bar()
mock_obj.Foo()
self.mox.V... |
'Multiple unordered groups should maintain external order'
| def testMultipleUnorderdGroupsOutOfOrder(self):
| mock_obj = self.mox.CreateMockAnything()
mock_obj.Method(1).InAnyOrder()
mock_obj.Method(2).InAnyOrder()
mock_obj.Foo().InAnyOrder('group2')
mock_obj.Bar().InAnyOrder('group2')
self.mox.ReplayAll()
mock_obj.Method(2)
self.assertRaises(mox.UnexpectedMethodCallError, mock_obj.Bar)
|
'Unordered groups should work with return values.'
| def testUnorderedGroupWithReturnValue(self):
| mock_obj = self.mox.CreateMockAnything()
mock_obj.Open()
mock_obj.Method(1).InAnyOrder().AndReturn(9)
mock_obj.Method(2).InAnyOrder().AndReturn(10)
mock_obj.Close()
self.mox.ReplayAll()
mock_obj.Open()
actual_two = mock_obj.Method(2)
actual_one = mock_obj.Method(1)
mock_obj.Close... |
'Unordered groups should work with comparators'
| def testUnorderedGroupWithComparator(self):
| def VerifyOne(cmd):
if (not isinstance(cmd, str)):
self.fail(('Unexpected type passed to comparator: ' + str(cmd)))
return (cmd == 'test')
def VerifyTwo(cmd):
return True
mock_obj = self.mox.CreateMockAnything()
mock_obj.Foo(['test'], mox.Func(VerifyOne... |
'Test if MultipleTimesGroup works.'
| def testMultipleTimes(self):
| mock_obj = self.mox.CreateMockAnything()
mock_obj.Method(1).MultipleTimes().AndReturn(9)
mock_obj.Method(2).AndReturn(10)
mock_obj.Method(3).MultipleTimes().AndReturn(42)
self.mox.ReplayAll()
actual_one = mock_obj.Method(1)
second_one = mock_obj.Method(1)
actual_two = mock_obj.Method(2)
... |
'Test if MultipleTimesGroup works with a IsA parameter.'
| def testMultipleTimesUsingIsAParameter(self):
| mock_obj = self.mox.CreateMockAnything()
mock_obj.Open()
mock_obj.Method(mox.IsA(str)).MultipleTimes('IsA').AndReturn(9)
mock_obj.Close()
self.mox.ReplayAll()
mock_obj.Open()
actual_one = mock_obj.Method('1')
second_one = mock_obj.Method('2')
mock_obj.Close()
self.mox.VerifyAll()... |
'Test that the Func is not evaluated more times than necessary.
If a Func() has side effects, it can cause a passing test to fail.'
| def testMutlipleTimesUsingFunc(self):
| self.counter = 0
def MyFunc(actual_str):
"Increment the counter if actual_str == 'foo'."
if (actual_str == 'foo'):
self.counter += 1
return True
mock_obj = self.mox.CreateMockAnything()
mock_obj.Open()
mock_obj.Method(mox.Func(MyFunc)).MultipleTi... |
'Test if MultipleTimesGroup works with three or more methods.'
| def testMultipleTimesThreeMethods(self):
| mock_obj = self.mox.CreateMockAnything()
mock_obj.Open()
mock_obj.Method(1).MultipleTimes().AndReturn(9)
mock_obj.Method(2).MultipleTimes().AndReturn(8)
mock_obj.Method(3).MultipleTimes().AndReturn(7)
mock_obj.Method(4).AndReturn(10)
mock_obj.Close()
self.mox.ReplayAll()
mock_obj.Ope... |
'Test if MultipleTimesGroup fails if one method is missing.'
| def testMultipleTimesMissingOne(self):
| mock_obj = self.mox.CreateMockAnything()
mock_obj.Open()
mock_obj.Method(1).MultipleTimes().AndReturn(9)
mock_obj.Method(2).MultipleTimes().AndReturn(8)
mock_obj.Method(3).MultipleTimes().AndReturn(7)
mock_obj.Method(4).AndReturn(10)
mock_obj.Close()
self.mox.ReplayAll()
mock_obj.Ope... |
'Test if MultipleTimesGroup works with a group after a
MultipleTimesGroup.'
| def testMultipleTimesTwoGroups(self):
| mock_obj = self.mox.CreateMockAnything()
mock_obj.Open()
mock_obj.Method(1).MultipleTimes().AndReturn(9)
mock_obj.Method(3).MultipleTimes('nr2').AndReturn(42)
mock_obj.Close()
self.mox.ReplayAll()
mock_obj.Open()
actual_one = mock_obj.Method(1)
mock_obj.Method(1)
actual_three = m... |
'Test if MultipleTimesGroup fails with a group after a
MultipleTimesGroup.'
| def testMultipleTimesTwoGroupsFailure(self):
| mock_obj = self.mox.CreateMockAnything()
mock_obj.Open()
mock_obj.Method(1).MultipleTimes().AndReturn(9)
mock_obj.Method(3).MultipleTimes('nr2').AndReturn(42)
mock_obj.Close()
self.mox.ReplayAll()
mock_obj.Open()
actual_one = mock_obj.Method(1)
mock_obj.Method(1)
actual_three = m... |
'Test side effect operations actually modify their target objects.'
| def testWithSideEffects(self):
| def modifier(mutable_list):
mutable_list[0] = 'mutated'
mock_obj = self.mox.CreateMockAnything()
mock_obj.ConfigureInOutParameter(['original']).WithSideEffects(modifier)
mock_obj.WorkWithParameter(['mutated'])
self.mox.ReplayAll()
local_list = ['original']
mock_obj.ConfigureInOutPara... |
'Test side effect operations actually modify their target objects.'
| def testWithSideEffectsException(self):
| def modifier(mutable_list):
mutable_list[0] = 'mutated'
mock_obj = self.mox.CreateMockAnything()
method = mock_obj.ConfigureInOutParameter(['original'])
method.WithSideEffects(modifier).AndRaise(Exception('exception'))
mock_obj.WorkWithParameter(['mutated'])
self.mox.ReplayAll()
loca... |
'Test that a method is replaced with a MockAnything.'
| def testStubOutMethod(self):
| test_obj = TestClass()
self.mox.StubOutWithMock(test_obj, 'OtherValidCall')
self.assert_(isinstance(test_obj.OtherValidCall, mox.MockAnything))
test_obj.OtherValidCall().AndReturn('foo')
self.mox.ReplayAll()
actual = test_obj.OtherValidCall()
self.mox.VerifyAll()
self.mox.UnsetStubs()
... |
'Test a mocked class whose __init__ returns a Mock.'
| def testStubOutClass_OldStyle(self):
| self.mox.StubOutWithMock(mox_test_helper, 'TestClassFromAnotherModule')
self.assert_(isinstance(mox_test_helper.TestClassFromAnotherModule, mox.MockObject))
mock_instance = self.mox.CreateMock(mox_test_helper.TestClassFromAnotherModule)
mox_test_helper.TestClassFromAnotherModule().AndReturn(mock_instanc... |
'Test that user is warned if they try to stub out a MockAnything.'
| def testWarnsUserIfMockingMock(self):
| self.mox.StubOutWithMock(TestClass, 'MyStaticMethod')
self.assertRaises(TypeError, self.mox.StubOutWithMock, TestClass, 'MyStaticMethod')
|
'Test than object is replaced with a Mock.'
| def testStubOutObject(self):
| class Foo(object, ):
def __init__(self):
self.obj = TestClass()
foo = Foo()
self.mox.StubOutWithMock(foo, 'obj')
self.assert_(isinstance(foo.obj, mox.MockObject))
foo.obj.ValidCall()
self.mox.ReplayAll()
foo.obj.ValidCall()
self.mox.VerifyAll()
self.mox.UnsetStubs... |
'If there is an AttributeError on a MockMethod, give users a helpful msg.'
| def testForgotReplayHelpfulMessage(self):
| foo = self.mox.CreateMockAnything()
bar = self.mox.CreateMockAnything()
foo.GetBar().AndReturn(bar)
bar.ShowMeTheMoney()
try:
foo.GetBar().ShowMeTheMoney()
except AttributeError as e:
self.assertEquals('MockMethod has no attribute "ShowMeTheMoney". Did you re... |
'Replay should put objects into replay mode.'
| def testReplay(self):
| mock_obj = mox.MockObject(TestClass)
self.assertFalse(mock_obj._replay_mode)
mox.Replay(mock_obj)
self.assertTrue(mock_obj._replay_mode)
|
'Replacement for setUp in the test class instance.
Assigns a mox.Mox instance as the mox attribute of the test class instance.
This replacement Mox instance is under our control before setUp is called
in the test class instance.'
| def _setUpTestClass(self):
| self.test.mox = self.test_mox
self.test.stubs = self.test_stubs
|
'Create a test from our example mox class.
The created test instance is assigned to this instances test attribute.'
| def _CreateTest(self, test_name):
| self.test = mox_test_helper.ExampleMoxTest(test_name)
self.mox.stubs.Set(self.test, 'setUp', self._setUpTestClass)
|
'Run the checks to confirm test method completed successfully.'
| def _VerifySuccess(self):
| self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
self.mox.StubOutWithMock(self.test_mox, 'VerifyAll')
self.mox.StubOutWithMock(self.test_stubs, 'UnsetAll')
self.mox.StubOutWithMock(self.test_stubs, 'SmartUnsetAll')
self.test_mox.UnsetStubs()
self.test_mox.VerifyAll()
self.test_stubs.Uns... |
'Successful test method execution test.'
| def testSuccess(self):
| self._CreateTest('testSuccess')
self._VerifySuccess()
|
'Let testSuccess() unset all the mocks, and verify they\'ve been unset.'
| def testSuccessNoMocks(self):
| self._CreateTest('testSuccess')
self.test.run(result=self.result)
self.assertTrue(self.result.wasSuccessful())
self.assertEqual(OS_LISTDIR, mox_test_helper.os.listdir)
|
'Test that "self.stubs" is provided as is useful.'
| def testStubs(self):
| self._CreateTest('testHasStubs')
self._VerifySuccess()
|
'Let testHasStubs() unset the stubs by itself.'
| def testStubsNoMocks(self):
| self._CreateTest('testHasStubs')
self.test.run(result=self.result)
self.assertTrue(self.result.wasSuccessful())
self.assertEqual(OS_LISTDIR, mox_test_helper.os.listdir)
|
'Stubbed out method is not called.'
| def testExpectedNotCalled(self):
| self._CreateTest('testExpectedNotCalled')
self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
self.mox.StubOutWithMock(self.test_stubs, 'UnsetAll')
self.mox.StubOutWithMock(self.test_stubs, 'SmartUnsetAll')
self.test_mox.UnsetStubs()
self.test_stubs.UnsetAll()
self.test_stubs.SmartUnsetAll... |
'Let testExpectedNotCalled() unset all the mocks by itself.'
| def testExpectedNotCalledNoMocks(self):
| self._CreateTest('testExpectedNotCalled')
self.test.run(result=self.result)
self.failIf(self.result.wasSuccessful())
self.assertEqual(OS_LISTDIR, mox_test_helper.os.listdir)
|
'Stubbed out method is called with unexpected arguments.'
| def testUnexpectedCall(self):
| self._CreateTest('testUnexpectedCall')
self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
self.mox.StubOutWithMock(self.test_stubs, 'UnsetAll')
self.mox.StubOutWithMock(self.test_stubs, 'SmartUnsetAll')
self.mox.StubOutWithMock(self.test_mox, 'VerifyAll')
self.test_mox.UnsetStubs()
self.t... |
'Failing assertion in test method.'
| def testFailure(self):
| self._CreateTest('testFailure')
self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
self.mox.StubOutWithMock(self.test_stubs, 'UnsetAll')
self.mox.StubOutWithMock(self.test_stubs, 'SmartUnsetAll')
self.mox.StubOutWithMock(self.test_mox, 'VerifyAll')
self.test_mox.UnsetStubs()
self.test_stu... |
'Run test from mix-in test class, ensure it passes.'
| def testMixin(self):
| self._CreateTest('testStat')
self._VerifySuccess()
|
'Run same test as above but from the current test class.
This ensures metaclass properly wrapped test methods from all base classes.
If unsetting of stubs doesn\'t happen, this will fail.'
| def testMixinAgain(self):
| self._CreateTest('testStatOther')
self._VerifySuccess()
|
'Verify should be called for all objects.
This should throw an exception because the expected behavior did not occur.'
| def testVerify(self):
| mock_obj = mox.MockObject(TestClass)
mock_obj.ValidCall()
mock_obj._Replay()
self.assertRaises(mox.ExpectedMethodCallsError, mox.Verify, mock_obj)
|
'Should empty all queues and put mocks in record mode.'
| def testReset(self):
| mock_obj = mox.MockObject(TestClass)
mock_obj.ValidCall()
self.assertFalse(mock_obj._replay_mode)
mock_obj._Replay()
self.assertTrue(mock_obj._replay_mode)
self.assertEquals(1, len(mock_obj._expected_calls_queue))
mox.Reset(mock_obj)
self.assertFalse(mock_obj._replay_mode)
self.asser... |
'Should be properly overriden in a derived class.'
| def testMethodOverride(self):
| self.assertEquals(42, self.another_critical_variable)
self.another_critical_variable += 1
|
'Should be able to access members created by all parent setUp().'
| def testMultipleInheritance(self):
| self.assert_(isinstance(self.mox, mox.Mox))
self.assertEquals(42, self.critical_variable)
|
'Should run before MyTestCase.testMethodOverride.'
| def testMethodOverride(self):
| self.assertEquals(99, self.another_critical_variable)
self.another_critical_variable = 42
super(MoxTestBaseMultipleInheritanceTest, self).testMethodOverride()
self.assertEquals(43, self.another_critical_variable)
|
'Return the value for key.'
| def __getitem__(self, key):
| return self.d[key]
|
'Set the value for key to value.'
| def __setitem__(self, key, value):
| self.d[key] = value
|
'Returns True if d contains the key.'
| def __contains__(self, key):
| return (key in self.d)
|
'Constructor for Storage.
Args:
model: db.Model, model class
key_name: string, key name for the entity that has the credentials
property_name: string, name of the property that is a CredentialsProperty'
| def __init__(self, model, key_name, property_name):
| self.model = model
self.key_name = key_name
self.property_name = property_name
|
'Retrieve Credential from datastore.
Returns:
Credentials'
| def get(self):
| entity = self.model.get_or_insert(self.key_name)
credential = getattr(entity, self.property_name)
if (credential and hasattr(credential, 'set_store')):
credential.set_store(self.put)
return credential
|
'Write a Credentials to the datastore.
Args:
credentials: Credentials, the credentials to store.'
| def put(self, credentials):
| entity = self.model.get_or_insert(self.key_name)
setattr(entity, self.property_name, credentials)
entity.put()
|
'Retrieve Credential from file.
Returns:
apiclient.oauth.Credentials'
| def get(self):
| self._lock.acquire()
try:
f = open(self._filename, 'r')
credentials = pickle.loads(f.read())
f.close()
credentials.set_store(self.put)
except:
credentials = None
self._lock.release()
return credentials
|
'Write a pickled Credentials to file.
Args:
credentials: Credentials, the credentials to store.'
| def put(self, credentials):
| self._lock.acquire()
f = open(self._filename, 'w')
f.write(pickle.dumps(credentials))
f.close()
self._lock.release()
|
'Handle a GET request
Parses the query parameters and prints a message
if the flow has completed. Note that we can\'t detect
if an error occurred.'
| def do_GET(s):
| s.send_response(200)
s.send_header('Content-type', 'text/html')
s.end_headers()
query = s.path.split('?', 1)[(-1)]
query = dict(parse_qsl(query))
s.server.query_params = query
s.wfile.write('<html><head><title>Authentication Status</title></head>')
s.wfile.write('<body><p>The authe... |
'Do not log messages to stdout while running as command line program.'
| def log_message(self, format, *args):
| pass
|
'Calculate the reason for the error from the response content.'
| def _get_reason(self):
| if self.resp.get('content-type', '').startswith('application/json'):
try:
data = simplejson.loads(self.content)
reason = data['error']['message']
except (ValueError, KeyError):
reason = self.content
else:
reason = self.resp.reason
return reason
|
'Constructor for an UnexpectedMethodError.'
| def __init__(self, methodId=None):
| super(UnexpectedMethodError, self).__init__(('Received unexpected call %s' % methodId))
|
'Constructor for an UnexpectedMethodError.'
| def __init__(self, expected, provided):
| super(UnexpectedBodyError, self).__init__(('Expected: [%s] - Provided: [%s]' % (expected, provided)))
|
'consumer - An instance of oauth.Consumer.
token - An instance of oauth.Token constructed with
the access token and secret.
user_agent - The HTTP User-Agent to provide for this application.'
| def __init__(self, consumer, token, user_agent):
| self.consumer = consumer
self.token = token
self.user_agent = user_agent
self.store = None
self._invalid = False
|
'True if the credentials are invalid, such as being revoked.'
| @property
def invalid(self):
| return getattr(self, '_invalid', False)
|
'Set the storage for the credential.
Args:
store: callable, a callable that when passed a Credential
will store the credential back to where it came from.
This is needed to store the latest access_token if it
has been revoked.'
| def set_store(self, store):
| self.store = store
|
'Trim the state down to something that can be pickled.'
| def __getstate__(self):
| d = copy.copy(self.__dict__)
del d['store']
return d
|
'Reconstitute the state of the object from being pickled.'
| def __setstate__(self, state):
| self.__dict__.update(state)
self.store = None
|
'Authorize an httplib2.Http instance with these Credentials
Args:
http - An instance of httplib2.Http
or something that acts like it.
Returns:
A modified instance of http that was passed in.
Example:
h = httplib2.Http()
h = credentials.authorize(h)
You can\'t create a new OAuth
subclass of httplib2.Authenication becaus... | def authorize(self, http):
| request_orig = http.request
signer = oauth.SignatureMethod_HMAC_SHA1()
def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None):
'Modify the request headers to add the appropriate\n Auth... |
'Args:
consumer_key: string, An OAuth 1.0 consumer key
consumer_secret: string, An OAuth 1.0 consumer secret
user_agent: string, The HTTP User-Agent to provide for this application.'
| def __init__(self, consumer_key, consumer_secret, user_agent):
| self.consumer = oauth.Consumer(consumer_key, consumer_secret)
self.user_agent = user_agent
self.store = None
self._requestor = None
|
'True if the credentials are invalid, such as being revoked.
Always returns False for Two Legged Credentials.'
| @property
def invalid(self):
| return False
|
'Set the storage for the credential.
Args:
store: callable, a callable that when passed a Credential
will store the credential back to where it came from.
This is needed to store the latest access_token if it
has been revoked.'
| def set_store(self, store):
| self.store = store
|
'Trim the state down to something that can be pickled.'
| def __getstate__(self):
| d = copy.copy(self.__dict__)
del d['store']
return d
|
'Reconstitute the state of the object from being pickled.'
| def __setstate__(self, state):
| self.__dict__.update(state)
self.store = None
|
'Authorize an httplib2.Http instance with these Credentials
Args:
http - An instance of httplib2.Http
or something that acts like it.
Returns:
A modified instance of http that was passed in.
Example:
h = httplib2.Http()
h = credentials.authorize(h)
You can\'t create a new OAuth
subclass of httplib2.Authenication becaus... | def authorize(self, http):
| request_orig = http.request
signer = oauth.SignatureMethod_HMAC_SHA1()
def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None):
'Modify the request headers to add the appropriate\n Auth... |
'discovery - Section of the API discovery document that describes
the OAuth endpoints.
consumer_key - OAuth consumer key
consumer_secret - OAuth consumer secret
user_agent - The HTTP User-Agent that identifies the application.
**kwargs - The keyword arguments are all optional and required
parameter... | def __init__(self, discovery, consumer_key, consumer_secret, user_agent, **kwargs):
| self.discovery = discovery
self.consumer_key = consumer_key
self.consumer_secret = consumer_secret
self.user_agent = user_agent
self.params = kwargs
self.request_token = {}
required = {}
for uriinfo in discovery.itervalues():
for (name, value) in uriinfo['parameters'].iteritems()... |
'Returns a URI to redirect to the provider.
oauth_callback - Either the string \'oob\' for a non-web-based application,
or a URI that handles the callback from the authorization
server.
If oauth_callback is \'oob\' then pass in the
generated verification code to step2_exchange,
otherwise pass in the query parameters re... | def step1_get_authorize_url(self, oauth_callback='oob'):
| consumer = oauth.Consumer(self.consumer_key, self.consumer_secret)
client = oauth.Client(consumer)
headers = {'user-agent': self.user_agent, 'content-type': 'application/x-www-form-urlencoded'}
body = urllib.urlencode({'oauth_callback': oauth_callback})
uri = _oauth_uri('request', self.discovery, se... |
'Exhanges an authorized request token
for OAuthCredentials.
Args:
verifier: string, dict - either the verifier token, or a dictionary
of the query parameters to the callback, which contains
the oauth_verifier.
Returns:
The Credentials object.'
| def step2_exchange(self, verifier):
| if (not (isinstance(verifier, str) or isinstance(verifier, unicode))):
verifier = verifier['oauth_verifier']
token = oauth.Token(self.request_token['oauth_token'], self.request_token['oauth_token_secret'])
token.set_verifier(verifier)
consumer = oauth.Consumer(self.consumer_key, self.consumer_se... |
'Updates outgoing requests with a serialized body.
Args:
headers: dict, request headers
path_params: dict, parameters that appear in the request path
query_params: dict, parameters that appear in the query
body_value: object, the request body as a Python object, which must be
serializable.
Returns:
A tuple of (headers,... | def request(self, headers, path_params, query_params, body_value):
| _abstract()
|
'Convert the response wire format into a Python object.
Args:
resp: httplib2.Response, the HTTP response headers and status
content: string, the body of the HTTP response
Returns:
The body de-serialized as a Python object.
Raises:
apiclient.errors.HttpError if a non 2xx response is received.'
| def response(self, resp, content):
| _abstract()
|
'Logs debugging information about the request if requested.'
| def _log_request(self, headers, path_params, query, body):
| if FLAGS.dump_request_response:
logging.info('--request-start--')
logging.info('-headers-start-')
for (h, v) in headers.iteritems():
logging.info('%s: %s', h, v)
logging.info('-headers-end-')
logging.info('-path-parameters-start-')
for (h, v) in path_pa... |
'Updates outgoing requests with a serialized body.
Args:
headers: dict, request headers
path_params: dict, parameters that appear in the request path
query_params: dict, parameters that appear in the query
body_value: object, the request body as a Python object, which must be
serializable by simplejson.
Returns:
A tupl... | def request(self, headers, path_params, query_params, body_value):
| query = self._build_query(query_params)
headers['accept'] = self.accept
headers['accept-encoding'] = 'gzip, deflate'
if ('user-agent' in headers):
headers['user-agent'] += ' '
else:
headers['user-agent'] = ''
headers['user-agent'] += 'google-api-python-client/1.0'
if (b... |
'Builds a query string.
Args:
params: dict, the query parameters
Returns:
The query parameters properly encoded into an HTTP URI query string.'
| def _build_query(self, params):
| if (self.alt_param is not None):
params.update({'alt': self.alt_param})
astuples = []
for (key, value) in params.iteritems():
if (type(value) == type([])):
for x in value:
x = x.encode('utf-8')
astuples.append((key, x))
else:
if... |
'Logs debugging information about the response if requested.'
| def _log_response(self, resp, content):
| if FLAGS.dump_request_response:
logging.info('--response-start--')
for (h, v) in resp.iteritems():
logging.info('%s: %s', h, v)
if content:
logging.info(content)
logging.info('--response-end--')
|
'Convert the response wire format into a Python object.
Args:
resp: httplib2.Response, the HTTP response headers and status
content: string, the body of the HTTP response
Returns:
The body de-serialized as a Python object.
Raises:
apiclient.errors.HttpError if a non 2xx response is received.'
| def response(self, resp, content):
| self._log_response(resp, content)
if (resp.status < 300):
if (resp.status == 204):
return self.no_content_response
return self.deserialize(content)
else:
logging.debug(('Content from bad request was: %s' % content))
raise HttpError(resp, content)
|
'Perform the actual Python object serialization.
Args:
body_value: object, the request body as a Python object.
Returns:
string, the body in serialized form.'
| def serialize(self, body_value):
| _abstract()
|
'Perform the actual deserialization from response string to Python
object.
Args:
content: string, the body of the HTTP response
Returns:
The body de-serialized as a Python object.'
| def deserialize(self, content):
| _abstract()
|
'Construct a JsonModel.
Args:
data_wrapper: boolean, wrap requests and responses in a data wrapper'
| def __init__(self, data_wrapper=False):
| self._data_wrapper = data_wrapper
|
'Constructs a ProtocolBufferModel.
The serialzed protocol buffer returned in an HTTP response will be
de-serialized using the given protocol buffer class.
Args:
protocol_buffer: The protocol buffer class used to de-serialize a
response from the API.'
| def __init__(self, protocol_buffer):
| self._protocol_buffer = protocol_buffer
|
'Constructor.
Args:
discovery: object, Deserialized discovery document from which we pull
out the named schema.'
| def __init__(self, discovery):
| self.schemas = discovery.get('schemas', {})
self.pretty = {}
|
'Get pretty printed object prototype from the schema name.
Args:
name: string, Name of schema in the discovery document.
seen: list of string, Names of schema already seen. Used to handle
recursive definitions.
Returns:
string, A string that contains a prototype object with
comments that conforms to the given schema.'
| def _prettyPrintByName(self, name, seen=None, dent=0):
| if (seen is None):
seen = []
if (name in seen):
return ('# Object with schema name: %s' % name)
seen.append(name)
if (name not in self.pretty):
self.pretty[name] = _SchemaToStruct(self.schemas[name], seen, dent).to_str(self._prettyPrintByName)
seen.pop()
re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.