执行多线程unittest和pytest

#codin=utf-8

from selenium import webdriver
from selenium.webdriver.common.by import By
import time, unittest

class TEST1(unittest.TestCase):

    # 类方法(不需要实例化类就可以被类本身调用)
    @classmethod
    def setUpClass(cls): # cls : 表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。
        cls.dr = webdriver.Chrome()

    # 实例化方法(必须实例化类之后才能被调用)
    def test_01(self):  # self : 表示实例化类后的地址id
        self.dr.get("http://www.baidu.com")
        self.dr.find_element(By.ID, "kw").send_keys("线程一")
        self.dr.find_element(By.ID, "su").click()
        time.sleep(3)
        assert self.dr.title == "线程一_百度搜索"

    def test_02(self):
        self.dr.get("http://www.baidu.com")
        self.dr.find_element(By.ID, "kw").send_keys("第二个线程")
        self.dr.find_element(By.ID, "su").click()
        time.sleep(3)
        assert self.dr.title == "第二个线程_百度搜索"

    def test_03(self):
        self.dr.get("http://www.baidu.com")
        self.dr.find_element(By.ID, "kw").send_keys("第3个线程")
        self.dr.find_element(By.ID, "su").click()
        time.sleep(3)
        assert self.dr.title == "第二个线程_百度搜索"

    @classmethod
    def tearDownClass(cls):
        cls().dr.quit()

if __name__ == '__main__':
    unittest.main()

unittest执行

1、根据线程数生成多份测试报告,每个测试报告仅统计当前线程的测试结果

2、没有nth参数,只会有1个报告,但第2个线程运行的结果不能展示在一张报告上

3、每个线程中的用例要至少保证有一个启动/关闭浏览器的代码

#coding=utf-8

import unittest, os, HTMLTestRunner
from tomorrow3 import threads

BASE_DIR = os.path.dirname(os.path.realpath(__file__))
# print(BASE_DIR)
TEST_DIR = os.path.join(BASE_DIR, "test_dir")
REPORT_DIR = os.path.join(BASE_DIR, "test_report")

def test_suits():
    """
    加载所有测试用例
    """
    discover = unittest.defaultTestLoader.discover(
        TEST_DIR,
        pattern="test_*.py"
    )
    return discover

@threads(3) #设置线程数
def run_case(all_case, nth=0):
    report_path = os.path.join(REPORT_DIR, "result{0}.html".format(nth))
    with open(report_path, "wb") as file:
        runner = HTMLTestRunner.HTMLTestRunner(stream=file, title="多线程报告")
        runner.run(all_case)

if __name__ == "__main__":
    cases = test_suits()
    for i, j in zip(cases, range(len(list(cases)))):
        run_case(i, nth=j)

pytest执行

1、pytest实现多线程相对unittest很简单,测试结果也可以在一个测试报告中展示

2、每个用例中都要启动/关闭浏览器的代码,除了消耗启动时间外

3、用例绝对独立性,用例无法依赖上条用例的执行结果

4、不能控制用例的执行顺序

#coding=utf-8

import os, pytest,time

#当前文件所在目录
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
# print(BASE_DIR)
#测试文件目录
TEST_DIR = os.path.join(BASE_DIR, "test_dir")
# print(TEST_DIR)
#测试报告目录
REPORT_DIR = os.path.join(BASE_DIR, "test_report")


if __name__ == '__main__':
    report_date = time.strftime("%Y-%m-%d_%H_%M_%S")
    report_file = os.path.join(REPORT_DIR, str(report_date) + "result.html")
    pytest.main([
        "-n", "3", #设置线程数
        "-v", "-s", TEST_DIR,
        "--html=" + report_file,
    ])

 

posted @ 2021-12-10 00:40  轻幻  阅读(297)  评论(0编辑  收藏  举报