6.跳过测试和预期失败

2018-10-30  本文已影响0人  MirrorAi

新增于3.1

unittest支持跳过单独的测试方法和整个测试类。另外,它还支持将测试标记为“预期失败”,表明该测试已被破坏并且执行时将会失败,预期失败不会被作为一个失败统计在测试结果TestResult中。

跳过测试是很简单的,使用skip()装饰器或者它的条件变体之一就可以完成。

最基本的跳过测试就像下面的代码:

class MyTestCase(unittest.TestCase):

  @unittest.skip("demonstrating skipping")
  def test_nothing(self):
    self.fail("shouldn't happen")

  @unittest.skipIf(mylib.__version__ < (1, 3), "not supported in this library version")
  def test_format(self):
    # Tests that work for only a certain version of the library.
    pass

  @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
  def test_windows_support(self):
    # windows specific testing code
    pass

对上面示例略加修改后,具体代码如下:

这是以详细模式运行上面示例的输出:

类也可以像方法一样被跳过:

@unittest.skip("showing class skipping")
class MySkippedTestCase(unittest.TestCase):
  def test_not_run(self):
    pass

TestCase.setUp()也可以用来跳过测试。当需要建立的资源不可用时,这个方法就很有用了。

预期失败使用expectedFailure()装饰器实现。

class ExpectedFailureTestCase(unittest.TestCase):
  @unittest.expectedFailure
  def test_fail(self):
    self.assertEqual(1, 0, "broke")

通过在需要跳过测试时调用skip()装饰器,可以很容易地跳过测试。装饰器会跳过测试,除非传递的对象有某个属性(自定义跳转装饰器):

def skipUnlessHasattr(obj, attr):
  if hasattr(obj, attr):
    return lambda func: func
  return unittest.skip(" {!r} doesn't have {!r}".format(obj, attr))

下面是用来实现测试跳过和预期失败的装饰器:
@unittest.skip(reason)
无条件地跳过被装饰的测试。reason参数应该描述为什么跳过测试。
@unittest.skipIf(condition, reason)
如果condition为真,则跳过被装饰的测试。
@unittest.skipUnless(condition, reason)
除非condition为真,否则跳过被装饰的测试。(即condition为假,就跳过)
@unittest.expectedFailure
标记被装饰的测试为预期失败,如果在执行该测试时失败了,测试结果中是不会记录的。
exception unittest.SkipTest(reason)
在抛出该异常时跳过测试。
通常,你可以使用TestCase.skipTest()或者跳过装饰器中的一个来代替直接抛出异常。
TestCase.skipTest():在测试方法或setUp()期间调用此方法会跳过当前测试。

def download_test_files_if_not_present(self):
  ...
  if not self.use_network:
    raise unittest.SkipTest("Requires download of data from the web")
  ...

跳过的测试不会运行setUp()tearDown()。跳过的类不会运行setUpClass()tearDownClass()。跳过的模块不会运行setUpModule()tearDownModule()

上一篇下一篇

猜你喜欢

热点阅读