使用 pyfakefs 创建模拟文件夹失败

问题描述 投票:0回答:1

我正在开发一个项目,该项目使用 pyfakefs 来模拟我的文件系统,以测试先前定义的树结构中的文件夹创建和丢失文件夹。我在 Windows 上使用 Python 3.13 并在运行测试后从终端获取以下输出:

终端输出:

(有人有格式化终端输出而不自动语法突出显示的提示吗?)

E
======================================================================
ERROR: test_top_folders_exist (file_checker.tests.file_checker_tests.TestFolderCheck.test_top_folders_exist)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\juank\dev\projects\python\gamedev_eco\file_checker\tests\file_checker_tests.py", line 20, in test_top_folders_exist
    self.fs.create_dir(Path.cwd() / "gdd")
    ~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\juank\AppData\Local\Programs\Python\Python313\Lib\site-packages\pyfakefs\fake_filesystem.py", line 2191, in create_dir
    dir_path = self.absnormpath(dir_path)
  File "C:\Users\juank\AppData\Local\Programs\Python\Python313\Lib\site-packages\pyfakefs\fake_filesystem.py", line 1133, in absnormpath
    path = self.replace_windows_root(path)
  File "C:\Users\juank\AppData\Local\Programs\Python\Python313\Lib\site-packages\pyfakefs\fake_filesystem.py", line 1418, in replace_windows_root
    if path and self.is_windows_fs and self.root_dir:
                                       ^^^^^^^^^^^^^
  File "C:\Users\juank\AppData\Local\Programs\Python\Python313\Lib\site-packages\pyfakefs\fake_filesystem.py", line 357, in root_dir
    return self._mount_point_dir_for_cwd()
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^
  File "C:\Users\juank\AppData\Local\Programs\Python\Python313\Lib\site-packages\pyfakefs\fake_filesystem.py", line 631, in _mount_point_dir_for_cwd
    if path.startswith(str_root_path) and len(str_root_path) > len(mount_path):
       ^^^^^^^^^^^^^^^
AttributeError: 'WindowsPath' object has no attribute 'startswith'

----------------------------------------------------------------------
Ran 1 test in 0.011s

FAILED (errors=1)

测试:

from pyfakefs.fake_filesystem_unittest import TestCase

class TestFolderCheck(TestCase):
    """Test top folders = gdd marketing business"""

    @classmethod
    def setUp(cls):
        cls.setUpClassPyfakefs()
        cls.fake_fs().create_dir(Path.cwd() / "gamedev_eco")
        cls.fake_fs().cwd = Path.cwd() / "gamedev_eco"

    def test_top_folders_exist(self):
        self.fs.create_dir(Path.cwd() / "gdd")

让我感到困惑的是,Setup 类方法可以创建一个文件夹并将 cwd 更改为该新文件夹,但我无法在测试中创建文件夹。

有人有使用 pyfakefs 的经验吗?

有人可以帮我解决这个问题吗?

python mocking python-unittest pyfakefs
1个回答
0
投票

事实证明

fakefs
cls.fake_fs().cwd
需要在
Windows
上转换为 str。正如 Simon 在尝试在他的 Linux 机器上重现问题后在评论中提到的那样,这很可能与平台相关。在这种情况下,代码
cwd
需要这样设置:

`cls.fake_fs().cwd = str(Path.cwd() / "gamedev_co)

© www.soinside.com 2019 - 2024. All rights reserved.