web-dev-qa-db-ja.com

PyTestで一時ディレクトリを作成する

私のPythonプロジェクトは問題なくpytest 2.9.0をインポートします。

テストセッションの寿命だけが続く新しい空のディレクトリを作成したいと思います。 pytestが一時ディレクトリをサポートしていることがわかります。

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

Tmpdirフィクスチャを使用できます。これは、ベースの一時ディレクトリに作成された、テスト呼び出しに固有の一時ディレクトリを提供します。

tmpdirは、os.pathメソッドなどを提供するpy.path.localオブジェクトです。テストの使用例は次のとおりです。

Pytestのソースコードはdef tmpdirはグローバル/モジュール関数です: https://pytest.org/latest/_modules/_pytest/tmpdir.html

しかし、私のテストファイルは失敗します:

import pytest

# ...

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

エラーあり:

AttributeError: 'module'オブジェクトに属性 'tmpdir'がありません

やっているfrom pytest import tmpdirは失敗します:

ImportError:名前tmpdirをインポートできません

11
Dai

調べてみたところ、独特の動作が見つかりました。直観的に理解できない人のために、以下で学んだことを要約します。

tmpdirsetupがここで定義される方法に似たpytestの定義済みフィクスチャです:

import pytest

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

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

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

したがって、tmpdirpytestで定義された固定名であり、引数名として持っている場合にテスト関数に渡されます。

使用例:

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でした)

UPDATE:tmpdirの代わりにtmp_pathを使用します。 tmp_pathpathlib.Path / pathlib2.Path です。 tmpdirpy.path (実際には LocalPath )であり、pathlib.Pathによく似た構文を提供しています。 pytest issue を参照してください。

開発者はpy.pathの使用を推奨しなくなりました。

構文は同じです。例:

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

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

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

    assert f1.read() == "text to myfile" 
27
M.T

Tmpdirはpy.testフィクスチャであるため、関数パラメーターとして渡す必要があります。

def test_foo(tmpdir):
    # do things with tmpdir
9
Ilyas