如何删除临时测试文件?
How to delete temporary test file?
我想使用 pytest 创建一个 python 测试。在测试中,我将创建一个临时 JSON 文件并对 json 文件执行一些操作。完成此测试后如何删除此文件?
def test_can_do_something():
tmp_json = create_some_tmp_json_file()
do_something(tmp_json)
assert some_statement
基本上我想保证临时 JSON 文件被删除,无论这个测试如何结束。即使 do_something() 抛出一些异常。 RAII idiom 是一个不错的选择。但是我如何在 python 中实施?
对于这种需要与文件系统交互的用例,pytest 有一个很棒的特性:tmp_path
fixture。它将创建一个临时目录,您可以在其中写入文件,这些文件将被自动删除。
只需将 tmp_path
传递给您的测试并在测试中使用它,就像将它传递给写入 json 文件的方法一样。
def test_can_do_something(tmp_path):
tmp_json = create_some_tmp_json_file(tmp_path)
do_something(tmp_json)
assert some_statement
这样您就不必处理删除临时文件夹的问题。它们将在系统临时目录中创建,该目录将在重新启动或超过 3 个测试 运行 时被清除。这样您甚至可以在出现问题时调试测试,并查看临时文件夹中发生的情况。
查看 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.
使用 try、except 和 finally
def test_can_do_something():
try:
tmp_json = create_some_tmp_json_file()
do_something(tmp_json)
assert some_statement
except Exception:
assert False
finally:
deletefile()
我想使用 pytest 创建一个 python 测试。在测试中,我将创建一个临时 JSON 文件并对 json 文件执行一些操作。完成此测试后如何删除此文件?
def test_can_do_something():
tmp_json = create_some_tmp_json_file()
do_something(tmp_json)
assert some_statement
基本上我想保证临时 JSON 文件被删除,无论这个测试如何结束。即使 do_something() 抛出一些异常。 RAII idiom 是一个不错的选择。但是我如何在 python 中实施?
对于这种需要与文件系统交互的用例,pytest 有一个很棒的特性:tmp_path
fixture。它将创建一个临时目录,您可以在其中写入文件,这些文件将被自动删除。
只需将 tmp_path
传递给您的测试并在测试中使用它,就像将它传递给写入 json 文件的方法一样。
def test_can_do_something(tmp_path):
tmp_json = create_some_tmp_json_file(tmp_path)
do_something(tmp_json)
assert some_statement
这样您就不必处理删除临时文件夹的问题。它们将在系统临时目录中创建,该目录将在重新启动或超过 3 个测试 运行 时被清除。这样您甚至可以在出现问题时调试测试,并查看临时文件夹中发生的情况。
查看 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.
使用 try、except 和 finally
def test_can_do_something():
try:
tmp_json = create_some_tmp_json_file()
do_something(tmp_json)
assert some_statement
except Exception:
assert False
finally:
deletefile()