jeudi 17 septembre 2020

Python returning MagicMock instead of return_value

I am trying to read mocked response from AWS secretmanager.get_secret_value.

Function in code looks like

import boto3

def get_secret()
  session = boto3.Session(
        {aws credentials}
  )
  
  client = session.client(
    service_name='secretmsmanager'
  )
  
  try:
    get_secret_value_response = client.get_secret_value(
      SecretId={id}
    )
  except Exception as e:
      do something
  else:
    if 'SecretString' in get_secret_value_response:
        do something
    else:
        do something

And my test looks like this

import boto3
from unittest.mock import patch, MagicMock
from function_code_module import function_code


@patch('function_code_module.fucntion_code.boto3')
def test_secretsmanager(mock_boto):
    get_Secret_Response = {
        'ARN': 'string',
        'Name': 'string',
        'VersionId': 'string',
        'SecretBinary': b'bytes',
        'SecretString': 'string',
        'VersionStages': [
            'string',
        ],
        'CreatedDate': datetime(2020, 1, 1)
    }
    
    client_mock = MagicMock()
    client_mock.get_secret_value = MagicMock(return_value=get_Secret_Response)
    mock_boto.client = MagicMock(return_value=client_mock)
    
    response = function.get_secret()
    assert response is not None

Problem I am facing is even though mocked response has 'SecretString' it goes in else part of if statement in function. Because it does not read as dict instead it is MagicMock at that place.

Error I am receiving is:

TypeError: argument should be a bytes-like object or ASCII string, not 'MagicMock'

I tried many combinations of return_value, execute in following three statements, no luck as of now

    client_mock = MagicMock()
    client_mock.get_secret_value = MagicMock(return_value=get_Secret_Response)
    mock_boto.client = MagicMock(return_value=client_mock)

Aucun commentaire:

Enregistrer un commentaire