Patch 'Logging' used as variable - Python Unittest

Viewed 40

Below is sample snippet from my code,

main.py

 import logging
 import centralised_log.log as log #custom module to override logging

 def checkin():
  logger.warning(f"checkin failed - {resp.status_code}  | {resp.text}")


if __name__ == '__main__':
  logging.setLoggerClass(log.Log)
  logging.basicConfig()
  logger = logging.getLogger(__name__)

test_main.py

import main
def test_check_in(self):
  main.checkin()

if I run the above code, It produces below error.

logger.warning(f"checkin failed - {resp.status_code}  | {resp.text}")
NameError: name 'logger' is not defined

what I have done is I have patched the logger as below,

test_main.py

import main
@patch.object(main, "logger", MagicMock())
def test_check_in(self,logger):
  main.checkin()

But this produce below error

raise AttributeError(
            "%s does not have the attribute %r" % (target, name)
        )
AttributeError: <module 'process_service.main' from '/home/user/Documents/projects/my-reader/process_service/main.py'> does not have the attribute 'logger'
  

Can anyone help me with this. I am quite new to this Unittesting.

0 Answers
Related