如何在pytest中修补对象方法

问题描述 投票:0回答:1

在一个类中,我有一个属性(self.data),它是pandas.DataFrame。

我在类中有一个方法save(),该方法基本上事先调用了self.data.to_csv()并且进行了一些验证。在测试中,我想对此进行打补丁,以便它实际上不会在目录中存储数据,我只需要确保它可以模拟运行即可。

我无法解决如何修补它的问题。到目前为止,我有:

# Myclass.py

import pandas as pd
class Myclass:
    def __init__(self, data):
        self.data = pd.DataFrame(data=data)

    def save(self, path):
        # Do something validation
        # I would like to patch the line below. 
        self.data.to_csv(path)

test_myclass.py中:

from unittest import mock
import Myclass

@mock.patch(Myclass.to_csv)
def test_save(myclass_fixture):
    myclass_fixture.save(path)

我收到错误:

AttributeError: type object 'Portfolio' has no attribute 'to_csv'
python pytest python-unittest
1个回答
0
投票

'to_csv`是数据框的方法,因此您必须修补该方法:

@patch("module_path_to_my_class.Myclass.pd.DataFrame.to_csv")
def test_save(patched_to_csv):
    data = some_test_data  # this may come from a fixture
    my = MyClass(data)
    my.save("some_path")
    patched_to_csv.assert_called_once()

还请注意,patch的第一个参数是一个字符串,其中包含修补对象的路径(有关其内容,请参见where to patch)。

似乎您想从固定装置中学习课程-在这种情况下,您必须将此固定装置添加到参数中:

@pytest.fixture
def myclass_fixture():
   test_data = ...
   yield MyClass(test_data)

@patch("module_path_to_my_class.Myclass.pd.DataFrame.to_csv")
def test_save(patched_to_csv, myclass_fixture):
    myclass_fixture.save("some_path")
    patched_to_csv.assert_called_once()
© www.soinside.com 2019 - 2024. All rights reserved.