Python: Mock Patch Errors with Flask

2019-03-01 02:17发布

问题:

I am a complete newb when it comes to writing Python, let alone testing it.

Here is my Flask endpoint:

@blueprint.route('/mailing_finish/<account_id>/<sumall_stream_id>/', methods=['POST'])
def mailing_finish(account_id, sumall_stream_id):
    """
    Get Response for mailing_id and update Dataset:
    * MYEMMA_EMAIL_SENDS: response['sent']
    """

    # TODO: webhook does not fire

    data = json.loads(request.data)['data']

    access_token = sumall_redis.get_oauth_token(account_id)

    response_data = sumall_audience.get_response_data(
        access_token=access_token,
        account_id=account_id,
        mailing_id=data['mailing_id'],
    )

    event = {
        'timeStamp': data['timestamp'][3:],
        'eventId': 'mailing_id:{mailing_id}'.format(
            mailing_id=data['mailing_id'],
        ),
        'data': {
            'MYEMMA_EMAIL_SENDS': {
                'value': response_data['recipient_count'],
                'dimensions': [
                    {
                        'dimension': 'MAILINGS',
                        'value': data['mailing_id'],
                    },
                ],
            },
        },
    }

    status = sumall_api.post_stream_event(
        stream_id=sumall_stream_id,
        event=event,
    )

    return 'Data sent to SumAll', status

Here is my test:

@mock.patch('sumall.utils.sumall_api')
@mock.patch('sumall.utils.sumall_audience')
@mock.patch('sumall.utils.sumall_redis')
def test_mailing_finish(self, sumall_redis_mock, sumall_audience_mock, sumall_api_mock):

    sumall_redis_mock.get_oauth_token.return_value = self.access_token

    sumall_audience_mock.get_response_data.return_value = {'recipient_count': 2}

    event = {
        'timeStamp': self.data['timestamp'][3:],
        'eventId': 'mailing_id:{mailing_id}'.format(mailing_id=self.data['mailing_id'],),
        'data': {
            'EMAIL_SENDS': {
                'value': sumall_audience_mock.get_response_data.get('recipient_count'),
                'dimensions': [
                    {
                        'dimension': 'MAILINGS',
                        'value': self.data['mailing_id'],
                    },
                ],
            },
        },
    }

    res = self.client.post(
        '/webhooks/mailing_finish/{account_id}/{sumall_stream_id}'.format(
            account_id=self.account_id,
            sumall_stream_id=self.sumall_stream_id
        ),
        data=json.dumps({'data': self.data}),
        content_type='application/json',
    )

    sumall_redis_mock.get_oauth_token.assert_called_with(self.account_id)

    sumall_audience_mock.get_response_data.assert_called_with(
        access_token=self.access_token,
        account_id=self.account_id,
        mailing_id=self.data['mailing_id']
    )

    sumall_api_mock.post_stream_event.assert_called_with(
        stream_id=self.sumall_stream_id,
        event=event,
    )

The error I am receiving is:

AssertionError: Expected call: get_oauth_token('123456')
Not called

I am not sure what is wrong. Any help would be greatly appreciated! Thanks!

回答1:

You imported sumall_redis as a local name in your view module, but mock the original sumall.utils.sumall_redis.

You probably have this at the top of your view module:

from sumall.utils import sumall_redis

This binds that object to a local name in the module. When the test starts and the patch is applied, only the original sumall_redis object in the sumall.utils module will be affected, not this local name.

You'll need to mock the name bound in your view module instead:

@mock.patch('view_module.sumall_redis')

This applies to your other 2 imports as well.

The mock documentation includes a guide on where to patch that you might want to read.