Tuesday, 2 April 2019

Python 2.7 Unittest check if warning is logged

I am trying to write a unit-test for my module that is written in Python 2.7, I can't migrate to 3.x right now. What i want is for this test do is to check if my module generates an warning logs, if it does then capture it. I couldn't find an answer for Python 2.7 from my searching the web and stack-overflow. i have included a simple testable code that you could use to try things out or understand my question better.

UPDATE: Just to clarify i am willing to change my test case i.e test_warning_2 to be able to catch log.warn current implementation of that method is just a place holder.

import logging
import warnings
from unittest import TestCase

def generate_warning_2():
    logging.warn("this is a warning")


def generate_warning_1():
    warnings.warn("this is a warning")


class TestWarning(TestCase):

    def test_warning_1(self):
        warnings.simplefilter("always")
        with warnings.catch_warnings(record=True) as w:
            generate_warning_1()
            self.assertEquals(len(w), 1)

    def test_warning_2(self):
        warnings.simplefilter("always")
        with warnings.catch_warnings(record=True) as w:
            generate_warning_2()
            self.assertEquals(len(w), 1)

Here if you see function generate_warning_2 you will notice i am using conventional python logging warning that is not captured by my test case. I know the reason is because it doesn't use warnings module. I just wanted to show what i want it to do.

The other function generate_warning_1 i use warnings module to capture warning log, this is my current implementation that works fine.

I would like to be able to catch log.warn instead of having to use warning to achieve this. Is this possible in Python 2.7? Please don't provide answers for Python 3.x, as i already know its possible there.

Hope my question is clear, please feel free to ask me questions or edit where appropriate. Any help here is appreciated.



from Python 2.7 Unittest check if warning is logged

No comments:

Post a Comment