'How to mock CONSTANT at Module-imported level

I have some classes that declared like below:

Processor.py

from package.moduleA.moduleB.LogService import LogService
class Processor:
  ....

LogService.py

LOG_PATH = "log/file.txt"
file_handler =TimedRotatingFileHandler(LOG_PATH)

class LogService:
 ....

test.py (test for Processor)

from package.moduleA.moduleB.Processor import Processor
class Test(unittest.TestCase):
  def test_something(self):
    .....

The problem is when I tried to run the unit test by the command below, I got the error because the LOG_PATH is incorrect.

As I know so far, before the test run, it will import the Processor module. The Processor module is depended on the LogService module. Thus, it will scan the LOG_PATH and init the TimedRotatingFileHandler as well. It's happened at module-import level.

coverage run -m unittest discover

Are there anyway to mock / change the value for LOG_PATH?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source