0

I have a code in python as below:

import logging

def method():
  value = get_value()
  if value is not None:
    do_something()
  else:
    logging.critical("value cannot be None")

I wanted to write a unit-test to cover both of the above scenarios. The first case for success was easy. But for the failure scenario, what is the correct way to catch that logging.critical was called?

I tried to put the method inside try-except block and it works.

... Mock required function and specify return values ...
try:
  method()
except Exception as ex:
  import traceback
  traceback.format_exc()

Though the above method works, I don't think I correctly captured that logging.critical was called rather than an exception being raised. What is the correct way to go about it?

1 Answer 1

1

You could mock the logger. But, you are currently using the default logger, which you'd rather not mock. You could change your code to use a module specific logger:

import logging

logger = logging.getLogger(__name__)

def method():
  value = get_value()
  if value is not None:
    return True
  else:
    logger.critical("value cannot be None")

Instead of method accessing that global logger object, you could pass a Logger object as an argument to method, or have a class around method and make a Logger object a class member, etc.

However, staying with the example as it is, you can then mock this logger object and assert that it is called as expected:

import unittest
import unittest.mock

class TestStringMethods(unittest.TestCase):

    def test_method_withNone_shallLogCritical(self):
        # setup
        global logger
        tmpLogger = logger
        logger = unittest.mock.Mock()

        # exercise
        method()

        # verify
        logger.critical.assert_called() # python >= 3.6

        # teardown
        logger = tmpLogger
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.