【selenium】Unittest跳过测试和预期失败

一、 跳过测试

Unittest 支持跳过单个或整组的测试用例,跳过测试的方式:

  1. 通过条件判断跳过单个测试用例执行,如:@unittest.skipIf(3>2,"条件成立跳过")
  2. 通过调用 skipTest() 跳过单个测试用例执行
  3. 通过 @unittest.skip() 装饰器跳过整组的测试用例

1.通过条件判断跳过单个测试用例执行

test_case_skip_01.py

import unittest
import sys
# 通过skip装饰器中的条件判断是否跳过用例的用法
class TestCaseSkip01(unittest.TestCase):

    @unittest.skip("无条件跳过")
    def test_01(self):
        print("test_01")

    @unittest.skipIf(3>2,"条件成立跳过")
    def test_02(self):
        print("test_02")

    @unittest.skipUnless(1<0,"跳过这个用例,除非条件为真才执行")
    def test_03(self):
        print("test_03")

    @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
    def test_windows_support(self):
        print("在windows上才会执行")

# 执行结果:
# Skipped: 无条件跳过
# Skipped: 条件成立跳过
# Skipped: 跳过这个用例,除非条件为真才执行
# 在windows上才会执行

2.通过调用 skipTest() 跳过单个测试用例执行

test_case_skip_02.py


import unittest
# 通过条件判断,直接调用skipTest()跳过执行
class TestCaseSkip02(unittest.TestCase):

    def external_resource_available(self):
        """"伪代码:外部资源是否可用的判断方法"""
        return False  # 表示外部资源不可用

    def test_maybe_skipped(self):
        if self.external_resource_available() == False:
            self.skipTest("external resource not available")  #调用skipTest()跳过执行
        # test code that depends on the external resource
        print("test_maybe_skipped") # if条件成立,用例会被跳过,此行不会被执行,
if __name__ == '__main__':
    unittest.main()

# 执行结果:
# OK (skipped=1)

3. 通过 @unittest.skip() 装饰器跳过整组的测试用例

test_case_skip_03.py

import unittest
'''
使用@unittest.skip()装饰器,跳过整个测试类
整个类中的测试用例都不会执行
'''
@unittest.skip("showing class skipping")
class MySkippedTestCase(unittest.TestCase):
    def test_not_run1(self):
        print("test_not_run1")
    def test_not_run2(self):
        print("test_not_run2")

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

# 执行结果
# Ran 2 tests in 0.004s
# OK (skipped=2)
# Process finished with exit code 0
# Skipped: showing class skipping
# Skipped: showing class skipping

二、预期失败

多用于编写异常场景的测试用例,举个例子
正常场景:用户名正确、密码正确 —> 登录响应—>断言code=200
异常场景:用户名正确、密码传空 —> 登录响应—> 断言code= 200 断言是失败的,但测试验证功能、场景是正常的
示例:

expectedFailure.py

import unittest
import random

class ExpectedFailureTestCase(unittest.TestCase):

    def get_login_code(self,name,password):
        """伪代码,调用login接口获取响应"""
        if (name == "admin" and password == "admin112SS"):
            return 200
        else:
            response_code_list = [400,401,402,403,404]
            return response_code_list[random.randint(0,5)]

    def test_login_success(self):
        """正常场景验证"""
        actual_code = self.get_login_code("admin","admin112SS")
        self.assertEqual(actual_code, 200, "登录成功")

    @unittest.expectedFailure
    def test_login_fail(self):
        """异常场景验证"""
        actual_code = self.get_login_code("admin"," ")
        # print("actual_code=",actual_code)
        self.assertEqual(actual_code, 200, "登录参数错误")  #参数不正确,那么code!=200  但是具体code是多少不一定就是一个固定的404

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

# 执行主要结果:
# Ran 1 test in 0.004s
# 
# OK (expected failures=1)
# ....
#     raise self.failureException(msg)
# AssertionError: 402 != 200 : 登录参数错误
  • test_login_fail() 使用@unittest.expectedFailure 执行的日志: OK (expected failures=1) 代表测试场景通过,如果是接口测试,说明接口正常
  • test_login_fail() 未使用@unittest.expectedFailure 执行的日志:FAILED (failures=1) 测试场景没通过,如果是接口测试,说明接口存在bug

常见的unittest中测试用例执行结果和对应含义

        1、FAILED(errors=1) 可能是本身python编码错误
        2、FAILED (failures=1) 断言没通过,所测的接口或功能异常
        3、OK 断言成功
        4、OK(expected failures = 1) 断言通过,预期失败,所测接口、功能正常
<think>好的,我现在需要帮助用户实现使用Python Selenium结合unittest框架进行Excel数据驱动的自动化测试。首先,我得回忆一下用户提供的引用内容,看看有没有相关的信息可以利用。 根据引用[2],excel_util文件处理Excel的方法,包括获取绝对路径读取数据,这应该是关键部分。用户提到需要将测试数据存储在Excel中,所以首先需要处理如何读取这些数据。可能需要用到xlrd库,如引用[3]中提到的,使用xlrd读取Excel文件。 接下来,用户想结合unittestddt进行数据驱动测试。引用[1][3]都提到了ddt数据驱动,所以需要安装ddt库,并在测试中使用@ddt装饰器。引用[2][3]详细说明了如何将Excel数据与测试结合,比如通过for循环嵌套处理数据格式,使其适合ddt的数据结构。 然后,测试的封装也很重要。引用[3]提到对页面元素定位方法进行封装,如进入课程详情页获取课程名称的方法。这提示我需要创建页面对象模型(POM),提高代码的可维护性。 另外,报告生成部分,引用[5]讨论了使用HTMLTestRunner生成带时间戳的测试报告,避免覆盖。因此,在测试执行完毕后,需要集成HTMLTestRunner,并动态生成报告文件名。 可能还需要截图功能,如引用[4]中的take_screenshot方法,在测试失败时截取屏幕截图,帮助调试。 现在需要把这些步骤整合起来。首先,搭建项目结构,包括data、testcase、page_object、utils、report等文件夹。然后,编写Excel工具类读取数据,使用ddt驱动测试,封装页面对象,处理异常截图,最后生成测试报告。 需要注意的是,用户可能对具体代码实现有疑问,比如如何读取Excel,如何传递参数给测试方法,如何处理动态报告名称。需要详细解释每个步骤,并确保代码示正确无误,符合Pythonunittest的规范。 最后,验证整个流程是否正确,确保数据驱动测试能够按预期运行,测试报告生成,并且截图功能正常工作。如果有遗漏的步骤,比如异常处理或数据格式转换,也需要补充说明。</think>以下是如何使用Python Selenium结合unittest框架实现Excel数据驱动测试的完整实现方案: ### 一、环境准备 1. 安装依赖库 ```python pip install selenium xlrd ddt HTMLTestRunner ``` 2. 创建项目结构 ``` project/ ├── data/ # 测试数据 │ └── test_data.xlsx ├── testcase/ # 测试 │ └── test_login.py ├── page_object/ # 页面对象封装 │ └── login_page.py ├── utils/ # 工具类 │ ├── excel_util.py │ └── driver.py └── report/ # 测试报告截图 ``` ### 二、核心实现步骤 #### 1. Excel数据处理(utils/excel_util.py) ```python import xlrd import os def read_excel(file_name, sheet_name): """读取Excel测试数据[^2]""" data_path = os.path.join(os.path.dirname(__file__), '../data', file_name) workbook = xlrd.open_workbook(data_path) sheet = workbook.sheet_by_name(sheet_name) data = [] for row in range(1, sheet.nrows): # 跳过标题行 row_data = [] for col in range(sheet.ncols): cell_value = sheet.cell_value(row, col) row_data.append(cell_value) data.append(tuple(row_data)) return data ``` #### 2. 测试实现(testcase/test_login.py) ```python import unittest from ddt import ddt, data, unpack from selenium import webdriver from utils.excel_util import read_excel from page_object.login_page import LoginPage @ddt class TestLogin(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = webdriver.Chrome() @data(*read_excel('test_data.xlsx', 'login')) @unpack def test_login(self, username, password, expected_result): """登录测试[^3]""" login_page = LoginPage(self.driver) login_page.open() login_page.input_username(username) login_page.input_password(password) login_page.submit() self.assertIn(expected_result, self.driver.page_source) @classmethod def tearDownClass(cls): cls.driver.quit() ``` #### 3. 页面对象封装(page_object/login_page.py) ```python class LoginPage: def __init__(self, driver): self.driver = driver self.url = "https://example.com/login" def open(self): self.driver.get(self.url) def input_username(self, username): self.driver.find_element_by_id("username").send_keys(username) def input_password(self, password): self.driver.find_element_by_id("password").send_keys(password) def submit(self): self.driver.find_element_by_css_selector("button[type='submit']").click() ``` #### 4. 生成测试报告 ```python import unittest import time from HTMLTestRunner import HTMLTestRunner if __name__ == "__main__": test_dir = './testcase' discover = unittest.defaultTestLoader.discover(test_dir, pattern='test_*.py') # 生成动态报告名称 now = time.strftime("%Y-%m-%d_%H-%M-%S") report_path = f'./report/{now}_result.html' with open(report_path, 'wb') as f: runner = HTMLTestRunner( stream=f, title='自动化测试报告', description='数据驱动测试' ) runner.run(discover) ``` ### 三、执行流程 1. Excel数据格式示: | username | password | expected_result | |----------|----------|------------------| | admin | 123456 | Dashboard | | test | wrong_pw | Invalid login | 2. 运行测试 ```bash python test_login.py ``` ### 四、优化建议 1. 异常处理:添加try-except块处理元素定位异常 2. 截图功能:在tearDown方法中添加失败截图[^4] 3. 数据驱动增强:支持多种数据格式(CSV/JSON) 4. 日志记录:集成logging模块记录执行过程
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值