我为一个函数编写了一个测试,该函数将文件从/videos/vid_youtube.mp4重命名为/videos/youtube/vid.mp4。这个测试用Pyfak厨师对fs进行了补丁。
当代码实际上重命名文件时,我会得到这个错误。
FileNotFoundError: [Errno 2] No such file or directory: '/home/user/code/project/test/DLV/videos/vid_youtube.mp4' -> '/home/user/code/project/test/DLV/videos/youtube/vid.mp4'我就是这样建立假厨师的
def setUp(self) -> None:
self.setUpPyfakefs()
self.fs.create_dir(Path(Dirs.VIDEOS)) # /home/user/code/project/test/DLV/videos
self.fs.create_file(Path(Dirs.VIDEOS / "vid_youtube.mp4"))正在测试的代码。
class Files:
@staticmethod
def rename_video_files():
all_files = Collect.video_files()
for files_for_type in all_files:
for file in all_files[files_for_type]:
path = Path(file)
platform = Files.detect_platform(path)
platform_dir = Path(Dirs.VIDEOS, platform)
platform_dir.mkdir(exist_ok=True)
new_name = path.stem.replace(f'_{platform}', '')
new_path = Dirs.VIDEOS / platform / f'{new_name}{path.suffix}'
old_path = Dirs.VIDEOS / path
old_path.rename(new_path) # throws FileNotFoundError我调试了测试和正在测试的方法,甚至将假fs传递给了rename_video_files(冒牌厨师)来检查文件和目录。所有文件和目录看起来都是正确的。
这里出什么问题了?
发布于 2022-04-02 10:27:09
这里的问题很可能是Dirs.VIDEOS的静态初始化。这将在加载时作为pathlib.Path进行初始化,并且在安装pyfakefs时不会进行修补(如果在何处使用unittest.patch进行修补,也会出现同样的问题)。
有两种方法可以解决这个问题:
str路径,并在运行时将其转换为Path,或者使用方法获取路径而不是属性(例如,Dirs.VIDEO()而不是Dirs.VIDEO`)。pyfakefs初始化后重新加载测试代码,它将被正确修补。pyfakefs在setUpPyfakefs中提供了一个论据,它可以这样做:from pyfakefs.fake_filesystem_unittest import TestCase
from my_module import video_files
from my_module.video_files import Dirs, Files
class MyTest(TestCase):
def setUp(self) -> None:
self.setUpPyfakefs(modules_to_reload=[video_files])
self.fs.create_dir(
Path(Dirs.VIDEOS)) # /home/user/code/project/test/DLV/videos
self.fs.create_file(Path(Dirs.VIDEOS / "vid_youtube.mp4"))(假设所测试的代码位于my_module.video_files.py中)
免责声明
我是俾法克厨师的贡献者。
https://stackoverflow.com/questions/71716196
复制相似问题