Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterating array of Mock: Mock object is not iterable

I’m trying to iterate an array of Mock objects with Python UnitTest.

When I run the tests, I get the error:

Error while generating images - 'Mock' object is not iterable

Here’s the function I’m trying to test:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def generate_images(models, latent_dim=120, n_samples=20):
    latent_points = generate_latent_points(latent_dim, n_samples)
    batch_size = n_samples / len(models)

    images = []

    try:
        for i in range(len(models)):
            start = int(i * batch_size)
            end = int((i * batch_size) + batch_size - 1)
            gen_imgs = models[i].predict(latent_points[start:end])
            images = [*images, *gen_imgs]

        image_matplot = encode_images(np.asarray(images))
        return image_matplot

    except Exception as e:
        print("Error while generating images - ", e)

And here’s my test function:

def test_image_generation(self):
    # Given
    model = Mock()
    models = [model, model]

    # When
    result = generate_images(models, 120, 10)

    # Then
    model.predict.assert_called()
    self.assertIsNotNone(result)
    self.assertIs(type(result), io.BytesIO)

I debbuged and it seems that the code does a run in the for loop and calls the "predict" function, but doesn’t pass more than once in that loop and the exception kicks in with the "Mock object is not iterable".

I don’t understand this error since when I debbug and check the type of the "models" array, I get "list".

>Solution :

The problem lies here

gen_imgs = models[i].predict(latent_points[start:end])
images = [*images, *gen_imgs]

gen_imgs is again a Mock and you are trying to unpack it. However, it is not iterable hence you cannot unpack it. You would have mock the predict function explicitly to return an iterable. Something like

m = Mock()
m.predict = Mock(return_value=[1,2,3])

but probably with a different return_value that matches your needs.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading