python assert: 自动生成错误信息

用过python assert的朋友应该会经常碰到这样的疑惑,如:

    (a,b) = (1,'1')

     assert a==b     # error: AssertionError

在代码调试的时候,很难直观的看出为什么错了,除非写成这样:

    assert 1=='1',  "fact==expect, [fact]=%s, [expect]=%s" % ([a],[b])    # AssertionError: fact==expect, [fact]=[1], [expect]=['1']

但是这样每次都要去写错误信息,用得频繁了会有些繁琐,本文介绍一种【动态断言】的机制,形如:

   assertx('1', "==", 1)   # (%s['f'] == %s['e']), [fact]=['1'], [expe]=[1]

 

代码如下:

 1 #encoding=utf-8
 2 def assertx(fact, expr, expe):
 3     """ #原有的assert看不到表达式内部、且无法自动生成错误信息
 4 if __name__=='__main__':
 5     assertx(1, "!=", 2)
 6     assertx(1, "%s['f'] in %s['e']", [1,11])
 7     assertx([1,100], "%s['e'] in %s['f']", 100)
 8     try:
 9         assertx('1', "==", 1)
10     except StandardError,e:
11         print e   # (%s['f'] == %s['e']), [fact]=['1'], [expe]=[1]
12     
13     try:
14         assertx('1', "not in", ['1'])
15     except StandardError,e:
16         print e  # when typeSimple, assert: expr.find(' ')==-1, [expr]=['not in']
17     """
18     fDc = {'f':fact}
19     eDc = {'e':expe}
20     atFact = expr.find("%s['f']")
21     atExpe = expr.find("%s['e']")
22     if (atFact>-1 and atExpe>-1):       #【type=Custom】
23         exprStr = expr
24         if atFact < atExpe:
25             exprFormat = expr%(fDc,eDc)
26         else:
27             exprFormat = expr%(eDc,fDc)
28     else:                               #【type=Simple】
29         assert expr.find(' ')==-1, \
30                 "when typeSimple, assert: expr.find(' ')==-1, [expr]=%s"%[expr]
31         exprStr = "(%%s['f'] %s %%s['e'])" % expr   # exam: '(%s['f'] == %s['e'])'
32         exprFormat = exprStr%(fDc,eDc)            # exam: '("factValue" == "expeValue")'
33     if not eval(exprFormat):   # exam: "'%s' == '%s'"
34         raise StandardError("""%s, [fact]=%s, [expe]=%s"""%(exprStr,[fact],[expe]))

 

posted on 2016-03-05 15:09  JayveeYao  阅读(1094)  评论(0编辑  收藏  举报

导航