Beispiel #1
0
def save_history(history_dir, dist_dir):
    if not os.path.exists(os.path.join(dist_dir, "history")):
        PubMethod.create_dirs(os.path.join(dist_dir, "history"))
    else:
        # 遍历报告report下allure-report下的history目录下的文件
        for file in os.listdir(os.path.join(dist_dir, "history")):
            old_data_dic = {}
            old_data_list = []
            # 1、从report下allure-report下的history目录下的文件读取最新的历史纪录
            with open(os.path.join(dist_dir, "history", file), 'rb') as f:
                new_data = json.load(f)
            # 2、从Report下的history(历史文件信息存储目录)读取老的历史记录
            try:
                with open(os.path.join(history_dir, file), 'rb') as fr:
                    old_data = json.load(fr)
                    if isinstance(old_data, dict):
                        old_data_dic.update(old_data)
                    elif isinstance(old_data, list):
                        old_data_list.extend(old_data)
            except Exception as fe:
                print("{}文件查找失败信息:{},开始创建目标文件!!!".format(history_dir, fe))
                PubMethod.create_file(os.path.join(history_dir, file))
            # 3、合并更新最新的历史纪录到report下的history目录对应浏览器目录中
            with open(os.path.join(history_dir, file), 'w') as fw:
                if isinstance(new_data, dict):
                    old_data_dic.update(new_data)
                    json.dump(old_data_dic, fw, indent=4)
                elif isinstance(new_data, list):
                    old_data_list.extend(new_data)
                    json.dump(old_data_list, fw, indent=4)
                else:
                    print("旧历史数据异常")
Beispiel #2
0
def modify_report_environment_file(report_widgets_dir):
    """
    向environment.json文件添加测试环境配置,展现在allure测试报告中
    @return:
    """
    environment_info = [{
        "name": '测试地址',
        "values": [config_yaml['allure_environment']['URL']]
    }, {
        "name":
        '测试版本号',
        "values": [config_yaml['allure_environment']["version"]]
    }, {
        "name":
        '测试账户',
        "values": [config_yaml['allure_environment']['username']]
    }, {
        "name":
        '测试说明',
        "values": [config_yaml['allure_environment']['description']]
    }]
    # 确保目录存在
    PubMethod.create_dirs(os.path.join(report_widgets_dir, 'widgets'))
    with open('./Report/allure-results/widgets/environment.json',
              'w',
              encoding='utf-8') as f:
        json.dump(environment_info, f, ensure_ascii=False, indent=4)
def get_elem(login_elem_data, elem_name):
    elems_info = PubMethod.read_yaml(login_elem_data)
    print(elems_info)
    for item in elems_info["parameters"]:
        if item["elem_name"] == elem_name:
            elem_locator = ("By.{}".format(item["data"]["method"]),
                            item["data"]["value"])
            method = item["data"]["method"]
            value = item["data"]["value"]
            logging.info("元素定位方式为:{},元素对象值为:{}".format(method, value))
            if method == "ID" and value is not None:
                return elem_locator
            elif method == "XPATH" and value is not None:
                return elem_locator
            elif method == "LINK_TEXT" and value is not None:
                return elem_locator
            elif method == "PARTIAL_LINK_TEXT" and value is not None:
                return elem_locator
            elif method == "NAME" and value is not None:
                return elem_locator
            elif method == "TAG_NAME" and value is not None:
                return elem_locator
            elif method == "CLASS_NAME" and value is not None:
                return elem_locator
            elif method == "CSS_SELECTOR" and value is not None:
                return elem_locator
            else:
                logging.error("该定位方式异常,定位元素值异常,请检查!!!")
Beispiel #4
0
def import_history_data(history_save_dir, result_dir):
    if not os.path.exists(history_save_dir):
        print("未初始化历史数据!!!进行首次数据初始化!!!")
    else:
        # 读取历史数据
        for file in os.listdir(history_save_dir):
            # 读取最新的历史纪录
            with open(os.path.join(history_save_dir, file), 'rb') as f:
                new_data = json.load(f)
            # 写入目标文件allure-result中,用于生成趋势图
            PubMethod.create_file(os.path.join(result_dir, "history", file))
            try:
                with open(os.path.join(result_dir, "history", file),
                          'w') as fw:
                    json.dump(new_data, fw, indent=4)
            except Exception as fe:
                print("文件查找失败信息:{},开始创建目标文件".format(fe))
Beispiel #5
0
    def get_login_url_from_config(self):
        """

        @return: 配置文件URL
        """
        config_info = PubMethod.read_yaml(conf_path)
        print("config_info地址:{}".format(config_info))
        return config_info["test_info"]["test_URL"]
Beispiel #6
0
 def assert_contain_screen_shot(driver, exceptor):
     if not isinstance(exceptor, tuple):
         logging.error('exceptor参数类型错误,必须传元祖类型:exceptor=("xx","xx")')
     else:
         try:
             logging.info("正在进行元素断言:断言方式->%s:是否包含->%s" % (exceptor[0], exceptor[1]))
             assert exceptor[0] in exceptor[1]
         except Exception as e:
             logging.error("断言执行失败,错误信息为:{}".format(e))
             picture_url = PubMethod.screen_picture(driver)
             return picture_url
Beispiel #7
0
 def assert_false_screen_shot(driver, bool_value):
     if not isinstance(bool_value, bool):
         logging.error('bool_value参数类型错误,必须传bool类型:exceptor=Ture/False')
     else:
         try:
             logging.info("正在进行元素断言:断言方式->{}:是否等于False->{}}".format(False, bool_value))
             assert False == bool_value
         except Exception as e:
             logging.error("断言执行失败,错误信息为:{}".format(e))
             picture_url = PubMethod.screen_picture(driver)
             return picture_url
Beispiel #8
0
 def assert_true_screen_shot(driver, bool_value):
     if not isinstance(bool_value, bool):
         logging.error('bool_value参数类型错误,必须传bool类型:exceptor=Ture/False')
     else:
         logging.info("正在进行元素断言:断言方式->%s:是否等于True" % bool_value)
         try:
             assert True == bool_value
         except Exception as e:
             logging.error("断言执行失败,错误信息为:{}".format(e))
             picture_url = PubMethod.screen_picture(driver)
             raise e
Beispiel #9
0
    def __run(self, dir_name, root_dir_name, file_name):
        config_dir_name = os.path.join(root_dir_name, dir_name)
        file_path = os.path.abspath(os.path.join(config_dir_name, file_name))
        try:

            self.info = PubMethod().read_yaml(file_path)['parameters']
            for i in self.info:
                self.elem_name.append(i['elem_name'])
                self.desc.append(i['desc'])
                self.data.append(i['data'])
        except Exception as e:
            logging.error("文件解析失败!{},文件路径:{}".format(e, file_path))
Beispiel #10
0
 def assert_arg_in_list(driver, exceptor):
     if not isinstance(exceptor[1], list):
         logging.error("断言传递参数错误:{}".format(exceptor[1]))
     else:
         logging.info("正在进行元素断言:断言方式->{}:是否位于列表->{}中".format(
             exceptor[0], exceptor[1]))
         try:
             assert exceptor[0] in exceptor[1]
         except Exception as e:
             logging.error("断言执行失败,错误信息为:{}".format(e))
             picture_url = PubMethod.screen_picture(driver)
             raise e
Beispiel #11
0
 def assert_equal_screen_shot(driver, exceptor):
     if not isinstance(exceptor, tuple):
         logging.error('exceptor参数类型错误,必须传元祖类型:exceptor=("xx","xx")')
     else:
         logging.info("正在进行元素断言:断言方式:{}是否等于{}".format(
             exceptor[0], exceptor[1]))
         try:
             assert exceptor[0] == exceptor[1]
         except Exception as e:
             logging.error("断言执行失败,错误信息为:{}".format(e))
             picture_url = PubMethod.screen_picture(driver)
             raise e
Beispiel #12
0
 def assert_lte_screen_shot(driver, exceptor):
     if not isinstance(exceptor, tuple):
         logging.error('exceptor参数类型错误,必须传元祖类型:exceptor=("xx","xx")')
     else:
         logging.info("正在进行元素断言:断言方式->%s:是否小于等于->%s" %
                      (exceptor[0], exceptor[1]))
         try:
             assert int(exceptor[0]) <= int(exceptor[1])
         except Exception as e:
             logging.error("断言执行失败,错误信息为:{}".format(e))
             picture_url = PubMethod.screen_picture(driver)
             raise e
Beispiel #13
0
# -*- coding: utf-8 -*-
# @Time    : 2020/5/27 9:15
# @Author  : luozhongwen
# @Email   : [email protected]
# @File    : conftest.py
# @Software: PyCharm
import os
import pytest
import logging
from appium import webdriver
from Common.publicMethod import PubMethod

appium_config_path = os.path.join(os.path.dirname(__file__), "Conf", "appium_config.yaml")
appium_config = PubMethod.read_yaml(appium_config_path)["appium_config"]


# 定义钩子函数hook进行测试用例name和_nodeid输出
def pytest_collection_modifyitems(items):
    for item in items:
        item.name = item.name.encode("utf-8").decode("unicode_escape")
        print(item)
        logging.info(item.name)
        item._nodeid = item._nodeid.encode("utf-8").decode("unicode_escape")
        logging.info(item._nodeid)


# 定义钩子函数hook实现ios和android系统测试切换
def pytest_addoption(parser):
    parser.addoption("--mobile_system", action="store", default="android", help="choose system version, android or ios")

Beispiel #14
0
# !/user/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/5/12 21:11
# @Author  : chineseluo
# @Email   : [email protected]
# @File    : run.py
# @Software: PyCharm
import os
import sys
import json
import logging
import pytest
from Common.publicMethod import PubMethod

root_dir = os.path.dirname(__file__)
config_yaml = PubMethod.read_yaml("./Conf/config.yaml")


def modify_report_environment_file(report_widgets_dir):
    """
    向environment.json文件添加测试环境配置,展现在allure测试报告中
    @return:
    """
    environment_info = [{
        "name": '测试地址',
        "values": [config_yaml['allure_environment']['URL']]
    }, {
        "name":
        '测试版本号',
        "values": [config_yaml['allure_environment']["version"]]
    }, {
Beispiel #15
0
        @param locator: 定位器
        @return: 返回placeholder属性值
        """
        elem = self.find_element(locator)
        try:
            elem_placeholder_text = elem.get_attribute("placeholder")
            logging.info("该元素对象获取placeholder成功,placeholder值为:{}".format(
                elem_placeholder_text))
        except Exception as e:
            logging.error("该元素对象获取placeholder失败,错误信息为:{}".format(e))
        return elem_placeholder_text

    def check_select_is_existence(self, locator):
        """

        @param locator: 定位器
        @return: 返回TRUE、FALSE
        """
        try:
            elem = self.find_element(locator)
            return True
        except Exception as e:
            return False


if __name__ == "__main__":
    print(conf_path)
    config_info = PubMethod.read_yaml(conf_path)
    print(config_info["test_info"])
Beispiel #16
0
def run_all_case(browser, browser_opt, type_driver, nginx_opt):
    """

    @param browser:传入浏览器,chrome/firefox/ie
    @param browser_opt: 浏览器操作,是否开启浏览器操作窗口,关闭操作窗口效率更高,open or close
    @param type_driver:驱动类型,是本地driver还是远程driver,local or remote
    @param nginx_opt:是否启用nginx测试报告上传功能,在配置了nginx服务器的情况下开启,enable or disable
    @return:
    """
    # 测试结果文件存放目录
    result_dir = os.path.abspath("./Report/{}/allure-result".format(browser))
    # 测试报告文件存放目录
    report_dir = os.path.abspath("./Report/{}/allure-report".format(browser))
    # 测试历史结果文件存放目录,用于生成趋势图
    history_dir = os.path.abspath("./Report/history/{}".format(browser))
    PubMethod.create_dirs(history_dir)
    # 定义测试用例features集合
    allure_features = ["--allure-features"]
    allure_features_list = [
        # 'Register_page_case',
        'Login_page_case'
    ]
    allure_features_args = ",".join(allure_features_list)
    # 定义stories集合
    allure_stories = ["--allure-stories"]
    allure_stories_args = ['']
    allure_path_args = ['--alluredir', result_dir, '--clean-alluredir']
    test_args = [
        '-s', '-q', '--browser={}'.format(browser),
        '--browser_opt={}'.format(browser_opt),
        '--type_driver={}'.format(type_driver)
    ]
    # 拼接运行参数
    run_args = test_args + allure_path_args + allure_features + [
        allure_features_args
    ] + allure_stories + allure_stories_args
    # 使用pytest.main
    pytest.main(run_args)
    # 导入历史数据
    import_history_data(history_dir, result_dir)
    # 生成allure报告,需要系统执行命令--clean会清楚以前写入environment.json的配置
    cmd = 'allure generate ./Report/{}/allure-result -o ./Report/{}/allure-report --clean'.format(
        browser.replace(" ", "_"), browser.replace(" ", "_"))
    logging.info("命令行执行cmd:{}".format(cmd))
    try:
        os.system(cmd)
    except Exception as e:
        logging.error('命令【{}】执行失败!'.format(cmd))
        sys.exit()
    # 定义allure报告环境信息
    modify_report_environment_file(report_dir)
    # 保存历史数据
    save_history(history_dir, report_dir)
    # 报告文件压缩上传
    if nginx_opt == "enable":
        report_file_path = path.join(root_dir, 'report.zip')
        compress_file(report_file_path, path.join(root_dir, 'Report'))
        time.sleep(3)
        up_load_report(report_file_path)
        nginx_report_url = 'http://10.5.16.224/ui/{}/allure-report/index.html'.format(
            browser)
        print("nginx服务器远端访问地址:{}".format(nginx_report_url))
        # 删除本地压缩文件
        if path.exists(report_file_path):
            os.remove(report_file_path)
    elif nginx_opt == "disable":
        logging.info("不开启nginx文件上传功能")
    else:
        logging.error(
            "nginx_opt传递参数错误,请检查参数:{},报告上传nginx服务器失败".format(nginx_opt))
    # 打印url,方便直接访问
    url = '本地报告链接:http://127.0.0.1:63342/{}/Report/{}/allure-report/index.html'.format(
        root_dir.split('/')[-1], browser.replace(" ", "_"))
    print(url)
Beispiel #17
0
# -*- coding: utf-8 -*-
# !/user/bin/env python
# @Time    : 2020/6/4 9:35
# @Author  : luozhongwen
# @Email   : [email protected]
# @File    : elem_params.py
# @Software: PyCharm

import os
from Common.publicMethod import PubMethod
import logging
from selenium.webdriver.common.by import By

pub_api = PubMethod()
root_dir = os.path.dirname(os.path.dirname(__file__))
config_path = os.path.join(root_dir, 'PageObject')
config_path = os.path.abspath(config_path)


class Elem_params:
    def __init__(self, dir_name, file_name, root_dir_name=config_path):
        self.elem_name = []
        self.desc = []
        self.data = []
        self.info = []
        self.__run(dir_name, root_dir_name, file_name)

    def __run(self, dir_name, root_dir_name, file_name):
        config_dir_name = os.path.join(root_dir_name, dir_name)
        file_path = os.path.abspath(os.path.join(config_dir_name, file_name))
        try:
Beispiel #18
0
@Time    : 2020/4/2 14:00
@Auth    : wrc
@Email   : [email protected]
@File    : Log.py
@IDE     : PyCharm
------------------------------------
"""
import logging
import logging.config
from os import path

from Common.publicMethod import PubMethod as pub_api

logger_config_path = path.dirname(__file__)
logging.config.dictConfig(
    pub_api.read_yaml(path.join(logger_config_path, 'logging.config.yml')))


class MyLog:
    def __init__(self):
        self.logger = logging.getLogger('mylogger')

    def __console(self, level, message):
        level = level.upper()
        if level == 'INFO':
            self.logger.info(message)
        elif level == 'DEBUG':
            self.logger.debug(message)
        elif level == 'WARNING':
            self.logger.warning(message)
        elif level == 'ERROR':
Beispiel #19
0
# @File    : conftest.py
# @Software: PyCharm
import os
import pytest
import logging
from selenium import webdriver
from selenium.webdriver import Remote
from Common.publicMethod import PubMethod
from selenium.webdriver.chrome.options import Options as CO
from selenium.webdriver.firefox.options import Options as FO
from selenium.webdriver.ie.options import Options as IEO
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile as FP

# 读取selenium分布式配置文件
selenium_config_path = os.path.join(os.path.dirname(__file__), "Conf", "selenium_config.yaml")
selenium_config = PubMethod.read_yaml(selenium_config_path)


def pytest_addoption(parser):
    """
    定义钩子函数hook进行命令行定义浏览器传参,默认chrome,定义浏览器启动方式传参,默认启动
    @param parser:
    @return:
    """
    # 浏览器选项
    parser.addoption("--browser", action="store", default="chrome", help="browser option: firefox or chrome or ie")
    # 是否开启浏览器界面选项
    parser.addoption("--browser_opt", action="store", default="open", help="browser GUI open or close")
    # driver选项,本地还是远程模式
    parser.addoption("--type_driver", action="store", default="local", help="type of driver: local or remote")
Beispiel #20
0
import imaplib
import json
import time
import sys
import re
import os
import email
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.parser import Parser
from Common.publicMethod import PubMethod
from imapclient import IMAPClient

config_path = os.path.join(os.path.dirname(__file__).split("Common")[0], "Conf/config.yaml")
config_yaml = PubMethod.read_yaml(config_path)
email_info = config_yaml["mail_info"]


class Mail:

    def rec_email(self, sender, pattern):
        """
        根据正则表达式匹配邮件中想要的内容,车载项目在注册确认链接正则(r'<a href="(.*?)"')返回列表中
        第二个元素, 不存在的返回None, 只接收最新的一封邮件
        :param sender: 查找从哪个发件人发送的当天邮件
        :param pattern: 正则表达式
        :return: 返回符合正则表达式的列表
        """
        today_s = str(time.strftime("%d-%b-%Y"))
        server = IMAPClient(host=email_info["imap_server"], ssl=True)