I'm trying to write a Unit Test for a piece of python code that raises a warning via logger.warn('...')
under certain conditions. How do I assert that this warning has been logged? I noticed that assertLogged
is not available until at least Python 3.4, unfortunately I am in 2.7.
相关问题
- 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
Python 3.4 Added to unittest exactly that feature. See TestCase.assertLogs. The API is really easy to use:
Now, this question is tagged
python2.7
but it will show up when search for similar title forpython + unittest + logging
. And it's pretty easy to back-port that feature to Python2.7, so here it is:Now in your unit-testing modules you can use that class:
In your unit test setup, add a logging handler which buffers records, and remove it during teardown. You can use as a basis a couple of utility classes,
TestHandler
andMatcher
, which are part of the Python test infrastructure. (The link is to Python's default branch, but the classes should be usable in other Python versions). For information on how to use these classes, see this post.