Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Python's nosetests results in a tearDown() method

Tags:

python

nose

I want to be able to get the result of a particular test method and output it inside the teardown method, while using the nose test runner. There is a very good example here.

But unfortunately, running nosetests example.py does not work, since nose doesn't seem to like the fact that the run method in the superclass is being overridden:

AttributeError: 'ResultProxy' object has no attribute 'wasSuccessful'
like image 784
Rafael Avatar asked Aug 16 '12 03:08

Rafael


People also ask

What is Nosetests 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.

How are test failures identified in Python?

If the test fails, an exception will be raised with an explanatory message, and unittest will identify the test case as a failure. Any other exceptions will be treated as errors.

Can pytest run Nose tests?

pytest has basic support for running tests written for nose.

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

Caveat: the following doesn't actually access the test during the tearDown, but it does access each result.

You might want to write a nose plugin (see the API documentation here). The method that you are probably interested in is afterTest(), which is run... after the test. :) Though, depending on your exact application, handleError()/handleFailure() or finalize() might actually be more useful.

Here is an example plugin that accesses the result of a test immediately after it is executed.

from nose.plugins import Plugin
import logging
log = logging.getLogger('nose.plugins.testnamer')

class ReportResults(Plugin):
    def __init__(self, *args, **kwargs):
        super(ReportResults, self).__init__(*args, **kwargs)
        self.passes = 0
        self.failures = 0
    def afterTest(self, test):
        if test.passed:
            self.passes += 1
        else:
            self.failures += 1
    def finalize(self, result):
        print "%d successes, %d failures" % (self.passes, self.failures)

This trivial example merely reports the number of passes and failures (like the link you included, but I'm sure you can extend it to do something more interesting (here's another fun idea). To use this, make sure that it is installed in Nose (or load it into a custom runner), and then activate it with --with-reportresults.

like image 186
dbn Avatar answered Sep 23 '22 09:09

dbn