0

I'm trying to write a unit test with unittest which tests that the behaviour of the below function only opens files that have a filename pattern of test_*.json.

import glob
import json

def get_tests():
    tests = []
    for test in list(glob.iglob(f'**/test_*.json', recursive=True)):
        with open(test) as f:
            contents = f.read()
            to_json = json.loads(contents)
            tests.append(to_json)

    return tests

I've seen this SO post How do I mock an open used in a with statement (using the Mock framework in Python)? which is to use patch and mock_open, however, trying to follow the top answer, it's mainly focussed on opening a mock file, rather than testing the function that OP has written testme with a mock file. Also, I'm unsure in how to tie in filenames of a specific pattern either with mock file.

I want the unit tests to prove that it only opens files of that pattern, and not any other file.

3
  • 1
    That's very difficult to test, as written. If you could point it at a specific directory you could set up some fixture data, a mix of JSON and non-JSON files and sub-directories, and assert that you got the right result. Commented Dec 20, 2024 at 10:38
  • Thanks, that makes sense to me Commented Dec 20, 2024 at 10:50
  • If you don't want to test in the real filesystem, and don't mind an additional dependency, you could also use pyfakefs to create and test the files (disclaimer: I'm a maintainer of pyfakefs). Commented Dec 20, 2024 at 14:43

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.