Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Unit Test Function opening a json file?

The function below opens and loads a Json file. My question is whats the best approach to test it?

def read_file_data(filename, path):
    os.chdir(path)
    with open(filename,  encoding="utf8") as data_file:
        json_data = json.load(data_file)
    return json_data

filename and path are passed in as sys.argv's.

I figured that i would need sample data in my test case for a start but not sure how i would actually use it to test the function

class TestMyFunctions(unittest.TestCase):
    def test_read_file_data(self):
        sample_json = {
                      'name' : 'John',
                      'shares' : 100,
                      'price' : 1230.23
                      }

Any pointer will be appreciated.

like image 605
Darth Avatar asked Sep 14 '25 18:09

Darth


1 Answers

As stated above you do not need to retest the standard python library code works correctly, so by creating a hard coded file as also stated, you are defeating the point of a unit test by testing outside of your unit of code.

Instead a correct approach would be to mock the opening of the file using pythons mocking framework. And thus test that your function returns the json that's read in correctly.

e.g.

from unittest.mock import patch, mock_open
import json

class TestMyFunctions(unittest.TestCase):


@patch("builtins.open", new_callable=mock_open,
       read_data=json.dumps({'name' : 'John','shares' : 100,
                        'price' : 1230.23}))
def test_read_file_data(self):
    expected_output = {
                  'name' : 'John',
                  'shares' : 100,
                  'price' : 1230.23
                  }
    filename = 'example.json'
    actual_output = read_file_data(filename, 'example/path')

    # Assert filename is file that is opened
    mock_file.assert_called_with(filename)

    self.assertEqual(expected_output, actual_output)
like image 119
bmjrowe Avatar answered Sep 16 '25 07:09

bmjrowe