覆盖 pathlib.Path.exists 进行条件测试
Override pathlib.Path.exists for a conditional test
我想让 Path.exists() 仅在测试特定路径时 return 为真:
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")
您的代码几乎是正确的。这是一个工作版本:
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
只是一个独立于实际函数调用的 return 值(或 return 值的列表),因此使用 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"]))
我想让 Path.exists() 仅在测试特定路径时 return 为真:
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")
您的代码几乎是正确的。这是一个工作版本:
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
只是一个独立于实际函数调用的 return 值(或 return 值的列表),因此使用 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"]))