【问题标题】:Pytest: Why is my mocked functions not called?Pytest:为什么我的模拟函数没有被调用?
【发布时间】:2020-08-31 18:45:17
【问题描述】:

我正在尝试为我的代码编写单元测试。但是我得到了没有调用模拟的断言错误。如何解决这个问题?

在我的code.py

from SDK import ManagementClient

def init_client():
    MGMT_CLIENT = ManagementClient(credentials) 
    # ManagementClient is an imported module, MGMT_CLIENT is a global variable
    

def add_db(ids):
    for id in ids:
        db_connection = MGMT_CLIENT.databases
        db_connection.database_operations.create()

test.py


@pytest.fixture()
def database_operations_mock():
    with mock.patch("code.MGMT_CLIENT.databases") as database_operations_mock:
        yield database_operations_mock

@pytest.fixutre
def client_mock():
        with mock.patch("code.ManagementClient") as client_mock:
        yield client_mock


def test_add():
    # prepare test data
    ids_mock = ['1','2'] 
    # update global variable for code.py to run add_db() 
    code.MGMT_CLIENT = client_mock()  
    # run actual functions
    code.add_db(ids_mock)  
    assert database_operations_mock.call_count == len(ids_mock)

我收到了这个错误:

>       assert database_operations_mock.call_count == len(ids_mock)
E       assert 0 == 2
E         +0
E         -2

【问题讨论】:

    标签: unit-testing pytest python-unittest


    【解决方案1】:

    您只需要第二个模拟。另外,我认为您不太了解对模拟的调用是如何工作的,调用计数对应于调用的 方法,在您的情况下它是 db_connection.database_operations.create。此外,您不能从测试脚本更新实际 Python 脚本中的全局变量,Python 不能那样工作。如果我理解正确,您的代码应该如下所示。

    def test_add(client_mock):
        # prepare test data
        ids_mock = ['1','2']
        # make the mock return itself when we call ManagementClient(credentials)
        # this will allow us to validate call counts
        client_mock.return_value = client_mock
        # since ManagementClient is mocked the `add_db` function should already call the mock
        code.add_db(ids_mock)
        # we have to check that `create` is being called
        assert client_mock.databases.database_operations.create == len(ids_mock)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-17
      • 2020-04-15
      • 1970-01-01
      • 1970-01-01
      • 2016-10-20
      • 2011-08-08
      相关资源
      最近更新 更多