Python自动化测试学习(三)— 使用 HTMLTestRunner 生成测试报告

1、HTMLTestRunner介绍

HTMLTestRunner 是 Python 标准库的 unittest 单元测试框架的一个扩展。它生成易于使用的 HTML 测试报告

2、生成测试报告的步骤

1、创建TestSuite实例
2、通过test_suite.addTest()添加测试用例
3、创建报告生成后的文件位置
4、创建报告fs = open(file_path, 'wb')
5、使用HTMLTestRunner.HTMLTestRunner()方法描述测试报告总概况
6、使用runner.run(test_suite)方法运行最后生成测试报告

2、丰富LoginCase测试用例
class TestLoginCase(unittest.TestCase):
    """ 用户登录测试 """
    username = "1521099989"
    password = "wsxcdf"

    def setUp(self):
        self.driver = webdriver.Chrome()
        self.url = "http://mail.163.com/"
        # 打开浏览器
        LoginPage(self.driver).open_browser(self.url)
        sleep(1)

    def test_login_user_or_pwd_error(self):
        """用户名或密码错误"""
        LoginPage(self.driver).login_operation(self.username, self.password)
        try:
            self.assertEqual("15210996111", self.username, "用户名或密码错误")
        except AssertionError:
            print("用户名或密码错误")

        print("测试用例成功")

    def test_login_username_null(self):
        """用户名不能为空"""
        LoginPage(self.driver).login_operation(self.username, self.password)
        try:
            self.assertEqual("wssss", self.password, "用户名不能为空")
        except AssertionError:
            print("密码不能为空")
        print("测试用例成功")

    def test_login_pwd_null(self):
        """密码不能为空"""
        LoginPage(self.driver).login_operation(self.username, self.password)
        try:
            self.assertEqual("wssss", self.password, "密码不能为空")
        except AssertionError:
            print("密码不能为空")
        print("测试用例成功")

    def tearDown(self):
        self.driver.quit()
3、创建生成报告的类
import unittest,time
from src.testcase.TestLoginCase import TestLoginCase
import HTMLTestRunner
class HtmlReport:
    # 创建TestSuite的实例
    test_suite = unittest.TestSuite()
    # 测试用例加入到测试套件中
    test_suite.addTest(TestLoginCase("test_login_user_or_pwd_error"))
    test_suite.addTest(TestLoginCase("test_login_username_null"))
    test_suite.addTest(TestLoginCase("test_login_pwd_null"))
    # 创建报告输入的文件位置
    now_time = time.strftime("%Y%m%d-%H%M%S")
    file_path = "D:\Programs\pythonProject\src\report\report_html\" + now_time + ".html"
    fs = open(file_path, 'wb')
    '''
        stream=fs:指定测试报告文件
        title:标题
        description:描述
    '''
    runner = HTMLTestRunner.HTMLTestRunner(
        stream=fs,
        title="126邮箱测试报告",
        description="用例执行情况,如下图所示:"
    )

    # 执行测试用例
    runner.run(test_suite)
4、运行HtmlReport类,生成HTMLTestRunner测试报告


1、报告中红框信息的显示,是因为TestLoginCase中使用了"""的注释,使用"""注释会在生成报告的时候自动将注释信息注入,注意具体写法和格式
2、报告中最上面的总概述,就是HTMLTestRunner()方法的描述


5、总结

对有些地方理解不是很透彻,如果有不合理的地方,希望能够得到指正,谢谢!

原文地址:https://www.cnblogs.com/liho/p/13847790.html