Exemplo n.º 1
0
def get_log(logger_name):
    # 获取项目的根目录
    project_path = getcwd.get_cwd()
    Logs_path = os.path.join(project_path, 'logs')
    # 获取本地时间,转为年-月-日格式
    local_date = time.strftime('%Y-%m-%d', time.localtime(time.time()))
    # 日期文件夹路径
    date_file_path = os.path.join(Logs_path, local_date)
    # 如果没有日期文件夹,创建该文件夹
    if not os.path.exists(date_file_path):
        os.makedirs(date_file_path)
    # 完整日志存放路径
    all_log_path = os.path.join(date_file_path, 'All_Logs/')
    # 如果没有完整日志文件夹,创建该文件夹
    if not os.path.exists(all_log_path):
        os.makedirs(all_log_path)
    # 错误日志存放路径
    error_log_path = os.path.join(date_file_path, 'Error_Logs/')
    # 如果没有错误日志文件夹,创建该文件夹
    if not os.path.exists(error_log_path):
        os.makedirs(error_log_path)
    # 获取本地时间,转为年月日时分秒格式
    local_time = time.strftime('%Y-%m-%d %H%M%S', time.localtime(time.time()))
    # 设置日志文件名
    all_log_name = all_log_path + local_time + '.log'
    error_log_name = error_log_path + local_time + '.log'

    # 创建一个logger
    logger = logging.getLogger(logger_name)
    logger.setLevel(logging.INFO)

    # 创建handler
    # 创建一个handler写入所有日志
    fh = logging.FileHandler(all_log_name, encoding='utf-8')
    fh.setLevel(logging.INFO)
    # 创建一个handler写入错误日志
    eh = logging.FileHandler(error_log_name, encoding='utf-8')
    eh.setLevel(logging.ERROR)
    # 创建一个handler输出到控制台
    ch = logging.StreamHandler()
    ch.setLevel(logging.INFO)

    # 定义日志输出格式
    # 以时间-日志器名称-日志级别-日志内容的形式展示
    all_log_formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    # 以时间-日志器名称-日志级别-文件名-函数行号-错误内容
    error_log_formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(module)s  - %(lineno)s - %(message)s'
    )
    # 将定义好的输出形式添加到handler
    fh.setFormatter(all_log_formatter)
    ch.setFormatter(all_log_formatter)
    eh.setFormatter(error_log_formatter)

    # 给logger添加handler
    logger.addHandler(fh)
    logger.addHandler(eh)
    logger.addHandler(ch)
    return logger
Exemplo n.º 2
0
def set_data_yaml(key,value):
    """
    设置data.yml内容
    :param key:
    :param value:
    :return:
    """
    path = getcwd.get_cwd()  # 获取相对路径
    yaml_path = os.path.join(path, 'Params\Param\data.yml')  # 获取配置文件路径
    with open(yaml_path, 'r', encoding='utf-8') as f:
        lines = []  # 创建了一个空列表,里面没有元素
        for line in f.readlines():
            if line != '\n':
                lines.append(line)
        f.close()
    with open(yaml_path, 'w', encoding='utf-8') as f:
        for line in lines:
            str1 = "'" + key + "'"
            str2 = '"' + key + '"'
            if str1 in line or str2 in line and "#" not in line: #兼容""  ''的数据
                num = line.find("{")
                str = line[num:]
                dict=eval(str)
                dict[key] = value
                leftstr = line.split(":")[0]
                newline = "{0}: {1}".format(leftstr, dict)
                f.write('%s\n' % newline)
                # print(newline)
            else:
                f.write('%s' % line)
        f.close()
Exemplo n.º 3
0
def get_log(logger_name):
    logger = logging.getLogger(logger_name)
    logger.setLevel(logging.INFO)
    rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
    path = getcwd.get_cwd()
    all_log_path = os.path.join(path, 'logs/all_logs/')
    error_log_path = os.path.join(path, 'logs/error_logs/')
    all_log_name = all_log_path + rq + '.log'
    error_log_name = error_log_path + rq + '.log'
    fh = logging.FileHandler(all_log_name)
    fh.setLevel(logging.INFO)
    eh = logging.FileHandler(error_log_name)
    eh.setLevel(logging.ERROR)
    ch = logging.StreamHandler()
    ch.setLevel(logging.INFO)
    all_log_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    error_log_formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(module)s  - %(lineno)s - %(message)s')

    fh.setFormatter(all_log_formatter)
    ch.setFormatter(all_log_formatter)
    eh.setFormatter(error_log_formatter)
    logger.addHandler(fh)
    logger.addHandler(eh)
    logger.addHandler(ch)
    return logger
Exemplo n.º 4
0
def add_filehandler(level, fmt, filename, mode, backup_count, limit, when,
                    encoding):
    '''Add a file handler to the global logger.'''
    kwargs = {}

    # If the filename is not set, use the default filename
    if filename is None:
        filename = getattr(sys.modules['__main__'], '__file__', 'log.py')
        filename = os.path.basename(filename.replace('.py', '.log'))
        filepath = os.path.join(getcwd.get_cwd(), 'logs')
        mkDirs(filepath)  #如果没有这个文件夹就新建
        filename = os.path.join(filepath, filename)

    kwargs['filename'] = filename  #文件名
    kwargs['encoding'] = encoding  #文件编码

    # Choose the filehandler based on the passed arguments
    if backup_count == 0:  # Use FileHandler
        cls = logging.FileHandler
        kwargs['mode'] = mode
    elif when is None:  # Use RotatingFileHandler
        cls = logging.handlers.RotatingFileHandler  #基于文件大小切分
        kwargs['maxBytes'] = limit  #切分后的每个文件大小
        kwargs['backupCount'] = backup_count  #切分文件数
        kwargs['mode'] = mode
    else:  # Use TimedRotatingFileHandler
        cls = logging.handlers.TimedRotatingFileHandler  #基于文件日期切分,按天切分
        kwargs['when'] = when
        kwargs['interval'] = limit  #切分后的每个文件大小
        kwargs['backupCount'] = backup_count  #切分文件数

    return add_handler(cls, level, fmt, False, **kwargs)
Exemplo n.º 5
0
class api_detect(unittest.TestCase):
    '''人脸识别'''
    #装载测试数据
    execlName=os.path.join(getcwd.get_cwd(),"data\\api_data_detect.xls")
    caseData_excel = ExcelUtil(execlName, 'Sheet1')
    writer_table=ExcelAdd(execlName,sheet='Sheet1')
    log.info('装载测试数据成功')
    col_Num=writer_table.get_cols()
    writer_table.modify_cell(0, writer_table.get_cols(), 'status')
    writer_table.modify_cell(0, writer_table.get_cols()+1, 'return_msg')
    log.info('Execl文件表头写入成功')

    @classmethod
    def setUpClass(self):
        log.info('开始测试...')
    
    @classmethod
    def tearDownClass(self):
        self.writer_table.save()#保存execl测试结果
        #self.dr.quit()  #关闭浏览器
        log.info('测试完成,退出系统,关闭浏览器')
    
    def setUp(self):        
        print('case_id: ',self.id(),'开始执行<br />') #固定格式,用于报表生成        
             
    def tearDown(self):
        '''测试报错或者用例不通过则截图'''
        if not testPass(self):
            print('截图: img\\report_img.png <br />')#固定格式,用于报表生成
        print('结束执行<br />')#固定格式,用于报表生成

    @ddt.data(*caseData_excel.next())  
    def test_index(self,test_data):
     
        place_dict={
            'cur_row':test_data['curRow'],#当前execl数据表数据行
            'place_name':test_data['place_name'].strip(), #企业名称
            'industry_name':test_data['industry_name'].strip(), #所属行业
            'person_name':test_data['person_name'].strip(), #法人姓名
            'person_phone':test_data['person_phone'].strip(), #法人电话号码           
            }
        print('备案信息:',place_dict)            
        
        
        '''第一页 选择行业'''
        self.page=placeIndex(self.dr) #企业备案引导首页 元素
        self.assertEqual('新增企业备案' ,self.page.get_page_title(),'页面标题不一致')
        self.page.select_industry(place_dict['industry_name'])
         

        #断言
        if self.page.place_success_name_is_enabled():
            self.assertTrue(1==1,'企业备案成功')
            self.writer_table.modify_cell(place_dict['cur_row'], writer_table.get_cols(),globals()['node_name'])
            self.writer_table.modify_cell(place_dict['cur_row'], writer_table.get_cols()+1,'备案成功')
            log.info("企业备案成功:%s,%s,%s,%s" %(globals()['node_name'],globals()['login_name'],place_dict['industry_name'],place_dict['place_name']))
        else:
            self.assertTrue(1==2,'企业备案失败')
Exemplo n.º 6
0
 def get_img(self):
     jt_path = os.path.join(getcwd.get_cwd(), 'img/')  #拼接截图保存路径
     rq = time.strftime('%Y%m%d%H%M',
                        time.localtime(time.time()))  #按格式获取当前时间
     img_name = jt_path + rq + '.png'  #拼接截图文件名
     # noinspection PyBroadException
     try:
         self.driver.get_screenshot_as_file(img_name)
         log1.info('截图保存成功')
     except BaseException:
         log1.error('截图失败', exc_info=1)
Exemplo n.º 7
0
 def get_img(self):
     '''截图'''
     path = os.path.join(getcwd.get_cwd(), 'screenshots/')  # 拼接截图保存路径
     rq = time.strftime('%Y%m%d%H%M',
                        time.localtime(time.time()))  # 按格式获取当前时间
     screen_name = path + rq + '.png'  # 拼接截图文件名
     try:
         self.driver.get_screenshot_as_file(screen_name)
         log1.info("截图保存成功")
     except BaseException:
         log1.error("截图失败", exc_info=1)
Exemplo n.º 8
0
def test():    
    import getcwd

    srcFilename = 'D:\\work\\昆山\\WHCS_12_05_01.apk'  
    desFilename = os.path.join(getcwd.get_cwd(),"download")  
      
    cmd = [  
        srcFilename,  
        desFilename  
    ]
    print(cmd)
    runCopy(cmd) 
Exemplo n.º 9
0
class test_login(unittest.TestCase):
    '''登录页'''
    #装载测试数据
    execlName = os.path.join(getcwd.get_cwd(),
                             "data\\YDJFN_login_account_app.xlsx")
    caseData_excel = ExcelUtil(execlName, 'Sheet1')
    log.info('装载测试数据成功')

    #测试用例类级的方法,在所有测试用例执行之前执行
    @classmethod
    def setUpClass(self):
        warnings.simplefilter('ignore', ResourceWarning)
        self.dr = AppDriver()
        self.page = pageElements(self.dr)
        log.info('测试App登录功能')

    #测试用例类级的方法,在所有测试用例执行完成后执行
    @classmethod
    def tearDownClass(self):
        self.dr.quit()
        log.info('登录功能测试完成')

    def setUp(self):
        print('case_id: ', self.id(), '开始执行<br />')  #固定格式,用于报表生成

    def tearDown(self):
        '''测试报错或者用例不通过则截图'''
        if not testPass(self):
            print('截图: ', self.dr.getScreenshot(self.id()),
                  '<br />')  #固定格式,用于报表生成
        print('结束执行<br />')  #固定格式,用于报表生成

    @ddt.data(*caseData_excel.next())
    def test_login(self, test_data):
        '''测试登录功能'''
        login_name = test_data['login_name']  #登录账号
        password = test_data['password']  #密码
        ER = test_data['ER']  #预期结果
        desc = test_data['desc']  #测试描述
        AR = ''  #实际结果
        print('测试用例描述:%s' % (desc))
        print('账号:%s' % (login_name))
        print('密码:%s' % (password))

        self.page.input_login_name(login_name)
        self.page.input_password(password)
        self.page.click_login_button()
        if self.page.find_element():
            AR = '登录成功'
        else:
            AR = '登录失败'
        print(AR)
        self.assertEqual(ER, AR)
Exemplo n.º 10
0
def read_data(index=None):
    '''
    :param index:
    :param param:
    :return:
    '''
    path = getcwd.get_cwd()  # 获取相对路径
    yaml_path = os.path.join(path, 'Params\Param\data.yml')  # 获取配置文件路径
    with open(yaml_path, 'rb') as y:
        cont = y.read()  # 获取data.yml所有信息
        yaml.warnings({'YAMLLoadWarning': False})
        cf = yaml.load(cont)
        y.close()
    return cf[index]['data']
Exemplo n.º 11
0
 def __init__(self):
     self.mail_host = cf.get_config("EMAIL", "mail_host")
     self.mail_user = cf.get_config("EMAIL", "mail_user")
     self.mail_pass = cf.get_config("EMAIL", "mail_pass")
     self.mail_port = cf.get_config("EMAIL", "mail_port")
     self.from_ = cf.get_config("EMAIL", 'from')
     self.receiver = cf.get_config("EMAIL", 'receiver')
     self.subject = cf.get_config("EMAIL", "subject")
     self.content = cf.get_config("EMAIL", "content")
     self.logo_image = cf.get_config("EMAIL", "logo_image")
     self.on_off = cf.get_config("EMAIL", "on_off")
     self.me = self.mail_user.split("@")[0] + "<" + self.mail_user + ">"
     self.server = smtplib.SMTP(self.mail_host, port=self.mail_port)
     self.server.login(self.mail_user, self.mail_pass)
     self.logo_image = os.path.join(getcwd.get_cwd(), self.logo_image)
Exemplo n.º 12
0
class test_login(unittest.TestCase):
    '''登录页'''
    #装载测试数据
    execlName=os.path.join(getcwd.get_cwd(),"data\\KS_login_account.xlsx")
    caseData_excel = ExcelUtil(execlName, 'Sheet1')
    log.info('装载测试数据成功')
    
    #测试用例类级的方法,在所有测试用例执行之前执行
    @classmethod
    def setUpClass(self):
        self.dr = PySelenium()
        self.page=pageElements(self.dr)
        self.page.open_browser()
        log.info('测试系统登录功能')
    
    #测试用例类级的方法,在所有测试用例执行完成后执行
    @classmethod
    def tearDownClass(self):
        self.dr.quit()
        log.info('登录功能测试完成')

    def setUp(self):
        print('case_id: ',self.id(),'开始执行<br />') #固定格式,用于报表生成
        self.page.winLocation()
 
    def tearDown(self):
        '''测试报错或者用例不通过则截图'''
        if not testPass(self):
            print('截图: ',self.dr.getScreenshot( self.id()),'<br />')#固定格式,用于报表生成
        print('结束执行<br />')#固定格式,用于报表生成

    @ddt.data(*caseData_excel.next()) 
    def test_login(self,test_data):
        '''测试登录功能'''
        login_name=test_data['login_name'] #登录账号
        password=test_data['password'] #密码
        desc=test_data['desc'] #测试描述
        print('测试用例描述:%s' %(desc))
        print('账号:%s' %(login_name))
        print('密码:%s' %(password))

        self.page.input_login_name(login_name)
        self.page.input_password(password)
        self.page.input_verify_code()
        self.page.click_login_type()
        self.page.click_login_button()
        
        self.assertEqual(self.page.get_page_title(),'行业信息概览') 
Exemplo n.º 13
0
def read_url(index=None):
    '''
    :param index:
    :param param:
    :return:
    '''
    path = getcwd.get_cwd()  # 获取相对路径
    yaml_path = os.path.join(path, 'Params\\Param\\url.yml')  # 获取配置文件路径
    with open(yaml_path, 'rb') as y:
        cont = y.read()  # url.yml所有信息
        yaml.warnings({'YAMLLoadWarning': False})
        cf = yaml.load(cont)
        y.close()
    test_url = read_config.read_config("基础信息", 'url')
    url = '/'.join([test_url,cf[index]['url']])
    return url
Exemplo n.º 14
0
def get_log(logger_name):

    #创建一个logger
    logger = logging.getLogger(logger_name)
    logger.setLevel(logging.INFO)

    #设置日志存放路径,日志文件名
    #获取本地时间,转换为设置的格式
    rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
    #设置所有日志和错误日志的存放路径
    path = getcwd.get_cwd()
    #通过getcwd.py文件的绝对路径来拼接日志存放路径
    all_log_path = os.path.join(path, 'Logs/All_Logs/')
    error_log_path = os.path.join(path, 'Logs/Error_Logs/')
    #设置日志文件名
    all_log_name = all_log_path + rq + '.log'
    error_log_name = error_log_path + rq + '.log'

    #创建handler
    #创建一个handler写入所有日志
    fh = logging.FileHandler(all_log_name)
    fh.setLevel(logging.INFO)
    #创建一个handler写入错误日志
    eh = logging.FileHandler(error_log_name)
    eh.setLevel(logging.ERROR)
    #创建一个handler输出到控制台
    ch = logging.StreamHandler()
    ch.setLevel(logging.INFO)

    #定义日志输出格式
    #以时间-日志器名称-日志级别-日志内容的形式展示
    all_log_formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    #以时间-日志器名称-日志级别-文件名-函数行号-错误内容
    error_log_formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(module)s  - %(lineno)s - %(message)s'
    )
    #将定义好的输出形式添加到handler
    fh.setFormatter(all_log_formatter)
    ch.setFormatter(all_log_formatter)
    eh.setFormatter(error_log_formatter)

    #给logger添加handler
    logger.addHandler(fh)
    logger.addHandler(eh)
    logger.addHandler(ch)
    return logger
Exemplo n.º 15
0
def get_log(logger_name):
    #创建一个logger
    logger = logging.getLogger(logger_name)
    logger.setLevel(logging.INFO)

    #设置日志存放路径,日志文件名
    # 获取本地时间,设置时间格式
    rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
    #设置日志存放路径
    path = get_cwd()
    #通过获取到的路径更新日志路径
    all_log_path = os.path.join(path, 'Logs/All_Logs/')
    error_log_path = os.path.join(path, 'Logs/Error_Logs/')
    #设置日志名称
    all_log_name = all_log_path + rq + '.log'  #以拼接的方式记录文件名称
    error_log_name = error_log_path + rq + '.log'

    #创建handler(日志经办人)
    #创建handler写入所有日志
    fh = logging.FileHandler(all_log_name)
    fh.setLevel(logging.INFO)
    #写入错误日志
    eh = logging.FileHandler(error_log_name)
    eh.setLevel(logging.ERROR)
    #输出到控制台
    ch = logging.StreamHandler()
    ch.setLevel(logging.INFO)

    #定义日志输出格式
    #以时间-日志器名称-日志级别-日志内容的形式展示
    all_log_formatter = logging.Formatter(
        '%(asctime)s-%(name)s-%(levelname)s-%(message)s')
    #以时间-日志器名称-日志级别-文件名-函数行号-错误内容
    error_log_formatter = logging.Formatter(
        '%(asctime)s-%(name)s-%(levelname)s-%(module)s-%(lineno)s-%(message)s')
    #将定义好的输出格式添加到handler
    fh.setFormatter(all_log_formatter)
    eh.setFormatter(error_log_formatter)
    ch.setFormatter(all_log_formatter)

    #给logging添加遭handler
    logger.addHandler(fh)
    logger.addHandler(eh)
    logger.addHandler(ch)
    return logger
Exemplo n.º 16
0
    def __init__(self, logPath="Logs", logName="log.txt"):
        #定义路径, logPath='..\tmp\logs'
        #创建文件,logName='log.txt'
        #默认在这个文件相同路径下创建logs文件夹,在logs文件夹下创建log.txt文件
        #cur_path = os.path.dirname(os.path.realpath(__file__))#当前文件路径
        proj_path = getcwd.get_cwd()  #项目根目录路径,默认在项目根目录下创建日志文件夹

        log_path = os.path.join(proj_path, logPath)  #拼接文件路径
        log_path = log_path.replace("/", "//")
        log_path = log_path.replace("\\", "//")
        if os.path.exists(log_path) and os.path.isdir(log_path):  #如果没有这个文件夹就新建
            pass
        else:
            mkdirs(log_path)

        log_name = os.path.join(log_path, logName)  #拼接文件路径
        #print(log_name)

        #写入日志文件

        #在py3.7出现保存日志文件有中文乱码的情况,需要修改logging文件
        #第1849行,更改为:h = FileHandler(filename, mode,encoding='utf-8')

        #按照级别写入: CRITICAL > ERROR > WARNING > INFO > DEBUG
        logging.basicConfig(
            level=logging.INFO,  #更改level可以控制哪些级别的日志需要写入到日志文件
            format=
            "[%(levelname)s] [%(asctime)s] [pid:%(process)s] [%(filename)s] %(message)s",
            datefmt="%Y-%m-%d %H:%M:%S",
            filename=log_name,
            filemode="a")
        #发送至控制台打印日志信息,注意:控制台打印的日志需要包含在日志文件中
        #按照级别在控制台显示: CRITICAL > ERROR > WARNING > INFO > DEBUG
        console = logging.StreamHandler()
        console.setLevel(
            logging.INFO
        )  #更改setLevel可以控制在控制台显示哪些级别的日志信息,如这里只有大于等于INOF级别的才会在控制台显示
        #formatter = logging.Formatter("[%(levelname)s] %(message)s")
        formatter = logging.Formatter(
            "%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        console.setFormatter(formatter)
        logging.getLogger("").addHandler(console)
Exemplo n.º 17
0
 def __init__(self):
     platformName=Config.config_read('appium', 'platformName')
     deviceName=Config.config_read('appium', 'deviceName')
     platformVersion=Config.config_read('appium', 'platformVersion')
     apkpath = Config.config_read('appium', 'app')
     appPackage = Config.config_read('appium', 'appPackage')
     appActivity = Config.config_read('appium', 'appActivity')
     path = getcwd.get_cwd()
     apk_path = os.path.join(path, apkpath)
     desired_caps = {
         'platformName': platformName,
         'deviceName': deviceName,  # 手机设备名称,通过adb devices查看
         'platformVersion': platformVersion,  # android系统的版本号
         'app': apk_path,
         'appPackage': appPackage,  # apk包名
         'appActivity': appActivity,  # apk的launcherActivity
         'noRset':'true',
         'automationNname':'uiautomator2'
     }
     self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)
     self.driver.implicitly_wait(3)
Exemplo n.º 18
0
 def readCode(self,css):
     accept = False
     code=''
     whileNum=0
     img_path=os.path.join(getcwd.get_cwd(),"img//")
     
     while not accept:
         try:
             whileNum=whileNum+1
             img_name=self.getVerifyImg(img_path,css)
             code=getVerifyCode().getCode(img_path,img_name)        
             #print('code:' + code)
     
             # 如果验证码没有识别正确,可能会弹出提示框,这里我们需要对提示框进行处理        
             # 在页面中寻找提示框
             time.sleep(1)
             res = EC.alert_is_present()(self.driver)
     
             # 如果弹出提示框
             if res:
                 # 点击提示框的确认,从新搜索一遍
                 res.accept()
                 time.sleep(1)
             else:
                 # 说明已经识别成功并搜索成功,跳出循环进行下一步操作
                 accept = True
             
             #如果第一次没有获取到验证码,则重复执行
             if len(code)!=4 and whileNum<10:
                 accept=False
                 #print('读取验证码失败,重复执行第 ',whileNum+1,' 次')
             if whileNum >= 10:
                 raise NameError('读取验证码失败,程序多次尝试任无法获得验证码')
                 
         except UnicodeDecodeError:
             accept = False
             time.sleep(1)            
     return code
Exemplo n.º 19
0
 def savePngName(self, Spath='screenshots',Sname='temp'):
     """
     Sname:自定义图片的名称
     Spath:图片路径
     """
     proj_path=getcwd.get_cwd()
     img_path = os.path.join(proj_path, Spath, time.strftime('%Y-%m-%d', time.localtime(time.time())))#拼接文件路径
     img_path = img_path.replace("/","//")
     img_path = img_path.replace("\\","//")
     #print(img_path)
     mkDirs(img_path)#如果没有这个文件夹就新建
    
     img_type='.png'   
     img_name= time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())) 
     img_name =img_name+"_"+Sname+img_type
     
     re_name=os.path.join(img_path,img_name)
     try:
         self.driver.get_screenshot_as_file(re_name)
         return re_name
     except NameError as e:
         print(e)
         return False
Exemplo n.º 20
0
 def get_img(self):
     """截图"""
     # img文件夹路径
     img_path = os.path.join(getcwd.get_cwd(), 'img/')
     # img文件夹不存在,新建该文件夹
     if not os.path.exists(img_path):
         os.makedirs(img_path)
     # 获取当前日期
     local_date = time.strftime('%Y-%m-%d', time.localtime(time.time()))
     # 日期文件夹路径
     date_file_path = os.path.join(img_path,local_date)
     # 日期文件夹不存在,新建该文件夹
     if not os.path.exists(date_file_path):
         os.makedirs(date_file_path)
     # 截图存放路径
     local_time = time.strftime('%Y-%m-%d %H%M%S', time.localtime(time.time()))
     jt_name = local_time+'.png'
     jt_path = os.path.join(date_file_path, jt_name)
     try:
         self.driver.get_screenshot_as_file(jt_path)
         log1.info('截图保存成功')
     except BaseException:
         log1.error('截图失败', exc_info=1)
Exemplo n.º 21
0
def works():
    execlName = os.path.join(getcwd.get_cwd(), "data\\device_ip.xls")
    reader = ExcelReader(execlName, sheet='test_ip', title_line=False)
    data_table = reader.data
    log.info('Execl文件读取成功')
    writer_table = ExcelAdd(execlName, sheet='test_ip')
    col_Num = writer_table.get_cols()
    writer_table.modify_cell(0, col_Num, 'receive_count')
    writer_table.modify_cell(0, col_Num + 1, 'min_time')
    writer_table.modify_cell(0, col_Num + 2, 'max_time')
    writer_table.modify_cell(0, col_Num + 3, 'avg_time')
    log.info('Execl文件表头写入成功')

    failed = 0
    for i in range(1, len(data_table)):
        ip = data_table[i][1]
        ping = get_ping_result(ip)
        receive_count = ping[0]
        min_time = ping[1]
        max_time = ping[2]
        avg_time = ping[3]

        if receive_count == 0:
            failed = failed + 1
        if min_time == '' and max_time == '' and avg_time == '':
            failed = failed + 1
        writer_table.modify_cell(i, col_Num, receive_count)
        writer_table.modify_cell(i, col_Num + 1, min_time)
        writer_table.modify_cell(i, col_Num + 2, max_time)
        writer_table.modify_cell(i, col_Num + 3, avg_time)
    ret_file = writer_table.save('test112.xls')
    log.info('Execl文件数据保存成功<%s>' % ret_file)

    if failed > 0:
        mail = SendEmail()
        mail.send_mail(files=[ret_file], subject='注意:监控的设备列表中有设备不在线')
Exemplo n.º 22
0
class Mysql():
    '''配置数据库IP,端口等信息,获取数据库连接'''
    path = getcwd.get_cwd()
    config_path = os.path.join(path, 'Config/config.ini')

    def __init__(self):
        self.config = configparser.ConfigParser()
        self.config.read(self.config_path)
        self.host = self.config['db-test']['host']
        self.port = self.config['db-test']['port']
        self.user = self.config['db-test']['user']
        self.password = self.config['db-test']['password']
        self.dbName = self.config['db-test']['dbName']
        self.cursor = None
        self.conn = None

    def connectDB(self):
        try:
            self.conn = pymysql.connect(host=self.host,
                                        port=int(self.port),
                                        user=self.user,
                                        password=self.password,
                                        database=self.dbName)
        except pymysql.Error as e:
            log.error(e)
            return False
            sys.exit()
        self.cursor = self.conn.cursor()
        return True

    # 关闭数据库
    def close(self):
        # 如果数据打开,则关闭;否则没有操作
        if self.conn and self.cursor:
            self.cursor.close()
            self.conn.close()
        return True

    # 执行数据库的sq语句,主要用来做插入操作
    def execute(self, sql, params=None):
        # 连接数据库
        self.connectDB()
        try:
            if self.conn and self.cursor:
                # 正常逻辑,执行sql,提交操作
                self.cursor.execute(sql, params)
                self.conn.commit()
        except pymysql.Error as e:
            log.error("插入数据库失败! sql: %s,params: %s" % (sql, params))
            log.error(e)
            self.close()
            return False
        return True

    # 用来查询表数据
    def fetchall(self, sql, params=None):
        res = ''
        if self.connectDB():
            try:
                self.cursor.execute(sql, params)
                res = self.cursor.fetchall()
            except pymysql.Error as e:
                log.error("查询数据库失败! sql: %s,params: %s" % (sql, params))
                log.error(e)
                self.close()
            return res

    def update(self, sql, params):
        flag = False
        if self.connectDB():
            try:
                self.cursor.execute(sql, params)
                self.conn.commit()
                flag = True
            except pymysql.Error as e:
                flag = False
                log.error("更新数据库失败! sql: %s,params: %s" % (sql, params))
                self.close()
        return flag
Exemplo n.º 23
0
class ConfigParse:
    '''
    解析ini配置文件
    '''
    path = getcwd.get_cwd()
    config_path = os.path.join(path, 'Config/config.ini')

    def __init__(self):
        self.config = configparser.ConfigParser()  # ConfigParser对象实例
        self.config.read(self.config_path)  # 一启动就读取配置文件

    # 添加指定的节
    def add_section(self, section):
        sections = self.config.sections()
        if section in sections:
            return
        else:
            self.config.add_section(section)

    # 移除指定的节
    def remove_section(self, section):
        return self.config.remove_section(section)

    def get(self, section, option):
        return self.config.get(section, option)

    def set(self, section, option, value):
        if self.config.has_section(section):
            self.config.set(section, option, value)

    # 移除指定节内的指定选项
    def remove_option(self, section, option):
        if self.config.has_section(section):
            return self.config.remove_option(section, option)
        return False

    # 返回节内的键值列表
    def items(self, section):
        return self.config.items(section)

    # 返回所有节的列表
    def sections(self):
        return self.config.sections()

    # 返回节内的键列表
    def options(self, section):
        return self.config.options(section)

    # 获取所有收件人邮箱
    def get_Recievers(self, receivers):
        sum = 0
        recieverList = []
        for i in receivers:
            if sum < len(receivers):
                emails = self.get('receivers', i)
                list.append([emails])
                sum += 1
        return recieverList

    # 获取url
    def getUrl(self, section, option, url=None):
        for sec in self.sections():
            if sec == 'url':
                config_url = self.config.get(sec, 'baseUrl')
                if url != None:
                    curryUrl = config_url + url
                    log.info("请求的url:%s" % curryUrl)
                    return curryUrl
                    print(curryUrl)
                else:
                    return config_url
                    print(config_url)
            else:
                return self.config.get(section, option)
Exemplo n.º 24
0
 def upload_att(self,css,att):
     autoit3_path=os.path.join(getcwd.get_cwd(),"api//upload.exe")
     self.getElement(css).click()
     os.system(autoit3_path+' '+att)
Exemplo n.º 25
0
#-*- coding:utf-8 -*-
'''

Created on 2018年9月28日

@author: zhilh

'''
from framework import log
import configparser
import getcwd
import os


configPath = os.path.join(getcwd.get_cwd(),'config', "config.ini") 

class ReadConfig:
    def __init__(self):
        self.cf = configparser.ConfigParser()
        self.cf.read(configPath)

    def get_config(self, field, key):
        '''获取config.ini信息'''
        result = self.cf.get(field, key)
        # log.debug('%s的%s是:%s' % (field, key, result))
        return result

    def set_config(self, field, key, value):
        '''修改config.ini信息'''
        fd = open(configPath, "w")
        self.cf.set(field, key, value)
Exemplo n.º 26
0
# coding:utf-8

import HTMLTestRunner
import getcwd, os, time, unittest
from Common.Email import send_email

case_path = os.path.join(getcwd.get_cwd(), "Cases")
report_path = os.path.join(getcwd.get_cwd(), "Report")

t = time.strftime("%Y%m%d%H%MS", time.localtime(time.time()))
# 报告存放绝对路径
report_real_path = os.path.join(report_path, "report.html")

def all_case():
    discover = unittest.defaultTestLoader.discover(start_dir=case_path, pattern="test*.py", top_level_dir=None)
    return discover

if __name__ == '__main__':
    with open(report_real_path, 'wb') as f:
        runner = HTMLTestRunner.HTMLTestRunner(stream=f, title="登录接口", description="测试结果如下:")
        runner.run(all_case())

    time.sleep(3)

    sender = ""
    password = ""
    address_email = []
    receivers = ",".join(address_email)

    send_email(sender, password, receivers, report_real_path)
Exemplo n.º 27
0
class Industry_Search(unittest.TestCase):
    '''企业变更'''
    #装载测试数据
    execlName=os.path.join(getcwd.get_cwd(),"data\\place_modify_data.xlsx")
    caseData_excel = ExcelUtil(execlName, 'Sheet1')
    log.info('装载测试数据成功')

    @classmethod
    def setUpClass(self):
        self.dr = PySelenium()
        loginGo(self.dr).click_login()#登录系统
        self.menu_page=leftPage(self.dr) #左边菜单元素
        globals()['login_name']=self.menu_page.get_login_name()  #登录用户名
        globals()['node_name']=self.menu_page.get_node_name()    #登录用户所属机构名
        log.info('登录系统成功,开始测试...')
    
    @classmethod
    def tearDownClass(self):
        #self.menu_page.go_login_out()  #退出登录
        #self.dr.quit()  #关闭浏览器
        log.info('测试完成,退出系统,关闭浏览器')
    
    def setUp(self):        
        print('case_id: ',self.id(),'开始执行<br />') #固定格式,用于报表生成
        self.menu_page.go_place_modify()   #点击菜单到 企业变更 功能链接
        self.dr.switchFrame(MAIN_IFRAME)   #指向iframe页,中间数据展示位置
               
    def tearDown(self):
        '''测试报错或者用例不通过则截图'''
        if not testPass(self):
            print('截图: ',self.dr.getScreenshot( self.id()),'<br />')#固定格式,用于报表生成
        print('结束执行<br />')#固定格式,用于报表生成
        self.dr.switchFrameOut()    #指向iframe上一级,左边菜单位置
  
    
    @ddt.data(*caseData_excel.next())  
    def test_index(self,test_data):
        self.page=centerPage(self.dr)
      
        '''企业查询'''
        search_dict={
            'place_name':test_data['place_name'].strip(), #企业名称
            'industry_name':test_data['industry_name'].strip(), #所属行业
            'region_name':test_data['region_name'].strip(), #管辖机构
            'place_code':test_data['place_name'].strip(),#统一社会信用代码/注册号
            #'region_police':test_data['region_police'].strip(), #责任民警
            'person_name':test_data['person_name'].strip(), #法人姓名
            #'person_id_card':test_data['person_id_card'].strip(), #法人证件号码
            'place_type':test_data['place_type'].strip(), #企业类型            
            'operating_state':test_data['operating_state'].strip(), #营业状态
            #'opening_date_from':test_data['opening_date_from'].strip(), #开业时间-开始            
            #'opening_date_to':test_data['opening_date_to'].strip() #开业时间-结束            
            }
        print('查询条件:',search_dict)            
                
        self.page.input_place_name(search_dict['place_name'])#输入企业名称
        self.page.select_industry(search_dict['industry_name'])#所属行业
        if search_dict['region_name']!='':
            self.page.select_region_first_name(search_dict['region_name'])#管辖机构
        #self.page.input_region_police(search_dict['region_police']) #责任民警/编号
        self.page.input_person_name(search_dict['person_name'])#法人姓名
        #self.page.input_person_id_card(search_dict['person_id_card'])#法人身份证
        self.page.select_input_place_type(search_dict['place_type'])#企业类型
        self.page.select_operating_state(search_dict['operating_state'])#经营状态
        #self.page.input_opening_date_from(search_dict['opening_date_from']) #开业时间-开始
        #self.page.input_opening_date_to(search_dict['opening_date_to'])#开业时间-结束
        self.page.click_search_button()
        self.dr.waitSleep(2)
        
        '''断言查询结果:
        1、只验证查询结果第一页数据,只对有查询结果的数据进行准确性验证
        2、根据显示数据,只做部分查询条件验证: 场所名称、所属行业、企业法人、企业类型、经营状态、统一社会信用代码/注册号
        3、其他查询条件犹豫没有对应结果显示在页面,暂时无法验证
        4、查询结果中只要有一条数据验证失败,则这条case不通过,只有全部数据验证通过,这条case才通过
        5、这里只验证查询出来的数据是否正确,没有查询到数据的情况无法验证是否正确
        '''
        if search_dict['place_name']=='' and search_dict['industry_name']=='' and search_dict['person_name']==''  \
        and search_dict['place_type']=='所有' and search_dict['region_name']=='' and search_dict['operating_state']=='所有'  \
        and search_dict['place_code']==''  :
            self.assertTrue(1==2,'查询条件(场所名称、所属行业、企业法人、企业类型、管辖机构、经营状态、统一社会信用代码/注册号)为空,不做变更操作!')        
        table_data=self.page.get_table_data() # 获取查询结果table内的所有数据
        #print(len(table_data),table_data)
        okFlag = -1
        for i in range(len(table_data)):
            #print(search_dict['place_name'],industry_name,': ',table_data[i])
            if int(len(table_data[i])>1):
                okFlag = 0  
                if (table_data[i][0].lower().find(search_dict['place_name'].lower()) != -1 and len(search_dict['place_name']) >0) \
                or ( table_data[i][3].lower() == search_dict['place_code'].lower() and search_dict['place_code']!=''):#验证输入了企业名称时,查询结果企业名称(或者统一社会信用代码/注册号)包含输入的企业名称信息
                    okFlag=1
                if search_dict['industry_name'].lower().find(table_data[i][1].lower()) != -1 and len(search_dict['industry_name'])>0:#验证输入了所属行业时,查询结果包含输入的所属行业信息
                    okFlag=1
                if search_dict['place_type']==table_data[i][2] and search_dict['place_type']!='所有' :#验证输入了企业类型时,查询结果等于输入的企业类型信息
                    okFlag=1
                if table_data[i][4].lower().find(search_dict['person_name'].lower()) != -1 and len(search_dict['person_name'])>0:#验证输入了企业法人时,查询结果包含输入的企业法人信息
                    okFlag=1
                if table_data[i][5].lower().find(search_dict['region_name'].lower()) != -1 and search_dict['region_name']!='':#验证输入了管辖机构时,查询结果包含输入的管辖机构信息,不包含该管辖机构的下属机构
                    okFlag=1
                if search_dict['operating_state'] == table_data[i][6] and search_dict['operating_state']!='所有' :#验证输入了经营状态时,查询结果等于输入的经营状态信息
                    okFlag=1
                if okFlag == 0:
                    self.assertTrue(1==2,'查询结果验证有错!'+str(table_data[i]))
        if okFlag == -1:
            self.assertTrue(1==2,'查询结果为空,不做变更操作!')
        
        #变更,只选取列表的第一条数据
        for i in range(len(table_data)):
            if int(len(table_data[i])>1 ):
                self.page.select_modify_button(i)#选择点击变更按钮
                
                self.dr.waitSleep(3)
                self.dr.mouseScroll(-1000)#滚动鼠标,到页面底部                
                self.page.click_second_button()#点击填写基本信息页面,下一步按钮
                
                self.dr.waitSleep(3)
                self.dr.mouseScroll(-1000)#滚动鼠标,到页面底部                
                self.page.click_third_button()#点击填写附加信息页面,下一步按钮
                
                self.dr.waitSleep(2)
                self.dr.mouseScroll(-1000)#滚动鼠标,到页面底部       
                self.page.click_save_button()#点击填写设备信息页面,保存按钮
                
                if self.page.success_name_is_enabled():
                    self.assertTrue(1==1,'企业变更成功')
                    log.info("企业变更成功,操作员:%s,%s;注销信息:%s,%s,%s,%s" %(globals()['node_name'],globals()['login_name'],table_data[i][0],table_data[i][2],table_data[i][3],table_data[i][4]))
                else:
                    self.assertTrue(1==2,"企业变更失败:%s"%self.page.get_fail_text())
                break
Exemplo n.º 28
0
import os
import getcwd
from framework.u2base import u2base
import uiautomator2 as ui
import time
u2 = u2base()
d = u2.u2driver()
'''d=ui.connect('4f367dbe')
d.app_start('zhongxinjiantou.szkingdom.android.newphone')'''
path = os.path.join(getcwd.get_cwd(), 'screenshots/')
rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
screen_name = path + rq + '.png'
d.screenshot(screen_name)
d(text='理财').click()
d.screenshot(screen_name)
d(text='我知道了').wait(timeout=10.0)
d(text='我知道了').click()
d.screenshot(screen_name)
time.sleep(3)
d.app_stop('zhongxinjiantou.szkingdom.android.newphone')
Exemplo n.º 29
0
from email.mime.multipart import MIMEMultipart
import getcwd
import os
from Logs.log import log1
from Common.Base_test import webrequests
import time

rq = time.strftime('%Y%m%d', time.localtime(time.time()))  #获取本地时间 转换成日期
my_mail = webrequests()
sender = my_mail.confige_get('sender', 'email')  # 发件人邮箱账号
password = my_mail.confige_get('sender', 'password')  # 发件人邮箱密码
usernmae = my_mail.confige_get('sender', 'username')  #发件人姓名
users = my_mail.confige_options('addressed')  #收件人
addressed_eamils = my_mail.get_addkey(users)  #收件人邮箱

path = getcwd.get_cwd()
file = os.path.join(path, 'report/钱包接口自动化测试报告.html')


def mail():
    try:
        # 创建一个带附件的实例
        message = MIMEMultipart()
        message['From'] = formataddr([usernmae,
                                      sender])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
        log1.info('发件人姓名:%s' % usernmae)
        log1.info('发件人邮箱:%s' % sender)
        message['To'] = ';'.join(addressed_eamils)  # 括号里的对应收件人邮箱昵称、收件人邮箱账号
        log1.info('收件人邮箱:' + ';'.join(addressed_eamils))
        message['Subject'] = rq + "钱包接口自动化测试报告.html"  # 邮件的主题,也可以说是标题
Exemplo n.º 30
0
#-*- coding:utf-8 -*-
'''
Created on 2018年9月26日
@author: zhilh
Description: 自动化测试框架主入口 
'''

from framework.HTMLTestRunner import HTMLTestRunner
from framework.Email import SendEmail
from framework import log
import getcwd

import unittest
import time, os

casepath = os.path.join(getcwd.get_cwd(), "testsuites")  #测试用例存放路径
reportpath = os.path.join(getcwd.get_cwd(), "report")  #测试报告存放路径
reportname = time.strftime("%Y%m%d-%H%M%S", time.localtime(
    time.time())) + "-result.html"  #生成的测试报告文件名


def add_case():
    '''加载测试用例'''
    discover = unittest.defaultTestLoader.discover(casepath,
                                                   pattern="test_*_logout.py",
                                                   top_level_dir=None)
    return discover


def run_case():
    '''执行测试用例,生成测试报告'''