unit test python code that has configparser reading from config file

Viewed 5187

I'm new to python unit test. I learned and did sample unit test where method accepts input and returns output.

But for code as mentioned below, I've some questions.

  1. How I mock configparser of init method in unittest? Path /config/program.cfg is on production server and not exists in dev directory. program.cfg file exists at other location in code directory. Is there a way to handle that in unittest?
  2. How I send or skip something like hardcoded path in unittest e.g. /var/log/info_server.log
  3. If possible, can you please tell me how would you write unittest for below code using pytest module? This will be helpful to understand the flow and I can do that with rest of code.

    def __init__(self):
        self.setup_logger()
    
        # Read config parameters
        config = configparser.ConfigParser()
        config.read("/config/program.cfg")
        self.host_ip = config.get('default','HostIP')
        self.redis_ip = config.get('default','RedisIP')
        self.redis_port = config.get('default','RedisPort')
        self.info_port = config.get('default','InfoPort')
        self.sqlite_db_file = config.get('default','SQLiteDbFile')
    
        self.connect_redis()
    
    def setup_logger(self):
        #Initialize logger
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.INFO)
    
        # Create a file handler
        handler = logging.FileHandler('/var/log/info_server.log')
        handler.setLevel(logging.INFO)
    
        # Create a logging format
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
    
        # Add the handlers to the logger
        self.logger.addHandler(handler)
    
    def connect_redis(self):
        # Start up a Redis instance
        self.logger.info("Start Redis instance")
        self.ad_info = redis.StrictRedis(host=self.redis_ip, port=self.redis_port, db=0)
    
        if self.ad_info is None:
            self.logger.error("Failed to start Redis instance")
        else:
            self.logger.info("Started Redis instance")
    
1 Answers

Sure, we could mock many things, but a simple re-factoring the class being tested, adding config and log, will make life much easier.

def __init__(self, cfg='/config/program.cfg', log='/var/log/info_server.log'):

In development server where /config/program.cfg is not present, you could just

TheClass(cfg='~/dev.cfg', log='/tmp/dev.log')

self.server_obj.connect_redis() log_mock.logger.info.assert_called_with('Started Redis instance') not working

import logging
logging.getLogger

# <function getLogger at 0x7f3d2ed427b8>
logger = logging.getLogger()
type(logger)
# <class 'logging.RootLogger'>
logger.info
# <bound method Logger.info of <RootLogger root (WARNING)>>

The patch should be sth like this:

with mock.patch.object(logging.RootLogger, 'info') as mock_info:

    server_obj = Server(cfg='sth', log='sth')
    mock_info.assert_called_with('xxx')
Related