2016-04-25 82 views
2

我在python中使用assert。 每次断言失败时,我都会收到失败消息,我将把它打印出来。但我想知道是否有任何方式来打印自定义成功的消息,当断言条件通过? 我正在使用py.test框架。python中断言的打印成功消息

例如:

assert self.clnt.stop_io()==1, "IO stop failed" 

对于上述断言我得到的消息“IO停止失败”如果断言失败,但我期待有“IO停止成功”如果断言通过。像

assert self.clnt.stop_io()==1, "IO stop failed", "IO stop succeeded" 

回答

5

是的,最简单的肯定是放置断言下面的打印:

assert self.clnt.stop_io()==1, "IO stop failed" 
print("IO stop passed at location ==1") 
+0

没错。我想过这个。 真正令人担忧的是我们设计的内部框架是在某些情况下忽略某些测试(断言)并继续进行的。 和在这些情况下,这不会是一个虚假的消息,无论断言通过还是失败都会打印出来? – cool77

+0

是的,如果忽略断言,下面的指令将被执行,给你一个错误的反馈。你需要告诉我们这里如何跳过断言。 –

2

如果你真的喜欢冒险的感觉,你可以只写你自己的可扩展的断言包装 - 与您可以指望的断言失败的数量或类似在安静或冗长模式测试中添加功能 如:

def assert(condition, fail_str, suc_str): 
    if condition: 
      print fail_str 
    else: 
      num_tests_passed = num_tests_passed + 1 
      if verbose_enabled: 
       print suc_str 
2

编写一个简单的辅助函数:

def myfunc(msg='assert OK'): 
    print msg 
    return True 

包括在右侧的状态,后and

assert self.clnt.stop_io()==1 and myfunc("IO stop succeeded"), "IO stop failed" 
1

我将结合@dashingdw和@Reblochon面膜液

def my_assert(condition, fail_str, suc_str): 
    assert condition, fail_str 
    print suc_str 

从我的观点。这看起来不那么“危险”,并且您不需要每次插入额外的print行。