Create a gzip file like object for unit testing

Martin Preusse :

I want to test a Python function that reads a gzip file and extracts something from the file (using pytest).

import gzip

def my_function(file_path):
    output = []

    with gzip.open(file_path, 'rt') as f:
        for line in f:
            output.append('something from line')

    return output

Can I create a gzip file like object that I can pass to my_function? The object should have defined content and should work with gzip.open()

I know that I can create a temporary gzip file in a fixture but this depends on the filesystem and other properties of the environment. Creating a file-like object from code would be more portable.

hoefling :

You can use the io library to create in-memory file objects. Example:

def inmem():
    stream = io.BytesIO()
    with gzip.open(stream, 'wb') as f:
        f.write(b'spam\neggs\n')
    stream.seek(0)
    return stream

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=20442&siteId=1