首页 > 解决方案 > 在 with 中使用函数

问题描述

Pythonunittest.Testcase类有一系列检查函数,包括一个检查断言是否被引发的函数:

311 -    def assertRaises(self, excClass, callableObj, *args, **kwargs): 
319          try: 
320              callableObj(*args, **kwargs) 
321          except excClass: 
322              return 
323          else: 
324              if hasattr(excClass,'__name__'): excName = excClass.__name__ 
325              else: excName = str(excClass) 
326              raise self.failureException, "%s not raised" % excName 

用户像这样扩展TestCase和使用上述内容:

with self.AssertRaises(ValueError):
   x = 5/"3"

如果你提出,你就会提出一个错误ValueError

我想取出这个函数TestCase并以同样的方式在我的测试脚本中使用它,但我不知道如何使assertRaises函数在with语句中工作。

如何进行这种转变?我在TestCase 源代码中看不到任何设置上下文的内容。没有__enter__or__exit__功能,TestCase也没有扩展任何东西。

标签: pythonwith-statement

解决方案


推荐阅读