执行多线程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执行

#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执行

#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,
    ])

 

上一篇:华为思科笔试题


下一篇:全csdn最全最详细的Pytest自动化测试框架实战,封神级讲解