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.
- 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?
- How I send or skip something like hardcoded path in unittest e.g. /var/log/info_server.log
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")