Skip to content

Commit 2b93c98

Browse files
committed
Merge pull request googleapis#103 from craigcitro/master
Finish switching to mock from mox.
2 parents 5f053b6 + ec26d89 commit 2b93c98

File tree

5 files changed

+152
-215
lines changed

5 files changed

+152
-215
lines changed

tests/test_appengine.py

Lines changed: 81 additions & 100 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333

3434
import dev_appserver
3535
dev_appserver.fix_sys_path()
36-
import mox
36+
import mock
3737
import webapp2
3838

3939
from google.appengine.api import apiproxy_stub
@@ -159,13 +159,9 @@ def test_raise_correct_type_of_exception(self):
159159
'memcache', memcache_stub.MemcacheServiceStub())
160160

161161
scope = 'http://www.googleapis.com/scope'
162-
try:
163-
credentials = AppAssertionCredentials(scope)
164-
http = httplib2.Http()
165-
credentials.refresh(http)
166-
self.fail('Should have raised an AccessTokenRefreshError')
167-
except AccessTokenRefreshError:
168-
pass
162+
credentials = AppAssertionCredentials(scope)
163+
http = httplib2.Http()
164+
self.assertRaises(AccessTokenRefreshError, credentials.refresh, http)
169165

170166
def test_get_access_token_on_refresh(self):
171167
app_identity_stub = self.AppIdentityStubImpl()
@@ -201,19 +197,19 @@ def test_get_access_token_on_refresh(self):
201197
def test_custom_service_account(self):
202198
scope = "http://www.googleapis.com/scope"
203199
account_id = "[email protected]"
204-
m = mox.Mox()
205-
m.StubOutWithMock(app_identity, 'get_access_token')
206-
app_identity.get_access_token(
207-
[scope], service_account_id=account_id).AndReturn(('a_token_456', None))
208-
m.ReplayAll()
209200

210-
credentials = AppAssertionCredentials(scope, service_account_id=account_id)
211-
http = httplib2.Http()
212-
credentials.refresh(http)
213-
m.VerifyAll()
214-
m.UnsetStubs()
215-
self.assertEqual('a_token_456', credentials.access_token)
216-
self.assertEqual(scope, credentials.scope)
201+
with mock.patch.object(app_identity, 'get_access_token',
202+
return_value=('a_token_456', None),
203+
autospec=True) as get_access_token:
204+
credentials = AppAssertionCredentials(
205+
scope, service_account_id=account_id)
206+
http = httplib2.Http()
207+
credentials.refresh(http)
208+
209+
self.assertEqual('a_token_456', credentials.access_token)
210+
self.assertEqual(scope, credentials.scope)
211+
get_access_token.assert_called_once_with(
212+
[scope], service_account_id=account_id)
217213

218214
def test_create_scoped_required_without_scopes(self):
219215
credentials = AppAssertionCredentials([])
@@ -538,7 +534,8 @@ def get(self, *args, **kwargs):
538534
'wsgi.url_scheme': 'http',
539535
'HTTP_HOST': 'localhost',
540536
})
541-
users.get_current_user = user_mock()
537+
self.current_user = user_mock()
538+
users.get_current_user = self.current_user
542539
self.httplib2_orig = httplib2.Http
543540
httplib2.Http = Http2Mock
544541

@@ -562,30 +559,28 @@ def test_required(self):
562559
self.assertEqual('code', q['response_type'][0])
563560
self.assertEqual(False, self.decorator.has_credentials())
564561

565-
m = mox.Mox()
566-
m.StubOutWithMock(appengine, '_parse_state_value')
567-
appengine._parse_state_value('foo_path:xsrfkey123',
568-
mox.IgnoreArg()).AndReturn('foo_path')
569-
m.ReplayAll()
570-
571-
# Now simulate the callback to /oauth2callback.
572-
response = self.app.get('/oauth2callback', {
573-
'code': 'foo_access_code',
574-
'state': 'foo_path:xsrfkey123',
575-
})
576-
parts = response.headers['Location'].split('?', 1)
577-
self.assertEqual('http://localhost/foo_path', parts[0])
578-
self.assertEqual(None, self.decorator.credentials)
579-
if self.decorator._token_response_param:
580-
response = urlparse.parse_qs(
581-
parts[1])[self.decorator._token_response_param][0]
582-
self.assertEqual(Http2Mock.content, json.loads(urllib.unquote(response)))
583-
self.assertEqual(self.decorator.flow, self.decorator._tls.flow)
584-
self.assertEqual(self.decorator.credentials,
585-
self.decorator._tls.credentials)
586-
587-
m.UnsetStubs()
588-
m.VerifyAll()
562+
with mock.patch.object(appengine, '_parse_state_value',
563+
return_value='foo_path',
564+
autospec=True) as parse_state_value:
565+
# Now simulate the callback to /oauth2callback.
566+
response = self.app.get('/oauth2callback', {
567+
'code': 'foo_access_code',
568+
'state': 'foo_path:xsrfkey123',
569+
})
570+
parts = response.headers['Location'].split('?', 1)
571+
self.assertEqual('http://localhost/foo_path', parts[0])
572+
self.assertEqual(None, self.decorator.credentials)
573+
if self.decorator._token_response_param:
574+
response_query = urlparse.parse_qs(parts[1])
575+
response = response_query[self.decorator._token_response_param][0]
576+
self.assertEqual(Http2Mock.content,
577+
json.loads(urllib.unquote(response)))
578+
self.assertEqual(self.decorator.flow, self.decorator._tls.flow)
579+
self.assertEqual(self.decorator.credentials,
580+
self.decorator._tls.credentials)
581+
582+
parse_state_value.assert_called_once_with(
583+
'foo_path:xsrfkey123', self.current_user)
589584

590585
# Now requesting the decorated path should work.
591586
response = self.app.get('/foo_path')
@@ -599,13 +594,9 @@ def test_required(self):
599594

600595
# Raising an exception still clears the Credentials.
601596
self.should_raise = True
602-
try:
603-
response = self.app.get('/foo_path')
604-
self.fail('Should have raised an exception.')
605-
except Exception:
606-
pass
607-
self.assertEqual(None, self.decorator.credentials)
597+
self.assertRaises(Exception, self.app.get, '/foo_path')
608598
self.should_raise = False
599+
self.assertEqual(None, self.decorator.credentials)
609600

610601
# Invalidate the stored Credentials.
611602
self.found_credentials.invalid = True
@@ -623,37 +614,34 @@ def test_storage_delete(self):
623614
response = self.app.get('/foo_path')
624615
self.assertTrue(response.status.startswith('302'))
625616

626-
m = mox.Mox()
627-
m.StubOutWithMock(appengine, '_parse_state_value')
628-
appengine._parse_state_value('foo_path:xsrfkey123',
629-
mox.IgnoreArg()).AndReturn('foo_path')
630-
m.ReplayAll()
631-
632-
# Now simulate the callback to /oauth2callback.
633-
response = self.app.get('/oauth2callback', {
634-
'code': 'foo_access_code',
635-
'state': 'foo_path:xsrfkey123',
636-
})
637-
self.assertEqual('http://localhost/foo_path', response.headers['Location'])
638-
self.assertEqual(None, self.decorator.credentials)
639-
640-
# Now requesting the decorated path should work.
641-
response = self.app.get('/foo_path')
617+
with mock.patch.object(appengine, '_parse_state_value',
618+
return_value='foo_path',
619+
autospec=True) as parse_state_value:
620+
# Now simulate the callback to /oauth2callback.
621+
response = self.app.get('/oauth2callback', {
622+
'code': 'foo_access_code',
623+
'state': 'foo_path:xsrfkey123',
624+
})
625+
self.assertEqual('http://localhost/foo_path', response.headers['Location'])
626+
self.assertEqual(None, self.decorator.credentials)
627+
628+
# Now requesting the decorated path should work.
629+
response = self.app.get('/foo_path')
642630

643-
self.assertTrue(self.had_credentials)
631+
self.assertTrue(self.had_credentials)
644632

645-
# Credentials should be cleared after each call.
646-
self.assertEqual(None, self.decorator.credentials)
633+
# Credentials should be cleared after each call.
634+
self.assertEqual(None, self.decorator.credentials)
647635

648-
# Invalidate the stored Credentials.
649-
self.found_credentials.store.delete()
636+
# Invalidate the stored Credentials.
637+
self.found_credentials.store.delete()
650638

651-
# Invalid Credentials should start the OAuth dance again.
652-
response = self.app.get('/foo_path')
653-
self.assertTrue(response.status.startswith('302'))
639+
# Invalid Credentials should start the OAuth dance again.
640+
response = self.app.get('/foo_path')
641+
self.assertTrue(response.status.startswith('302'))
654642

655-
m.UnsetStubs()
656-
m.VerifyAll()
643+
parse_state_value.assert_called_once_with(
644+
'foo_path:xsrfkey123', self.current_user)
657645

658646
def test_aware(self):
659647
# An initial request to an oauth_aware decorated path should not redirect.
@@ -670,23 +658,20 @@ def test_aware(self):
670658
q['state'][0].rsplit(':', 1)[0])
671659
self.assertEqual('code', q['response_type'][0])
672660

673-
m = mox.Mox()
674-
m.StubOutWithMock(appengine, '_parse_state_value')
675-
appengine._parse_state_value('bar_path:xsrfkey456',
676-
mox.IgnoreArg()).AndReturn('bar_path')
677-
m.ReplayAll()
678-
679-
# Now simulate the callback to /oauth2callback.
680-
url = self.decorator.authorize_url()
681-
response = self.app.get('/oauth2callback', {
682-
'code': 'foo_access_code',
683-
'state': 'bar_path:xsrfkey456',
684-
})
685-
self.assertEqual('http://localhost/bar_path', response.headers['Location'])
686-
self.assertEqual(False, self.decorator.has_credentials())
687-
688-
m.UnsetStubs()
689-
m.VerifyAll()
661+
with mock.patch.object(appengine, '_parse_state_value',
662+
return_value='bar_path',
663+
autospec=True) as parse_state_value:
664+
# Now simulate the callback to /oauth2callback.
665+
url = self.decorator.authorize_url()
666+
response = self.app.get('/oauth2callback', {
667+
'code': 'foo_access_code',
668+
'state': 'bar_path:xsrfkey456',
669+
})
670+
671+
self.assertEqual('http://localhost/bar_path', response.headers['Location'])
672+
self.assertEqual(False, self.decorator.has_credentials())
673+
parse_state_value.assert_called_once_with(
674+
'bar_path:xsrfkey456', self.current_user)
690675

691676
# Now requesting the decorated path will have credentials.
692677
response = self.app.get('/bar_path/2012/01')
@@ -703,13 +688,9 @@ def test_aware(self):
703688

704689
# Raising an exception still clears the Credentials.
705690
self.should_raise = True
706-
try:
707-
response = self.app.get('/bar_path/2012/01')
708-
self.fail('Should have raised an exception.')
709-
except Exception:
710-
pass
711-
self.assertEqual(None, self.decorator.credentials)
691+
self.assertRaises(Exception, self.app.get, '/bar_path/2012/01')
712692
self.should_raise = False
693+
self.assertEqual(None, self.decorator.credentials)
713694

714695

715696
def test_error_in_step2(self):

tests/test_gce.py

Lines changed: 23 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,11 @@
2020

2121
__author__ = '[email protected] (Joe Gregorio)'
2222

23-
import httplib2
24-
try:
25-
from mox3 import mox
26-
except ImportError:
27-
import mox
2823
import unittest
2924

25+
import httplib2
26+
import mock
27+
3028
from oauth2client.client import AccessTokenRefreshError
3129
from oauth2client.client import Credentials
3230
from oauth2client.client import save_to_well_known_file
@@ -36,56 +34,29 @@
3634
class AssertionCredentialsTests(unittest.TestCase):
3735

3836
def test_good_refresh(self):
39-
m = mox.Mox()
40-
41-
httplib2_response = m.CreateMock(object)
42-
httplib2_response.status = 200
43-
44-
httplib2_request = m.CreateMock(object)
45-
httplib2_request.__call__(
46-
('http://metadata.google.internal/0.1/meta-data/service-accounts/'
47-
'default/acquire'
48-
'?scope=http%3A%2F%2Fexample.com%2Fa%20http%3A%2F%2Fexample.com%2Fb'
49-
)).AndReturn((httplib2_response, '{"accessToken": "this-is-a-token"}'))
50-
51-
m.ReplayAll()
37+
http = mock.MagicMock()
38+
http.request = mock.MagicMock(
39+
return_value=(mock.Mock(status=200),
40+
'{"accessToken": "this-is-a-token"}'))
5241

5342
c = AppAssertionCredentials(scope=['http://example.com/a',
5443
'http://example.com/b'])
55-
56-
c._refresh(httplib2_request)
57-
44+
self.assertEquals(None, c.access_token)
45+
c.refresh(http)
5846
self.assertEquals('this-is-a-token', c.access_token)
5947

60-
m.UnsetStubs()
61-
m.VerifyAll()
48+
http.request.assert_called_exactly_once_with(
49+
'http://metadata.google.internal/0.1/meta-data/service-accounts/'
50+
'default/acquire'
51+
'?scope=http%3A%2F%2Fexample.com%2Fa%20http%3A%2F%2Fexample.com%2Fb')
6252

6353
def test_fail_refresh(self):
64-
m = mox.Mox()
65-
66-
httplib2_response = m.CreateMock(object)
67-
httplib2_response.status = 400
68-
69-
httplib2_request = m.CreateMock(object)
70-
httplib2_request.__call__(
71-
('http://metadata.google.internal/0.1/meta-data/service-accounts/'
72-
'default/acquire'
73-
'?scope=http%3A%2F%2Fexample.com%2Fa%20http%3A%2F%2Fexample.com%2Fb'
74-
)).AndReturn((httplib2_response, '{"accessToken": "this-is-a-token"}'))
75-
76-
m.ReplayAll()
54+
http = mock.MagicMock()
55+
http.request = mock.MagicMock(return_value=(mock.Mock(status=400), '{}'))
7756

7857
c = AppAssertionCredentials(scope=['http://example.com/a',
7958
'http://example.com/b'])
80-
81-
try:
82-
c._refresh(httplib2_request)
83-
self.fail('Should have raised exception on 400')
84-
except AccessTokenRefreshError:
85-
pass
86-
87-
m.UnsetStubs()
88-
m.VerifyAll()
59+
self.assertRaises(AccessTokenRefreshError, c.refresh, http)
8960

9061
def test_to_from_json(self):
9162
c = AppAssertionCredentials(scope=['http://example.com/a',
@@ -111,30 +82,19 @@ def test_create_scoped(self):
11182
self.assertEqual('dummy_scope', new_credentials.scope)
11283

11384
def test_get_access_token(self):
114-
m = mox.Mox()
115-
116-
httplib2_response = m.CreateMock(object)
117-
httplib2_response.status = 200
118-
119-
httplib2_request = m.CreateMock(object)
120-
httplib2_request.__call__(
121-
('http://metadata.google.internal/0.1/meta-data/service-accounts/'
122-
'default/acquire?scope=dummy_scope'
123-
)).AndReturn((httplib2_response, '{"accessToken": "this-is-a-token"}'))
124-
125-
m.ReplayAll()
85+
http = mock.MagicMock()
86+
http.request = mock.MagicMock(
87+
return_value=(mock.Mock(status=200),
88+
'{"accessToken": "this-is-a-token"}'))
12689

12790
credentials = AppAssertionCredentials(['dummy_scope'])
128-
129-
http = httplib2.Http()
130-
http.request = httplib2_request
131-
13291
token = credentials.get_access_token(http=http)
13392
self.assertEqual('this-is-a-token', token.access_token)
13493
self.assertEqual(None, token.expires_in)
13594

136-
m.UnsetStubs()
137-
m.VerifyAll()
95+
http.request.assert_called_exactly_once_with(
96+
'http://metadata.google.internal/0.1/meta-data/service-accounts/'
97+
'default/acquire?scope=dummy_scope')
13898

13999
def test_save_to_well_known_file(self):
140100
credentials = AppAssertionCredentials([])

0 commit comments

Comments
 (0)