andrea
andrea

Reputation: 890

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?

Upvotes: 1

Views: 648

Answers (1)

SpaceKatt
SpaceKatt

Reputation: 1401

json.dump() is tested by the maintainers of the json package.

So, I don't think you have to test it yourself.

This is how they test the function without writing to disk:

        sio = StringIO()
        self.json.dump({}, sio)
        self.assertEqual(sio.getvalue(), '{}')

Upvotes: 2

Related Questions