PyTest:断言函数内部对象的调用

PyTest: Assert a a call of a object inside a function

我正在尝试测试是否在函数内部调用了对象方法。该对象在函数本身中实例化。所以我嘲笑了 class 并尝试使用 class.

断言调用

我确实调试了它调用的函数和方法,但是 断言一直失败 原因是:

    raise AssertionError(msg)
    AssertionError: Expected 'populate' to have been called.

这是测试m 运行

from pytest_mock import MockerFixture
def test_populate_model(mocker: MockerFixture):
    mocker.patch('pyspark.sql.functions.col')
    mocker.patch('pyspark.sql.functions.concat')
    mocker.patch('pyspark.sql.functions.lit')
    mocker.patch('pyspark.sql.functions.trim')
    mocker.patch('pyspark.sql.functions.regexp_replace')
    with mocker.patch('src.core.model.my_model.MyModel') as amm:
        from src.core.tasks import populate_model
        from src.core.model.my_model import MyModel
        MyModel.check_state.return_value = 1
        populate_model("", "", "", "", "", "", "")
        MyModel.populate.assert_called() # Fails here
        MyModel.store.assert_called()

测试函数代码:

def populate_model(spark_context, dbutils, user, password, url, driver, model_path):
    model = MyModel(
        user=user,
        password=password,
        url=url,
        driver=driver,
        spark_context=spark_context,
        dbutils=dbutils,
        model_path=model_path
    )
    if model.check_state():
        model.populate()
        model.store()

我想通了。我需要在实例方法的模拟中进行断言调用 (调用构造函数时返回 MagicMock)而不是 class 方法的 mock。在代码中:

改变这个

   MyModel.populate.assert_called()
   MyModel.store.assert_called()

进入这个:

    MyModel.return_value.populate.assert_called()
    MyModel.return_value.store.assert_called()

因为MyModelreturn_value内部调用构造函数时返回的MagicMock populate_model。因此调用的填充函数是实例的一个而不是class'一个