【发布时间】:2018-10-02 15:34:04
【问题描述】:
我有一个方法要进行单元测试。该方法需要一个文件路径,然后使用上下文管理器打开该文件路径以解析一个值,然后返回该值,如果它存在的话,足够简单。
@staticmethod
def read_in_target_language(file_path):
"""
.. note:: Language code attributes/values can occur
on either the first or the second line of bilingual.
"""
with codecs.open(file_path, 'r', encoding='utf-8') as source:
line_1, line_2 = next(source), next(source)
get_line_1 = re.search(
'(target-language=")(.+?)(")', line_1, re.IGNORECASE)
get_line_2 = re.search(
'(target-language=")(.+?)(")', line_2, re.IGNORECASE)
if get_line_1 is not None:
return get_line_1.group(2)
else:
return get_line_2.group(2)
出于显而易见的原因,我想避免针对外部文件进行测试,并且不希望创建临时文件。另外,在这种情况下我不能使用 StringIO 。
如何在单元测试用例中模拟 file_path 对象?最终我需要创建一个包含不同值的模拟路径。感谢您提供任何帮助。
【问题讨论】:
标签: python-3.x unit-testing testing mocking