Skip to content

Commit 29347a9

Browse files
Merge pull request googleapis#305 from dhermes/remove-test-yagni
Removed unused test code.
2 parents 4a0072a + 64ab3c8 commit 29347a9

File tree

5 files changed

+53
-89
lines changed

5 files changed

+53
-89
lines changed

tests/http_mock.py

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -24,21 +24,15 @@
2424
class HttpMock(object):
2525
"""Mock of httplib2.Http"""
2626

27-
def __init__(self, filename=None, headers=None):
27+
def __init__(self, headers=None):
2828
"""HttpMock constructor.
2929
3030
Args:
31-
filename: string, absolute filename to read response from
3231
headers: dict, header to return with response
3332
"""
3433
if headers is None:
35-
headers = {'status': '200 OK'}
36-
if filename:
37-
f = file(filename, 'r')
38-
self.data = f.read()
39-
f.close()
40-
else:
41-
self.data = None
34+
headers = {'status': '200'}
35+
self.data = None
4236
self.response_headers = headers
4337
self.headers = None
4438
self.uri = None
@@ -78,10 +72,7 @@ class HttpMockSequence(object):
7872
7973
* 'echo_request_headers' means return the request headers in the response
8074
body
81-
* 'echo_request_headers_as_json' means return the request headers in
82-
the response body
8375
* 'echo_request_body' means return the request body in the response body
84-
* 'echo_request_uri' means return the request uri in the response body
8576
"""
8677

8778
def __init__(self, iterable):
@@ -107,13 +98,17 @@ def request(self, uri,
10798
if getattr(body, 'read', None) else None)
10899
if content == 'echo_request_headers':
109100
content = headers
110-
elif content == 'echo_request_headers_as_json':
111-
content = json.dumps(headers)
112101
elif content == 'echo_request_body':
113102
content = (body
114103
if body_stream_content is None else body_stream_content)
115-
elif content == 'echo_request_uri':
116-
content = uri
117-
elif not isinstance(content, bytes):
118-
raise TypeError('http content should be bytes: %r' % (content,))
119104
return httplib2.Response(resp), content
105+
106+
107+
class CacheMock(object):
108+
109+
def __init__(self):
110+
self.cache = {}
111+
112+
def get(self, key, namespace=''):
113+
# ignoring namespace for easier testing
114+
return self.cache.get(key, None)

tests/test_appengine.py

Lines changed: 1 addition & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
import mock
3535
import webapp2
3636

37+
from .http_mock import CacheMock
3738
from google.appengine.api import apiproxy_stub
3839
from google.appengine.api import apiproxy_stub_map
3940
from google.appengine.api import app_identity
@@ -80,19 +81,6 @@ def load_and_cache(existing_file, fakename, cache_mock):
8081
cache_mock.cache[fakename] = {client_type: client_info}
8182

8283

83-
class CacheMock(object):
84-
def __init__(self):
85-
self.cache = {}
86-
87-
def get(self, key, namespace=''):
88-
# ignoring namespace for easier testing
89-
return self.cache.get(key, None)
90-
91-
def set(self, key, value, namespace=''):
92-
# ignoring namespace for easier testing
93-
self.cache[key] = value
94-
95-
9684
class UserMock(object):
9785
"""Mock the app engine user service"""
9886

tests/test_client.py

Lines changed: 8 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
import six
3434
from six.moves import urllib
3535

36+
from .http_mock import CacheMock
3637
from .http_mock import HttpMock
3738
from .http_mock import HttpMockSequence
3839
from oauth2client import GOOGLE_REVOKE_URI
@@ -112,19 +113,6 @@ def load_and_cache(existing_file, fakename, cache_mock):
112113
cache_mock.cache[fakename] = {client_type: client_info}
113114

114115

115-
class CacheMock(object):
116-
def __init__(self):
117-
self.cache = {}
118-
119-
def get(self, key, namespace=''):
120-
# ignoring namespace for easier testing
121-
return self.cache.get(key, None)
122-
123-
def set(self, key, value, namespace=''):
124-
# ignoring namespace for easier testing
125-
self.cache[key] = value
126-
127-
128116
class CredentialsTests(unittest.TestCase):
129117

130118
def test_to_from_json(self):
@@ -133,23 +121,6 @@ def test_to_from_json(self):
133121
restored = Credentials.new_from_json(json)
134122

135123

136-
class MockResponse(object):
137-
"""Mock the response of urllib2.urlopen() call."""
138-
139-
def __init__(self, headers):
140-
self._headers = headers
141-
142-
def info(self):
143-
class Info:
144-
def __init__(self, headers):
145-
self.headers = headers
146-
147-
def get(self, key, default=None):
148-
return self.headers.get(key, default)
149-
150-
return Info(self._headers)
151-
152-
153124
@contextlib.contextmanager
154125
def mock_module_import(module):
155126
"""Place a dummy objects in sys.modules to mock an import test."""
@@ -169,27 +140,19 @@ def mock_module_import(module):
169140
class GoogleCredentialsTests(unittest.TestCase):
170141

171142
def setUp(self):
172-
self.env_server_software = os.environ.get('SERVER_SOFTWARE', None)
173-
self.env_google_application_credentials = (
174-
os.environ.get(GOOGLE_APPLICATION_CREDENTIALS, None))
175-
self.env_appdata = os.environ.get('APPDATA', None)
176143
self.os_name = os.name
177144
from oauth2client import client
178145
client.SETTINGS.env_name = None
179146

180147
def tearDown(self):
181-
self.reset_env('SERVER_SOFTWARE', self.env_server_software)
182-
self.reset_env(GOOGLE_APPLICATION_CREDENTIALS,
183-
self.env_google_application_credentials)
184-
self.reset_env('APPDATA', self.env_appdata)
148+
self.reset_env('SERVER_SOFTWARE')
149+
self.reset_env(GOOGLE_APPLICATION_CREDENTIALS)
150+
self.reset_env('APPDATA')
185151
os.name = self.os_name
186152

187-
def reset_env(self, env, value):
153+
def reset_env(self, env):
188154
"""Set the environment variable 'env' to 'value'."""
189-
if value is not None:
190-
os.environ[env] = value
191-
else:
192-
os.environ.pop(env, '')
155+
os.environ.pop(env, None)
193156

194157
def validate_service_account_credentials(self, credentials):
195158
self.assertTrue(isinstance(credentials, _ServiceAccountCredentials))
@@ -796,7 +759,7 @@ def test_unicode_header_checks(self):
796759
# First, test that we correctly encode basic objects, making sure
797760
# to include a bytes object. Note that oauth2client will normalize
798761
# everything to bytes, no matter what python version we're in.
799-
http = credentials.authorize(HttpMock(headers={'status': '200'}))
762+
http = credentials.authorize(HttpMock())
800763
headers = {u'foo': 3, b'bar': True, 'baz': b'abc'}
801764
cleaned_headers = {b'foo': b'3', b'bar': b'True', b'baz': b'abc'}
802765
http.request(u'http://example.com', method=u'GET', headers=headers)
@@ -825,7 +788,7 @@ def test_no_unicode_in_request_params(self):
825788
refresh_token, token_expiry, token_uri,
826789
user_agent, revoke_uri=revoke_uri)
827790

828-
http = HttpMock(headers={'status': '200'})
791+
http = HttpMock()
829792
http = credentials.authorize(http)
830793
http.request(u'http://example.com', method=u'GET',
831794
headers={u'foo': u'bar'})
@@ -941,8 +904,6 @@ def test_token_refresh_success(self):
941904
self.fail('should throw exception if token expires')
942905
except AccessTokenCredentialsError:
943906
pass
944-
except Exception:
945-
self.fail('should only throw AccessTokenCredentialsError')
946907

947908
def test_token_revoke_success(self):
948909
_token_revoke_test_helper(

tests/test_clientsecrets.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
import httplib2
2323

24+
from oauth2client._helpers import _from_bytes
2425
from oauth2client import GOOGLE_AUTH_URI
2526
from oauth2client import GOOGLE_REVOKE_URI
2627
from oauth2client import GOOGLE_TOKEN_URI
@@ -207,10 +208,7 @@ def test_validate_error(self):
207208
]
208209
for src, match in ERRORS:
209210
# Ensure that it is unicode
210-
try:
211-
src = src.decode('utf-8')
212-
except AttributeError:
213-
pass
211+
src = _from_bytes(src)
214212
# Test load(s)
215213
try:
216214
clientsecrets.loads(src)

tests/test_devshell.py

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222

2323
import mock
2424

25+
from oauth2client._helpers import _from_bytes
2526
from oauth2client._helpers import _to_bytes
2627
from oauth2client.client import save_to_well_known_file
2728
from oauth2client.devshell import _SendRecv
@@ -107,9 +108,10 @@ def __init__(self, response=None):
107108
super(_AuthReferenceServer, self).__init__(None)
108109
self.response = (response or
109110
'["[email protected]", "fooproj", "sometoken"]')
111+
self.bad_request = False
110112

111113
def __enter__(self):
112-
self.start_server()
114+
return self.start_server()
113115

114116
def start_server(self):
115117
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
@@ -139,28 +141,48 @@ def run(self):
139141
s, unused_addr = self._socket.accept()
140142
resp_buffer = ''
141143
resp_1 = s.recv(6).decode()
142-
if '\n' not in resp_1:
143-
raise Exception('invalid request data')
144144
nstr, extra = resp_1.split('\n', 1)
145145
resp_buffer = extra
146146
n = int(nstr)
147147
to_read = n - len(extra)
148148
if to_read > 0:
149-
resp_buffer += s.recv(to_read, socket.MSG_WAITALL)
149+
resp_buffer += _from_bytes(s.recv(to_read, socket.MSG_WAITALL))
150150
if resp_buffer != CREDENTIAL_INFO_REQUEST_JSON:
151-
raise Exception('bad request')
151+
self.bad_request = True
152152
l = len(self.response)
153153
s.sendall(('%d\n%s' % (l, self.response)).encode())
154154
finally:
155-
if s:
156-
s.close()
155+
# Will fail if s is None, but these tests never encounter
156+
# that scenario.
157+
s.close()
157158

158159

159160
class DevshellCredentialsTests(unittest.TestCase):
160161

161162
def test_signals_no_server(self):
162163
self.assertRaises(NoDevshellServer, DevshellCredentials)
163164

165+
def test_bad_message_to_mock_server(self):
166+
request_content = CREDENTIAL_INFO_REQUEST_JSON + 'extrastuff'
167+
request_message = _to_bytes(
168+
'%d\n%s' % (len(request_content), request_content))
169+
response_message = 'foobar'
170+
with _AuthReferenceServer(response_message) as auth_server:
171+
self.assertFalse(auth_server.bad_request)
172+
sock = socket.socket()
173+
port = int(os.getenv(DEVSHELL_ENV, 0))
174+
sock.connect(('localhost', port))
175+
sock.sendall(request_message)
176+
177+
# Mimic the receive part of _SendRecv
178+
header = sock.recv(6).decode()
179+
len_str, result = header.split('\n', 1)
180+
to_read = int(len_str) - len(result)
181+
result += sock.recv(to_read, socket.MSG_WAITALL).decode()
182+
183+
self.assertTrue(auth_server.bad_request)
184+
self.assertEqual(result, response_message)
185+
164186
def test_request_response(self):
165187
with _AuthReferenceServer():
166188
response = _SendRecv()

0 commit comments

Comments
 (0)