def waitUntil(self, nsadminId, status, timeOut = 60): for _ in range(0, timeOut): msgResp = self.nsObj.getMessagesById([nsadminId])[0] if msgResp.status in status: Logger.log('returning ') return msgResp else: time.sleep(1) Logger.log('returning false') return False
def readFileFromS3(bucketName, keyName): bucketName = AWSHelper.updateBucketName(bucketName) Logger.log('Reading File from BucketName :{} and keyName :{}'.format( bucketName, keyName)) session = boto3.Session(aws_access_key_id=constant.awsKey, aws_secret_access_key=constant.awsSecret) s3 = session.resource('s3') data = s3.Object(bucketName, keyName).get()['Body'].read().decode('utf-8') return data.split('\n')
def assertCommunicationDetailInErrorState(groupVersionId, communicationId): for _ in range(10): time.sleep(30) try: social_info( groupVersionid=groupVersionId, messageId=communicationId).veneno_monitoringStatus() break except Exception, exp: Logger.log('Monitoring Status Still Not Updated')
def createCustomList(self, userlist, customAudienceListDetails, socialAccountDetails, orgId, recepientlistId, requestId): Logger.log('Call :{} , Params :{},{},{},{},{},{}'.format( 'createCustomList', userlist, customAudienceListDetails, socialAccountDetails, orgId, recepientlistId, requestId)) return self.log( self.conn.createCustomList(userlist, customAudienceListDetails, socialAccountDetails, orgId, recepientlistId, requestId))
def getDimAttrValuesByConstraints(self, dimName, levelName, searchText): Logger.log( 'Params : OrgId :{} and clientType as :{} and LevelName :{} and searchText :{}' .format(constant.config['orgId'], dimName, levelName, searchText)) return self.log( self.conn.getDimAttrValuesByConstraints( constant.config['orgId'], dimName, levelName, ReonObject().TDimOperationType['SEARCH'], ReonObject().TDimParams(searchText), list(), ReonObject().TMetaClient['READ_API']))
def assertGetAdsetInsight(AdInsightObject, adsetId): Assertion.constructAssertion( AdInsightObject.orgId == constant.config['orgId'], 'Adsetinsight Mapped to Correct org :{}'.format( constant.config['orgId'])) Assertion.constructAssertion( Adsetinsight.adsetId == adsetId, 'Adset Mapping to Insight , Actual :{} and Expected :{}'.format( Adsetinsight.adsetId, adsetId)) Logger.log(Adsetinsight.insights)
def setupStrategy(daily=None, weekly=None, monthly=None, channel='SMS'): Logger.log( 'Setting up Strategy with Daily :{} , weekly :{} and monthly :{}'. format(daily, weekly, monthly)) if daily is not None: dbCallsAuthorize.setupStrategy(daily=daily, channel=channel) if weekly is not None: dbCallsAuthorize.setupStrategy(weekly=weekly, channel=channel) if monthly is not None: dbCallsAuthorize.setupStrategy(monthly=monthly, channel=channel)
def goToOverviewpage(self): try: Logger.log('Going To Overview Page using heading-campaign-name') self.waitForElement(self.txt_campaignNameOnOverview_id) if self.isElementPresent(self.txt_campaignNameOnOverview_id): self.elementClick(self.txt_campaignNameOnOverview_id) else: assert False, 'Overview Page Locator is not Present' except Exception, exp: raise Exception('Go To OverviewPage Exception :{}'.format(exp))
def openNewCampaignCreationForm(self): try: Logger.log('Opening Create Campaign Form Fill Page ') self.waitForElement(self.btn_newCampaign_id) if self.isElementPresent(self.btn_newCampaign_id): self.elementClick(self.btn_newCampaign_id) else: assert False, 'Create Campaign Button Locator is not Present' except Exception, exp: raise Exception('Campaign Create Exception :{}'.format(exp))
def test_pasteList_wrongOrgId(self): response, payload = campaigns.createCampaign(campaignTypeParams=['LIVE', 'ORG']) campaigns.assertCreateCampaign(response, 200) campaignId = response.get('json').get('entity').get('campaignId') previousOrgId = construct.updateOrgId(0) try: responseCreateList, payload, campaignId = campaignList.createList({}, campaignId=campaignId) campaignList.assertCreateList(responseCreateList, 400, 2003, 'Invalid campaign id : ' + str(campaignId)[:3] + ',' + str(campaignId)[3:]) except AssertionError, exp: Logger.log('Assertioin Failed as :', exp)
def validate(self): for eachentity in self.response['json']['entity']: Logger.log('Validation for Programe id : {}'.format( eachentity['programId'])) Assertion.constructAssertion( eachentity['programId'] in self.pointsMeta, 'Programeid :{} found in DB'.format(eachentity['programId'])) self.basicValidationForProgram(eachentity) self.validateTiersForEachEntity(eachentity) self.validateStrategy(eachentity)
def test_campaignShardThrift_reloadFilterBasedList_newBucket_partiallyDistributedBucket( self, campaignType, audienceType): self.bucketDetails = CampaignShardHelper.updateBucketIdRowCount( rows_count=14999990) existingList = constant.thiriftCampaignShardTestReferenceObject[ campaignType]['campaign']['lists'][audienceType][1] userPayloadInfo = CampaignShardHelper.loyaltyUserDataConstructHelper() s3InfoForUsedList = CampaignShardHelper.getS3Info(existingList['uuid']) thriftCampaignGroup = lambda campaignTargetType: self.campaignShardObject.CampaignGroup( { 'campaignId': constant.thiriftCampaignShardTestReferenceObject[campaignType][ 'campaign']['id'], 'groupId': existingList['groupDetails']['id'], 'groupLabel': existingList['groupLabel'], 'params': str(), 'campaignGroupType': 'LOYALTY', 'campaignTargetType': 'TEST', 'customerCount': existingList['groupVersionDetails'][campaignTargetType][ 'customer_count'], 'uuId': existingList['uuid'], 'versionNumber': 1, 's3Path': s3InfoForUsedList['response']['data']['s3Path'], 's3Headers': s3InfoForUsedList['response']['data']['s3Header'], 's3BucketTag': s3InfoForUsedList['response']['data']['s3Path'].split('/')[2] }) for eachTargetType in ['TEST']: if not self.connObj.reloadGroup( thriftCampaignGroup(eachTargetType)): Logger.log( 'For TargetType :{} , reload was unsuccesfull'.format( eachTargetType)) CampaignShardHelper.validateBucketIdWhenBucketUpdated( existingList['groupDetails']['id'], self.bucketDetails['oldBucket']) CampaignShardDBAssertion( constant.thiriftCampaignShardTestReferenceObject[campaignType] ['campaign']['id'], campaignType, 'loyalty', existingList['groupLabel'], existingList['groupDetails']['id'], 'firstName,lastName,mobile', userPayloadInfo).check()
def createTemplate(self, channel='sms', TemplateType='Use Editor'): try: Logger.log('Creating Template') self.waitForElement(self.btn_createTemplate_xpath, locatorType='xpath') if self.isElementPresent(self.btn_createTemplate_xpath, locatorType='xpath'): self.elementClick(self.btn_createTemplate_xpath, locatorType='xpath') else: assert False, 'Create Template Button Not Found for channel :{}'.format( channel) if channel.lower() == 'email': if TemplateType == 'Use Editor': emailTemplateType = self.getElements( self.sel_template_emailType_xpath, locatorType='xpath') for eachEmailTemplateType in emailTemplateType: if eachEmailTemplateType.text == 'Use Editor': eachEmailTemplateType.click() self.waitForElement(self.layout_email_xpath, locatorType='xpath') if self.isElementPresent(self.layout_email_xpath, locatorType='xpath'): firstLayout = self.getElements(self.layout_email_xpath, locatorType='xpath')[0] self.moveToElement(firstLayout) self.moveToElement( self.getElement(self.layout_btn_selectLayout_xpath, locatorType='xpath')) self.elementClickWithAction( self.layout_btn_selectLayout_xpath, locatorType='xpath') elif TemplateType == 'Upload File': Logger.log('Uploading File from path :', constant.randomHtmlPath) time.sleep(5) inputFieldForUpload = self.getElement( self.upload_filename_xpath, locatorType='xpath') inputFieldForUpload.send_keys(constant.randomHtmlPath) else: raise Exception( 'NoSuchTemplateTypeException : TemplateType :{}'. format(TemplateType)) elif channel.lower() == 'mobile push': templateTypeElement = self.getElement( self.push_templateType_xpath.replace( '{templateType}', TemplateType), locatorType='xpath') templateTypeElement.click() except Exception, exp: raise Exception('CreateTemplate Exception :{}'.format(exp))
def getSecretAValueOfUsersInList(self): allUsersValueToPassAsString = "" getSecretValueBasedOn = self.userDataSchema.split(',')[2] if len(self.usersDataPassed) == 0: return () for eachUser in self.usersDataPassed: allUsersValueToPassAsString = allUsersValueToPassAsString + "'" + eachUser.split( ',')[2] + "'," Logger.log(allUsersValueToPassAsString) return dbCallsList.getSecretA( getSecretValueBasedOn, allUsersValueToPassAsString[:len(allUsersValueToPassAsString) - 1])
def getCouponsCreated_Count(couponSeriesId, isValid=-1): query = 'SELECT count(1) FROM `luci`.`coupons_created` WHERE `org_id` = ' + str(constant.config['orgId']) + \ ' AND `coupon_series_id` = ' + str(couponSeriesId) if isValid >= 0: query = query + ' AND is_valid = ' + str(isValid) result = dbHelper.queryDB(query, "luci") if len(result) == 0: Logger.log('No records found') return None else: return result[0][0]
def getPointsDeductions(customerId, deductionSummaryId): Logger.log('Get Point deduction summary Details') query = 'SELECT deduction_type,points_deducted,deduction_currency_value FROM warehouse.points_deductions WHERE org_id = {} AND program_id = {} AND customer_id = {} AND deduction_summary_id = {}'.format(constant.config['orgId'],constant.config['programId'],customerId,deductionSummaryId) result = dbHelper.queryDB(query, 'warehouse') pointsDeduction = {} if len(result) == 0: Logger.log('No records found') else: for k in result: pointsDeduction.update({'deductionType' : k[0], 'pointsDeducted' : k[1], 'deductionCurrencyValue' : k[2]}) return pointsDeduction
def getSumOfPointsAwarded(customerId): Logger.log('Get Points Awarded sum values') query = "SELECT SUM(points_value),SUM(redeemed_value) FROM warehouse.points_awarded WHERE org_id = {} AND program_id = {} and customer_id = {}".format(constant.config['orgId'],constant.config['programId'],customerId) result = dbHelper.queryDB(query, 'warehouse') sumOfPA = {} if len(result) == 0: Logger.log('No records found') else: for k in result: sumOfPA.update({'sumOfPointsValue' : k[0], 'sumOfRedeemedValue' : k[1]}) return sumOfPA
def getLineItemIds(userId, loyalty_log_id): Logger.log('Get Point deduction summary Details') query = 'SELECT id FROM user_management.loyalty_bill_lineitems WHERE org_id = {} AND user_id = {} AND loyalty_log_id = {}'.format(constant.config['orgId'],userId,loyalty_log_id) result = dbHelper.queryDB(query, 'user_management') lineItemIdList = [] if len(result) == 0: Logger.log('No records found') else: for k in result: lineItemIdList.append({'lineItemId' : k[0]}) return lineItemIdList
def getPointsCategoryIds(): Logger.log('Get Point deduction summary Details') query = 'SELECT id,description,is_redeemable FROM warehouse.points_categories where org_id = {} and program_id = {}'.format(constant.config['orgId'], constant.config['programId']) result = dbHelper.queryDB(query, 'warehouse') pointCategoryList = [] if len(result) == 0: Logger.log('No records found') else: for k in result: pointCategoryList.append({'id': k[0], 'description' : k[1], 'isRedeemable' : k[2]}) constant.config.update({'loyalty': {'pointCategory' : pointCategoryList}})
def getMessageQueueFromMessageId(message_id, payload={}): Logger.log('Getting Message Queue Informtion using message ID:', message_id) query = 'select id,type,org_id,campaign_id,group_id,status,scheduled_type,params,Approved,default_arguments,guid from message_queue where id = ' + str(message_id) result = dbHelper.queryDB(query, 'msging')[0] param = json.loads(result[7]) if result[1].lower() == 'wechat' and 'message' in payload: param['message'] = json.loads(param['message']) if param['message']['isUrlInternal']: param['message']['url'] = payload['message']['url'] param['message'].pop('urlInternal') return {'id':result[0], 'type':result[1], 'org_id':result[2], 'campaign_id':result[3], 'group_id':result[4], 'status':result[5], 'scheduled_type':result[6], 'param': param, 'Approved':result[8], 'default_arguments':result[9], 'guid':result[10]}
def test_LUCI_UC_01(self,description, couponConfig, uploadType, dracarysUploadInput): #Save Coupon Config for i in range(5): self.userIds.append(constant.config['usersInfo'][i]['userId']) couponConfigObj, couponSeriesId = LuciHelper.saveCouponConfigAndAssertions(self) time.sleep(2) couponCodeList = LuciHelper.uploadCouponAndAssertions(self,couponSeriesId, self.constructObj.importType[uploadType],noOfCouponsToBeUpload=5, dracraysUpload=dracarysUploadInput)['coupons'] Logger.log('Coupon Code list : ', couponCodeList) for couponCode, self.userId in zip(couponCodeList,self.userIds): LuciHelper.getCouponDetailsAndAssertion(self,couponSeriesId,couponCode, couponDetailsRequest={'onlyActive': True, 'couponCodeFilter': [couponCode]}) LuciHelper.getCouponConfigAndAssertion(self,couponSeriesId,5,0)
def __init__(self, metaDetails, campaignGroupRecipients=False, campaignGroupRecipientsForCustomTag=False): Logger.log('Getting Data Details for groupId : {}'.format( metaDetails['groupId'])) self.metaDetails = metaDetails self.dataDetail = dict() if campaignGroupRecipients: self.campaignGroupRecipients() if campaignGroupRecipientsForCustomTag: self.campaignGroupRecipientsForCustomTag()
def elementClick(self, locator, locatorType="id"): try: element = self.getElement(locator, locatorType) Logger.log("Clicked on element :{} with locator {}".format( element, locator)) element.click() except Exception, exp: Logger.log( 'ElementClick Exception :{} but we will retry to click on Element as Element is captured' .format(exp)) self.retryElementClick(locator, locatorType)
def saveTemplate(self): try: self.waitForElement(self.selectTemplateNext_id) for retry in range(10): if self.isElementPresent(self.selectTemplateNext_id): time.sleep(5) self.elementClick(self.selectTemplateNext_id) else: if retry > 2: break except Exception, exp: Logger.log('Exception :{} while Save Template'.format(exp))
def createSlabAndUpdateStrategies(self, programId, orgId, slabInfo, strategyInfos, lastModifiedBy, lastModifiedOn): Logger.log('programId: ', programId, ' orgId: ', orgId, ' slabInfo: ', slabInfo, ' strategyInfos: ', strategyInfos, ' lastModifiedBy: ', lastModifiedBy, ' lastModifiedOn: ', lastModifiedOn, ' serverReqId: ', self.serverRequestID) return self.log( self.conn.createSlabAndUpdateStrategies( strategyInfo, programId, orgId, slabInfo, strategyInfos, lastModifiedBy, lastModifiedOn, self.serverRequestID))
def bulkPointsExpiredInit(self, orgID, fromExpiryDate, toExpiryDate, includeExpired, includeRedeemed): Logger.log('orgID: ', orgID, ' fromExpiryDate:', fromExpiryDate, ' toExpiryDate: ', toExpiryDate, ' includeExpired: ', includeExpired, ' includeRedeemed: ', includeRedeemed, ' serverReqId: ', self.serverRequestID) return self.log( self.conn.bulkPointsExpiredInit(orgID, fromExpiryDate, toExpiryDate, includeExpired, includeRedeemed, self.serverRequestID))
def getElement(self, locator, locatorType="id"): element = None try: element = self.getByType(locatorType, locator)[0] Logger.log("Element found with locator: " + locator + " and locatorType: " + locatorType) except: Logger.log("Element not found with locator: " + locator + " and locatorType: " + locatorType) finally: return element
def test_updateCampaign_WrongCampaignId(self, description, campaignId): updateResponse, createResponse, updatePayload, createPayload = campaigns.updateCampaign( {'name': 'Wrong_CampaignId' + str(int(time.time()))}, campaignId=campaignId) Logger.log( 'updateResponse :{} , createResponse :{} , updatePayload :{} ,createPayload :{}' .format(updateResponse, createResponse, updatePayload, createPayload)) campaigns.assertUpdateCampaign( updateResponse, createResponse, 400, 100, 'Invalid request : must be greater than or equal to 1')
def validateBucketIdWhenBucketUpdated(groupId, expectedBucketDetails): Logger.log( 'Checking for Bucket Id with groupId :{} and expectedBucketDetails:' .format(groupId, expectedBucketDetails)) groupVersionDetailslatest = dbCallsList.getGroupVersionDetailsWithGroupId( groupId) latestBucketId = groupVersionDetailslatest['TEST']['bucket_id'] Assertion.constructAssertion( int(latestBucketId) == expectedBucketDetails, 'Expected Bucket Id :{} but actually in DB :{}'.format( expectedBucketDetails, latestBucketId))
def test_updateCampaign_WithDifferntCampaignName_NegativeCases( self, description, campaignName, statusCode, errorCode, errorMessage): updateResponse, createResponse, updatePayload, createPayload = campaigns.updateCampaign( {'name': campaignName}, campaignType=['LIVE', 'ORG']) Logger.log( 'updateResponse :{} , createResponse :{} , updatePayload :{} ,createPayload :{}' .format(updateResponse, createResponse, updatePayload, createPayload)) campaigns.assertUpdateCampaign(updateResponse, createResponse, statusCode, errorCode, errorMessage)