Writing Unit Tests for a Python function that works with a file

A bit of a shot in the dark here, but I’m trying to write unit tests for a personal project that works with files. I have a class called Tune with methods like so:

from tinytag import TinyTag
from os import path
from pathlib import Path

class Tune():

    def __init__(self, file_path_to_song):
        self.file_path_to_song = file_path_to_song

    def is_file(self):
        if path.isfile(self.file_path_to_song):
            # print("Yep, it's a file.")
            return True
        else:
            # print("Nope, not a file.")
            return False

    def get_artist(self):
        return TinyTag.get(self.file_path_to_song).artist

    def get_album(self):
        return TinyTag.get(self.file_path_to_song).album
...

As you can see, the Tune class relies on a file_path_to_song value, which, when testing locally, I have pointed to a locally saved MP3 file.

Is there a way I can “mock”/“fake”/etc. a file (in this case, .m4a or .mp3 files) so that I can write unit tests for these class methods?

Thank you in advance for your time.

Hello!

Hmmm, you could create a small mp4 file (search online for small audio file) and use any program to edit the meta details (like MusicBrainz Picard). Copy that file to the tests folder and write the tests (you would need to setup your tests to use the path to the tests folder and file).

1 Like

Yes, it’s called pyfakefs. You can install it with pip or poetry and the documentation is a google away. You can create a whole fake filesystem that basically works like the underlying real filesystem. You can even fill the fake files with arbitrary data, so you could programmatically create empty or small files of whatever media type you need if you wanted.

2 Likes