def throw_up(something, gowrong=False):""">>> throw_up('Fish n Chips')Traceback (most recent call last):...Exception: Fish n Chips
>>> throw_up('Fish n Chips', gowrong=True)'I feel fine!'"""if gowrong:return "I feel fine!"raise Exception(something)
if __name__ == '__main__':import doctestdoctest.testmod()
from testcase import TestCase
import mymod
class MyTestCase(TestCase):def test1(self):self.assertRaisesWithMessage(SomeCoolException,'expected message',mymod.myfunc)
import unittest
def broken_function():raise Exception('This is broken')
class MyTestCase(unittest.TestCase):def test(self):with self.assertRaises(Exception) as context:broken_function()
self.assertTrue('This is broken' in context.exception)
if __name__ == '__main__':unittest.main()
import unittest
class TestClass():def raises_exception(self):raise Exception("test")
class MyTestCase(unittest.TestCase):def test_if_method_raises_correct_exception(self):test_class = TestClass()# note that you dont use () when passing the method to assertRaisesself.assertRaises(Exception, test_class.raises_exception)
def square_value(a):"""Returns the square value of a."""try:out = a*aexcept TypeError:raise TypeError("Input should be a string:")
return out
以下是要执行的测试(仅插入此测试):
import dum_function as df # import function moduleimport unittestclass Test(unittest.TestCase):"""The class inherits from unittest"""def setUp(self):"""This method is called before each test"""self.false_int = "A"
def tearDown(self):"""This method is called after each test"""pass#---## TESTSdef test_square_value(self):# assertRaises(excClass, callableObj) prototypeself.assertRaises(TypeError, df.square_value(self.false_int))
if __name__ == "__main__":unittest.main()
我们现在准备测试我们的函数!这是尝试运行测试时发生的事情:
======================================================================ERROR: test_square_value (__main__.Test)----------------------------------------------------------------------Traceback (most recent call last):File "test_dum_function.py", line 22, in test_square_valueself.assertRaises(TypeError, df.square_value(self.false_int))File "/home/jlengrand/Desktop/function.py", line 8, in square_valueraise TypeError("Input should be a string:")TypeError: Input should be a string:
----------------------------------------------------------------------Ran 1 test in 0.000s
FAILED (errors=1)
import unittest
class DeviceException(Exception):def __init__(self, msg, code):self.msg = msgself.code = codedef __str__(self):return repr("Error {}: {}".format(self.code, self.msg))
class MyDevice(object):def __init__(self):self.name = 'DefaultName'
def setParameter(self, param, value):if isinstance(value, str):setattr(self, param , value)else:raise DeviceException('Incorrect type of argument passed. Name expects a string', 100001)
def getParameter(self, param):return getattr(self, param)
class TestMyDevice(unittest.TestCase):
def setUp(self):self.dev1 = MyDevice()
def tearDown(self):del self.dev1
def test_name(self):""" Test for valid input for name parameter """
self.dev1.setParameter('name', 'MyDevice')name = self.dev1.getParameter('name')self.assertEqual(name, 'MyDevice')
def test_invalid_name(self):""" Test to check if error is raised if invalid type of input is provided """
self.assertRaises(DeviceException, self.dev1.setParameter, 'name', 1234)
def test_exception_message(self):""" Test to check if correct exception message and code is raised when incorrect value is passed """
with self.assertRaises(DeviceException) as cm:self.dev1.setParameter('name', 1234)self.assertEqual(cm.exception.msg, 'Incorrect type of argument passed. Name expects a string', 'mismatch in expected error message')self.assertEqual(cm.exception.code, 100001, 'mismatch in expected error code')
if __name__ == '__main__':unittest.main()
def assert_error(e, x):try:e(x)except:returnraise AssertionError()
def failing_function(x):raise ValueError()
def dummy_function(x):return x
if __name__=="__main__":assert_error(failing_function, 0)assert_error(dummy_function, 0)
它在正确的行上失败了:
Traceback (most recent call last):File "assert_error.py", line 16, in <module>assert_error(dummy_function, 0)File "assert_error.py", line 6, in assert_errorraise AssertionError()AssertionError
with self.assertRaises(TypeError):function_raising_some_exception(parameters)
如果我想检查该函数是否正在提升TypeError或IndexError,我会写:
with self.assertRaises((TypeError,IndexError)):function_raising_some_exception(parameters)
如果我想要更多关于异常的细节,我可以在这样的上下文中捕获它:
# Here I catch any exceptionwith self.assertRaises(Exception) as e:function_raising_some_exception(parameters)
# Here I check actual exception type (but I could# check anything else about that specific exception,# like it's actual message or values stored in the exception)self.assertTrue(type(e.exception) in [TypeError,MatrixIsSingular])
def set_string(prop, value):if not isinstance(value, str):raise TypeError("i told you i take strings only ")return value
class BuyVolume(ndb.Model):stock_id = ndb.StringProperty(validator=set_string)
from pytest import raisesbuy_volume_instance: BuyVolume = BuyVolume()with raises(TypeError):buy_volume_instance.stock_id = 25