简体   繁体   中英

Python mock: AssertionError: Expected and actual call not same

I am new to unittest.mock library and unable to solve the issue I am experiencing. I have a class called 'function.py' in the below folder structure

  • src _ init .py
    • function.py
  • tests
    • init .py
    • test_function.py

In test_function.py I have some code like this:

    import unittest
    from unittest import mock
    from ..src.function import get_subscriptions
    from ..src import function

class TestCheckOrder(unittest.TestCase):
    @mock.patch.object(function, 'table')
    def test_get_subscriptions_success(self, mocked_table):

        mocked_table.query.return_value = []
        user_id = "test_user"
        status = True

        get_subscriptions(user_id, status) 
        mocked_table.query.assert_called_with(
          KeyConditionExpression=conditions.Key('user_id').eq(user_id),
          FilterExpression=conditions.Attr('status').eq(int(status)))

In function.py:

import boto3
from boto3.dynamodb import conditions
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table("Subscriptions")

def get_subscriptions(user_id, active=True):
    results = table.query(
        KeyConditionExpression=conditions.Key(
        'user_id').eq(user_id),
        FilterExpression=conditions.Attr('status').eq(int(active))
    )

return results['Items']

If I run this I get the following exception:

**AssertionError: Expected call: query(FilterExpression=<boto3.dynamodb.conditions.Equals object at 0x1116011d0>, KeyConditionExpression=<boto3.dynamodb.conditions.Equals object at 0x111601160>)
Actual call: query(FilterExpression=<boto3.dynamodb.conditions.Equals object at 0x1116010f0>, KeyConditionExpression=<boto3.dynamodb.conditions.Equals object at 0x111601080>)**

Thanks in advance for helping me out.

The issue is that when you're calling assert_called_with in your test, you're creating new instances of conditions.Key and conditions.Attr . And as these instances are different from one we had in the actual call, there's a mismatch(check the hex ids shown in the traceback).

Instead of this you can fetch the kwargs from the function call itself and test their properties:

name, args, kwargs = mocked_table.query.mock_calls[0]
assert kwargs['KeyConditionExpression'].get_expression()['values'][1] == user_id
assert kwargs['FilterExpression'].get_expression()['values'][1] == int(status)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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