如何使用assertRaises

如何使用assertRaises

本文介绍了如何使用assertRaises()单元测试python类的__init __()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类:

  class MyClass:
def __init __(self,foo):
如果foo!= 1:
raise错误(foo不等于1!)

和一个单元测试,应该确保错误的参数传递给构造函数正确引发错误:

  def testInsufficientArgs(self):
foo = 0
self.assertRaises((Error),myClass = MyClass(Error,foo))

但是我得到...

  NameError:全局名称'Error'是没有定义

为什么?我应该在哪里定义这个Error对象?我以为它是内置的默认异常类型,不是?

解决方案

'这个例子中的'错误'可能是任何异常目的。我想也许你已经阅读了一个代码示例,它使用它作为一个metasyntatic占位符,意思是适当的异常类。



所有异常的基类称为异常',而且它的大多数子类是所涉及的错误类型的描述性名称,例如'OSError','ValueError','NameError','TypeError'。



在这种情况下,适当的错误是'ValueError'(foo的值是错误的,因此是ValueError)。我建议在您的脚本中替换'ErrorError'与'ValueError'。



这是一个完整版本的代码,你正在写,我正在复制一切,因为您的原始示例中您有一个奇怪的关键字参数,您似乎与一个作业混合,我使用的是'failUnless'函数名,因为这是函数的非别名名称:

  class MyClass:
def __init __(self,foo):
如果foo!= 1:
raise ValueError(foo不等于1!)

import unittest
class TestFoo(unittest.TestCase):
def testInsufficientArgs(self):
foo = 0
self.failUnlessRaises(ValueError,MyClass,foo)

如果__name__ =='__main__':
unittest.main()
 
---------------------------------------------- ------------------------
一个测试在0.007s

OK

单元测试库'unittest'有其他单元测试框架修复的缺陷。您将注意到,无法从调用上下文访问异常对象。如果要解决这个问题,您必须在UnitTest的子类中重新定义该方法:



这是一个正在使用的示例:

  class TestFoo(unittest.TestCase):
def failUnlessRaises(self,excClass,callableObj,* args,** kwargs):
try:
callableObj(* args,** kwargs)
except excClass,excObj:
return excObj#实际返回异常对象
else:
如果hasattr (excClass,'__ name__'):excName = excClass .__ name__
else:excName = str(excClass)
raise self.failureException,%s not raise%excName

def testInsufficientArgs(self):
foo = 0
excObj = self.failUnlessRaises(ValueError,MyClass,foo)
self.failUnlessEqual(excObj [0],'foo不等于1! ')

我已从unittest.py的python2.5和mo中复制了failUnlessRaises函数略有差异。


I have a class:

class MyClass:
def __init__(self, foo):
    if foo != 1:
        raise Error("foo is not equal to 1!")

and a unit test that is supposed to make sure the incorrect arg passed to the constructor properly raises an error:

def testInsufficientArgs(self):
    foo = 0
    self.assertRaises((Error), myClass = MyClass(Error, foo))

But I get...

NameError: global name 'Error' is not defined

Why? Where should I be defining this Error object? I thought it was built-in as a default exception type, no?

解决方案

'Error' in this example could be any exception object. I think perhaps you have read a code example that used it as a metasyntatic placeholder to mean, "The Appropriate Exception Class".

The baseclass of all exceptions is called 'Exception', and most of its subclasses are descriptive names of the type of error involved, such as 'OSError', 'ValueError', 'NameError', 'TypeError'.

In this case, the appropriate error is 'ValueError' (the value of foo was wrong, therefore a ValueError). I would recommend replacing 'Error' with 'ValueError' in your script.

Here is a complete version of the code you are trying to write, I'm duplicating everything because you have a weird keyword argument in your original example that you seem to be conflating with an assignment, and I'm using the 'failUnless' function name because that's the non-aliased name of the function:

class MyClass:
    def __init__(self, foo):
        if foo != 1:
            raise ValueError("foo is not equal to 1!")

import unittest
class TestFoo(unittest.TestCase):
    def testInsufficientArgs(self):
        foo = 0
        self.failUnlessRaises(ValueError, MyClass, foo)

if __name__ == '__main__':
    unittest.main()

The output is:

.
----------------------------------------------------------------------
Ran 1 test in 0.007s

OK

There is a flaw in the unit testing library 'unittest' that other unit testing frameworks fix. You'll note that it is impossible to gain access to the exception object from the calling context. If you want to fix this, you'll have to redefine that method in a subclass of UnitTest:

This is an example of it in use:

class TestFoo(unittest.TestCase):
    def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
        try:
            callableObj(*args, **kwargs)
        except excClass, excObj:
            return excObj # Actually return the exception object
        else:
            if hasattr(excClass,'__name__'): excName = excClass.__name__
            else: excName = str(excClass)
            raise self.failureException, "%s not raised" % excName

    def testInsufficientArgs(self):
        foo = 0
        excObj = self.failUnlessRaises(ValueError, MyClass, foo)
        self.failUnlessEqual(excObj[0], 'foo is not equal to 1!')

I have copied the failUnlessRaises function from unittest.py from python2.5 and modified it slightly.

这篇关于如何使用assertRaises()单元测试python类的__init __()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 08:00