使用unittest.mock.patch断言pathlib.Path.touch特定调用失败的问题求助
使用unittest.mock.patch断言pathlib.Path.touch特定调用失败的问题求助
我在使用pathlib.Path.touch创建文件,想用unittest.mock.patch装饰器在单元测试中断言相关调用,但是遇到了问题。以下是我的代码和测试情况:
sessions.py
from pathlib import Path def generate_folders(paths: list): for p in paths: p.mkdir() Path(p / "output").mkdir() Path(p / "output" / "output_file").touch() Path(p / "session_file").touch()
测试代码
import unittest from unittest.mock import patch from pathlib import Path import sessions class TestSessionsCreation(unittest.TestCase): @patch("os.mkdir") @patch("pathlib.Path.touch") def test_folder_creation(self, touch_mock, mkdir_mock): tags = ["concepts", "models", "animations", "vfx", "sfx", "vo", "music"] paths = sessions.generate_paths(category="character", name="player", tags=tags) sessions.generate_folders(paths) for p in paths: mkdir_mock.assert_any_call(p, 511) mkdir_mock.assert_any_call(p / "output", 511) touch_mock.assert_any_call(Path(p / "output" / "output_file"), 511) touch_mock.assert_any_call(Path(p / "session_file"), 511)
我可以正常断言os.mkdir的文件夹创建,也能确认pathlib.Path.touch被调用过,但用assert_any_call()断言特定调用时总是失败。测试抛出的错误如下:
ssF... ====================================================================== FAIL: test_folder_creation (sessions.tests.sessions_tests.TestSessionsCreation.test_folder_creation) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\juank\AppData\Local\Programs\Python\Python313\Lib\unittest\mock.py", line 1424, in patched return func(*newargs, **newkeywargs) File "C:\Users\juank\dev\projects\python\gamedev_eco\sessions\tests\sessions_tests.py", line 51, in test_folder_creation touch_mock.assert_any_call(Path(p / "output" / "output_file"), 511) ~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\juank\AppData\Local\Programs\Python\Python313\Lib\unittest\mock.py", line 1048, in assert_any_call raise AssertionError( '%s call not found' % expected_string ) from cause AssertionError: touch(WindowsPath('C:/Users/juank/dev/projects/python/gamedev_eco/sessions/character/player/concepts/output/output_file'), 511) call not found ---------------------------------------------------------------------- Ran 6 tests in 0.004s FAILED (failures=1, skipped=2)
让我费解的是,我用pdb调试确认过方法的输入值是完全一致的,但测试还是失败。我也反复检查了os.mkdir和pathlib.Path.touch的装饰器顺序是正确的。另外我也尝试用with语句来patchtouch,测试还是不通过。我搞不清这是代码的问题还是测试的问题,想请教大家有没有什么提示?我哪里做错了?漏掉了什么?
备注:内容来源于stack exchange,提问作者wavesinaroom
相关产品推荐
相关产品推荐

