Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should we test exceptions with nose?

I'm testing exceptions with nose. Here's an example:

def testDeleteUserUserNotFound(self):     "Test exception is raised when trying to delete non-existent users"     try:         self.client.deleteUser('10000001-0000-0000-1000-100000000000')         # make nose fail here     except UserNotFoundException:         assert True 

The assert is executed if the exception is raised, but if no exception is raised, it won't be executed.

Is there anything I can put on the commented line above so that if no exception is raised nose will report a failure?

like image 480
BartD Avatar asked Oct 17 '11 21:10

BartD


People also ask

Which command is used to run nose tests?

nose can be integrated with DocTest by using with-doctest option in athe bove command line. The result will be true if the test run is successful, or false if it fails or raises an uncaught exception. nose supports fixtures (setup and teardown methods) at the package, module, class, and test level.

What is nose test Python?

Nose is a popular test automation framework in Python that extends unittest to make testing easier. The other advantages of using the Nose framework are the enablement of auto discovery of test cases and documentation collection.

What is nose tools?

The nose. tools module provides a number of testing aids that you may find useful, including decorators for restricting test execution time and testing for exceptions, and all of the same assertX methods found in unittest.


1 Answers

nose provides tools for testing exceptions (like unittest does). Try this example (and read about the other tools at Nose Testing Tools

from nose.tools import *  l = [] d = dict()  @raises(Exception) def test_Exception1():     '''this test should pass'''     l.pop()  @raises(KeyError) def test_Exception2():     '''this test should pass'''     d[1]  @raises(KeyError) def test_Exception3():     '''this test should fail (IndexError raised but KeyError was expected)'''     l.pop()  def test_Exception4():     '''this test should fail with KeyError'''     d[1] 

I would think that this is the proper way that you were looking for because it lets you be specific about the exceptions that you expect or want. So you actually provoke the error to see that it raises the right exception. And then you let nose evaluate the result. (Put as little logic into the unit tests as possible!)

like image 142
Malte Avatar answered Sep 24 '22 02:09

Malte