Python:如何在我的测试套件中制作临时文件?

Ram*_*hum 25 python testing unit-testing temporary-files

(我正在使用Python 2.6和nose.)

我正在为我的Python应用程序编写测试.我想要一个测试打开一个新文件,关闭它,然后删除它.当然,我更喜欢这会发生在临时目录中,因为我不想丢弃用户的文件系统.而且,它需要跨OS.

我该怎么做?

hpk*_*k42 27

使用py.test的FWIW你可以写:

def test_function(tmpdir):
    # tmpdir is a unique-per-test-function invocation temporary directory
Run Code Online (Sandbox Code Playgroud)

使用"tmpdir"函数参数的每个测试函数将获得一个干净的空目录,创建为"/ tmp/pytest-NUM"的子目录(linux,win32具有不同的路径),其中每次测试运行都增加NUM.保留最后三个目录以便于检查,并自动删除旧的目录.您还可以使用基本临时目录进行设置py.test --basetemp=mytmpdir.

tmpdir对象是一个py.path.local对象,它也可以像这样使用:

sub = tmpdir.mkdir("sub")
sub.join("testfile.txt").write("content")
Run Code Online (Sandbox Code Playgroud)

但是将它转换为"字符串"路径也没关系:

tmpdir = str(tmpdir)
Run Code Online (Sandbox Code Playgroud)


bgp*_*ter 16

请参阅标准库中的tempfile模块 - 应该是您所需要的.


小智 5

我建议不要直接使用tempfile,我建议使用上下文管理器包装器 - 上下文管理器负责在所有情况下(成功/失败/异常)删除目录,基本上没有样板。

以下是它的使用方法:

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...
Run Code Online (Sandbox Code Playgroud)

到目前为止,当我还需要在其他地方使用它时,我一直在使用自己开发的版本(实现相当短 - 不到 20 行),所以我环顾四周是否有准备安装的软件包,确实有:临时文件


注意:上面的代码片段有点过时了。


les*_*usz 5

要为测试创建包含自定义内容的临时文件,您可以使用此类:

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)                                                                                        
Run Code Online (Sandbox Code Playgroud)

此类将创建一个临时文件,在其中写入您的内容,然后关闭该文件。您可以在语句中使用它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
Run Code Online (Sandbox Code Playgroud)