我正在尝试为此功能编写一个 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
if Path(SCHEDULE, dir).is_dir():
try:
_ = datetime.datetime.strptime(dir, '%Y-%m-%d')
schedule_dates.append(dir)
except ValueError:
pass
return schedule_dates
模拟 os.listdir 工作正常。(当我关闭 isdir 检查时)
from mymod import mycode as asc
import mock
def test_get_schedule_dates():
with mock.patch('os.listdir', return_value=['2019-09-15', 'temp']):
result = asc.get_schedule_dates()
assert '2019-09-15' in result
assert 'temp' not in result
同时模拟 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?