我有一个测试类,其中包含很少的测试方法,并且我想从测试方法中修补一些应用程序类和方法。在pytest文档中,我找到了一个有关如何使用Monkeypatch模块进行测试的示例。该示例中的所有测试仅是函数,而不是testclass方法。
但是我有一个带有测试方法的类:
class MyTest(TestCase):
def setUp():
pass
def test_classmethod(self, monkeypatch):
# here I want to use monkeypatch.setattr()
pass
Run Code Online (Sandbox Code Playgroud)
而且,仅将monkeypatch方法参数作为参数传递显然是行不通的。因此,看起来py.test魔术无法以这种方式工作。
因此,问题很简单,甚至可能很愚蠢:如何 monkeypatch.setattr()从测试类方法中将pytest用于内部?
虽然pytest支持通过非单位测试方法的测试函数参数接收固定装置,但unittest.TestCase方法无法直接接收固定装置函数参数,因为实现可能会影响运行常规unittest.TestCase测试套件的能力。
您可以monkeypatch直接创建
from _pytest.monkeypatch import MonkeyPatch
class MyTest(TestCase):
def setUp():
self.monkeypatch = MonkeyPatch()
def test_classmethod(self):
self.monkeypatch.setattr ...
...
Run Code Online (Sandbox Code Playgroud)
或创建自己的灯具,它将添加monkeypatch到您的班级中并使用@pytest.mark.usefixtures
@pytest.fixture(scope="class")
def monkeypatch_for_class(request):
request.cls.monkeypatch = MonkeyPatch()
@pytest.mark.usefixtures("monkeypatch_for_class")
class MyTest(TestCase):
def setUp():
pass
def test_classmethod(self):
self.monkeypatch.setattr ...
...
Run Code Online (Sandbox Code Playgroud)
小智 6
我有完全相同的问题。这很完美
import unittest
import pandas as pd
from _pytest.monkeypatch import MonkeyPatch
from src.geipan_data import loadLongitudeLatitudeDateTestimony
class TestGeipanData(unittest.TestCase):
def setUp(self):
self.monkeypatch = MonkeyPatch()
def test_loadLongitudeLatitudeDateTestimony(self):
def read_csv(*args, **kwargs):
return pd.DataFrame({
'obs_date_heure': ['2010-05-21', '1926-05-21'],
'obs_1_lon': [45.123, 78.4564],
'obs_1_lat': [32.123, 98.4564],
})
self.monkeypatch.setattr(pd, 'read_csv', read_csv)
df = loadLongitudeLatitudeDateTestimony()
self.assertListEqual(
df.columns.values.tolist(),
['obs_date_heure', 'obs_1_lon', 'obs_1_lat']
)
Run Code Online (Sandbox Code Playgroud)
在此示例中,我使用猴子补丁模拟 pd.read_csv 方法,并使用从unittest.TestCase扩展的asserListEqual