示例#1
0
    def __init__(self, logger=None):
        # 创建一个logger
        self.logger = logging.getLogger(logger)  # 创建一个logger
        self.logger.setLevel(logging.DEBUG)  # 指定日志级别

        # 创建一个handle, 用于写入日志文件
        self.log_time = time.strftime("%Y_%m_%d_")
        # 路径需要修改
        self.log_path = project_path() + "/Logs/"
        self.log_name = self.log_path + self.log_time + 'log.log'
        self.file_handle = logging.FileHandler(self.log_name,
                                               'a',
                                               encoding='utf-8')
        self.file_handle.setLevel(logging.INFO)
        """
       设置日志格式
           %(asctime)s         日志事件发生的时间
           %(filename)s        pathname的文件名部分,包含文件后缀
           %(funcName)s        调用日志记录函数的函数名
           %(levelname)s       该日志记录的文字形式的日志级别('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL')
           %(message)s         日志记录的文本内容
       """
        file_formatter = logging.Formatter(
            '[%(asctime)s] %(filename)s->%(funcName)s line:%(lineno)d '
            '[%(levelname)s] %(message)s')
        self.file_handle.setFormatter(file_formatter)
        # 给logger添加handler
        self.logger.addHandler(self.file_handle)
示例#2
0
 def setUpClass(cls):
     cls.data = read_excel(project_path() + 'Data/testdata.xlsx', 0)
     cls.driver = webdriver.Chrome()
     cls.driver.get(config_url())
     cls.driver.maximize_window()
     cls.log = FrameLog()
     cls.logger = cls.log.get_log()
示例#3
0
 def test_search(self):
     self.driver.get(
         "https://trains.ctrip.com/TrainBooking/SearchTrain.aspx")
     self.data = read_xls_by_row(project_path() + "/Data/testdata2.xls", 0)
     search = SearchPage(self.driver)
     res = search.search_train(
         self.data.get(1)[0],
         self.data.get(1)[1],
         self.data.get(1)[2])
     ##新增断言
     self.assertIn('booking', res)
示例#4
0
 def test_01(self):
     self.data = get_exceldata(project_path() + "/Data/testdata2.xls", 0)
     for i in range(len(self.data)):
         self.driver.get(
             "https://trains.ctrip.com/TrainBooking/SearchTrain.aspx")
         print(self.data[i]['leave'], self.data[i]['arrive'],
               self.data[i]['leave_date'])
         # self.driver.get("https://trains.ctrip.com/TrainBooking/SearchTrain.aspx")
         search = SearchPage(self.driver)
         res = search.search_train(self.data[i]['leave'],
                                   self.data[i]['arrive'],
                                   self.data[i]['leave_date'])
         ##新增断言
         self.assertIn('booking', res)
示例#5
0
    def __init__(self, logger=None):
        self.logger = logging.getLogger(logger)
        self.logger.setLevel(logging.DEBUG)
        self.log_time = time.strftime("%Y_%m_%d_")
        self.log_path = project_path() + "Logs\\"
        self.log_name = self.log_path + self.log_time + 'log.log'
        print(self.log_name)
        fh = logging.FileHandler(self.log_name, 'w', encoding='utf-8')
        fh.setLevel(logging.INFO)

        formatter = logging.Formatter(
            '[%(asctime)s]   %(filename)s->%(funcName)s line:%(lineno)d\
                                       [%(levelname)s]%(message)s')
        fh.setFormatter(formatter)
        self.logger.addHandler(fh)
        fh.close()
示例#6
0
def sync_run_case2(browser_name, thread_num=5):
    """
    同时执行不同用例( 通过动态修改'suite.py'文件中'TestSuite'类中的'run'方法,使得每个线程中的结果都可以记录到测试报告中 )
    :param browser_name: 浏览器名称
    :param thread_num: 线程数

    【 备 注 】
     开启浏览器操作(每个用例执行一次):在每个'测试类'的 setUp 方法中执行 ( 继承 ParaCase 父类 )
     关闭浏览器操作(每个用例执行一次):在每个'测试类'的 tearDown 方法中执行 ( 继承 ParaCase 父类 )
    """

    gl.BROWSER_NAME = browser_name
    gl.THREAD_NUM = thread_num

    # 配置需要执行的'测试类'列表
    test_class_list = [TrainTest, DemoTest]

    # 将'测试类'中的所有'测试方法'添加到 suite 对象中
    suite = ParaCase.parametrize(test_class_list=test_class_list)

    # 为实例对象'suite'<TestSuite>动态添加两个方法'run_test_custom'、'show_result_custom'( 目的:供多线程中调用 )
    suite.run_test_custom = MethodType(run_test_custom, suite)
    suite.show_result_custom = MethodType(show_result_custom, suite)

    # 为实例对象'suite'<TestSuite>动态修改实例方法'run'( 目的:启用多线程来执行case )
    suite.run = MethodType(new_run, suite)

    print("实例对象suite是否存在'run_test_custom'方法:" + str(hasattr(suite, "run_test_custom")))
    print("实例对象suite是否存在'show_result_custom'方法:" + str(hasattr(suite, "show_result_custom")))
    print("实例对象suite是否存在'run'方法:" + str(hasattr(suite, "run")))
    print(suite)
    print(suite.__class__)
    print(suite.__class__.__base__)
    print("+++++++++++++++++++++++++++++++++++")

    # 运行内容再控制台显示(verbosity:表示控制台显示内容的等级,大于1时显示的内容更具体)
    # runner = unittest.TextTestRunner(verbosity=1)
    # test_result = runner.run(suite)

    # 运行内容在报告中显示
    now = time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime(time.time()))
    report_path = project_path() + "Reports/" + now + '.html'
    with open(report_path, 'wb') as fp:
        runner = HTMLTestRunner(stream=fp, title='UI自动化测试报告', description='详细测试用例结果', tester="费晓春", verbosity=2)
        test_result = runner.run(suite)
示例#7
0
def run_suite(driver, test_class_list):
    """
    多线程中run方法实际执行的内容
    :param driver:
    :return:
    """
    # 将'测试类'中的所有'测试方法'添加到 suite 对象中
    suite = unittest.TestSuite()
    suite.addTest(ParaCase.parametrize(test_class_list=test_class_list, driver=driver))

    # 运行内容再控制台显示
    # suite = unittest.defaultTestLoader.discover(project_path() + "TestCases", pattern='Train*.py')
    # runner = unittest.TextTestRunner(verbosity=1)
    # test_result = runner.run(suite)
    # print("执行总数 testsRun:" + str(test_result.testsRun))
    # print("执行的用例列表:")
    # print("成功的用例列表:")
    # print("错误的用例列表(错误日志)errors:" + str(test_result.errors))
    # print("失败的用例列表(失败日志)failures:" + str(test_result.failures))
    # print("每个用例的时间:开始时间、结束时间、运行时间:")
    # print()

    # 运行内容再报告中显示
    now = time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime(time.time()))
    report_path = project_path() + "Reports/" + now + '.html'
    with open(report_path, 'wb') as fp:
        runner = HTMLTestRunner(stream=fp, title='自动化测试报告', description='详细测试用例结果', tester="费晓春", verbosity=2)
        test_result = runner.run(suite)

    print(test_result)
    print("执行总数:" + str(test_result.error_count + test_result.success_count + test_result.failure_count))
    print("执行的用例列表:" + str(test_result.result))
    print("错误数:" + str(test_result.error_count))
    print("错误的用例列表:" + str(test_result.errors))
    print("失败数:" + str(test_result.failure_count))
    print("失败的用例列表:" + str(test_result.failures))
    print("成功数:" + str(test_result.success_count))
    print("成功的用例列表:" + str([success[1] for success in test_result.result if success[0] == 0]))
    print("每个用例的时间:开始时间、结束时间、运行时间:")

    for n, t, o, e in test_result.result:
        print(o)
        print("++++++++++")
示例#8
0
def log(str):
    # 创建一个handler,用于写入日志文件
    log_time = time.strftime("%Y_%m_%d_")
    # 路径需要修改
    log_path = project_path() + "/logs/"
    log_name = log_path + log_time + 'log.log'
    print(log_name)
    logging.basicConfig(
        level=logging.DEBUG,
        format=
        '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s %(funcName)s',
        datefmt='%Y-%m-%d %H:%M:%S',
        filename=log_name,
        filemode='w')
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
    console.setFormatter(formatter)
    logging.getLogger('').addHandler(console)
    logging.info(str)
示例#9
0
    def __init__(self, logger=None):

        # 创建一个logger <记录器> 、 <记录器>指定日志级别(决定消息是否要传递给<处理器>)
        self.logger = logging.getLogger(logger)
        self.logger.setLevel(logging.DEBUG)

        # 每个实例对象都要先清空 handlers ,否则会出现重复的日志
        # self.logger.handlers.clear()

        # 判断是否已经添加过 handlers,否则会出现重复的日志记录
        if not self.logger.handlers:
            # 指定日志 存放路径 和 名称
            self.log_path = project_path() + "Logs/"
            self.log_time = time.strftime("%Y_%m_%d_")
            self.log_name = self.log_path + self.log_time + 'log.log'
            # print("日志路径:" + self.log_name)

            # 【 创建 handler <处理器>, 写入日志文件、终端输出 】
            # 1.创建日志句柄:指定日志文件 ( mode:'a'追加、'w'覆盖写入 )
            fh = logging.FileHandler(self.log_name, mode='a', encoding="utf-8")
            ch = logging.StreamHandler()

            # 2.<处理器>句柄指定日级别(决定消息是否要发送至文件和终端)
            fh.setLevel(logging.INFO)
            ch.setLevel(logging.INFO)

            # 3.设置<处理器>句柄的显示格式
            fm = logging.Formatter(
                "[%(asctime)s] %(filename)s -> %(funcName)s line:%(lineno)d [%(levelname)s]  %(message)s"
            )
            fh.setFormatter(fm)
            ch.setFormatter(fm)

            # 4.将<处理器>句柄添加入日志对象
            self.logger.addHandler(fh)
            self.logger.addHandler(ch)

            # 6.关闭<处理器>句柄
            fh.close()
            ch.close()
示例#10
0
 def setUpClass(cls):
     cls.driver = webdriver.Chrome(
         executable_path='D:\chromedriver_win32 (1)\chromedriver.exe')
     user_agent = 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'
     cls.driver.get(project_path())  #config_url)
示例#11
0
        except:
            self.logger.error("用例失败")

    def test_03(self):
        book = BookPage(self.driver)
        res = book.book_btn()
        # 断言当前页面的URL是否包含“InputPassengers”
        self.assertIn("InputPassengers", res)

    def test_04(self):
        order = OrderPage(self.driver)
        res = order.user_info("小王")
        self.assertIn("RealTimePay", res)

    @classmethod
    def tearDownClass(cls):
        cls.log.close_handle()
        cls.driver.close()


if __name__ == '__main__':
    suiteTest = unittest.TestSuite()
    suiteTest.addTest(logingTest("test_02"))
    suiteTest.addTest(logingTest("test_03"))
    suiteTest.addTest(logingTest("test_04"))
    now = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(time.time()))
    filepath = project_path() + 'Reports\\' + now + '.html'
    fp = open(filepath, 'wb')
    runner = HTMLTestRunner(stream=fp, title=u'自动化测试报告', description=u'测试报告')
    runner.run(suiteTest)
    fp.close()
示例#12
0
import unittest
from HTMLTestRunner import HTMLTestRunner
import time
from Common.function import project_path

if __name__ == '__main__':
    test_dir = project_path() + "Testcases"
    tests = unittest.defaultTestLoader.discover(test_dir,
                                                pattern='test*.py',
                                                top_level_dir=None)
    now = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(time.time()))
    filepath = project_path() + "/Report/" + now + '.html'
    fp = open(filepath, 'wb')
    # 定义测试报告的标题和描述
    runner = HTMLTestRunner(stream=fp, title=u'自动化测试报告', description=u'测试报告')
    runner.run(tests)
    fp.close()
示例#13
0
    :return:
    '''
    test_list = []
    testdict = MyClass.__dict__
    if isinstance(cases, str):
        cases = [cases]
    for case in cases:
        tmp_cases = filter(
            lambda cs: cs.startswith(case) and callable(getattr(MyClass, cs)),
            testdict)
        for tmp_case in tmp_cases:
            test_list.append(MyClass(tmp_case))
    suite = unittest.TestSuite()
    suite.addTests(test_list)
    return suite


if __name__ == '__main__':
    test_dir = project_path() + "/TestCases"
    tests = unittest.defaultTestLoader.discover(test_dir,
                                                pattern="Case*.py",
                                                top_level_dir=None)
    now = time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime(time.time()))
    filepath = project_path() + "/Reports" + now + '.html'
    fp = open(filepath, 'wb')
    runner = HTMLTestRunnerCNNew.HTMLTestRunner(stream=fp,
                                                title='WEB-UI自动化测试报告',
                                                description="测试报告")
    runner.run(tests)
    fp.close()
示例#14
0
 def setUpClass(cls):
     cls.data = read_excel(project_path() + "Data/testdata.xlsx", 0)
示例#15
0
		rows_dic = {}
		for y in range(0,rows0_num):
			rows_dic[rows0[y]]=rows_data[y]
		list.append(rows_dic)
	return list

def get_dicvalue(list,key):
    """处理嵌套dict的列表"""
    for i in range(len(list)):
        value = list[i][key]
        print(value)
    return value


if __name__ == '__main__':
    data_01 = read_excel(project_path() + '/Data/testdata2.xls',0)
    data_02 = read_excel_byList(project_path() + '/Data/testdata2.xls',0)
    data_03 = get_exceldata(project_path() + '/Data/testdata2.xls',0)
    data_04 = read_xls_by_row(project_path() + '/Data/testdata2.xls',0)
    print("打印read_excel方法:*********************")
    print(data_01)
    print("打印read_excel_byList方法:*********************")
    print(data_02)
    print("打印get_exceldata方法:*********************")
    print(data_03)
    print("read_xls_by_row:*********************")
    print(data_04)
    print("##########第一种##########")
    print(data_01.get(0))
    print("########第二种############")
    print(data_02.pop(1))
示例#16
0
        # print(res)
        self.assertIn('TESTKM06', res)
        self.driver.close()

    def tearDown(self):
        print('测试结束,关闭浏览器器!')

if __name__ == '__main__':
    report_title = u'登录自动化测试报告'
    # 定义脚本内容,加u为了防止中文乱码
    desc = u'搜索测试详情:'
    # 定义date为日期,time为时间
    date = time.strftime("%Y%m%d")
    time = time.strftime("%Y%m%d%H%M%S")
    # 定义一个测试容器
    testsuite = unittest.TestSuite()
    # 将测试用例添加到容器
    testsuite.addTest(LoginTest("test_login"))
    print("++++开始执行测试++++")
    with open(project_path() + "/Reports/"  + time + ".html", 'wb') as fp:
        runner = HTMLTestRunnerCNNew.HTMLTestRunner(stream=fp, title=report_title, description=desc,verbosity=2,retry=1)
        runner.run(testsuite)
        fp.close()

    '''
    retry,用例执行失败后指定重试次数,
    如果save_last_try 为True ,一个用例仅显示最后一次测试的结果。
                     为Flase,则展示全部测试结果。
    verbosity=2 为信息输出控制台的展示方式
    retry,指定重试次数
    '''
示例#17
0
文件: suite.py 项目: zhaokch/test_git
import unittest
import HTMLTestRunner
from Common.function import project_path
import time

if __name__ == '__main__':
    test_dir = project_path() + 'testcases'
    tests = unittest.defaultTestLoader.discover(test_dir,
                                                pattern='train_*.py',
                                                top_level_dir=None)
    now = time.strftime('%Y-%m-%d-%H_%M_%S', time.localtime(time.time()))
    filepath = project_path() + '/Reports/' + now + '.html'
    fp = open(filepath, 'wb')
    # 定义测试报告都标题和描述
    runner = HTMLTestRunner.HTMLTestRunner(stream=fp,
                                           title=u'自动化测试报告',
                                           description=u'测试报告')
    runner.run(tests)
    fp.close()
示例#18
0
 def setUpClass(cls) -> None:
     cls.data = read_excel(project_path() + "Data/testData.xlsx", 0)
     cls.driver = webdriver.Chrome()
     cls.driver.get(config_url())
     cls.driver.maximize_window()
示例#19
0
        book = BookPage(self.driver)
        res = book.book_btn()
        # 本例断言是根据当前页面的URL来判断的
        self.assertIn('inputPassengers', res)

    def test_order_page(self):
        order = OrderPage(self.driver)
        res = order.user_info("时玉祥", "412726199005045859", "18538187569")
        self.assertIn('orderDetail', res)

    @classmethod
    def tearDownClass(cls) -> None:
        cls.driver.quit()


if __name__ == '__main__':
    suiteTest = unittest.TestSuite()
    suiteTest.addTest(logingTest("test_search_train"))
    suiteTest.addTest(logingTest("test_book_page"))
    suiteTest.addTest(logingTest("test_order_page"))

    now = time.strftime("%Y-%m-%d-%H_%M_%S", time.localtime(time.time()))
    filepath = project_path() + "/Reports/" + now + '.html'
    fp = open(filepath, 'wb')
    # 定义测试报告的标题与描述
    runner = HTMLTestRunner.HTMLTestRunner(stream=fp,
                                           title='自动化测试报告',
                                           description='测试报告')
    runner.run(suiteTest)
    fp.close()