Pytest:为什么不调用我的模拟函数?

问题描述

我正在尝试为我的代码编写单元测试。但是我收到断言错误,即未调用模拟程序。如何解决此问题?

在我的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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)