简体   繁体   English

Python-使用side_effect模拟出在类的init内部调用的函数

[英]Python - Mocking out a function called inside the init of a class using side_effect

I have this class, Foo, whose functions use dataframes I initialize in its constructor. 我有一个Foo类,它的函数使用我在其构造函数中初始化的数据帧。 I want to test its functions in my test class, FooTest. 我想在测试类FooTest中测试其功能。

from src.shared.utils import get_spark_dataframe

class Foo(object):
    def __init__(self, x, y):
        self.a = get_spark_dataframe(x, y.some_db, "table_a")
        self.b = get_spark_dataframe(x, y.some_db, "table_b")

    def some_foo_function(self):
         return self.a.join(self.b, ['pk'])

I want to mock out this get_spark_dataframe function and replace it with my own, since I'm merely interested in replacing the dataframes in the class with fake dataframes I define in my test class. 我想模拟这个get_spark_dataframe函数,并用我自己的函数替换,因为我只想用在测试类中定义的伪造数据帧替换类中的数据帧。

def get_spark_dataframe(x, db_name, table_name):
    return x.get_table(db=db_name, table=table_name).toDF()

This is vaguely what my test class looks like: 这是我的测试类的模棱两可的样子:

class FooTest(PysparkTest):
    def setUp(self):
         self.a_df = self.spark.createDataFrame([Row(...)])
         self.b_df = self.spark.createDataFrame([Row(...)])

         self.x = None
         self.y = None

    def mock_get_spark_dataframe(self, x, db_name, table_name):
         if table_name == "table_a":
               return self.a_df
         elif table_name == "table_b":
               return self.b_df

    @patch('src.shared.utils.get_spark_dataframe', side_effect=mock_get_spark_dataframe)
    def test_some_foo_function(self, mock_get_spark_dataframe):
        foo = Foo(self.x, self.y)
        return_value = foo.some_foo_function()
        ...

Am I doing something incorrectly? 我做错了什么吗? It doesn't seem like my mock function is being used when I create the Foo object. 创建Foo对象时,似乎没有使用我的模拟函数。 The real get_spark_dataframe function seems to be getting called, and it complains about x being None. 真正的get_spark_dataframe函数似乎正在被调用,它抱怨x为None。 Am I using side_effect incorrectly? 我使用side_effect错误吗?

Try these changes in your code: 尝试在代码中进行以下更改:

import src.shared.utils as utils

class Foo(object):
    def __init__(self, x, y):
        self.a = utils.get_spark_dataframe(x,...
        ...

and

class FooTest(PysparkTest):
    ...
    @patch('utils.get_spark_dataframe',...
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM