Is it possible to get the results of a test (i.e. whether all assertions have passed) in a tearDown() method? I'm running Selenium scripts, and I'd like to do some reporting from inside tearDown(), however I don't know if this is possible.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
If you are using Python2 you can use the method
_resultForDoCleanups
. This method return aTextTestResult
object:<unittest.runner.TextTestResult run=1 errors=0 failures=0>
You can use this object to check the result of your tests:
If you are using Python3 you can use
_outcomeForDoCleanups
:Name of current test can be retrieved with unittest.TestCase.id() method. So in tearDown you can check self.id().
Example shows how to:
Tested example here works with @scoffey 's nice example.
example of result:
Here's a solution for those of us who are uncomfortable using solutions that rely on
unittest
internals:First, we create a decorator that will set a flag on the
TestCase
instance to determine whether or not the test case failed or passed:This decorator is actually pretty simple. It relies on the fact that
unittest
detects failed tests via Exceptions. As far as I'm aware, the only special exception that needs to be handled isunittest.SkipTest
(which does not indicate a test failure). All other exceptions indicate test failures so we mark them as such when they bubble up to us.We can now use this decorator directly:
It's going to get really annoying writing this decorator all the time. Is there a way we can simplify? Yes there is!* We can write a metaclass to handle applying the decorator for us:
Now we apply this to our base
TestCase
subclass and we're all set:There are likely a number of cases that this doesn't handle properly. For example, it does not correctly detect failed subtests or expected failures. I'd be interested in other failure modes of this, so if you find a case that I'm not handling properly, let me know in the comments and I'll look into it.
*If there wasn't an easier way, I wouldn't have made
_tag_error
a private function ;-)Following on from amatellanes' answer, if you're on Python3.4, you can't use
_outcomeForDoCleanups
. Here's what I managed to hack together:yucky, but it seems to work.
Tested for python 3.7 - sample code for getting info of failing assertion but can give idea how to deal with errors: