python - Python 3.x 中的单元测试“pathlib.Path.is_file”
问题描述
我是 Python 单元测试的新手,在运行测试时遇到了问题。我想实现如下所示的测试类:https ://www.toptal.com/python/an-introduction-to-mocking-in-python ,但稍作修改。而不是使用os.path.isfile
我想使用pathlib.Path.is_file
.
这是要测试的实际类:
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)
如何FileUtils.deleteFile
使用@mock.patch
装饰器测试该方法?
解决方案
这里的问题是,当您修补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)
推荐阅读
- amazon-web-services - 使用 aws-cli 在 AWS API Gateway 中启用 CORS
- c# - .NET 如何报告并行工作负载的(集体)进度,其中每个对象/任务报告它自己的个人进度?
- java - 如何在 Spring Boot 中创建一个功能齐全的胖 jar,并在 Maven 中具有依赖项
- c++ - 在 C++ 中创建文件夹选择器对话框的最简单方法是什么?
- java - 错误:org.springframework.security.authentication.BadCredentialsException:错误的凭据
- python - 从两个元素之间的另一个数组中创建一个数组
- java - Talend 提取动态输入并将其转置
- c++ - 错误:在尝试检测 std::cout << t; 时将函数强制转换为数组类型 已验证
- r - 我什么时候应该在 R 中使用 read.csv() 与 read_csv()
- python - unittest blacklist 命名空间并失败任何引用它的尝试