我编写了一个Python程序,该程序利用resource
Unix系统上的模块执行一些计时操作,但是回退到time
在Windows上使用该模块(因为该resource
模块不可用)。该代码看起来像这样:
try:
import resource
except ImportError:
import time
def fn():
# Implementation using the time module
else:
def fn():
# Implementation using the resource module
但是,else
由于resource
模块在Linux上始终可用,因此我的测试目前仅在块中执行功能。有没有一种方法可以模拟内置模块的不可用性,以便我也可以测试time
基于-based的功能?我仔细阅读了mock
文档,但没有找到关于此的任何信息。
有点混乱,但是您可以创建一个目录,其中包含一个名为的文件,该文件resource.py
引发an ImportError
,并将该目录的路径添加到之前sys.path
。
如果要将模拟测试与未经模拟的测试混合使用,则还必须sys.modules
在想重试导入时从中删除模块,否则,更改sys.path
将无效。如果有子模块,可能还会有其他问题。
概念证明:
mocked_modules/resource.py
:
raise ImportError()
测试代码:
import sys
import os
original_path = sys.path[:]
def reset():
# Teardown
sys.path = original_path[:]
if "resource" in sys.modules:
del sys.modules["resource"]
import resource
print("resource exists")
reset()
sys.path.insert(0, os.path.join(os.getcwd(), "mocked_modules"))
try:
import resource
except ImportError:
print("resource does not exist")
reset()
import resource
print("resource exists")
输出:
resource exists
resource does not exist
resource exists
考虑到警告的数量,这让我有点不安(请参阅此问题),因此,如果是您的代码执行导入,则您可能更喜欢将导入抽象为一个函数并对其进行模拟。或者,您可以公开“使用时间模块的实现”并直接对其进行测试。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句