资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

Python单元测试中有哪些装饰器

Python单元测试中有哪些装饰器?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

创新互联是专业的珠海网站建设公司,珠海接单;提供成都网站建设、做网站,网页设计,网站设计,建网站,PHP网站建设等专业做网站服务;采用PHP框架,可快速的进行珠海网站开发网页制作和功能扩展;专业做搜索引擎喜爱的网站,专业的做网站团队,希望更多企业前来合作!

Python单元测试unittest中提供了一下四种装饰器实现测试跳过和预期故障。

请查考Python手册中:

#以下装饰器实施测试跳过和预期故障:

@unittest.skip(原因)
Unconditionally skip the decorated test. reason should describe why the test is being skipped.

#无条件跳过装饰测试。 原因应该说明为什么要跳过测试。

@unittest.skipIf(条件,原因)
Skip the decorated test if condition is true.

#如果条件为真,跳过装饰测试。

@unittest.skipUnless(条件,原因)
Skip the decorated test unless condition is true.

# 跳过装饰的测试,除非条件是真的。

@unittest.expectedFailure
Mark the test as an expected failure. If the test fails when run, the test is not counted as a failure.

#将测试标记为预期的失败。 如果测试在运行时失败,则测试不会被视为失败。

(以上采用谷歌翻译,可能会有差异)

好了,写段代码看下,test.py ,使用的Eclipse

#coding:UTF-8
import unittest
from test.test_pprint import uni
class Test_ce(unittest.TestCase):
  a=16
  b=10
  
  @unittest.skip('无条件跳过')
  def test_ce1(self):
    self.assertEqual((self.a-self.b), 16)
    #判断是否相等
    
  @unittest.skipIf(True==1, '条件为真则跳过')
  def test_ce_2(self):
    self.assertFalse(self.a==self.b)
    #判断是否为False
    
  @unittest.skipUnless(1==1, '条件为假则跳过')
  def test_ce_3(self):
    self.assertTrue(self.a>16)
    #判断是否为True

  @unittest.expectedFailure
  def test_ce_4(self):
    self.assertFalse(self.a==16)
    
  @unittest.expectedFailure 
  def test_ce_5(self): 
    self.assertFalse(self.a==15)
    
if __name__ == '__main__':
  unittest.main()

好的,运行一下

ssFxu
======================================================================
FAIL: test_ce_3 (__main__.Test_ce)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "D:\Escplise\workspace\Pytest\src\test001\CE.py", line 20, in test_ce_3
  self.assertTrue(self.a>16)
AssertionError: False is not true

----------------------------------------------------------------------
Ran 5 tests in 0.000s

FAILED (failures=1, skipped=2, expected failures=1, unexpected successes=1)

好的,我们对第1行代码进行分析:

s:全称是skipped(跳过)

s:条件为真,所以也是skipped(跳过)

F:条件为真,所以忽略装饰器,执行断言代码,显然是failures(失败)

x:断言结果显然是失败的,但是这是在我们意料之中,所以是expected failures(预期的失败)

u:断言结果显然是pass,但是我们预计可能不通过,所以是unexpected successes(意想不到的成功)

即第13行代码 所示  FAILED (failures=1, skipped=2, expected failures=1, unexpected successes=1)

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注创新互联行业资讯频道,感谢您对创新互联的支持。


文章名称:Python单元测试中有哪些装饰器
链接URL:http://cdkjz.cn/article/pepghe.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220