在测试特定路径时,我希望使Path.exists()只返回True:
from unittest import TestCase
from mock import patch
import pathlib
def fn(names):
for index, name in enumerate(names):
if pathlib.Path(name).exists():
return index
class T(TestCase):
@patch.object(pathlib.Path, 'exists', side_effect=lambda: self.name == "countme")
def test_fn(self, exists_mock):
self.assertEqual(2, fn(["not", "not", "countme", "not"]))我也试过用
@patch.object(pathlib.Path, 'exists', side_effect=lambda self: self.name == "countme")发布于 2020-07-26 06:32:55
你的代码几乎是正确的。以下是一个工作版本:
class T(TestCase):
@patch.object(pathlib.Path, 'exists', lambda self: self.name == "countme")
def test_fn(self):
self.assertEqual(2, fn(["not", "not", "countme", "not"]))使用lambda忽略了lambda参数,而不是使用side_effect,只需替换函数即可。
问题是,side_effect只是一个独立于实际函数调用的返回值(或返回值列表),因此使用lambda将无法工作--它将不会以self作为参数进行调用。替代使用的new参数将替换实际的函数,因此将用正确的参数调用它。
使用patch的类似版本如下所示:
class T(TestCase):
@patch('pathlib.Path.exists', lambda self: self.name == "countme")
def test_fn(self):
self.assertEqual(2, fn(["not", "not", "countme", "not"]))https://stackoverflow.com/questions/63095938
复制相似问题