Monday, October 10, 2022

pytest logging into logfile and html reports

 pypi.org/project/pytest-html/

----

pip install pytest-html

py.test --html=report.html


to add console logs to a log file:

log line standard, timestamp : type_of_error/loglevel : testcasename: message

error type: Debug,Info,warning,error,Critical

test_logging.py

import logging

def test_logging:
 logger=logging.getLogger(__name__)

 fileHandler=logger.FileHandler('logfile.log')
 formatter = logging.Formatter("%(asctime)s :%(levelname)s : %(name)s :%(message)s")
 fileHandler.setFormatter(formatter)
 logger.addHandler(fileHandler) #file handler object is passed
 ## setting log level, so below loglelvels will be ignored.say setting error will ignore  debug,info warning.
 logger.setlevel(logging.INFO)
 logger.debug("A debug statement is executed")
 logger.info("infomration statement")
 logger.warning("Something is in warning mode")
 logger.error("A major error has happened")
 logger.critical("Critical issue")


to add console logs using above code to exiting test cases:

BaseClass.py


import logging
class BaseClass:
 def getLogger(self):
   loggerName = inspect.stack()[1][3]
   logger = logging.getLogger(loggerName) ## as __name__ will print this baseclass name
   fileHandler=logger.FileHandler('logfile.log')
   formatter = logging.Formatter("%(asctime)s :%(levelname)s : %(name)s :%(message)s")
   logger.addHandler(fileHandler)
   logger.setlevel(logging.DEBUG)
   return logger

test_fixtureData.py
import pytest
from pytestsDemo.BaseClass import BaseClass

@pytest.mark.usefixtures("dataLoad")
class TestExample2(BaseClass):
  def test_editProfile(self,dataLoad):
    log = self.getLogger()
    log.info(dataLoad[0])
    log.info(dataLoad[2])

when we generate pytest with html reports, this logger object info will be embedded automatically.

No comments:

Post a Comment