1、无条件跳过skip
比如一个用例正在开发中或者用例废弃了,但是需要保存存档,此时可以加上skip装饰,同时加上跳过的原因,代码如下:
import unittest
class TestDemo01(unittest.TestCase):
@unittest.skip("正在开发中...")
def test_01(self):
print("in test_01...")
def test_02(self):
print("in test_02...")
if __name__ == "__main__":
unittest.main()
执行结果如下:
Skipped: 正在开发中...
in test_02...
Ran 2 tests in 0.002s
OK (skipped=1)
2.有条件跳过skipIf()和skipUnless()
skipIf()当后面的条件为True时跳过,skipUnless()当后面的条件为False时跳过,具体代码实现如下
import unittest
class TestDemo01(unittest.TestCase):
@unittest.skipIf(2 > 1, "不满足执行条件")
def test_01(self):
print("in test_01...")
@unittest.skipUnless(1 > 2, "当前面条件为假时跳过不执行")
def test_02(self):
print("in test_02...")
def test_03(self):
print("in test_03...")
if __name__ == "__main__":
unittest.main()
执行结果如下:
Ran 3 tests in 0.002s
OK (skipped=2)
Skipped: 不满足执行条件
Skipped: 当前面条件为假时跳过不执行
in test_03...
skipIf()和skipUnless()应用于动态的控制用例执行,比如当环境出现什么情况时,此用例执行没有意义了,此时可以通过这个去控制
3、用例失败时忽略expectedFailure
当某个用例失败时想忽略时可以使用expectedFailure去装饰用例,代码如下
import unittest
class TestDemo01(unittest.TestCase):
@unittest.expectedFailure
def test_01(self):
self.assertEqual(1, 2)
print("in test_01...")
def test_02(self):
print("in test_02...")
if __name__ == "__main__":
unittest.main()
执行结果如下:
Ran 2 tests in 0.004s
OK (expected failures=1)
Expected failure: Traceback (most recent call last):
File "D:\ProgrameFile\PyCharm 2020.1\plugins\python\helpers\pycharm\teamcity\diff_tools.py", line 32, in _patched_equals
old(self, first, second, msg)
File "d:\python39\lib\unittest\case.py", line 831, in assertEqual
assertion_func(first, second, msg=msg)
File "d:\python39\lib\unittest\case.py", line 824, in _baseAssertEqual
raise self.failureException(msg)
AssertionError: 1 != 2
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "d:\python39\lib\unittest\case.py", line 59, in testPartExecutor
yield
File "d:\python39\lib\unittest\case.py", line 593, in run
self._callTestMethod(testMethod)
File "d:\python39\lib\unittest\case.py", line 550, in _callTestMethod
method()
File "G:\src\UT\demo\test01.py", line 8, in test_01
self.assertEqual(1, 2)
File "D:\ProgrameFile\PyCharm 2020.1\plugins\python\helpers\pycharm\teamcity\diff_tools.py", line 38, in _patched_equals
raise error
teamcity.diff_tools.EqualsAssertionError: :: 1 != 2
in test_02...