gpt4 book ai didi

python - Python 3.x 中的单元测试 'pathlib.Path.is_file'

转载 作者:行者123 更新时间:2023-12-01 07:55:09 25 4
gpt4 key购买 nike

我是 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)

这是测试类:

import mock, unittest

class FileUtilsTest(unittest.TestCase):

testFilename = "filename"

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

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

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

这将导致以下错误消息:

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 方法?

最佳答案

这里的问题是,当您修补模块中的符号 Path 时,您正在替换 Path 构造函数的符号。但 is_file 不是构造函数的属性 - 它是构造函数返回的对象的属性。调用构造函数,然后对返回值调用 is_file。所以你也需要模拟那部分。为此,请设置在调用 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)

关于python - Python 3.x 中的单元测试 'pathlib.Path.is_file',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56023351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com