How to Unit Test Function opening a json file?

Viewed 9929

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.

3 Answers
  1. Check these answers first: How to use mock_open with json.load()?

  2. some of the answers are using json.dump instead of json.dumps interchagebly, which is wrong.

  3. read, open, load, as stated are from Standard Python Library, already been tested, so you'd rather think about testing some actual column's values/types or some rows in your json file instead, and if you did that, this would not be a unit test anymore, it'll be an integration test since you have dependencies coupled to your method (json data in this case) which would be meaningless to purposely decouple them via mocking.

Related