如何在模块导入级别模拟 CONSTANT

发布于 2025-01-15 23:20:50 字数 742 浏览 2 评论 0原文

我有一些类声明如下:

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 (测试处理器)

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

问题是当我尝试通过下面的命令运行单元测试时,我收到错误,因为 LOG_PATH 不正确。

据我所知,到目前为止,在测试运行之前,它将导入Processor模块。 Processor 模块依赖于 LogService 模块。因此,它将扫描 LOG_PATH 并初始化 TimedRotatingFileHandler。它发生在模块导入级别。

覆盖运行-m unittest发现

有没有办法模拟/更改 LOG_PATH 的值?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文