コード例 #1
0
ファイル: emfObject.py プロジェクト: anupsl/pyApps
 def PointsRedemptionReversalEventData(paramDict={}):
     constant.config['uniqueId'] = randValues.randomString(8)
     tmpDict = {
         'orgID':
         constant.config['orgId'],
         'storeUnitID':
         constant.config['storeIds'][0],
         'eventTimeInMillis':
         Utils.getTime(seconds=randValues.randomInteger(2),
                       milliSeconds=True),
         'userDetails':
         EMFObject.constructUserDetailsObject(0),
         'uniqueRedemptionId':
         None,
         'uniqueId':
         constant.config['uniqueId'],
         'serverReqId':
         constant.config['serverReqId'],
         'source':
         'INSTORE',
         'accountId':
         str(constant.config['programId']),
         'notes':
         'Auto points reversal'
     }
     tmpDict.update(paramDict)
     return emf.PointsRedemptionReversalEventData(**tmpDict)
コード例 #2
0
ファイル: emfObject.py プロジェクト: anupsl/pyApps
 def PointsRedemptionEventData(paramDict={}):
     constant.config['uniqueId'] = randValues.randomString(8)
     tmpDict = {
         'orgID':
         constant.config['orgId'],
         'customerID':
         0,
         'numPointsToBeRedeemed':
         constant.config['defaultRedeemPts'],
         'redeemedAtStoreUnitId':
         constant.config['storeIds'][0],
         'redeemedOnBillNumber':
         '-1',
         'redeemedOnBillId':
         constant.config['billNumber'],
         'eventTimeInMillis':
         Utils.getTime(seconds=(randValues.randomInteger(2)),
                       milliSeconds=True),
         'userDetails':
         EMFObject.constructUserDetailsObject(0),
         'uniqueId':
         constant.config['uniqueId'],
         'serverReqId':
         constant.config['serverReqId'],
         'source':
         'INSTORE',
         'accountId':
         str(constant.config['programId']),
     }
     constant.config['defaultRedeemPts'] = paramDict[
         'numPointsToBeRedeemed'] if paramDict.has_key(
             'numPointsToBeRedeemed') else 100
     tmpDict.update(paramDict)
     return emf.PointsRedemptionEventData(**tmpDict)
コード例 #3
0
ファイル: test_getCouponConfig.py プロジェクト: anupsl/pyApps
 def test_LUCI_GCC_008(self, description):
     randomValueCamp = randValues.randomInteger(digits=6)
     couponConfig, couponSeriesId = LuciHelper.saveCouponConfigAndAssertions(self, {'client_handling_type': 'DISC_CODE_PIN', 'created': Utils.getTime(seconds=0, milliSeconds=True), 'valid_till_date': Utils.getTime(days=1, milliSeconds=True), 'campaign_id' : randomValueCamp})
     configRequest = LuciObject.getCouponConfigRequest({'ownerId' : randomValueCamp, 'sort' : 1,  'includeUnclaimed' : True,  'limit' : 5 })
     couponConfigList = self.connObj.getCouponConfiguration(configRequest)
     for couponRes in couponConfigList:
         couponRes = couponRes.__dict__
         if couponRes['id'] == couponSeriesId:
             Assertion.constructAssertion(couponRes['owned_by'] == self.constructObj.ownedBy['OUTBOUND'], 'OwnedBy value is Matched Actual: {} and Expected: {}'.format(couponRes['owned_by'] , self.constructObj.ownedBy['OUTBOUND']))
             Assertion.constructAssertion(couponRes['owner_id'] == randomValueCamp, 'OwnerId is Matched Actual: {} and Expected: {}'.format(couponRes['owner_id'], randomValueCamp))
             break
     Assertion.constructAssertion(len(couponConfigList) == 5, 'GetCouponConfig Limit {} and couponconfig got {}'.format(5, len(couponConfigList)))
     Assertion.constructAssertion(couponConfigList != None, 'Retrieved couponConfig from GetCouponConfig by OwnedBy')
コード例 #4
0
    def test_LUCI_MU_001(self, description):
        toUserId = randValues.randomInteger(digits=6)
        actualUserId = self.userId
        try:
            couponConfigObj, couponSeriesId = LuciHelper.saveCouponConfigAndAssertions(
                self)
            LuciHelper.queuePumpWait(self, couponSeriesId)
            couponCode = LuciHelper.issueCouponAndAssertions(
                self, couponSeriesId)[0]

            mergeUserResponse = self.connObj.mergeUsers(
                fromUserId=self.userId,
                toUserId=toUserId,
                mergedbyTillId=self.tillId).__dict__
            Assertion.constructAssertion(
                mergeUserResponse['fromUserId'] == self.userId,
                'Merge From userId is Matched Actual: {} & Expected: {}'.
                format(mergeUserResponse['fromUserId'], self.userId))
            Assertion.constructAssertion(
                mergeUserResponse['toUserId'] == toUserId,
                'Merge to userId is Matched Actual: {} & Expected: {}'.format(
                    mergeUserResponse['toUserId'], toUserId))
            mergeStatus = mergeUserResponse['status'].__dict__
            Assertion.constructAssertion(
                mergeStatus['message'] == 'customer merge was successfull',
                'Merge status Msg Actual: {} & Expected: {}'.format(
                    mergeStatus['message'], 'customer merge was successfull'))
            Assertion.constructAssertion(
                mergeStatus['statusCode'] == constant.MERGE_SUCCESSFUL,
                'Merge status code Actual: {} & Expected: {}'.format(
                    mergeStatus['statusCode'], constant.MERGE_SUCCESSFUL))
            mergeStatus = self.connObj.getMergeStatus(
                fromUserId=self.userId, toUserId=toUserId).__dict__
            Assertion.constructAssertion(
                mergeStatus['message'] == 'customer is already merged',
                'Merge status Msg Actual: {} & Expected: {}'.format(
                    mergeStatus['message'], 'customer is already merged'))
            Assertion.constructAssertion(
                mergeStatus['statusCode'] == constant.MERGED_ALREADY_DONE,
                'Merge status code Actual: {} & Expected: {}'.format(
                    mergeStatus['statusCode'], constant.MERGED_ALREADY_DONE))
            LuciHelper.redeemCouponAndAssertions(
                self, [couponSeriesId], [couponCode],
                error=[
                    625, 'coupon not issued to this user redemption failed'
                ])
            self.userId = toUserId
            LuciHelper.redeemCouponAndAssertions(self, [couponSeriesId],
                                                 [couponCode])
        finally:
            self.userId = actualUserId
コード例 #5
0
    def est_LUCI_BulkIssual(self, description):
        couponConfigObj, couponSeriesId = LuciHelper.saveCouponConfigAndAssertions(
            self, couponConfigReq={"any_user": True})
        couponCodeList = []
        Logger.log('Coupon series Id: ', couponSeriesId)

        bulkUserIds = []
        for _ in range(1000000):
            bulkUserIds.append(randValues.randomInteger(9))
        bulkUserIds = list(set(bulkUserIds))
        limit = 500000
        i = 0
        Logger.log('Actial : ', len(bulkUserIds))
        for _ in range(len(bulkUserIds)):
            if limit > (len(bulkUserIds)):
                limit = len(bulkUserIds)
            issueMultipleCouponsRequest = {
                'couponSeriesId': couponSeriesId,
                'storeUnitId': self.tillId,
                'userIds': bulkUserIds[i:(limit)]
            }
            issueMultipleCouponsRequestObj = LuciObject.issueMultipleCouponsRequest(
                issueMultipleCouponsRequest)
            couponDetailsList = self.connObj.issueMultipleCoupons(
                issueMultipleCouponsRequestObj)

            for couponDetails in couponDetailsList:
                couponDetails = couponDetails.__dict__
                couponCodeList.append(couponDetails['couponCode'])
            if limit == len(bulkUserIds):
                break

            i = limit
            limit = limit + 1000

        for couponCode, userId in zip(couponCodeList, bulkUserIds):
            couponDetailsList = self.connObj.redeemCoupons(
                LuciHelper.redeemCouponRequest(
                    [couponCode],
                    userId,
                    billId=Utils.getTime(milliSeconds=True)))
コード例 #6
0
    def test_downloadCoupon_002(self):
        self.couponSeriesId = LuciHelper.saveCouponConfigAndAssertions(self)[1]
        tmpListOfUsers = []
        for _ in range(2500):
            tmpListOfUsers.append(randValues.randomInteger(7))
        listOfUsers = list(set(tmpListOfUsers))
        limit = 1000
        for i in range(0, len(listOfUsers)):
            if limit > len(listOfUsers):
                limit = len(listOfUsers)
            Logger.log(listOfUsers[i:limit])
            LuciHelper.issueMultipleCoupon(
                self,
                self.couponSeriesId,
                listOfUsers[i:limit],
                expectResponseException=[True, 'coupons exhausted'])
            i = limit
            limit = limit + 1000

        requestObj = DracarysObject.DownloadCouponsRequest(
            {'couponSeriesId': self.couponSeriesId})
        jobRes = self.DracraysConnObj.downloadCouponsReport(
            requestObj).__dict__
        requestsStatusObj = DracarysObject.GetDownloadStatus({
            'couponSeriesId':
            self.couponSeriesId,
            'jobId':
            jobRes['jobId']
        })
        statusRes = self.DracraysConnObj.getDownloadStatus(
            requestsStatusObj).__dict__
        for _ in range(10):
            if statusRes['downloadReportJobStatus'] != 2 and statusRes[
                    'downloadReportJobStatus'] != 1:
                time.sleep(1)
                statusRes = self.DracraysConnObj.getDownloadStatus(
                    requestsStatusObj).__dict__
            else:
                break
コード例 #7
0
 def getBulkUsers(noOfUsers=100):
     bulkUserIds = []
     for _ in range(noOfUsers):
         bulkUserIds.append(randValues.randomInteger(9))
     return list(set(bulkUserIds))
コード例 #8
0
 def generateCouponCode(isAlphaNumeric=True, size=9):
     if isAlphaNumeric:
         return randValues.randomString(size).upper()
     else:
         return str(randValues.randomInteger(size))
コード例 #9
0
ファイル: dracarysHelper.py プロジェクト: anupsl/pyApps
    def generateCouponUploadFile(self,
                                 identifier='userId',
                                 isUserTagged=False,
                                 isOnlyUser=False,
                                 noOfRecords=1,
                                 is_Invalid=[False, False],
                                 couponCodeCAPS=True):
        couponUploadFile = constant.luciS3FilePath
        filehandle = FileHelper(couponUploadFile)
        First = True
        data = []
        filehandle.eraseContentFromFile()
        if isUserTagged and not isOnlyUser:
            filehandle.appendToFile('Coupon Code, issuedTo')
            for i in range(noOfRecords):
                if not couponCodeCAPS:
                    couponCode = DracarysHelper.generateCouponCode().lower()
                else:
                    couponCode = DracarysHelper.generateCouponCode()
                    if First:
                        duplicateCoupon = couponCode + ', ' + str(
                            constant.config['usersInfo'][i][identifier])
                        First = False
                filehandle.appendToFile(
                    couponCode + ', ' +
                    str(constant.config['usersInfo'][i][identifier]))
                data.append(couponCode)
            if is_Invalid[0]:
                filehandle.appendToFile(duplicateCoupon)
            elif is_Invalid[1]:
                couponCode = DracarysHelper.generateCouponCode()
                if identifier == 'mobile':
                    filehandle.appendToFile(
                        couponCode + ', ' +
                        str(randValues.getRandomMobileNumber()))
                elif identifier == 'email':
                    filehandle.appendToFile(couponCode + ', ' +
                                            str(randValues.randomEmailId()))
                elif identifier in ['userId', 'externalId']:
                    filehandle.appendToFile(
                        couponCode + ', ' +
                        str(randValues.randomInteger(digits=8)))
        elif isOnlyUser:
            filehandle.appendToFile('issuedTo')
            for i in range(noOfRecords):
                filehandle.appendToFile(
                    str(constant.config['usersInfo'][i][identifier]))
            if is_Invalid[0]:
                filehandle.appendToFile(
                    str(constant.config['usersInfo'][0][identifier]))
            elif is_Invalid[1]:
                if identifier == 'mobile':
                    filehandle.appendToFile(
                        str(randValues.getRandomMobileNumber()))
                elif identifier == 'email':
                    filehandle.appendToFile(str(randValues.randomEmailId()))
                elif identifier in ['userId', 'externalId']:
                    filehandle.appendToFile(
                        str(randValues.randomInteger(digits=8)))
        else:
            filehandle.appendToFile('Coupon Code')
            for _ in range(noOfRecords):
                if not couponCodeCAPS:
                    couponCode = DracarysHelper.generateCouponCode().lower()
                else:
                    couponCode = DracarysHelper.generateCouponCode()
                if First:
                    duplicateCoupon = couponCode
                    filehandle.appendToFile(duplicateCoupon)
                    data.append(duplicateCoupon)
                    First = False
                else:
                    filehandle.appendToFile(couponCode)
                    data.append(couponCode)
            if is_Invalid[0]:
                filehandle.appendToFile(duplicateCoupon)
            elif is_Invalid[1]:
                filehandle.appendToFile(
                    DracarysHelper.generateCouponCode(size=21))

        return data
コード例 #10
0
    def initializeConstants(args):
        module = constant.config['module'] = args.module.lower()
        runId = args.runId
        collectOnly = constant.config['collectOnly'] = args.collectOnly
        tcFilter = args.tcFilter
        cluster = constant.config['cluster'] = args.cluster.lower()
        if collectOnly:
            if 'cluster' in args.cluster.lower():
                cluster = constant.config['cluster'] = 'nightly'
            constant.config['campaignId'] = 1

        if module.lower() == 'nsadmin':
            if tcFilter != '':
                tcFilter += ' and'
            if cluster.lower() in ['nightly', 'staging']:
                tcFilter += ' not Prod'
            else:
                tcFilter += ' Prod and ' + str(cluster.title())
            if args.prodEmail1 != '':
                constant.prodNumbers['prodEmail1'] = args.prodEmail1
        constant.config['tcFilter'] = tcFilter

        if not module in runId.lower():
            runId = module.title() + '_' + runId
        msg = 'Initializing Suite for Cluster: ' + cluster + ' Module: ' + module
        if tcFilter != '':
            msg += ' Filter: ' + tcFilter
        print msg

        constant.config['runId'] = runId
        constant.config['logDir'] = constant.logDirectory + runId
        constant.config['currentTimestamp'] = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
        constant.config.update(constant.portsUsed[cluster])
        constant.config.update(constant.clusterUrl[cluster])
        constant.config.update(constant.auth[cluster])
        constant.config.update(constant.intouchEndpoints)
        constant.config.update(constant.endpoints)
        BaseState.updateOrgDetails(module)
        if module in ['iris','irisv2', 'veneno', 'darknight', 'campaign_shard', 'campaignsui', 'social']:
            constant.config.update(constant.wechatMobilepush[cluster])
            if constant.config['cluster'] in ['nightly', 'staging', 'china']: constant.config['wecrm_details'] = \
                constant.config['wechat']['wecrm_details']
            constant.config.update(constant.aryaEndpoints)
            constant.config.update({'campaignDefaultObjectCopy': copy.deepcopy(constant.campaignDefaultValues)})
            try:
                authResponse = auth.authLogin()
                if authResponse['cookies'].get_dict() != {}:
                    constant.config['aryaCookiesDict'] = authResponse['cookies'].get_dict()
                    constant.config['token'] = authResponse['json']['token']
                else:
                    raise Exception('')
            except:
                print '------------------------------Arya Cookies Not Set------------------------------'

        if module in ['emf', 'peb']:
            orgId = constant.config['orgId']
            constant.config.update(constant.emfConstants[cluster][orgId])
        if module in ['luci', 'veneno', 'social']:
            constant.config['requestId'] = 'requestId_' + str(randValues.randomInteger(5))
            constant.config['dateTime'] = DracarysHelper.getValueOfDay()
        if not collectOnly:
            Utils.createFolder(constant.config['logDir'])
            Logger.configureLogging(constant.config['logDir'])
        if constant.config['os'] != 'windows':
            dbHelper.getIntouchShardNameForOrg(module)
            dbHelper.buildDBToTunnelPortMapping()
        if module == 'veneno' and not collectOnly:
            if constant.config['cluster'] == 'nightly': VenenoHelper.updateStartegyForRateLimit()
        if module == 'irisv2':
            constant.irisGenericValues = {'goalId': '1', 'objectiveId': '1', 'existingUserId': '1',
                                          'existingUserExternalId': '1'}
        if module in ['iris', 'veneno', 'campaign_shard', 'campaignsui', 'darknight', 'social']:
            constant.config['skipped_errors'] = dbCallsList.getSkippedErrorTypes()
            constant.config.update(constant.irisDetails[cluster])
            if collectOnly:
                constant.irisGenericValues = {'goalId': '1', 'objectiveId': '1', 'existingUserId': '1',
                                              'existingUserExternalId': '1'}
            else:
                try:
                    goalId = str(dbCallsCampaign.getValidGoalId())
                    objectiveId = str(dbCallsCampaign.getValidObjectiveId())
                    existingUserDetail = dbCallsMessage.getUsersInformation(1)[0]
                    constant.irisGenericValues = {'goalId': goalId, 'objectiveId': objectiveId,
                                                  'existingUserId': existingUserDetail[0],
                                                  'existingUserExternalId': existingUserDetail[5]}
                except Exception, exp:
                    constant.irisGenericValues = {'goalId': '1', 'objectiveId': '1', 'existingUserId': '1',
                                                  'existingUserExternalId': '1'}
                    Logger.log(
                        'Exception :{} occured while setting irisGeneric Values , so setting the values by Default as :{}'.format(
                            exp, constant.irisGenericValues))
コード例 #11
0
ファイル: test_createCoupons.py プロジェクト: anupsl/pyApps
class Test_CreateCoupons():
    def setup_method(self, method):
        Logger.logMethodName(method.__name__)

    @pytest.mark.parametrize('description,payloadData', [
        ('Unlimited Coupon', {
            'couponLimit': {
                'limit': 0,
                'type': 'UNLIMITED'
            },
            'discountOn': 'BILL',
            'discountType': 'ABS',
            'discountValue': 10
        }),
        ('Limited Coupon', {
            'couponLimit': {
                'limit': 10,
                'type': 'LIMITED'
            },
            'discountOn': 'BILL',
            'discountType': 'ABS',
            'discountValue': 10
        }),
    ])
    def test_createCoupon_Sanity(self, description, payloadData):
        response, payload, campaignId = coupons.createCoupons(
            payloadData=payloadData)
        coupons.assertCreateCoupon(response, 200)
        coupons.assertCreateCouponDbCalls(response, payload, campaignId)

    @pytest.mark.parametrize('description,payloadData', [
        ('TillIds as None in List', {
            'couponLimit': {
                'limit': 0,
                'type': 'UNLIMITED'
            },
            'discountOn': 'BILL',
            'discountType': 'ABS',
            'discountValue': 10,
            'redeemableTillIds': None,
            'issuableTillIds': None
        }),
    ])
    def test_createCoupon_TillIds(self, description, payloadData):
        response, payload, campaignId = coupons.createCoupons(
            payloadData=payloadData)
        coupons.assertCreateCoupon(response, 200)
        coupons.assertCreateCouponDbCalls(response, payload, campaignId)

    @pytest.mark.parametrize('description,payloadData',
                             [('Limited Discount On ITEM with ABS', {
                                 'couponLimit': {
                                     'limit': 10,
                                     'type': 'LIMITED'
                                 },
                                 'discountOn': 'ITEM',
                                 'discountType': 'ABS',
                                 'discountValue': 10
                             }),
                              ('Limited Discount On ITEM with PERC', {
                                  'couponLimit': {
                                      'limit': 10,
                                      'type': 'LIMITED'
                                  },
                                  'discountOn': 'ITEM',
                                  'discountType': 'PERC',
                                  'discountValue': 10
                              }),
                              ('Limited Discount On BILL with ABS', {
                                  'couponLimit': {
                                      'limit': 10,
                                      'type': 'LIMITED'
                                  },
                                  'discountOn': 'BILL',
                                  'discountType': 'ABS',
                                  'discountValue': 10
                              }),
                              ('Limited Discount On BILL with PERC', {
                                  'couponLimit': {
                                      'limit': 10,
                                      'type': 'LIMITED'
                                  },
                                  'discountOn': 'BILL',
                                  'discountType': 'PERC',
                                  'discountValue': 10
                              }),
                              ('Unlimited Discount On ITEM with ABS', {
                                  'couponLimit': {
                                      'limit': 0,
                                      'type': 'UNLIMITED'
                                  },
                                  'discountOn': 'ITEM',
                                  'discountType': 'ABS',
                                  'discountValue': 10
                              }),
                              ('Unlimited Discount On ITEM with PERC', {
                                  'couponLimit': {
                                      'limit': 0,
                                      'type': 'UNLIMITED'
                                  },
                                  'discountOn': 'ITEM',
                                  'discountType': 'PERC',
                                  'discountValue': 10
                              }),
                              ('Unlimited Discount On BILL with ABS', {
                                  'couponLimit': {
                                      'limit': 0,
                                      'type': 'UNLIMITED'
                                  },
                                  'discountOn': 'BILL',
                                  'discountType': 'ABS',
                                  'discountValue': 10
                              }),
                              ('Unlimited Discount On BILL with PERC', {
                                  'couponLimit': {
                                      'limit': 0,
                                      'type': 'UNLIMITED'
                                  },
                                  'discountOn': 'BILL',
                                  'discountType': 'PERC',
                                  'discountValue': 10
                              }),
                              ('Unlimited Campaign with Limited Numbers ', {
                                  'couponLimit': {
                                      'limit': 10,
                                      'type': 'UNLIMITED'
                                  },
                                  'discountOn': 'BILL',
                                  'discountType': 'ABS',
                                  'discountValue': 10
                              }),
                              ('Boundary value for Limit ', {
                                  'couponLimit': {
                                      'limit': 99999999,
                                      'type': 'LIMITED'
                                  },
                                  'discountOn': 'BILL',
                                  'discountType': 'ABS',
                                  'discountValue': 10
                              })])
    def test_createCoupon_Variation(self, description, payloadData):
        response, payload, campaignId = coupons.createCoupons(
            payloadData=payloadData)
        coupons.assertCreateCoupon(response, 200)
        coupons.assertCreateCouponDbCalls(response, payload, campaignId)

    @pytest.mark.parametrize('description,payloadData', [
        ('Unlimited Coupon with Till Ids', {
            'couponLimit': {
                'limit': 0,
                'type': 'UNLIMITED'
            },
            'discountOn': 'BILL',
            'discountType': 'ABS',
            'discountValue': 10
        }),
    ])
    def test_createCoupon_tillIds_all(self, description, payloadData):
        tillIdList = map(
            int,
            dbCallsCoupons.getEntityIdWithType()['TILL'].split(','))
        payloadData.update({
            'issuableTillIds': tillIdList,
            'redeemableTillIds': tillIdList
        })
        Logger.log('PayloadDate Including till list :', payloadData)
        response, payload, campaignId = coupons.createCoupons(
            payloadData=payloadData)
        coupons.assertCreateCoupon(response, 200)
        coupons.assertCreateCouponDbCalls(response, payload, campaignId)

    @pytest.mark.parametrize('description,payloadData', [
        ('Unlimited Coupon with only 1 redeemable id', {
            'couponLimit': {
                'limit': 0,
                'type': 'UNLIMITED'
            },
            'discountOn': 'BILL',
            'discountType': 'ABS',
            'discountValue': 10
        }),
    ])
    def test_createCoupon_tillIds_lessReedemableTills(self, description,
                                                      payloadData):
        tillIdList = map(
            int,
            dbCallsCoupons.getEntityIdWithType()['TILL'].split(','))
        payloadData.update({
            'issuableTillIds': tillIdList,
            'redeemableTillIds': [tillIdList[0]]
        })
        Logger.log('PayloadDate Including till list :', payloadData)
        response, payload, campaignId = coupons.createCoupons(
            payloadData=payloadData)
        coupons.assertCreateCoupon(response, 200)
        coupons.assertCreateCouponDbCalls(response, payload, campaignId)

    @pytest.mark.parametrize('description,payloadData', [
        ('Unlimited Coupon with Different reedem and issuable tills', {
            'couponLimit': {
                'limit': 0,
                'type': 'UNLIMITED'
            },
            'discountOn': 'BILL',
            'discountType': 'ABS',
            'discountValue': 10
        }),
    ])
    def test_createCoupon_tillIds_moreReedemableTillsThanIssuableTills(
            self, description, payloadData):
        tillIdList = map(
            int,
            dbCallsCoupons.getEntityIdWithType()['TILL'].split(','))
        payloadData.update({
            'redeemableTillIds': tillIdList,
            'issuableTillIds': [tillIdList[0]]
        })
        Logger.log('PayloadDate Including till list :', payloadData)
        response, payload, campaignId = coupons.createCoupons(
            payloadData=payloadData)
        coupons.assertCreateCoupon(response, 200)

    @pytest.mark.parametrize('description,payloadData', [
        ('Unlimited Coupon', {
            'couponLimit': {
                'limit': 0,
                'type': 'UNLIMITED'
            },
            'discountOn': 'BILL',
            'discountType': 'ABS',
            'discountValue': 10
        }),
    ])
    def test_createCoupon_tillIds_differentIssuableAndReedemableTills(
            self, description, payloadData):
        tillIdList = map(
            int,
            dbCallsCoupons.getEntityIdWithType()['TILL'].split(','))
        payloadData.update({
            'redeemableTillIds': [tillIdList[1]],
            'issuableTillIds': [tillIdList[0]]
        })
        Logger.log('PayloadDate Including till list :', payloadData)
        response, payload, campaignId = coupons.createCoupons(
            payloadData=payloadData)
        coupons.assertCreateCoupon(response, 200)

    @pytest.mark.parametrize('description,payloadData', [
        ('Multiple Coupon in Same Campaign', {
            'couponSeriesTag': 'IRIS_COUPON' + str(int(time.time())),
            'couponLimit': {
                'limit': 0,
                'type': 'UNLIMITED'
            },
            'discountOn': 'BILL',
            'discountType': 'ABS',
            'discountValue': 10
        }),
    ])
    def test_createCoupon_MultipleCouponInSameCampaign(self, description,
                                                       payloadData):
        response, payload, campaignId = coupons.createCoupons(
            payloadData=payloadData)
        coupons.assertCreateCoupon(response, 200)
        failedResponse, failedCasepayload, campaignId = coupons.createCoupons(
            payloadData=payloadData, campaignId=campaignId)
        coupons.assertCreateCoupon(
            failedResponse, 400, 4005,
            'Coupon Exists Exception :  Coupon Already Exists for this Campaign '
        )
        coupons.assertCreateCouponDbCalls(response, payload, campaignId)

    @pytest.mark.parametrize(
        'description,payloadData,statusCode,errorCode,errorMessage',
        [('Empty CouponName', {
            'couponSeriesTag': '',
            'couponLimit': {
                'limit': 0,
                'type': 'UNLIMITED'
            },
            'discountOn': 'BILL',
            'discountType': 'ABS',
            'discountValue': 10
        }, 400, 100,
          'Invalid request : Coupon series tag must have at least one letter.'
          ),
         ('CouponName more than 160 Character', {
             'couponSeriesTag':
             'IRIS_COUPON_' + str(randValues.randomInteger(170)),
             'couponLimit': {
                 'limit': 0,
                 'type': 'UNLIMITED'
             },
             'discountOn':
             'BILL',
             'discountType':
             'ABS',
             'discountValue':
             10
         }, 400, 100,
          'Invalid request : Coupon series tag should be less than 160 characters.'
          ),
         ('CouponName with Special Character', {
             'couponSeriesTag': '#$$%',
             'couponLimit': {
                 'limit': 0,
                 'type': 'UNLIMITED'
             },
             'discountOn': 'BILL',
             'discountType': 'ABS',
             'discountValue': 10
         }, 400, 100,
          'Invalid request : Coupon series tag must have at least one letter.'
          ),
         ('Wrong Coupon Limit Type', {
             'couponSeriesTag': 'IRIS_COUPON_LIMITTYPE_WRONG',
             'couponLimit': {
                 'limit': 0,
                 'type': 'WRONG'
             },
             'discountOn': 'BILL',
             'discountType': 'ABS',
             'discountValue': 10
         }, 400, 100,
          'Invalid request : Valid Coupon limit type is required.'),
         ('Wrong Discount On', {
             'couponSeriesTag': 'IRIS_COUPON_DISCOUNTON_WRONG',
             'couponLimit': {
                 'limit': 0,
                 'type': 'UNLIMITED'
             },
             'discountOn': 'WRONG',
             'discountType': 'ABS',
             'discountValue': 10
         }, 400, 100, 'Invalid request : Discount on is required.'),
         ('Wrong Discount Type', {
             'couponSeriesTag': 'IRIS_COUPON_DISCOUNTON_WRONG',
             'couponLimit': {
                 'limit': 0,
                 'type': 'UNLIMITED'
             },
             'discountOn': 'BILL',
             'discountType': 'WRONG',
             'discountValue': 10
         }, 400, 100, 'Invalid request : Discount type is required.'),
         ('Discount Value More than 100 PERC', {
             'couponSeriesTag': 'IRIS_COUPON_MORETHAN1000PERC',
             'couponLimit': {
                 'limit': 0,
                 'type': 'UNLIMITED'
             },
             'discountOn': 'BILL',
             'discountType': 'PERC',
             'discountValue': 999
         }, 400, 100, 'Invalid request : Invalid Discount Value.')])
    def test_createCoupon_NegativeCases_Variation(self, description,
                                                  payloadData, statusCode,
                                                  errorCode, errorMessage):
        response, payload, campaignId = coupons.createCoupons(
            payloadData=payloadData, campaignType=['LIVE', 'ORG'])
        coupons.assertCreateCoupon(response, statusCode, errorCode,
                                   errorMessage)

    @pytest.mark.parametrize(
        'description,payloadData', [('Wrong CampaignId ', {
            'couponSeriesTag': 'IRIS_COUPON_WRONG_CAMPAIGNID',
            'couponLimit': {
                'limit': 0,
                'type': 'UNLIMITED'
            },
            'discountOn': 'BILL',
            'discountType': 'ABS',
            'discountValue': 10
        })])
    def test_createCoupon_wrongCampaignId(self, description, payloadData):
        response, payload, campaignId = coupons.createCoupons(
            payloadData=payloadData, campaignId=0)
        coupons.assertCreateCoupon(
            response, 400, 100,
            'Invalid request : Campaign id should be a positive value.')

    def test_createCoupon_campaignIdNotInPassedOrg(self):
        campaignResponse, campaignPayload = campaigns.createCampaign({
            'name':
            'IRIS_' + str(int(time.time())),
            'goalId':
            constant.irisGenericValues['goalId'],
            'objectiveId':
            constant.irisGenericValues['objectiveId']
        })
        previousOrgId = construct.updateOrgId(0)
        try:
            response, payload, campaignId = coupons.createCoupons(
                campaignId=campaignResponse['json']['entity']['campaignId'])
            coupons.assertCreateCoupon(
                response, 400, 1007,
                'Campaign Id Exception : Invalid Campaign Id Passed {}'.format(
                    campaignId))
        except AssertionError, exp:
            Assertion.constructAssertion(False, exp)
        finally:
コード例 #12
0
 def couponConfiguration(couponConfigDict={}):
     tmpDict = {
         "id":
         0,
         "client_handling_type":
         "DISC_CODE",
         "org_id":
         constant.config['orgId'],
         "created_by":
         constant.config['adminId'],
         "campaign_id":
         constant.config['campaignId'],
         "created":
         Utils.getTime(milliSeconds=True),
         "last_used":
         Utils.getTime(milliSeconds=True),
         "redemption_valid_from":
         Utils.getTime(days=-1, milliSeconds=True),
         "dvs_expiry_date":
         Utils.getTime(milliSeconds=True),
         "series_code":
         str(Utils.getTime(milliSeconds=True)) +
         str(randValues.randomInteger(5)),
         "valid_till_date":
         Utils.getTime(days=2, milliSeconds=True),
         "description":
         "luci testing",
         "series_type":
         "CAMPAIGN",
         "discount_code":
         "XYZ123",
         "valid_days_from_create":
         30,
         "expiry_strategy_value":
         30,
         "transferrable":
         False,
         "any_user":
         False,
         "same_user_multiple_redeem":
         False,
         "allow_referral_existing_users":
         False,
         "multiple_use":
         False,
         "is_validation_required":
         False,
         "valid_with_discounted_item":
         False,
         "num_issued":
         0,
         "num_redeemed":
         0,
         "sms_template":
         "",
         "disable_sms":
         False,
         "info":
         "luci testing",
         "allow_multiple_vouchers_per_user":
         False,
         "do_not_resend_existing_voucher":
         False,
         "mutual_exclusive_series_ids":
         'false',
         "store_ids_json":
         '[-1]',
         "dvs_enabled":
         False,
         "priority":
         0,
         "terms_and_condition":
         "T&C Apply",
         "signal_redemption_event":
         False,
         "sync_to_client":
         False,
         "short_sms_template":
         "",
         "max_vouchers_per_user":
         -1,
         "min_days_between_vouchers":
         -1,
         "max_referrals_per_referee":
         -1,
         "show_pin_code":
         False,
         "discount_on":
         "BILL",
         "discount_type":
         "ABS",
         "discount_value":
         1,
         "dvs_items":
         "",
         "redemption_range":
         '{ "dom": ["-1"], "dow": ["-1"],"hours": ["-1"] }',
         "min_bill_amount":
         0,
         "max_bill_amount":
         0,
         "redeem_at_store":
         '[-1]',
         "tag":
         "",
         "max_redemptions_in_series_per_user":
         -1,
         "min_days_between_redemption":
         -1,
         "redeem_store_type":
         "redeemable_stores",
         "expiry_strategy_type":
         "DAYS",
         "old_flow":
         False,
         "max_create":
         -1,
         "max_redeem":
         -1,
         "pre_redeem_event_required":
         False,
         "source_org_id":
         -1,
         "issue_to_loyalty":
         False,
         "offline_redeem_type":
         False
     }
     tmpDict.update(couponConfigDict)
     return luci.CouponConfiguration(**tmpDict)