Python 3.x 使用pytest,如何模拟pathlib';s Path.isdir()函数与os.listdir一起使用
我正在尝试为此函数编写pytest测试。 它查找名为“像一天”的文件夹Python 3.x 使用pytest,如何模拟pathlib';s Path.isdir()函数与os.listdir一起使用,python-3.x,pytest,pytest-mock,Python 3.x,Pytest,Pytest Mock,我正在尝试为此函数编写pytest测试。 它查找名为“像一天”的文件夹 from settings import SCHEDULE from pathlib import Path import os import datetime def get_schedule_dates(): schedule_dates = [] for dir in os.listdir(SCHEDULE): # schedule is a path to a lot of directories
from settings import SCHEDULE
from pathlib import Path
import os
import datetime
def get_schedule_dates():
schedule_dates = []
for dir in os.listdir(SCHEDULE): # schedule is a path to a lot of directories
if Path(SCHEDULE, dir).is_dir():
try:
_ = datetime.datetime.strptime(dir, '%Y-%m-%d')
schedule_dates.append(dir)
except ValueError:
pass
return schedule_dates
mock os.listdir工作正常。(当我关闭isdir检查时)
同时模拟pathlib的路径不起作用:
def test_get_schedule_dates():
with (mock.patch('os.listdir', return_value=['2019-09-15', 'temp']),
mock.patch('pathlib.Path.isdir', return_value=True)):
result = asc.get_schedule_dates()
assert '2019-09-15' in result
assert 'temp' not in result
我得到一个错误:
E AttributeError: __enter__
如何在同一个调用中同时模拟listdir和Path?看起来每个with语句只能使用一个模拟, 用这种方法进行测试是可行的
def test_get_schedule_dates():
with mock.patch('os.listdir', return_value=['2019-09-15', 'temp']):
with mock.patch('pathlib.Path.is_dir', return_value=True):
result = asc.get_schedule_dates()
assert '2019-09-15' in result
assert 'temp' not in result
def test_get_schedule_dates():
with mock.patch('os.listdir', return_value=['2019-09-15', 'temp']):
with mock.patch('pathlib.Path.is_dir', return_value=True):
result = asc.get_schedule_dates()
assert '2019-09-15' in result
assert 'temp' not in result