Home > Back-end >  Iterating array of Mock: Mock object is not iterable
Iterating array of Mock: Mock object is not iterable

Time:02-22

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:

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".

CodePudding user response:

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.

  • Related