0

I would like to build a MagicMock for a nested call. Not quite sure how to do this. Please could you advise?

Many Thanks

Here is my code :

def kms_aliases(ids_include):
     client = boto3.client('kms')
     paginator = client.get_paginator('list_aliases')
     response_iterator = paginator.paginate(PaginationConfig={'MaxItems': 100})
     aliases = response_iterator.build_full_result() # I would like to mock this one

Here is my test:

class ReportTests(unittest.TestCase):
    def test_kms_aliases(self):
        # arrange
        boto3.client = MagicMock()
        ids_include = ["string1", "string2"]
        kms_aliases = {blah}

        # here we go... how do I mock the call to response_iterator.build_full_result()
        # wrong!
        response_iterator.build_full_result() = MagicMock(return_value = kms_aliases)
        expected = {blah}

        # act
        actual = info.kms_aliases(ids_include)

        # assert
        assert expected == actual
Banoona
  • 1,470
  • 3
  • 18
  • 32

1 Answers1

0
class ReportTests(unittest.TestCase):
@mock.patch("boto3.client")
def test_kms_aliases(self, boto3_mock):
    # arrange
    kms_aliases = {blah}
    # ===== here's the code I was looking for =====
    boto3_mock.return_value\
        .get_paginator.return_value\
        .paginate.return_value\
        .build_full_result.return_value = kms_aliases

    ids_include = ["string1", "string2"]

    expected = {blah}

    # act
    actual = info.kms_aliases(ids_include)

    # assert
    assert expected == actual

Thanks to How to mock nested functions? --> See the answer from https://stackoverflow.com/users/1731460/pymen

Banoona
  • 1,470
  • 3
  • 18
  • 32