I want to create a python test using pytest. In the test, I will create a temporary JSON file and do some something to the json file. How do I delete this file when I complete this test?
def test_can_do_something():
    tmp_json = create_some_tmp_json_file()
    do_something(tmp_json)
    assert some_statement
Basically I want to guarantee the temperory JSON file is deleted no matter how this test ends. Even if some exception thrown by do_something(). RAII idiom is a good choice. But how do I implement in python?
For this kind of use cases were you need to interact with the file system, pytest has a great feature: the tmp_path fixture. It will create a temporary direcotry, in which you can write files, which will be deleted automatically.
Just pass tmp_path to your test and use it in the test like pass it to the method that writes the json file.
def test_can_do_something(tmp_path):
    tmp_json = create_some_tmp_json_file(tmp_path)
    do_something(tmp_json)
    assert some_statement
This way you don't have to deal with deleting the temporary folders. They will be created in the systems temporary directory, which will be cleared at reboot or when more than 3 tests were run. This way you could even debug the test, when something goes wrong and review what happened in that temporary folder.
See the docs:
Temporary directories are by default created as sub-directories of the system temporary directory. The base name will be pytest-NUM where NUM will be incremented with each test run. Moreover, entries older than 3 temporary directories will be removed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With