[TIP] getting the result of a test in teardown_method?

Mark Roddy markroddy at gmail.com
Tue May 11 09:13:46 PDT 2010


On Tue, May 11, 2010 at 11:33 AM, Mark Roddy <markroddy at gmail.com> wrote:
> On Tue, May 11, 2010 at 10:44 AM, C. Titus Brown <ctb at msu.edu> wrote:
>> On Tue, May 11, 2010 at 11:30:10AM +0200, holger krekel wrote:
>>> > I hope this is where people do Q&A on py.test. Otherwise please direct me to
>>> > the right place.
>>>
>>> Yes, I think so.  Both nose and py.test (not sure about unittest2)
>>> also have their own mailing lists but policies are somewhat unclear.
>>> Often questions touch general testing issues and I find it interesting
>>> to see how a specific tools/other people see it.
>>
>> <moderator hat ON>
>> As long as it doesn't get excessively py.test specific for a long run of
>> messages, multiple times, I think it's fine.  It's not a high-traffic
>> list :)
>> <off>
>>
>> --titus
>> --
>> C. Titus Brown, ctb at msu.edu
>>
>> _______________________________________________
>> testing-in-python mailing list
>> testing-in-python at lists.idyll.org
>> http://lists.idyll.org/listinfo/testing-in-python
>>
>
> It's hacky, but you could accomplish this w/unittest by sub-classing
> TestResult (or more likely _TextTestResult), overriding the
> startTest(test) method and setting an attribute on the test instance
> passed to the test result instance.  Then in your tearDown() you can
> grab the test result object and find the result of the test run
> (though this will take some mucking w/the internal structures of
> TestResult which are not geared for accessing results for a specific
> test.  Due to this you should probably add some convenience methods to
> the TestResult class to make it easier).
>
> You'll also need to inject your new subclass to make sure your
> TestResult gets used instead of the underlying one.  Look at
> TestCase.defaultTestResult() and TextTestRunner._makeResult(),
>
> I'm not advocating this approach, but it will get the job done.
>
> -Mark
>

Here's an example implementation:
http://pastebin.com/rjitVx7P

Alternatively, to avoid the monkey patching and the circular
dependency between test result and the test case object you could just
subclass TestCase and override the run() method to set an attribute
when a failure occurs.  Down side of this is it involves a good deal
of code duplication.  See here:
http://pastebin.com/ivGS2gEL

-Mark



More information about the testing-in-python mailing list