Python pytest模拟失败,对函数调用断言“置为无”

时间:2020-08-05 13:42:01

标签: python unit-testing pytest pytest-mock

我正在尝试模拟对boto3的一些调用,并且看起来模拟函数正在返回正确的值,并且看起来如果我更改断言,那么它不再匹配断言中传递的内容,因为输入参数失败不匹配,但是如果我使它们匹配,则断言将失败:

E       AssertionError: assert None
E        +  where None = <bound method wrap_assert_called_with of <MagicMock name='get_item' id='139668501580240'>>(TableName='TEST_TABLE', Key={'ServiceName': {'S': 'Site'}})
E        +    where <bound method wrap_assert_called_with of <MagicMock name='get_item' id='139668501580240'>> = <MagicMock name='get_item' id='139668501580240'>.assert_called_with
E        +      where <MagicMock name='get_item' id='139668501580240'> = <botocore.client.DynamoDB object at 0x7f071b8251f0>.get_item
E        +        where <botocore.client.DynamoDB object at 0x7f071b8251f0> = site_dao.ddb_client

dynamo数据库对象是一个全局变量。

ddb_client = boto3.client("dynamodb")

def query_ddb():
        """Query dynamo DB for the current strategy.

        Returns:
            strategy (str): The latest strategy from dynamo DB.

        """
        response = None

        try:
            ddb_table = os.environ["DDB_DA_STRATEGY"]

            response = ddb_client.get_item(
                TableName=ddb_table, Key={"ServiceName": {"S": "Site"}}
            )
        except Exception as exception:
            LOGGER.error(exception)

            raise ServerException("The server was unable to process your request.", [])

        return response.get("Item").get("Strategy").get("S")

我的单元测试如下:

def test_data_access_context_strategy_ddb(mocker):
    object_key = {
        "ServiceName": {"S": "Site"}
    }

    table_name = "TEST_TABLE"

    expected_response = "SqlServer"

    os_env = {
        "DDB_DA_STRATEGY": table_name,
    }

    ddb_response = {
        "Item": {
            "Strategy": {
                "S": expected_response
            }
        }
    }

    mocker.patch.dict(os.environ, os_env)

    mocker.patch.object(site_dao.ddb_client, "get_item")

    site_dao.ddb_client.get_item.return_value = ddb_response

    data_access_context = site_dao.DataAccessContext()

    response = data_access_context.query_ddb()
    
    assert response == expected_response

    assert site_dao.ddb_client.get_item.assert_called_with(TableName=table_name, Key=object_key)

如果我更改了assert_called_with的期望值,我将无法解决问题,例如:

assert site_dao.ddb_client.get_item.assert_called_with(TableName="TT", Key=object_key)

测试失败:

E       AssertionError: expected call not found.
E       Expected: get_item(TableName='TT', Key={'ServiceName': {'S': 'Site'}})
E       Actual: get_item(TableName='TEST_TABLE', Key={'ServiceName': {'S': 'Site'}})
E       
E       pytest introspection follows:
E       
E       Kwargs:
E       assert {'Key': {'Ser... 'TEST_TABLE'} == {'Key': {'Ser...leName': 'TT'}
E         Omitting 1 identical items, use -vv to show
E         Differing items:
E         {'TableName': 'TEST_TABLE'} != {'TableName': 'TT'}
E         Use -v to get the full diff

因此,当预期输入和实际输入不同时,它就会因此失败,但是,当它们相同并且测试应该通过时,它就会失败,因为就好像从未调用过该函数一样。

1 个答案:

答案 0 :(得分:3)

您在此行上有两个断言:

assert site_dao.ddb_client.get_item.assert_called_with(TableName=table_name, Key=object_key)

第一个断言是assert_called_with,听起来像是您想要的。然后在行的开头有另一个断言:assert ...,它在assert_called_with函数的返回值上断言。断言通过时,该返回值为null。因此,整行结果为assert null

tl; dr请勿重复使用assert