Esempio n. 1
0
 def _getJobExecutionObj(self, jobObj):
     return JobExecutionClass(jobObj=jobObj,
                              executionName='TestExecutionName',
                              manual=False,
                              curDatetime=appObj.getCurDateTime(),
                              triggerJobObj=None,
                              triggerExecutionObj=None)
Esempio n. 2
0
def generateJWTToken(appObj, userDict, secret, key, personGUID,
                     currentlyUsedAuthProviderGuid, currentlyUsedAuthKey):
    expiryTime = appObj.getCurDateTime() + timedelta(
        seconds=int(APIAPP_JWT_TOKEN_TIMEOUT))
    if secret is None:
        raise Exception(
            "Trying to generate a JWT Token without a secret being set")
    if key is None:
        raise Exception(
            "Trying to generate a JWT Token without a key being set")

    JWTDict = copy.deepcopy(userDict)
    JWTDict['authedPersonGuid'] = personGUID
    JWTDict['currentlyUsedAuthProviderGuid'] = currentlyUsedAuthProviderGuid
    JWTDict['currentlyUsedAuthKey'] = currentlyUsedAuthKey
    JWTDict['iss'] = key
    JWTDict['exp'] = expiryTime
    ## JWTDict = appObj.gateway.enrichJWTClaims(JWTDict)
    encodedJWT = jwt.encode(JWTDict, b64decode(secret), algorithm='HS256')

    # print("generateJWTToken", expiryTime)

    return {
        'JWTToken': encodedJWT.decode('utf-8'),
        'TokenExpiry': expiryTime.isoformat()
    }
Esempio n. 3
0
  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_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 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")
Esempio n. 7
0
  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