0
votes

There two lines that are not being executed by django tests when they are called as self.assertRaises.

I am using: Python 3.6.9, Django 3, Coverage.

I have this class:

class AverageWeatherService:
    subclasses = WeatherService.__subclasses__()
    valid_services = {
        subclass.service_key: subclass for subclass in subclasses
    }

    @classmethod
    def _check_service(cls, one_service):
        if one_service not in cls.valid_services:
            logger.exception("Not valid service sent")
            raise NotValidWeatherFormException("Not valid service sent")

And I have a local API that is up in my pc.

Then I wrote this test:

def test_integration_average_temp_services_error(self):
    self.assertRaises
    (
        NotValidWeatherFormException,
        AverageWeatherService()._check_service,
        "MyFakeService",
    )

And although the test is successful with assert raises properly used this test is not adding coverage but If I call this method in a wrong way like this one:

def test_integration_average_temp_services_error2(self):
    self.assertRaises
    (
        NotValidWeatherFormException,
        AverageWeatherService()._check_service("MyFakeService")
    )

Then of course I get an error running the test because the exception is raised and not properly catched by assertRaises BUT It adds coverage. If I run this test wrongly I have my code 100% covered. If I use assertRaises as the first way these two lines are not being covered (According to coverage html).

logger.exception("Not valid service sent")
raise NotValidWeatherFormException("Not valid service sent")

Also If I execute the method as the first way, the logger exception is not shown in console and when I run tests as the second way I am able to visualize the logger.exception on the terminal.

Any ideas of what is going on?

Thanks in advance.

1

1 Answers

0
votes

I could solve it.

This is the workaround:

def test_integration_average_temp_services_error(self):
    with self.assertRaises(NotValidWeatherFormException):
        AverageWeatherService()._check_service("MyFakeService")