单元测试'pathlib.Path.is_文件'在Python 3.x中

2024-06-16 17:45:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我不熟悉Python中的单元测试,在运行测试时遇到了一些问题。我想实现如下测试类,如下所示:https://www.toptal.com/python/an-introduction-to-mocking-in-python,但是稍微 被改进的。 我想用pathlib.Path.is_file代替os.path.isfile。在

这是要测试的实际类:

import os

from pathlib import Path

class FileUtils:

    @staticmethod
    def isFile(file):
        return Path(file).is_file()

    @staticmethod
    def deleteFile(file):
        if FileUtils.isFile(file):
            os.remove(file)

这是测试课:

^{pr2}$

这将导致以下错误消息:

Finding files... done.
Importing test modules ... done.

======================================================================
FAIL: testDeleteFile (FileUtilsTest.FileUtilsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "...\AppData\Local\Continuum\anaconda3\lib\site-packages\mock\mock.py", line 1305, in patched
    return func(*args, **keywargs)
  File "...\FileUtilsTest.py", line 13, in testDeleteFile
    self.assertFalse(osMock.remove.called, 'Failed to not remove the file if not present.')
AssertionError: True is not false : Failed to not remove the file if not present.

----------------------------------------------------------------------
Ran 1 test in 0.003s

FAILED (failures=1)

如何通过使用@mock.patch修饰符测试方法FileUtils.deleteFile?在


Tags: topathinimportifisosnot
1条回答
网友
1楼 · 发布于 2024-06-16 17:45:35

这里的问题是,当您修补模块中的符号Path时,您正在替换Path的构造函数的符号。但是is_file不是构造函数的属性-它是构造函数返回的对象的属性。将调用构造函数,并对返回值调用is_file。所以你也要嘲笑这一部分。为此,请设置一个mock,以便在调用Path符号时返回。在

import mock, unittest

class FileUtilsTest(unittest.TestCase):

    testFilename = "filename"

    @mock.patch('FileUtils.Path')
    @mock.patch('FileUtils.os')
    def testDeleteFiles(self, osMock, pathMock):
        mock_path = MagicMock()
        pathMock.return_value = mock_path

        mock_path.is_file.return_value = False
        FileUtils.deleteFile(self.testFilename)
        self.assertFalse(osMock.remove.called, 'Failed to not remove the file if not present.')

        mock_path.is_file.return_value = True
        FileUtils.deleteFile(self.testFilename)
        osMock.remove.assert_called_with(self.testFilename)

相关问题 更多 >