unittest
如果测试用例之间有依赖关系,比如test_1成功才会执行test_2,如果失败则跳过不执行
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/1/12 18:22
# @Author : Zh
# @Email : zhangheng9394@163.com
# @Project : mytest
# @File : unittest_demo.py
# @Software: PyCharm
import unittest
from functools import wraps
def skip_depend(depend=""):
"""
被装饰的用例的依赖用例如果失败、发生错误、跳过,则被装饰的用例会跳过
:param depend: 依赖的用例函数名,默认为空
:return: wrapper_func
"""
def wrapper_func(test_func):
test_func) # @wraps:避免被装饰函数自身的信息丢失 (
def inner_func(self):
if depend == test_func.__name__:
raise ValueError("{} cannot depend on itself".format(depend))
# print("self._outcome", self._outcome.__dict__)
# 此方法适用于python3.4 +
# 如果是低版本的python3,请将self._outcome.result修改为self._outcomeForDoCleanups
# 如果你是python2版本,请将self._outcome.result修改为self._resultForDoCleanups
failures = str([fail[0] for fail in self._outcome.result.failures])
errors = str([error[0] for error in self._outcome.result.errors])
skipped = str([error[0] for error in self._outcome.result.skipped])
flag = (depend in failures) or (depend in errors) or (depend in skipped)
if failures.find(depend) != -1:
# 输出结果 [<__main__.TestDemo testMethod=test_login>]
# 如果依赖的用例名在failures中,则判定为失败,以下两种情况同理
# find()方法:查找子字符串,若找到返回从0开始的下标值,若找不到返回 - 1
test = unittest.skipIf(flag, "{} failed".format(depend))(test_func)
print("用例:", test_func.__name__, "因为依赖用例:", depend, "失败,跳过")
elif errors.find(depend) != -1:
test = unittest.skipIf(flag, "{} error".format(depend))(test_func)
print("用例:", test_func.__name__, "因为依赖用例:", depend, "发送错误,跳过")
elif skipped.find(depend) != -1:
test = unittest.skipIf(flag, "{} skipped".format(depend))(test_func)
print("用例:", test_func.__name__, "因为依赖用例:", depend, "跳过,跳过")
else:
test = test_func
return test(self)
return inner_func
return wrapper_func
class TestDemo(unittest.TestCase):
def test_login(self):
print("test_login")
self.assertEqual(1, 2, "登录失败")
depend="test_login") # 如果 test_login 失败,则跳过该条测试 (
def test_logout(self):
print("test_logout")
self.assertEqual(1, 1)
depend="test_logout") # 如果 test_login 失败,则跳过该条测试 (
def test_logout222(self):
print("test_logout2222")
self.assertEqual(1, 1)
def test_1(self):
print("test-11111111111111111111111111111")
self.assertEqual(1, 1)
depend="test_1") # 如果 test_1 成功,则执行该条测试 (
def test_2(self):
print("test-22222222222222222222222222")
skip("直接跳过") .
def test_a(self):
print("test-aaaaaaaaaaaaaaaaa")
self.assertEqual(1, 1)
depend="test_a") # 如果 test_a 跳过,则该用例也直接跳过 (
def test_b(self):
print("test-bbbbbbbbbbbbbbbbbbb")
def test_error(self):
a
self.assertEqual(1, 1)
depend="test_error") (
def test_error_2(self):
print("test_error_2")
if __name__ == '__main__':
unittest.main()
Python 单元测试unittest
unittest 单元测试