vendredi 27 mars 2020

How do I test a python function which writes a json to disk?

I would like to know what is the best way write a test function (to be run using pytest) for the following short function which serialises a json.

import json
import os

def my_function(folder):
    my_dict = {"a": "A", "b": "B", "c": "C"}
    with open(os.path.join(folder, 'my_json.json'), 'w') as f:
        json.dump(my_dict, f)

I would like the test to be written as a simple function (not as a method of a class inheriting from unittest.TestCase).

My current idea is

def test_my_function():
    my_function(folder)
    with open(os.path.join(folder, 'my_json.json'), 'r') as f:
        my_dict = json.load(f)
    assert my_dict == {"a": "A", "b": "B", "c": "C"}

I am wondering if there a more elegant way of testing this without touching the disk?

Aucun commentaire:

Enregistrer un commentaire