Python:如何在我的测试套件中制作临时文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4199700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: How do I make temporary files in my test suite?
提问by Ram Rachum
(I'm using Python 2.6 and nose.)
(我使用的是 Python 2.6 和nose.)
I'm writing tests for my Python app. I want one test to open a new file, close it, and then delete it. Naturally, I prefer that this will happen inside a temporary directory, because I don't want to trash the user's filesystem. And, it needs to be cross-OS.
我正在为我的 Python 应用程序编写测试。我想要一个测试来打开一个新文件,关闭它,然后删除它。自然,我更喜欢这将发生在临时目录中,因为我不想破坏用户的文件系统。而且,它需要是跨操作系统的。
How do I do it?
我该怎么做?
采纳答案by bgporter
回答by hpk42
FWIW using py.test you can write:
FWIW 使用 py.test 你可以写:
def test_function(tmpdir):
# tmpdir is a unique-per-test-function invocation temporary directory
Each test function using the "tmpdir" function argument will get a clean empty directory, created as a sub directory of "/tmp/pytest-NUM" (linux, win32 has different path) where NUM is increased for each test run. The last three directories are kept to ease inspection and older ones are automatically deleted. You can also set the base temp directory with py.test --basetemp=mytmpdir.
每个使用“tmpdir”函数参数的测试函数都会得到一个干净的空目录,创建为“/tmp/pytest-NUM”(linux,win32有不同路径)的子目录,每次测试运行时NUM增加。保留最后三个目录以方便检查,旧目录将被自动删除。您还可以使用py.test --basetemp=mytmpdir.
The tmpdir object is a py.path.local object which can also use like this:
tmpdir 对象是一个 py.path.local 对象,它也可以像这样使用:
sub = tmpdir.mkdir("sub")
sub.join("testfile.txt").write("content")
But it's also fine to just convert it to a "string" path:
但也可以将其转换为“字符串”路径:
tmpdir = str(tmpdir)
回答by Krisztian Fekete
Instead of using tempfiledirectly I suggest using a context manager wrapper for it - the context manager takes care of removing the directory in all cases (success/failure/exception) with basically no boilerplate.
我建议使用上下文管理器包装器代替直接使用临时文件- 上下文管理器负责在所有情况下(成功/失败/异常)删除目录,基本上没有样板。
Here is how it can be used:
以下是它的使用方法:
from tempfile import TempDir # "tempfile" is a module in the standard library
...
# in some test:
with TempDir() as d:
temp_file_name = os.path.join(d.name, 'your_temp_file.name')
# create file...
# ...
# asserts...
I have been using a home grown version (the implementation is rather short - under 20 lines) up to the point, when I needed to use it somewhere else as well, so I looked around if there is a package ready to install, and indeed there is: tempfile
到目前为止,当我还需要在其他地方使用它时,我一直在使用自己开发的版本(实现相当短 - 不到 20 行),所以我环顾四周是否有准备安装的软件包,确实有:临时文件
Note: the code snippet above is a little out-dated.
注意:上面的代码片段有点过时了。
- In Python 2.7, there is tempfile.mkdtemp
- In Python 3 there is tempfile.TemporaryDirectory
- 在 Python 2.7 中,有tempfile.mkdtemp
- 在 Python 3 中有tempfile.TemporaryDirectory
回答by leszek.hanusz
To create a temporary file with custom content for your tests you can use this class:
要为您的测试创建带有自定义内容的临时文件,您可以使用此类:
import os, tempfile
class TestFileContent:
def __init__(self, content):
self.file = tempfile.NamedTemporaryFile(mode='w', delete=False)
with self.file as f:
f.write(content)
@property
def filename(self):
return self.file.name
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
os.unlink(self.filename)
This class will create a temporary file, write your content inside it and then close the file.
You use it inside a withstatement to ensure that the file is deleted after usage like this:
此类将创建一个临时文件,在其中写入您的内容,然后关闭该文件。您在with语句中使用它以确保文件在使用后被删除,如下所示:
with TestFileContent(
'''Hello, world
'''
) as test_file:
# Here, a temporary file has been created in the file named test_file.filename with the specified content
# This file will be deleted once you leave the with block
回答by Chris L. Barnes
For people who come across this in the future, but also refuse to use pytest for some reason:
对于以后遇到这种情况,但又因某种原因拒绝使用 pytest 的人:
I wrote tempcase, a small library which provides a unittest.TestCasesubclass with convenience methods for handling temporary directories. No directories are created until you request the path to them, and they are namespaced to the project, TestCase class, timestamp, and test method. They are automatically cleaned up afterwards. You can disable cleanup to inspect the output by setting a property.
我写了tempcase,这是一个小库,它提供了一个unittest.TestCase子类,其中包含处理临时目录的便捷方法。在您请求目录的路径之前,不会创建任何目录,并且它们被命名为项目、TestCase 类、时间戳和测试方法。之后它们会自动清理。您可以通过设置属性来禁用清理以检查输出。
There is also a decorator which can be applied to individual test cases, if you're porting code gradually.
如果您正在逐步移植代码,还有一个装饰器可以应用于单个测试用例。

