Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

python - How can I pytest a function that creates a list of objects?

I have a function that takes a directory of images, reads them, and stores them in a list.

When pytesting a basic example of reading 3 images, I can't pass the test because the images have an allocation in memory data that makes the assertion to fail.

import os
from PIL import Image

def getImages(imageDir):
    files = os.listdir(imageDir)
    images = []
    for file in files:
        # Getting the full image name
        filePath = os.path.abspath(os.path.join(imageDir, file))
        try:
            # explicit load to prevent resources crunch
            fp = open(filePath, "rb")
            im = Image.open(fp)
            images.append(im)
            # force loading the image data from file
            im.load()
            # close the file
            fp.close()
        except Exception:
            # skip
            print("Invalid image: %s" % (filePath,))
    return images


def test_for_clean_data():
    assert getImages("test_images") == [Image.open("test_images/01.jpg"),
                                        Image.open("test_images/02.jpg"),
                                        Image.open("test_images/03.jpg")]

<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=2448x2765 at 0x1E48F5872C8> <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=2448x2765 at 0x1E48F5878C8>

As shown in the example error provided by the console, same image will have different properties when tested.

Function to test is PIL.Image based.

Perhaps, as someone suggested the test is flawed in its origin. If anyone knows a better way to pytest that the function is properly working, I would be more than happy to try a new idea. There's so much to learn.

Suggestions for correct test naming are also welcome.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Eyeballing the code, it looks like one potential reason your objects differ is that you call im.load() in getImages(), but not when you open your test images. Does this work? This is just a quick guess, I haven't tested it.

    assert getImages("test_images") == [Image.open("test_images/01.jpg").load(),
                                        Image.open("test_images/02.jpg").load(),
                                        Image.open("test_images/03.jpg").load()]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...