예제 #1
0
 def createFileForSkippedUsers(users):
     filePath = constant.autoTempFilePath + 'AutoList_{}_{}'.format(randValues.randomString(8),
                                                                    int(time.time() * 1000))
     file = FileHelper(filePath)
     for eachUser in users:
         file.appendToFile('{},{}'.format(eachUser,'Skip_{}'.format(eachUser)))
     Logger.log('FilePath Create for Skipped User :{}'.format(filePath))
     return filePath
예제 #2
0
def executeSuite():
    module = constant.config['module']
    tcFilter = constant.config['tcFilter']
    collectOnly = constant.config['collectOnly']
    try:
        testPath = constant.testFolder + module
        reportPath = constant.config['logDir'] + '/result.html'
        if collectOnly:
            pytest.main([testPath, '-k ' + tcFilter, '--collect-only'],
                        plugins=[MyPlugin()])
        else:
            pytest.main([
                testPath, '--tb=long', '-v', '--html=' + reportPath,
                '-k ' + tcFilter
            ],
                        plugins=[
                            MyPlugin()
                        ])  # For Debugging -s instead of --tb=line  , '--pdb'
            FileHelper.concateHTMLandCSS()
    except Exception as e:
        Logger.log('Exception in execution : ', e)
        print e
예제 #3
0
    def assertFileCreatedAndS3File(self, fileName, s3FilePath):
        filePath = constant.autoTempFilePath + fileName
        dataFromS3 = AWSHelper.readFileFromS3(
            '{}{}'.format(self.bucketUsed, constant.config['cluster']),
            s3FilePath)
        dataFromFile = FileHelper.readFile(filePath).split('\n')

        Assertion.constructAssertion(
            len(dataFromFile) == len(dataFromS3),
            'Data in File :{} and in s3 :{}'.format(dataFromFile, dataFromS3))
        for eachLine in dataFromS3:
            Assertion.constructAssertion(
                eachLine in dataFromFile,
                'line :{} Found in File used to Create List'.format(eachLine))
예제 #4
0
    def assertErrorFileCreateAndS3File(self, uploadObject, errorReasons):
        fileName = uploadObject['fileName']
        s3fileUrl = uploadObject['fileUrl']
        errorCount = uploadObject['errorCount']
        s3errorFileUrl = uploadObject['errorFileUrl']

        dataFromFile = filter(
            None,
            FileHelper.readFile(constant.autoTempFilePath +
                                fileName).split('\n'))
        correctDataFromS3 = filter(
            None,
            AWSHelper.readFileFromS3(
                '{}{}'.format(self.bucketUsed, constant.config['cluster']),
                s3fileUrl))
        errorDataFromoS3 = filter(
            None,
            AWSHelper.readFileFromS3(
                '{}{}'.format(self.bucketUsed, constant.config['cluster']),
                s3errorFileUrl))[1:]

        Logger.log(
            'DataList Of File :{} , Correct Data From s3 :{} and errorDataFroms3 :{}'
            .format(dataFromFile, correctDataFromS3, errorDataFromoS3))

        Assertion.constructAssertion(
            len(dataFromFile) == len(correctDataFromS3),
            'Total Error Count :{} and in s3 correct Data :{} , error Data :{}'
            .format(len(dataFromFile), len(correctDataFromS3),
                    len(errorDataFromoS3)))
        Assertion.constructAssertion(
            len(errorDataFromoS3) == errorReasons[fileName]['numberOfUser'],
            'In S3 Number Of Error Users are :{} and Expected :{}'.format(
                len(errorDataFromoS3), errorReasons[fileName]['numberOfUser']))
        maxLineCheck = 100
        for eachUser in errorDataFromoS3:
            if maxLineCheck == 0: break
            Assertion.constructAssertion(
                eachUser.split(',')[-1] in errorReasons[fileName]['reason'],
                'Error :{} in File for line :{} , is in Expected List :{} '.
                format(
                    eachUser.split(',')[-1], eachUser, errorReasons[fileName]))
            maxLineCheck = maxLineCheck - 1
예제 #5
0
 def test_sendMessage_EMAIL_withHTMLContentAndAttachment(self):
     filePath = constant.rootPath + '/src/modules/nsadmin/html'
     body = FileHelper.readFile(filePath)
     self.nsadminHelper.configureGateway('BULK', 'localmail_BULK')
     msgDict = {
         "messageClass": "EMAIL",
         "priority": "BULK",
         "receiver": "*****@*****.**",
         "message": "test message with html content",
         "body": body,
         "attachmentId": [23303]
     }
     msgObj = NSAdminObject.message(msgDict)
     msgId = self.nsObj.sendMessage(msgObj)
     resp = self.nsadminHelper.assertWithWaitUntil(
         msgId, ['RECEIVED_IN_QUEUE', 'SENT'], 'Messages status ACK', 10)
     currentMonthTable = NSAdminHelper.getDataTableName()
     query = 'select attachment_id from ' + currentMonthTable + ' where nsadmin_id=' + str(
         msgId)
     resp = dbHelper.queryDB(query, 'nsadmin')
     Assertion.constructAssertion(resp[0][0] == '23303',
                                  'Messages attachmentId')
예제 #6
0
 def revokes3FileAndRequestObject(self, couponSeriesId, couponData,
                                  revokeTypeIndex):
     invalidateDict = {
         'uploadedFileName':
         constant.config['uploadedFileName'] + '_revokeFile'
     }
     filehandle = FileHelper(constant.luciS3FilePath)
     filehandle.eraseContentFromFile()
     revokeType = [
         'COUPON_SERIES', 'ONLY_UNISSUED', 'userId', 'couponCode',
         'couponId', 'CUSTOMER_AND_COUPON'
     ]
     if revokeType[revokeTypeIndex] == 'userId':
         filehandle.appendToFile(revokeType[revokeTypeIndex])
         invalidateDict.update({'revokeHeaders': {'userId': 0}})
     elif revokeType[revokeTypeIndex] == 'couponCode':
         filehandle.appendToFile(revokeType[revokeTypeIndex])
         invalidateDict.update({'revokeHeaders': {'couponCode': 0}})
     elif revokeType[revokeTypeIndex] == 'couponId':
         filehandle.appendToFile(revokeType[revokeTypeIndex])
         invalidateDict.update({'revokeHeaders': {'couponId': 0}})
     elif revokeType[revokeTypeIndex] == 'CUSTOMER_AND_COUPON':
         filehandle.appendToFile('userId,couponCode')
         invalidateDict.update(
             {'revokeHeaders': {
                 'userId': 1,
                 'couponCode': 0
             }})
     for eachData in couponData:
         filehandle.appendToFile(eachData)
     invalidateDict.update(
         {'S3FilePath': DracarysHelper.s3FileUpload(self, couponSeriesId)})
     return invalidateDict
예제 #7
0
    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
예제 #8
0
class BaseState():
    @staticmethod
    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))
        if module == 'campaignsui':
            constant.config.update(constant.irisDetails[cluster])
            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({'headlessMode': args.headlessMode})
            constant.config.update(constant.campaignuiDetails)
            constant.config.update({'apiTesterDB': constant.dbNames[cluster]})
            constant.config.update({'shard': DBCallsCampaigns.getShardGettingUsed()})

            if collectOnly:
                constant.campaignuiUserInfo.update({'loyalty': {'name': 'name', 'email': 'email', 'mobile': 'mobile'}})
            else:
                fileHandle = FileHelper(constant.userFileMobile)
                existingUserDetail = DBCallsCampaigns.getLoyaltyUserInfo(1)[0]
                constant.campaignuiUserInfo.update({'loyalty': {'name': existingUserDetail[1],
                                                                'email': existingUserDetail[4],
                                                                'mobile': existingUserDetail[3]}})
                fileHandle.eraseContentFromFile()
                fileHandle.appendToFile('mobile,name')
                fileHandle.appendToFile(str(existingUserDetail[3]) + ',' + str(existingUserDetail[1]))
        if module == 'nsadmin':
            constant.config.update(constant.prodNumbers)
            constant.config.update({"clusterFileHandle": constant.clusterFileHandle[cluster]})
            constant.config.update({"dlrUrl": constant.dlrUrl[cluster]})

        if module == 'irisv2':
            constant.config.update({'node': copy.deepcopy(constant.node)})

        if not collectOnly:
            sortesListOfLogFiles = Utils.sorted_ls(constant.logDirectory)
            if len(sortesListOfLogFiles) > constant.maxNumberOfLogFiles:
                try:
                    Utils.deleteFolder(constant.logDirectory + '/' + sortesListOfLogFiles[0])
                except Exception as e:
                    Logger.log(str(e))
            BaseState.setBaseState()