简体   繁体   中英

Ignore logger function in python unit test case

I am writing test cases for few python programs. I have used a customize logger function.

logger.info("Some text")
logger.error("some text")

Now the logger is a object been created from some other program. I have a program as "logger_1.py" and I am importing the program in my current program to create a logger object.

from logger_1 import getlogger

global logger
logger = getlogger("addaccess", "_log)

In my unit test case I am getting logger is not defined.

How can I skip the statements which starts with logger in the function that been unit tested or any other way I can mock or patch all the logger statements in the function of the program?

There's three options I see:

  1. Don't change anything. Let the logger log and ignore whatever output it produces. Development/Testing/Staging environments should be logging to non-production systems anyway so and output should be able to be discarded without much thought. I'm mostly including this option for the sake of completeness, but for small or unimportant systems this is a valid solution. In your case this also won't work since logger_1.py does not seem to be available during testing.

  2. Change the code creating the logger, or in this case importing it from another place, so that it uses a different, testing-specific logger and output location. Catching that execution environment (command line, import, something else) can be a bit tricky, though. For example in our systems we usually include a

    if __name__ == "__main__": #do something with logger

    block, so that the logger points to somewhere else if the file is called from the command line as compared to being imported into a test suite.

  3. You can mock the logger for each test method with a dummy logger:

     from unittest import mock, TestCase create_dummy_logger(): #create and return a dummy logger pass SomethingTests(TestCase): @mock.patch("getlogger", create_dummy_logger) test_method_that_logs_something(self): pass

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM