def test_CanNotReissueUsedTicket(self): setup = self.setup() userID="ddddvv" InternalAuthUsername="******" InternalAuthPassword="******" #Auth default user for this tenant self.createIntarnalLoginForTenant( tenantName=setup["tenantName"], userID=userID, InternalAuthUsername=InternalAuthUsername, InternalAuthPassword=InternalAuthPassword ) #Use the ticket loginRespData = self.loginAsUser( tenant=setup["tenantName"], authProviderDICT=self.getTenantInternalAuthProvDict(tenant=setup["tenantName"]), username=InternalAuthUsername, password=InternalAuthPassword, ticketToPass=setup["ticketTypeWithAllowUserCreation"]["tickets"][0]["ticketGUID"] ) testTime2 = (setup["setupTime"] + datetime.timedelta(hours=int(1 + setup["ticketTypeWithAllowUserCreation"]["issueDuration"]))) appObj.setTestingDateTime(testTime2) requestResultRAW = self.requestReissue( tenantName=setup["tenantName"], ticketGUID=setup["ticketTypeWithAllowUserCreation"]["tickets"][0]["ticketGUID"], checkAndParseResponse = False ) self.assertEqual(requestResultRAW.status_code, 400) self.assertEqual(json.loads(requestResultRAW.get_data(as_text=True))["message"], "Not possible to renew this ticket")
def test_conversionRateChangesAndIsReloaded(self, mockGetLatestRatesFromFixerIO): #In this test we are going to make some calls, then arrange for the rate to expire and a new one to be loaded # we will then make some more calls and check we get expected results responses = [] responses.append(getLatestRatesFromFixerIO_Response_RateOf4) responses.append(getLatestRatesFromFixerIO_Response_RateOf2) mockGetLatestRatesFromFixerIO.side_effect = responses #Set a time in the appObj to initiate testing mode (Will stop any chance of expiry during the test) curDateTime = appObj.getCurDateTime() appObj.setTestingDateTime(curDateTime) converterInstance = CurrencyConverter(appObj, apikey) #call the code under test a number of times before the cache expiry numberOfCallsToMake = 4 for c in range(0, numberOfCallsToMake): self.assertEqual(converterInstance.convertFromGBPtoUSD(testAmounts['GBP']), testAmounts['USD4'], "Incorrect currency conversion result") #go forward 30 mintues - the rate should have changed because the cache will be invalidated appObj.setTestingDateTime(curDateTime + converterInstance.rateRefreshInterval + relativedelta(minutes=30)) #call the code under test a number of times after the cache expiry (new result) for c in range(0, numberOfCallsToMake): self.assertEqual(converterInstance.convertFromGBPtoUSD(testAmounts['GBP']), testAmounts['USD2'], "Incorrect currency conversion result") #Make sure there were two calls to the mock, one before the cache expiry and one after self.assertEqual(mockGetLatestRatesFromFixerIO.call_args_list,[call(apikey),call(apikey)],"Wrong calls to API") return
def test_getShoppingBasketWithZeroItems(self, mockConvertFromGBPtoUSD): responses = [] responses.append(123) mockConvertFromGBPtoUSD.side_effect = responses curDateTime = appObj.getCurDateTime() appObj.setTestingDateTime(curDateTime) expectedPriceExpiryDateTime = curDateTime + PriceValidatyDuration expectedResult = { 'Basket': { 'Items': [] }, 'Totals': { 'DiscountPercentage': 10, 'TotalPayable': { 'Amount': 0, 'CurrencyCode': 'USD' } }, 'PriceExpiry': expectedPriceExpiryDateTime.isoformat() } actualResult = self.testClient.post('/api/shoppingBasket/', json=inputPayloadWithZeroItems) self.assertEqual(actualResult.status_code, 200) actualResultJSON = json.loads(actualResult.get_data(as_text=True)) self.assertJSONStringsEqual(actualResultJSON, expectedResult) #If we have a 0 total cost the function hsould not try and convert self.assertEqual(mockConvertFromGBPtoUSD.call_args_list, [], "Wrong calls to API")
def test_createValidTicketType(self): testTime = datetime.datetime.now(pytz.timezone("UTC")) appObj.setTestingDateTime(testTime) resultJSON = self.createTicketType(constants.masterTenantName) expectedResult = copy.deepcopy( ticketManagerTestCommon.validTicketTypeDict) expectedResult["id"] = resultJSON["id"] expectedResult[object_store_abstraction.RepositoryObjBaseClass. getMetadataElementKey()] = { "creationDateTime": testTime.isoformat(), "lastUpdateDateTime": testTime.isoformat(), "objectKey": resultJSON["id"], "objectVersion": "1" } python_Testing_Utilities.assertObjectsEqual( unittestTestCaseClass=self, first=resultJSON, second=expectedResult, msg="JSON of created Ticket Type is not the same", ignoredRootKeys=[]) self.assertJSONStringsEqualWithIgnoredKeys( resultJSON, expectedResult, [], msg='JSON of created Ticket Type is not the same') #Not get the ticket type we just created and make sure it matches resultJSON2 = self.getTicketType(constants.masterTenantName, resultJSON["id"]) self.assertJSONStringsEqualWithIgnoredKeys(resultJSON2, expectedResult, [], msg='Get retrevial failed')
def test_GetTicketOfDisabledTicketType(self): testTime1 = datetime.datetime.now(pytz.timezone("UTC")) appObj.setTestingDateTime(testTime1) setup = self.setupTenantsTicketTypesAndTickets() tenantUsedInTest = setup["tenants"][0] tenantName = tenantUsedInTest["tenantJSON"]["Name"] ticketTypeUsedInTest=tenantUsedInTest["ticketTypes"][1] ticketTypeID=tenantUsedInTest["ticketTypes"][1]["createTicketTypeResult"]["id"] ticketTypeName=tenantUsedInTest["ticketTypes"][1]["createTicketTypeResult"]["ticketTypeName"] ticketUsedInTest=tenantUsedInTest["ticketTypes"][1]["ticketCreationProcessResult"]["results"][1] ticketGUID=tenantUsedInTest["ticketTypes"][1]["ticketCreationProcessResult"]["results"][1]["ticketGUID"] ticketForeignKey=tenantUsedInTest["ticketTypes"][1]["ticketCreationProcessResult"]["results"][1]["foreignKey"] ticketTypeUsedInTest["createTicketTypeResult"] = self.setEnabledForTicketType(ticketType=ticketTypeUsedInTest["createTicketTypeResult"], newValue=False) result = self.testClient.get( self.loginAPIPrefix + '/' + tenantName + '/tickets/' + ticketGUID, headers={"Origin": TestHelperSuperClass.httpOrigin} ) self.assertEqual(result.status_code, 200) resultJSON = json.loads(result.get_data(as_text=True)) expectedResult = { "ticketType": copy.deepcopy(ticketTypeUsedInTest["createTicketTypeResult"]), "isUsable": "INVALID", "expiry": (testTime1 + datetime.timedelta(hours=int(ticketTypeUsedInTest["createTicketTypeResult"]["issueDuration"]))).isoformat() } python_Testing_Utilities.assertObjectsEqual( unittestTestCaseClass=self, first=resultJSON, second=expectedResult, msg="Didn't get expected result", ignoredRootKeys=[] )
def test_loginAsInvalidUSerIDWithOfTwoPossibleUsers(self): testDateTime = datetime.now(pytz.timezone("UTC")) appObj.setTestingDateTime(testDateTime) userID1 = 'TestUser1' userID2 = 'TestUser2' result2JSON = self.setupLoginWithMutipleUserIDsAndGetLoginResponse('ABC', userID1, userID2) result = self.testClient.get( self.loginAPIPrefix + '/' + masterTenantName + '/authproviders', headers={"Origin": httpOrigin} ) self.assertEqual(result.status_code, 200) resultJSON = json.loads(result.get_data(as_text=True)) masterAuthProviderGUID = resultJSON[ 'AuthProviders' ][0]['guid'] loginJSON = { "UserID": 'invalid', "authProviderGUID": masterAuthProviderGUID, "credentialJSON": { "username": '******', "password": env['APIAPP_DEFAULTHOMEADMINPASSWORD'] } } result2 = self.testClient.post( self.loginAPIPrefix + '/' + masterTenantName + '/authproviders', data=json.dumps(loginJSON), content_type='application/json', headers={"Origin": httpOrigin} ) self.assertEqual(result2.status_code, 400, 'Login failed - ' + result2.get_data(as_text=True))
def test_CanNotUseTicketTwice(self): setup = self.setup() userName1 = "testSetUserName" password1 = "delkjgn4rflkjwned" userName2 = "testSetUserName22" password2 = "delkjgn4rflkjwned22" expectedRoles = [ constants.DefaultHasAccountRole ] + ticketManagerTestCommon.validTicketTypeDict["roles"] testDateTime2 = datetime.datetime.now(pytz.timezone("UTC")) appObj.setTestingDateTime(testDateTime2) _ = self.registerInternalUser( setup["tenantName"], userName1, password1, self.getTenantInternalAuthProvDict(tenant=setup["tenantName"]), ticketGUID=setup["ticketTypeWithAllowUserCreation"]["tickets"][0] ["ticketGUID"]) registerResultJSON2 = self.registerInternalUser( setup["tenantName"], userName2, password2, self.getTenantInternalAuthProvDict(tenant=setup["tenantName"]), ticketGUID=setup["ticketTypeWithAllowUserCreation"]["tickets"][0] ["ticketGUID"], expectedResults=[400]) self.assertEqual(registerResultJSON2["message"], "Ticket not usable")
def test_QueryBackTicketAfterExpiry(self): testTime1 = datetime.datetime.now(pytz.timezone("UTC")) appObj.setTestingDateTime(testTime1) setup = self.setupTenantsTicketTypesAndTickets() ticketToQueryBack = setup["tenants"][0]["ticketTypes"][1][ "ticketCreationProcessResult"]["results"][4] testTime2 = datetime.datetime.now( pytz.timezone("UTC")) + datetime.timedelta( hours=int(1 + setup["tenants"][0]["ticketTypes"][1] ["createTicketTypeResult"]["issueDuration"])) appObj.setTestingDateTime(testTime2) resultJSON = self.queryForTickets( tenantName=setup["tenants"][0]["tenantJSON"]["Name"], ticketTypeID=setup["tenants"][0]["ticketTypes"][1] ["createTicketTypeResult"]["id"], queryString=ticketToQueryBack["foreignKey"]) self.assertEqual(len(resultJSON), 1, msg="Wrong number of tickets returned") self.assertEqual(resultJSON[0]["id"], ticketToQueryBack["ticketGUID"]) self.assertEqual(resultJSON[0]["foreignKey"], ticketToQueryBack["foreignKey"]) self.assertEqual(resultJSON[0]["usableState"], "US_EXPIRED")
def test_RequestReissueOfExpiredTicket(self): setup = self.setup() testTime2 = (setup["setupTime"] + datetime.timedelta(hours=int(1 + setup["ticketTypeWithAllowUserCreation"]["issueDuration"]))) appObj.setTestingDateTime(testTime2) requestResultJSON = self.requestReissue( tenantName=setup["tenantName"], ticketGUID=setup["ticketTypeWithAllowUserCreation"]["tickets"][0]["ticketGUID"] ) self.assertEqual(requestResultJSON["isUsable"],"REISSUEREQUESTED") #Check ticket state is now REISSUED when we call a get ticketJSON = self.loginAPIGetTicket( tenantName=setup["tenantName"], ticketGUID=setup["ticketTypeWithAllowUserCreation"]["tickets"][0]["ticketGUID"] ) self.assertEqual(requestResultJSON["isUsable"],"REISSUEREQUESTED") qryRes = self.queryForTickets( tenantName=setup["tenantName"], ticketTypeID=setup["ticketTypeWithAllowUserCreation"]["id"], queryString=setup["ticketTypeWithAllowUserCreation"]["tickets"][0]["foreignKey"] ) self.assertEqual(len(qryRes),1) self.assertEqual(qryRes[0]["usableState"],"US_REISSUEREQUESTED") self.assertEqual(qryRes[0]["reissueRequestedDate"],testTime2.isoformat())
def test_updatePerson(self): createPersonTime = datetime.now(pytz.timezone("UTC")) updatePersonTime = createPersonTime + timedelta(seconds=int(12)) appObj.setTestingDateTime(createPersonTime) personDICT = self.createPersonAndReturnDICT() updPersonDict = copy.deepcopy(personDICT) appObj.setTestingDateTime(updatePersonTime) putResult = self.testClient.put( self.adminAPIPrefix + '/' + masterTenantName + '/persons/' + personDICT['guid'], data=json.dumps(updPersonDict), content_type='application/json', headers={jwtHeaderName: self.getNormalJWTToken()}) self.assertEqual(putResult.status_code, 200, msg="Update Person failed - " + putResult.get_data(as_text=True)) putResultJSON = json.loads(putResult.get_data(as_text=True)) expectedResult = copy.deepcopy(updPersonDict) expectedResult['ObjectVersion'] = "2" expectedResult['creationDateTime'] = createPersonTime.isoformat() expectedResult['lastUpdateDateTime'] = updatePersonTime.isoformat() self.assertJSONStringsEqualWithIgnoredKeys( putResultJSON, expectedResult, [], msg="Returned Person data wrong")
def test_newRefreshTokenHasExtendedExpiryTime(self): curTime = datetime.now(pytz.timezone("UTC")) appObj.setTestingDateTime(curTime) OrigLoginResult = self.loginAsDefaultUser() dt = parse(OrigLoginResult['refresh']['TokenExpiry']) firstRefreshExpiry = dt.astimezone(pytz.utc) secondsToWaitBeforeTryingRefresh = int(env['APIAPP_REFRESH_TOKEN_TIMEOUT']) - 2 curTime = curTime + timedelta(seconds=secondsToWaitBeforeTryingRefresh) appObj.setTestingDateTime(curTime) RefreshedLogin = self.testClient.post(self.loginAPIPrefix + '/' + masterTenantName + '/refresh', data=json.dumps({'token': OrigLoginResult['refresh']['token']}), content_type='application/json', headers={"Origin": httpOrigin}) self.assertEqual(RefreshedLogin.status_code, 200, msg="Did not get sucessful login") refreshedLoginInfo = json.loads(RefreshedLogin.get_data(as_text=True)) dt = parse(refreshedLoginInfo['refresh']['TokenExpiry']) secondRefreshExpiry = dt.astimezone(pytz.utc) secondsExtendedBy = (secondRefreshExpiry-firstRefreshExpiry).total_seconds() print(int(env['APIAPP_REFRESH_TOKEN_TIMEOUT'])) print(secondsExtendedBy) self.assertTrue(secondsExtendedBy > 0, msg="New tokens refresh time isn't later than origional") self.assertTrue(secondsExtendedBy < int(env['APIAPP_REFRESH_TOKEN_TIMEOUT']), msg="Refresh time was extended by more than a signle time out")
def test_putShortURL(self): testTime = datetime.datetime.now(pytz.timezone("UTC")) appObj.setTestingDateTime(testTime) loginSession = LoginUtilities.getUserLoginSession("TESTTenantName", 1) resultJSON = self.putUrl( loginSession=loginSession, tenantName="TESTTenantName", url=targetUrl, checkAndParseResponse=True ) self.assertTrue(resultJSON["shortURL"].startswith(TestHelperSuperClass.env["APIAPP_REDIRECTPREFIX"] + "/")) self.assertEqual(len(resultJSON["shortURL"]), len(TestHelperSuperClass.env["APIAPP_REDIRECTPREFIX"]) + 1 + 5) self.assertEqual(len(resultJSON["id"]), 5) self.assertNotEqual(resultJSON[RepositoryObjBaseClass.getMetadataElementKey()]["creationDateTime"], None) dt = parse(resultJSON[RepositoryObjBaseClass.getMetadataElementKey()]["creationDateTime"]) creationTime = dt.astimezone(pytz.utc) expectedExpireTime = creationTime + datetime.timedelta(days=int(TestHelperSuperClass.env["APIAPP_URLEXPIREDAYS"])) self.assertEqual(resultJSON["expectedExpire"],expectedExpireTime.isoformat()) reditectToUrl, result = self.getRedirectUrlUSINGPUBLICAPI( shortURL=resultJSON["shortURL"] ) self.assertEqual(reditectToUrl, targetUrl) resultGetJSON = self.getUrlByCode( loginSession=loginSession, tenantName="TESTTenantName", urlCode=resultJSON["id"], checkAndParseResponse=True ) self.assertEqual(resultGetJSON, resultJSON)
def test_repeatadlyUseRefreshTokensUntilSessionTimesout(self): curTime = datetime.now(pytz.timezone("UTC")) appObj.setTestingDateTime(curTime) OrigLoginResult = self.loginAsDefaultUser() timeRefreshSessionShouldEnd = curTime + timedelta(seconds=int(env['APIAPP_REFRESH_SESSION_TIMEOUT'])) secondsToWaitBeforeTryingRefresh = int(env['APIAPP_REFRESH_TOKEN_TIMEOUT']) - 2 refreshToken = OrigLoginResult['refresh']['token'] times = 0 running = True while running: times = times + 1 self.assertTrue(times < 999, msg='Went through loop too many times') curTime = curTime + timedelta(seconds=secondsToWaitBeforeTryingRefresh) appObj.setTestingDateTime(curTime) RefreshedLogin = self.testClient.post(self.loginAPIPrefix + '/' + masterTenantName + '/refresh', data=json.dumps({'token': refreshToken}), content_type='application/json', headers={"Origin": httpOrigin}) if curTime > timeRefreshSessionShouldEnd: self.assertEqual(RefreshedLogin.status_code, 401, msg="Got a sucessful refresh beyond the time that the refresh session should have timed out") running = False else: self.assertEqual(RefreshedLogin.status_code, 200, msg="Invalid response - " + RefreshedLogin.get_data(as_text=True)) refreshedLoginInfo = json.loads(RefreshedLogin.get_data(as_text=True)) refreshToken = refreshedLoginInfo['refresh']['token']
def test_refreshTokenGivesNewJWTToken(self): curTime = datetime.now(pytz.timezone("UTC")) appObj.setTestingDateTime(curTime) OrigLoginResult = self.loginAsDefaultUser() #Must go forward at least a second to make the new JWTToken be different appObj.setTestingDateTime(curTime + timedelta(seconds=int(1))) refreshToken = OrigLoginResult['refresh']['token'] dt = parse(OrigLoginResult['refresh']['TokenExpiry']) refreshExpiry = dt.astimezone(pytz.utc) RefreshedLogin = self.testClient.post(self.loginAPIPrefix + '/' + masterTenantName + '/refresh', data=json.dumps({'token': refreshToken}), content_type='application/json', headers={"Origin": httpOrigin}) self.assertEqual(RefreshedLogin.status_code, 200, msg="Invalid response - " + RefreshedLogin.get_data(as_text=True)) refreshedLoginInfo = json.loads(RefreshedLogin.get_data(as_text=True)) self.assertFalse('other_date' in refreshedLoginInfo) self.assertJSONStringsEqualWithIgnoredKeys(OrigLoginResult, refreshedLoginInfo, [ 'jwtData', 'refresh' ], msg='Data in origional auth details dosen\'t match new') # Check jwtData is as expected self.assertNotEqual(OrigLoginResult['jwtData']['JWTToken'],refreshedLoginInfo['jwtData']['JWTToken'],msg="New and old JWT tokens match") self.assertNotEqual(OrigLoginResult['jwtData']['TokenExpiry'],refreshedLoginInfo['jwtData']['TokenExpiry'],msg="New and old JWT tokens have the same expiry") # Check refresh is as expected self.assertNotEqual(OrigLoginResult['refresh']['token'],refreshedLoginInfo['refresh']['token'],msg="New and old refresh tokens match") self.assertNotEqual(OrigLoginResult['refresh']['TokenExpiry'],refreshedLoginInfo['refresh']['TokenExpiry'],msg="New and old refresh tokens have the same expiry")
def test_refreshTokenExpires(self): result2JSON = self.loginAsDefaultUser() refreshToken = result2JSON['refresh']['token'] dt = parse(result2JSON['refresh']['TokenExpiry']) refreshExpiry = dt.astimezone(pytz.utc) appObj.setTestingDateTime(refreshExpiry + timedelta(seconds=int(1))) result2 = self.testClient.post(self.loginAPIPrefix + '/' + masterTenantName + '/refresh', data=json.dumps({'token': refreshToken}), content_type='application/json') self.assertEqual(result2.status_code, 401)
def test_getShoppingBasketWithSingleItem(self, mockConvertFromGBPtoUSD): preConversionItemAmount = 2000 postConversionItemAmount = 2368 #since the discount is applied BEFORE the conversion and we are mocking the conversion function #with a fixed result the discount amount will not effect the output responses = [] responses.append(postConversionItemAmount) mockConvertFromGBPtoUSD.side_effect = responses curDateTime = appObj.getCurDateTime() appObj.setTestingDateTime(curDateTime) expectedPriceExpiryDateTime = curDateTime + PriceValidatyDuration inputPayloadWithOneItem = { 'Basket': { 'Items': [{ 'Description': 'Raspberry Pi', 'ItemPrice': { 'Amount': preConversionItemAmount, 'CurrencyCode': 'GBP' } }] } } expectedResult = { 'Basket': { 'Items': [{ 'Description': 'Raspberry Pi', 'ItemPrice': { 'Amount': preConversionItemAmount, 'CurrencyCode': 'GBP' } }], }, 'Totals': { 'DiscountPercentage': 10, 'TotalPayable': { 'Amount': postConversionItemAmount, 'CurrencyCode': 'USD' } }, 'PriceExpiry': expectedPriceExpiryDateTime.isoformat() } actualResult = self.testClient.post('/api/shoppingBasket/', json=inputPayloadWithOneItem) self.assertEqual(actualResult.status_code, 200) actualResultJSON = json.loads(actualResult.get_data(as_text=True)) self.assertJSONStringsEqual(actualResultJSON, expectedResult) #Finally we must also check the discount was correctly applied discountToApply = preConversionItemAmount * (discountPercentage / 100) self.assertEqual(mockConvertFromGBPtoUSD.call_args_list, [call(preConversionItemAmount - discountToApply)], "Wrong calls to API")
def setupTenantWithTwoTicketTypesAndTickets( self, authProv=TestHelperSuperClass.sampleInternalAuthProv001_CREATE): testDateTime = datetime.datetime.now(pytz.timezone("UTC")) appObj.setTestingDateTime(testDateTime) tenantDict = self.createTenantWithAuthProvider( tenantBase=TestHelperSuperClass.tenantWithNoAuthProviders, tenantUserCreation=False, authProvDict=authProv) ticketTypeWithAllowUserCreation = self.createTicketType( tenantDict["Name"], overrideName="TestTicketTypeWithAllowUserCreation") AllowUserCreationTickets = self.callBatchProcess( tenantName=tenantDict["Name"], ticketTypeID=ticketTypeWithAllowUserCreation["id"], foreignKeyList=["testTicket_001"], foreignKeyDupAction="Skip", checkAndParseResponse=True) ticketTypeWithOUTAllowUserCreation = self.createTicketType( tenantDict["Name"], overrideName="TestTicketTypeWithAllowUserCreation") ticketTypeWithOUTAllowUserCreation["allowUserCreation"] = False ticketTypeWithOUTAllowUserCreation = self.updateTicketType( ticketTypeID=ticketTypeWithOUTAllowUserCreation["id"], ticketTypeTenant=tenantDict["Name"], newDict=ticketTypeWithOUTAllowUserCreation, checkAndParseResponse=True) DISAllowUserCreationTickets = self.callBatchProcess( tenantName=tenantDict["Name"], ticketTypeID=ticketTypeWithOUTAllowUserCreation["id"], foreignKeyList=["testTicket_001_NOCREATION"], foreignKeyDupAction="Skip", checkAndParseResponse=True) return { "setupTime": testDateTime, "tenantName": tenantDict["Name"], "ticketTypeWithAllowUserCreation": { "id": ticketTypeWithAllowUserCreation["id"], "issueDuration": ticketTypeWithOUTAllowUserCreation["issueDuration"], "tickets": AllowUserCreationTickets["results"] }, "ticketTypeWithOUTAllowUserCreation": { "id": ticketTypeWithOUTAllowUserCreation["id"], "issueDuration": ticketTypeWithOUTAllowUserCreation["issueDuration"], "tickets": DISAllowUserCreationTickets["results"] } }
def test_putShortURLWithNoLogin_isUnAuth(self): testTime = datetime.datetime.now(pytz.timezone("UTC")) appObj.setTestingDateTime(testTime) result = self.putUrl( loginSession=None, tenantName="TESTTenantName", url=targetUrl, checkAndParseResponse=False ) self.assertEqual(result.status_code, 401, result.get_data(as_text=True))
def test_updateUserData(self): testDateTime = datetime.now(pytz.timezone("UTC")) appObj.setTestingDateTime(testDateTime) result = self.testClient.get( self.adminAPIPrefix + '/' + masterTenantName + '/users/' + appObj.defaultUserGUID, headers={jwtHeaderName: self.getNormalJWTToken()}) self.assertEqual(result.status_code, 200) origUserDICT = json.loads(result.get_data(as_text=True)) #ObjectVersion copied in from result newUserDICT = copy.deepcopy(origUserDICT) newUserDICT['known_as'] = 'ChangedValue' newUserDICT['other_data'] = {'a': "A", 'b': "B"} newUserDICT["creationDateTime"] = testDateTime.isoformat( ) #Main user is created before the testing date is set newUserDICT["lastUpdateDateTime"] = testDateTime.isoformat() print(testDateTime.isoformat()) result = self.testClient.put( self.adminAPIPrefix + '/' + masterTenantName + '/users/' + appObj.defaultUserGUID, data=json.dumps(newUserDICT), content_type='application/json', headers={jwtHeaderName: self.getNormalJWTToken()}) self.assertEqual(result.status_code, 200) newUserDICT['ObjectVersion'] = str( int(newUserDICT['ObjectVersion']) + 1) resultJSON = json.loads(result.get_data(as_text=True)) self.assertJSONStringsEqualWithIgnoredKeys( resultJSON, newUserDICT, ["TenantRoles", "creationDateTime"], msg="Returned user data") self.assertJSONStringsEqualWithIgnoredKeys(resultJSON["TenantRoles"], newUserDICT["TenantRoles"], [], msg="Returned user data") result2 = self.testClient.get( self.adminAPIPrefix + '/' + masterTenantName + '/users/' + appObj.defaultUserGUID, headers={jwtHeaderName: self.getNormalJWTToken()}) self.assertEqual(result2.status_code, 200) result2JSON = json.loads(result2.get_data(as_text=True)) self.assertJSONStringsEqualWithIgnoredKeys( result2JSON, newUserDICT, ["TenantRoles", "creationDateTime"], msg="Returned user data") self.assertJSONStringsEqualWithIgnoredKeys(result2JSON["TenantRoles"], newUserDICT["TenantRoles"], [], msg="Returned user data")
def test_getShoppingBasketWithThreeItems(self, mockConvertFromGBPtoUSD): itemDescriptions = ["Item A", "Item B", "Item C"] preConversionItemAmount = [2000, 111, 222] postConversionItemAmount = 55567 #since the discount is applied BEFORE the conversion and we are mocking the conversion function #with a fixed result the discount amount will not effect the output responses = [] responses.append(postConversionItemAmount) mockConvertFromGBPtoUSD.side_effect = responses curDateTime = appObj.getCurDateTime() appObj.setTestingDateTime(curDateTime) expectedPriceExpiryDateTime = curDateTime + PriceValidatyDuration inputPayload = copy.deepcopy( inputPayloadWithZeroItems ) #dict function ensures we copy the object for a in range(0, 3): inputPayload["Basket"]["Items"].append({ 'Description': itemDescriptions[a], 'ItemPrice': { 'Amount': preConversionItemAmount[a], 'CurrencyCode': 'GBP' } }) expectedResult = { 'Basket': inputPayload["Basket"], 'Totals': { 'DiscountPercentage': 10, 'TotalPayable': { 'Amount': postConversionItemAmount, 'CurrencyCode': 'USD' } }, 'PriceExpiry': expectedPriceExpiryDateTime.isoformat() } actualResult = self.testClient.post('/api/shoppingBasket/', json=inputPayload) self.assertEqual(actualResult.status_code, 200) actualResultJSON = json.loads(actualResult.get_data(as_text=True)) self.assertJSONStringsEqual(actualResultJSON, expectedResult) #Finally we must also check the discount was correctly applied totalGBP = 0 for a in preConversionItemAmount: totalGBP = totalGBP + a discountToApply = int(round(totalGBP * (discountPercentage / 100), 0)) self.assertEqual(mockConvertFromGBPtoUSD.call_args_list, [call(totalGBP - discountToApply)], "Wrong calls to API")
def test_createSingleValidTicket(self): testTime1 = datetime.datetime.now(pytz.timezone("UTC")) appObj.setTestingDateTime(testTime1) testTicketTypeName = "TestType001" setupData = self.setupNewTenantAndTicketType(tenantData=TestHelperSuperClass.tenantWithNoAuthProviders, ticketTypeName=testTicketTypeName) testTime2 = datetime.datetime.now(pytz.timezone("UTC")) appObj.setTestingDateTime(testTime2) resultJSON = self.callBatchProcess( tenantName=setupData["ticketTypeNewTanent"]["tenantName"], ticketTypeID=setupData["ticketTypeNewTanent"]["id"], foreignKeyList= [ "*****@*****.**" ], foreignKeyDupAction= "ReissueAllActive", checkAndParseResponse = True ) self.checkExpectedResults(resultJSON=resultJSON, keysExpected=[ "*****@*****.**" ], issued=1, reissued=0, skipped=0, msg="None") ticketsJSON = self.queryForTickets( tenantName=setupData["ticketTypeNewTanent"]["tenantName"], ticketTypeID=setupData["ticketTypeNewTanent"]["id"], queryString="*****@*****.**" ) self.assertEqual(len(ticketsJSON), 1, msg="Should have found a single ticket") expectedTicketJSON = { "id": resultJSON["results"][0]["ticketGUID"], "typeGUID": setupData["ticketTypeNewTanent"]["id"], "expiry": (testTime2 + datetime.timedelta(hours=int(setupData["ticketTypeNewTanent"]["issueDuration"]))).isoformat(), "foreignKey": "*****@*****.**", "usedDate": None, "useWithUserID": None, "reissueRequestedDate": None, "reissuedTicketID": None, "disabled": False, object_store_abstraction.RepositoryObjBaseClass.getMetadataElementKey(): { "creationDateTime": testTime2.isoformat(), "lastUpdateDateTime": testTime2.isoformat(), "objectKey": resultJSON["results"][0]["ticketGUID"], "objectVersion": "1" }, "usableState": "US_USABLEIFTICKETTYPEISENABLED" } python_Testing_Utilities.assertObjectsEqual( unittestTestCaseClass=self, first=ticketsJSON[0], second=expectedTicketJSON, msg="JSON of created Ticket is not what was expected", ignoredRootKeys=[] )
def test_InternalAuthRegisterWithInvalidGUIDTicketFails(self): setup = self.setup() userName = "******" password = "******" testDateTime2 = datetime.datetime.now(pytz.timezone("UTC")) appObj.setTestingDateTime(testDateTime2) registerResultJSON = self.registerInternalUser( setup["tenantName"], userName, password, self.getTenantInternalAuthProvDict(tenant=setup["tenantName"]), ticketGUID="INVALIDTICKETID", expectedResults=[400]) self.assertEqual(registerResultJSON["message"], "Invalid Ticket")
def test_registerInternalAuthWithTicket(self): #Auth provider has no allow user creatoin. Ticket has setup = self.setup() userName = "******" password = "******" expectedRoles = [ constants.DefaultHasAccountRole ] + ticketManagerTestCommon.validTicketTypeDict["roles"] testDateTime2 = datetime.datetime.now(pytz.timezone("UTC")) appObj.setTestingDateTime(testDateTime2) registerResultJSON = self.registerInternalUser( setup["tenantName"], userName, password, self.getTenantInternalAuthProvDict(tenant=setup["tenantName"]), ticketGUID=setup["ticketTypeWithAllowUserCreation"]["tickets"][0] ["ticketGUID"]) thisTenantRoles = None for dict in registerResultJSON["TenantRoles"]: if dict["TenantName"] == setup["tenantName"]: thisTenantRoles = dict self.assertEqual(thisTenantRoles["ThisTenantRoles"], expectedRoles) loginRespData2 = self.loginAsUser( tenant=setup["tenantName"], authProviderDICT=self.getTenantInternalAuthProvDict( tenant=setup["tenantName"]), username=userName, password=password, ticketToPass=None) self.assertEqual( loginRespData2["ThisTenantRoles"], expectedRoles, ) self.assertTicketUsed( tenantName=setup["tenantName"], foreignKey=setup["ticketTypeWithAllowUserCreation"]["tickets"][0] ["foreignKey"], ticketGUID=setup["ticketTypeWithAllowUserCreation"]["tickets"][0] ["ticketGUID"], ticketTypeID=setup["ticketTypeWithAllowUserCreation"]["id"], userID=registerResultJSON["UserID"], timeUsed=testDateTime2)
def test_getMutipleUserIDsResponseDefaultUser(self): testDateTime = datetime.now(pytz.timezone("UTC")) appObj.setTestingDateTime(testDateTime) userID1 = 'TestUser1' userID2 = 'TestUser2' result2JSON = self.setupLoginWithMutipleUserIDsAndGetLoginResponse('ABC', userID1, userID2) user1ExcpectedResult = { "UserID": userID1, "TenantRoles": [{ "TenantName": masterTenantName, "ThisTenantRoles": [DefaultHasAccountRole] }], "known_as": userID1, "other_data": { "createdBy": "test/createTwoUsersForOnePerson" }, "creationDateTime": testDateTime.isoformat(), "lastUpdateDateTime": testDateTime.isoformat() } user2ExcpectedResult = { "UserID": userID2, "TenantRoles": [{ "TenantName": masterTenantName, "ThisTenantRoles": [DefaultHasAccountRole] }], "known_as": userID2, "other_data": { "createdBy": "test/createTwoUsersForOnePerson" }, "creationDateTime": testDateTime.isoformat(), "lastUpdateDateTime": testDateTime.isoformat() } id1Found = False id2Found = False self.assertEqual(len(result2JSON['possibleUsers']), 2, msg="Wrong number of possible Users") for resultUser in result2JSON['possibleUsers']: if resultUser['UserID'] == userID1: id1Found = True self.assertJSONStringsEqualWithIgnoredKeys(resultUser, user1ExcpectedResult, [ 'guid', 'ObjectVersion', 'associatedPersonGUIDs' ], msg="Identity 1 result mismatch") if resultUser['UserID'] == userID2: id2Found = True self.assertJSONStringsEqualWithIgnoredKeys(resultUser, user2ExcpectedResult, [ 'guid', 'ObjectVersion', 'associatedPersonGUIDs' ], msg="Identity 2 result mismatch") self.assertTrue(id1Found, msg="Identity 1 not in response") self.assertTrue(id2Found, msg="Identity 2 not in response")
def test_expiredTokenReturns401(self): #create token respects appObj time # verify claim of token does not curTime = datetime.now(pytz.timezone("UTC")) timeToGenerateToken = curTime - timedelta( seconds=int(env['APIAPP_JWT_TOKEN_TIMEOUT'])) - timedelta( seconds=int(2)) appObj.setTestingDateTime(timeToGenerateToken) expiredJwtToken = self.getNormalJWTToken() appObj.setTestingDateTime(curTime) result = self.testClient.get(self.adminAPIPrefix + '/' + masterTenantName + '/tenants', headers={jwtHeaderName: expiredJwtToken}) self.assertEqual(result.status_code, 401)
def test_updateURLTenantMismachFails(self): testTime1 = datetime.datetime.now(pytz.timezone("UTC")) appObj.setTestingDateTime(testTime1) setupData = self.setupTestTicketsInTwoTenants() testTime2 = datetime.datetime.now(pytz.timezone("UTC")) appObj.setTestingDateTime(testTime2) changed = copy.deepcopy(setupData["okTicketResultJSON"][1]) changed["ticketTypeName"] = "okTicketResultJSONUPDATED" changed["tenantName"] = setupData["tenantJSON"]["Name"] resultRAW = self.updateTicketType( ticketTypeID=setupData["okTicketResultJSON"][1]["id"], ticketTypeTenant=constants.masterTenantName, newDict=changed, checkAndParseResponse=False) self.assertEqual(resultRAW.status_code, 400, msg="Err: should have failed " + resultRAW.get_data(as_text=True))
def test_authWithUserCreationWithTicket(self): setup = self.setupTenantWithTwoTicketTypesAndTickets(googleAuthProv001_CREATE) #Test authentication via google. ## Must use mocks ticketUseTime = datetime.datetime.now(pytz.timezone("UTC")) appObj.setTestingDateTime(ticketUseTime) expectedRoles = [constants.DefaultHasAccountRole] + ticketManagerTestCommon.validTicketTypeDict["roles"] googleAuthProvDict = self.getTenantSpercificAuthProvDict(setup['tenantName'], 'google') #print(googleAuthProvDict) result2JSON = self.loginWithGoogle( googleLoginAccountNum=0, tenantName=setup['tenantName'], authProviderDICT=googleAuthProvDict, ticketToPass=setup["ticketTypeWithAllowUserCreation"]["tickets"][0]["ticketGUID"], expectedResults=[200] ) self.assertEqual(result2JSON["ThisTenantRoles"], expectedRoles) self.assertTicketUsed( tenantName=setup['tenantName'], foreignKey=setup["ticketTypeWithAllowUserCreation"]["tickets"][0]["foreignKey"], ticketGUID=setup["ticketTypeWithAllowUserCreation"]["tickets"][0]["ticketGUID"], ticketTypeID=setup["ticketTypeWithAllowUserCreation"]["id"], userID=result2JSON["userGuid"], timeUsed=ticketUseTime ) #Turn off auto user creation tenantDict2 = self.getTenantDICT(setup['tenantName']) tenantDict2['AllowUserCreation'] = False tenantDict3 = self.updateTenant(tenantDict2, [200]) #Try and login - should not need to create so will suceed result3JSON = self.loginWithGoogle( googleLoginAccountNum=0, tenantName=setup['tenantName'], authProviderDICT=googleAuthProvDict, ticketToPass=None, expectedResults=[200] ) self.assertEqual(result3JSON["ThisTenantRoles"], expectedRoles)
def test_updateChangingTenantFails(self): testTime1 = datetime.datetime.now(pytz.timezone("UTC")) appObj.setTestingDateTime(testTime1) setupData = self.setupTestTicketsInTwoTenants() testTime2 = datetime.datetime.now(pytz.timezone("UTC")) appObj.setTestingDateTime(testTime2) changed = copy.deepcopy(setupData["okTicketResultJSON"][1]) changed["ticketTypeName"] = "okTicketResultJSONUPDATED" changed["tenantName"] = setupData["tenantJSON"]["Name"] resultRAW = self.updateTicketType( ticketTypeID=setupData["okTicketResultJSON"][1]["id"], ticketTypeTenant=setupData["tenantJSON"]["Name"], newDict=changed, checkAndParseResponse=False) #Tried to change the tenant name on a ticket - result in it not being found self.assertEqual(resultRAW.status_code, 404, msg="Err: should have failed " + resultRAW.get_data(as_text=True))
def tesT_updateMissingObjectversionElementFails(self): testTime1 = datetime.datetime.now(pytz.timezone("UTC")) appObj.setTestingDateTime(testTime1) setupData = self.setupTestTicketsInTwoTenants() testTime2 = datetime.datetime.now(pytz.timezone("UTC")) appObj.setTestingDateTime(testTime2) changed = copy.deepcopy(setupData["okTicketResultJSON"][1]) changed["ticketTypeName"] = "okTicketResultJSONUPDATED" del changed[object_store_abstraction.RepositoryObjBaseClass. getMetadataElementKey()] resultRAW = self.updateTicketType( ticketTypeID=setupData["okTicketResultJSON"][1]["id"], ticketTypeTenant=constants.masterTenantName, newDict=changed, checkAndParseResponse=False) self.assertEqual(resultRAW.status_code, 400, msg="Err: should have failed " + resultRAW.get_data(as_text=True))
def test_conversionRateIsCachedBetweenCalls(self, mockGetLatestRatesFromFixerIO): numberOfCallsToMake = 4 #setup mock object - setting up a number of responses even though we should only use the first one responses = [] for c in range(0, numberOfCallsToMake): responses.append(getLatestRatesFromFixerIO_Response_RateOf4) mockGetLatestRatesFromFixerIO.side_effect = responses #Set a time in the appObj to initiate testing mode (Will stop any chance of expiry during the test) curDateTime = appObj.getCurDateTime() appObj.setTestingDateTime(curDateTime) #call code under test converterInstance = CurrencyConverter(appObj, apikey) for c in range(0, numberOfCallsToMake): self.assertEqual(converterInstance.convertFromGBPtoUSD(testAmounts['GBP']), testAmounts['USD4'], "Incorrect currency conversion result") #Make sure there was only one call with the correct APIKEY self.assertEqual(mockGetLatestRatesFromFixerIO.call_args_list,[call(apikey)],"Wrong calls to API") return