2016-03-17 67 views
2

我的Python項目導入pytest 2.9.0罰款沒有任何問題。在PyTest中創建臨時目錄

我想創建一個新的空目錄,它只能保存測試會話的生命週期。我看到pytest提供臨時目錄支持:

https://pytest.org/latest/tmpdir.html

You can use the tmpdir fixture which will provide a temporary directory unique to the test invocation, created in the base temporary directory.

tmpdir is a py.path.local object which offers os.path methods and more. Here is an example test usage:

爲pytest的源代碼顯示def tmpdir是一個全球性的/模塊功能:https://pytest.org/latest/_modules/_pytest/tmpdir.html

但是我的測試文件失敗:

import pytest 

# ... 

def test_foo(): 
    p = pytest.tmpdir() 

有錯誤:

AttributeError: 'module' object has no attribute 'tmpdir'

from pytest import tmpdir失敗:

ImportError: cannot import name tmpdir

+2

該文檔還列出了一些示例。 'def test_foo(tmpdir):'爲你工作嗎? – vaultah

+1

[文檔](http://pytest.org/latest/tmpdir.html)演示瞭如何使用它,[這](http://stackoverflow.com/a/20545394/1832539)SO帖子也有一個例。那對你有用嗎? – idjaw

回答

6

我看着它一個也找到了特有的行爲,我總結一下我下面教訓,別人誰也不覺得那麼直觀。

看來tmpdir在同類pytest這裏是如何setup定義的預定義夾具:

import pytest 

class TestSetup: 
    def __init__(self): 
     self.x = 4 

@pytest.fixture() 
def setup(): 
    return TestSetup() 

def test_something(setup) 
    assert setup.x == 4 

因此tmpdir在被傳遞到您的testfunction pytest定義一個固定的名字,如果你把它當作一道參數名稱。

用法示例:

def test_something_else(tmpdir): 
    #create a file "myfile" in "mydir" in temp folder 
    f1 = tmpdir.mkdir("mydir").join("myfile") 

    #create a file "myfile" in temp folder 
    f2 = tmpdir.join("myfile") 

    #write to file as normal 
    f1.write("text to myfile") 

    assert f1.read() == "text to myfile" 

當您運行使用pytest它,如運行在終端py.test test_foo.py這工作。以這種方式生成的文件具有讀取和寫入權限,並且可以稍後在系統臨時文件夾中查看(對於我來說,這是/tmp/pytest-of-myfolder/pytest-1/test_create_file0

3

你只需要通過TMPDIR作爲函數的參數,因爲它是一個py.test夾具。

def test_foo(tmpdir): 
    # do things with tmpdir 
相關問題