Skip to content

Commit db51baf

Browse files
committed
Making fixes to unit tests and some minor code refactoring for tests
This change make unit tests pass for Windows running Python 3.5 This change removed all callbacks from the test code to match the code fixes recently pushed. Updated gitignore to ignore files created by VS
1 parent ff9a0ad commit db51baf

20 files changed

+344
-268
lines changed

.gitignore

+3
Original file line numberDiff line numberDiff line change
@@ -45,3 +45,6 @@ src/build
4545
# Virtual Environments
4646
/env*
4747

48+
# Visual Studio Files
49+
/.vs/*
50+
/tests/.vs/*

adal/self_signed_jwt.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,11 @@ def _raise_on_invalid_thumbprint(self, thumbprint):
108108

109109
@staticmethod
110110
def _sign_jwt(header, payload, certificate):
111-
encoded_jwt = SelfSignedJwt._encode_jwt(payload, certificate, header)
111+
try:
112+
encoded_jwt = SelfSignedJwt._encode_jwt(payload, certificate, header)
113+
except Exception as exp:
114+
raise AdalError("Error:Invalid Certificate: Expected Start of Certificate to be '-----BEGIN RSA PRIVATE KEY-----'", exp)
115+
112116
SelfSignedJwt._raise_on_invalid_jwt_signature(encoded_jwt)
113117
return encoded_jwt
114118

adal/token_request.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ def _perform_wstrust_assertion_oauth_exchange(self, wstrust_response):
171171

172172
oauth_parameters = {}
173173
grant_type = TokenRequest._get_saml_grant_type(wstrust_response)
174-
assertion = b64encode(wstrust_response.token)
174+
assertion = b64encode(wstrust_response.token.encode('utf-8'))
175175
oauth_parameters = self._create_oauth_parameters(grant_type)
176176
oauth_parameters[OAUTH2_PARAMETERS.ASSERTION] = assertion
177177

adal/wstrust_response.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,12 @@ def parse(self):
151151
raise AdalError("Received empty RSTR response body.")
152152

153153
try:
154-
self._dom = ET.fromstring(self._response)
154+
155+
try:
156+
self._dom = ET.fromstring(self._response)
157+
except Exception as exp:
158+
raise AdalError('Failed to parse RSTR in to DOM', exp)
159+
155160
self._parents = {c:p for p in self._dom.iter() for c in p}
156161
error_found = self._parse_error()
157162
if error_found:

tests/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727

2828
import sys
2929
import os
30+
from adal import authentication_parameters
3031

3132
if sys.version_info[:2] < (2, 7, ):
3233
try:

tests/config_sample.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
# the password created here.
4040

4141
"username" : "[email protected]",
42-
"password" : None,
42+
"password" : "None",
4343
"tenant" : "XXXXXXXX.onmicrosoft.com",
4444

4545
"authorityHostUrl" : "https://login.windows.net",

tests/test_authentication_parameters.py

+36-29
Original file line numberDiff line numberDiff line change
@@ -243,17 +243,17 @@ def test_create_from_url_happy_string_url(self):
243243

244244
httpretty.register_uri(httpretty.GET, uri=self.testUrl, body='foo', status=401, **{'www-authenticate':'Bearer authorization_uri="foobar,lkfj,;l,", fruitcake="f",resource="clark, &^()- q32,shark" , f="foo"'})
245245

246-
def _callback(err, parameters):
247-
self.assertIsNone(err, "An error was raised during function {0}".format(err))
248-
test_params = {
249-
'authorizationUri' : 'foobar,lkfj,;l,',
250-
'resource' : 'clark, &^()- q32,shark',
251-
}
252-
self.assertEqual(parameters.authorization_uri, test_params['authorizationUri'],
253-
'Parsed authorizationUri did not match expected value.: {0}'.format(parameters.authorization_uri))
254-
self.assertEqual(parameters.resource, test_params['resource'],
255-
'Parsed resource did not match expected value.: {0}'.format(parameters.resource))
256-
adal.authentication_parameters.create_authentication_parameters_from_url(self.testUrl, _callback, None)
246+
# maybe try-catch here to catch the error
247+
parameters = adal.authentication_parameters.create_authentication_parameters_from_url(self.testUrl)
248+
249+
test_params = {
250+
'authorizationUri' : 'foobar,lkfj,;l,',
251+
'resource' : 'clark, &^()- q32,shark',
252+
}
253+
self.assertEqual(parameters.authorization_uri, test_params['authorizationUri'],
254+
'Parsed authorizationUri did not match expected value.: {0}'.format(parameters.authorization_uri))
255+
self.assertEqual(parameters.resource, test_params['resource'],
256+
'Parsed resource did not match expected value.: {0}'.format(parameters.resource))
257257

258258
req = httpretty.last_request()
259259
util.match_standard_request_headers(req)
@@ -265,8 +265,8 @@ def test_create_from_url_happy_path_url_object(self):
265265

266266
url_obj = urlparse(self.testUrl)
267267

268-
def _callback(err, parameters):
269-
self.assertIsNone(err, "An error was raised during function {0}".format(err))
268+
try:
269+
parameters = adal.authentication_parameters.create_authentication_parameters_from_url(url_obj)
270270
test_params = {
271271
'authorizationUri' : 'foobar,lkfj,;l,',
272272
'resource' : 'clark, &^()- q32,shark',
@@ -276,45 +276,52 @@ def _callback(err, parameters):
276276
self.assertEqual(parameters.resource, test_params['resource'],
277277
'Parsed resource did not match expected value.: {0}'.format(parameters.resource))
278278

279-
adal.authentication_parameters.create_authentication_parameters_from_url(url_obj, _callback)
279+
except Exception as err:
280+
self.assertIsNone(err, "An error was raised during function {0}".format(err))
280281

281282
req = httpretty.last_request()
282283
util.match_standard_request_headers(req)
283284

284285
def test_create_from_url_bad_object(self):
285286

286-
def _callback(err, resp):
287-
self.assertIsNotNone(err, "Did not receive expected error.")
288-
289-
adal.authentication_parameters.create_authentication_parameters_from_url({}, _callback)
287+
try:
288+
parameters = adal.authentication_parameters.create_authentication_parameters_from_url({})
289+
except Exception as exp:
290+
self.assertIsNotNone(exp, "Did not receive expected error.")
291+
pass
290292

291293
def test_create_from_url_not_passed(self):
292294

293-
def _callback(err, resp):
294-
self.assertIsNotNone(err, "Did not receive expected error.")
295-
296-
adal.authentication_parameters.create_authentication_parameters_from_url(None, _callback)
295+
try:
296+
parameters = adal.authentication_parameters.create_authentication_parameters_from_url(None)
297+
except Exception as exp:
298+
self.assertIsNotNone(exp, "Did not receive expected error.")
299+
pass
297300

298301
@httpretty.activate
299302
def test_create_from_url_no_header(self):
300303

301304
httpretty.register_uri(httpretty.GET, uri=self.testUrl, body='foo', status=401)
302305

303-
def _callback(err, resp):
304-
self.assertIsNotNone(err, "Did not receive expected error.")
306+
receivedException = False
307+
try:
308+
adal.authentication_parameters.create_authentication_parameters_from_url(self.testUrl)
309+
except Exception as err:
310+
receivedException = True
305311
self.assertTrue(str(err).find('header') >= 0, 'Error did not include message about missing header')
306-
307-
adal.authentication_parameters.create_authentication_parameters_from_url(self.testUrl, _callback)
312+
pass
313+
finally:
314+
self.assertTrue(receivedException)
308315

309316
req = httpretty.last_request()
310317
util.match_standard_request_headers(req)
311318

312319
def test_create_from_url_network_error(self):
313320

314-
def _callback(err, resp):
321+
try:
322+
adal.authentication_parameters.create_authentication_parameters_from_url('https://0.0.0.0/foobar')
323+
except Exception as err:
315324
self.assertIsNotNone(err, "Did not receive expected error.")
316325

317-
adal.authentication_parameters.create_authentication_parameters_from_url('https://0.0.0.0/foobar', _callback)
318-
319326
if __name__ == '__main__':
320327
unittest.main()

tests/test_authority.py

+28-30
Original file line numberDiff line numberDiff line change
@@ -83,20 +83,21 @@ def test_success_dynamic_instance_discovery(self):
8383
self.nonHardCodedAuthorizeEndpoint
8484
)
8585

86-
responseOptions = { 'authority' : self.nonHardCodedAuthority}
86+
responseOptions = { 'authority' : self.nonHardCodedAuthority }
8787
response = util.create_response(responseOptions)
8888
wireResponse = response['wireResponse']
8989

9090
util.setup_expected_client_cred_token_request_response(200, wireResponse, self.nonHardCodedAuthority)
9191

92-
token_response = adal.acquire_token_with_client_credentials(
93-
self.nonHardCodedAuthority, cp['clientId'], cp['clientSecret'], response['resource'])
92+
context = adal.AuthenticationContext(self.nonHardCodedAuthority)
93+
token_response = context.acquire_token_with_client_credentials(
94+
response['resource'], cp['clientId'], cp['clientSecret'])
9495
self.assertTrue(
9596
util.is_match_token_response(response['cachedResponse'], token_response),
9697
'The response does not match what was expected.: ' + str(token_response)
9798
)
9899

99-
def performStaticInstanceDiscovery(self, authorityHost, callback):
100+
def performStaticInstanceDiscovery(self, authorityHost):
100101
hardCodedAuthority = 'https://' + authorityHost + '/' + cp['tenant']
101102

102103
responseOptions = {
@@ -106,8 +107,9 @@ def performStaticInstanceDiscovery(self, authorityHost, callback):
106107
wireResponse = response['wireResponse']
107108
tokenRequest = util.setup_expected_client_cred_token_request_response(200, wireResponse, hardCodedAuthority)
108109

109-
token_response = adal.acquire_token_with_client_credentials(
110-
hardCodedAuthority, cp['clientId'], cp['clientSecret'], response['resource'])
110+
context = adal.AuthenticationContext(hardCodedAuthority)
111+
token_response = context.acquire_token_with_client_credentials(
112+
response['resource'], cp['clientId'], cp['clientSecret'])
111113

112114
self.assertTrue(
113115
util.is_match_token_response(response['cachedResponse'], token_response),
@@ -117,32 +119,31 @@ def performStaticInstanceDiscovery(self, authorityHost, callback):
117119

118120
@httpretty.activate
119121
def test_success_static_instance_discovery(self):
120-
def callback(err):
121-
if err:
122-
raise Exception(err)
123122

124-
self.performStaticInstanceDiscovery('login.microsoftonline.com', callback)
125-
self.performStaticInstanceDiscovery('login.windows.net', callback)
126-
self.performStaticInstanceDiscovery('login.chinacloudapi.cn', callback)
127-
self.performStaticInstanceDiscovery('login.cloudgovapi.us', callback)
123+
self.performStaticInstanceDiscovery('login.microsoftonline.com')
124+
self.performStaticInstanceDiscovery('login.windows.net')
125+
self.performStaticInstanceDiscovery('login.chinacloudapi.cn')
126+
self.performStaticInstanceDiscovery('login.cloudgovapi.us')
128127

129128

130129
@httpretty.activate
131130
def test_http_error(self):
132131
util.setup_expected_instance_discovery_request(500, cp['authorityHosts']['global'], None, self.nonHardCodedAuthorizeEndpoint)
133132

134-
with self.assertRaisesRegexp(Exception, '500'):
135-
token_response = adal.acquire_token_with_client_credentials(
136-
self.nonHardCodedAuthority, cp['clientId'], cp['clientSecret'], cp['resource'])
133+
with self.assertRaisesRegex(Exception, '500'):
134+
context = adal.AuthenticationContext(self.nonHardCodedAuthority)
135+
token_response = context.acquire_token_with_client_credentials(
136+
cp['resource'], cp['clientId'], cp['clientSecret'])
137137

138138
@httpretty.activate
139139
def test_validation_error(self):
140140
returnDoc = { 'error' : 'invalid_instance', 'error_description' : 'the instance was invalid' }
141141
util.setup_expected_instance_discovery_request(400, cp['authorityHosts']['global'], returnDoc, self.nonHardCodedAuthorizeEndpoint)
142142

143-
with self.assertRaisesRegexp(Exception, 'instance was invalid'):
144-
token_response = adal.acquire_token_with_client_credentials(
145-
self.nonHardCodedAuthority, cp['clientId'], cp['clientSecret'], cp['resource'])
143+
with self.assertRaisesRegex(Exception, 'instance was invalid'):
144+
context = adal.AuthenticationContext(self.nonHardCodedAuthority)
145+
token_response = context.acquire_token_with_client_credentials(
146+
cp['resource'], cp['clientId'], cp['clientSecret'])
146147

147148
@httpretty.activate
148149
def test_validation_off(self):
@@ -159,8 +160,9 @@ def test_validation_off(self):
159160

160161
util.setup_expected_client_cred_token_request_response(200, wireResponse, self.nonHardCodedAuthority)
161162

162-
token_response = adal.acquire_token_with_client_credentials(
163-
self.nonHardCodedAuthority, cp['clientId'], cp['clientSecret'], response['resource'], validate_authority = False)
163+
context = adal.AuthenticationContext(self.nonHardCodedAuthority)
164+
token_response = context.acquire_token_with_client_credentials(
165+
response['resource'], cp['clientId'], cp['clientSecret'])
164166
self.assertTrue(
165167
util.is_match_token_response(response['cachedResponse'], token_response),
166168
'The response does not match what was expected.: ' + str(token_response)
@@ -169,12 +171,12 @@ def test_validation_off(self):
169171

170172
@httpretty.activate
171173
def test_bad_url_not_https(self):
172-
with self.assertRaisesRegexp(ValueError, "The authority url must be an https endpoint\."):
174+
with self.assertRaisesRegex(ValueError, "The authority url must be an https endpoint\."):
173175
context = AuthenticationContext('http://this.is.not.https.com/mytenant.com')
174176

175177
@httpretty.activate
176178
def test_bad_url_has_query(self):
177-
with self.assertRaisesRegexp(ValueError, "The authority url must not have a query string\."):
179+
with self.assertRaisesRegex(ValueError, "The authority url must not have a query string\."):
178180
context = AuthenticationContext(cp['authorityTenant'] + '?this=should&not=be&here=foo')
179181

180182
@httpretty.activate
@@ -190,13 +192,9 @@ def test_url_extra_path_elements(self):
190192
authority = Authority(authority_url, True)
191193
obj = util.create_empty_adal_object()
192194

193-
def callback(err):
194-
if err:
195-
self.assertFalse(err, 'Received unexpected error: ' + err.args[0])
196-
req = httpretty.last_request()
197-
util.match_standard_request_headers(req)
198-
199-
authority.validate(obj['call_context'], callback)
195+
authority.validate(obj['call_context'])
196+
req = httpretty.last_request()
197+
util.match_standard_request_headers(req)
200198

201199
if __name__ == '__main__':
202200
unittest.main()

tests/test_authorization_code.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
import mock
4141

4242
import adal
43+
from adal.authentication_context import AuthenticationContext
4344
from tests import util
4445
from tests.util import parameters as cp
4546

@@ -83,7 +84,8 @@ def test_happy_path(self):
8384

8485
self.setup_expected_auth_code_token_request_response(200, response['wireResponse'])
8586

86-
token_response = adal._acquire_token_with_authorization_code(cp['authUrl'], cp['clientId'], cp['clientSecret'], self.authorization_code, self.redirect_uri, response['resource'])
87+
context = adal.AuthenticationContext(cp['authUrl'])
88+
token_response = context.acquire_token_with_authorization_code(self.authorization_code, self.redirect_uri, response['resource'], cp['clientId'], cp['clientSecret'])
8789

8890
self.assertTrue(util.is_match_token_response(response['decodedResponse'], token_response), 'The response did not match what was expected')
8991

0 commit comments

Comments
 (0)