问题描述
我的项目中有两个不同的模块.一个是包含的配置文件
I have two different modules in my project. One is a config file which contains
LOGGING_ACTIVATED = False
该常量在第二个模块中使用(如下称其为main),如下所示:
This constant is used in the second module (lets call it main) like the following:
if LOGGING_ACTIVATED:
amqp_connector = Connector()
在主模块的测试类中,我想用值修补此常量
In my test class for the main module i would like to patch this constant with the value
True
不幸的是,以下内容不起作用
Unfortunately the following doesn't work
@patch("config.LOGGING_ACTIVATED", True)
这项工作也没有:
@patch.object("config.LOGGING_ACTIVATED", True)
有人知道如何修补来自不同模块的常量吗?
Does anybody know how to patch a constant from different modules?
推荐答案
如果if LOGGING_ACTIVATED:
测试发生在模块级别,则需要确保尚未首先导入该模块.模块级代码仅运行一次(第一次将模块导入任何地方),因此您无法测试不会再次运行的代码.
If the if LOGGING_ACTIVATED:
test happens at the module level, you need to make sure that that module is not yet imported first. Module-level code runs just once (the first time the module is imported anywhere), you cannot test code that won't run again.
如果测试在函数中,请注意,使用的全局名称为LOGGING_ACTIVATED
,不是 config.LOGGING_ACTIVATED
.因此,您需要在此处修补main.LOGGING_ACTIVATED
:
If the test is in a function, note that the global name used is LOGGING_ACTIVATED
, not config.LOGGING_ACTIVATED
. As such you need to patch out main.LOGGING_ACTIVATED
here:
@patch("main.LOGGING_ACTIVATED", True)
这是您要替换的实际参考.
as that's the actual reference you wanted to replace.
另请参见 在何处进行修补部分 mock
文档.
您应该考虑将模块级代码重构为更可测试的内容.尽管您可以通过从sys.modules
映射中删除模块对象来强制重新加载模块代码,但是将想要测试的代码移入函数中是一种较干净的方法.
You should consider refactoring module-level code to something more testable. Although you can force a reload of module code by deleting the module object from the sys.modules
mapping, it is plain cleaner to move code you want to be testable into a function.
因此,如果您的代码现在看起来像这样:
So if your code now looks something like this:
if LOGGING_ACTIVATED:
amqp_connector = Connector()
考虑改用函数:
def main():
global amqp_connector
if LOGGING_ACTIVATED:
amqp_connector = Connector()
main()
或产生具有均匀属性的对象.
or produce an object with attributes even.
这篇关于如何在python中修补常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!