Home > Blockchain >  How to unittest functions that relies on External Dependencies such as File Directory and Api Respon
How to unittest functions that relies on External Dependencies such as File Directory and Api Respon

Time:12-02

Folks i want to unit test a function which basically downloads a file, but i just don't have any idea of how to do it. This is the code:

from requests import get
from helpers.file_helper import get_file_path


def download_file(url, filename):
    r = get(url)
    filepath = get_file_path(filename)
    with open(filepath, 'wb') as f:
        f.write(r.content)

I'd like to know how you guys will approach this problem, and if it's possible explain it in simple terms so everybody can understand it.

CodePudding user response:

You can use pytest's temporary file/directory fixtures to download the file, read and test the output and be sure everything is clean afterwards. As for the API, you can mock it if you do not want to call it every-time you run the test (either wiht pytest-mock or the mock package itself

  • Related