Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python PyTest-登录生产代码_Python_Unit Testing_Logging_Pytest - Fatal编程技术网

Python PyTest-登录生产代码

Python PyTest-登录生产代码,python,unit-testing,logging,pytest,Python,Unit Testing,Logging,Pytest,我有一个简单的模块,其中包含密码解密、文件夹删除等实用方法,这些方法在代码中由其他模块使用。我正在尝试为这些方法编写单元测试 此模块导入另一个名为LogFactory的模块,该模块处理记录器和日志配置 simplemodule.py 问题就出现在这里。日志配置作为INI文件传递给LogFactory模块中的日志模块。整个python代码由一个shell脚本运行,该脚本在运行python模块之前替换INI文件中的某些条目。因此,在生产过程中,一切都顺利进行 问题在于,当pytest导入第一个生产代

我有一个简单的模块,其中包含密码解密、文件夹删除等实用方法,这些方法在代码中由其他模块使用。我正在尝试为这些方法编写单元测试

此模块导入另一个名为LogFactory的模块,该模块处理记录器和日志配置

simplemodule.py 问题就出现在这里。日志配置作为INI文件传递给LogFactory模块中的日志模块。整个python代码由一个shell脚本运行,该脚本在运行python模块之前替换INI文件中的某些条目。因此,在生产过程中,一切都顺利进行

问题在于,当pytest导入第一个生产代码时,当记录器所需的值没有被shell脚本替换时,它会遇到错误

test_simplemodule.py
import simplemodule首先,这似乎指出您可能希望重构日志代码,以避免导入的副作用。正如你刚刚发现的那样,在重要时刻做任何事情都会伤害你

排序后,您应该能够轻松创建一个自动使用装置,该装置将创建一个(虚拟)记录器实例,该实例将在测试期间调用。这可以很简单,因为所有日志记录都是一个noop,或者将其存储起来以在测试断言中进行检查(请参阅pytest capturelog以获取fixture inspiration,它对stdlib日志记录执行此操作)


如果您真的无法重构日志模块以使其正常工作,您可以通过在
pytest\u configure()
hook(并在
pytest\u unconfigure()中还原它)中创建正确的INI文件来解决此问题
,将在py.test执行其测试收集之前调用此挂钩,以便在尝试任何导入之前调用。

感谢@flub的建议。我认为我无法在导入时改变初始化,但我会再看一看。我觉得您在这里指出的更有意义。
from log import LogFactory

log = LogFactory.getlogger(__name__)

def decrypt(pass, key):
   #magic
   log.debug(message)
import simplemodule <----- ERROR, needed values absent from the INI

def test_decryption():
   #test code