Skip to content

Testing build plugins


Hatchling pluginsをテストする場合、通常は、実際のユーザーと同じようにビルドを実行するプロジェクトを生成する必要があります。たとえば、最小限のpytestフィクスチャとして:

from pathlib import Path

import pytest


@pytest.fixture
def new_project(tmp_path):
    project_dir = tmp_path / 'my-app'
    project_dir.mkdir()

    project_file = project_dir / 'pyproject.toml'
    project_file.write_text(
        f"""\
[build-system]
requires = ["hatchling", "hatch-plugin-name @ {Path.cwd().as_uri()}"]
build-backend = "hatchling.build"

[project]
name = "my-app"
version = "0.1.0"
""",
        encoding='utf-8',
    )
    ...

これに関する問題は、最初のテストセッションの後、プロジェクトがファイルパスに基づいてpipによって永続的にキャッシュされることである。したがって、後続のテスト実行では更新されたコードが使用されることはありません。

キャッシュを無効にするには、テストセッションごとにコードを新しいパスにコピーします。:

import shutil
from pathlib import Path
from tempfile import TemporaryDirectory

import pytest


@pytest.fixture(scope='session')
def plugin_dir():
    with TemporaryDirectory() as d:
        directory = Path(d, 'plugin')
        shutil.copytree(
            Path.cwd(), directory, ignore=shutil.ignore_patterns('.git')
        )

        yield directory.resolve()


@pytest.fixture
def new_project(tmp_path, plugin_dir):
    project_dir = tmp_path / 'my-app'
    project_dir.mkdir()

    project_file = project_dir / 'pyproject.toml'
    project_file.write_text(
        f"""\
[build-system]
requires = ["hatchling", "hatch-plugin-name @ {plugin_dir.as_uri()}"]
build-backend = "hatchling.build"

[project]
name = "my-app"
version = "0.1.0"
""",
        encoding='utf-8',
    )
    ...

Note

この例では、パフォーマンス上の理由から.gitのコピーを無視することを選択します。より多くのパターンを無視するか、this pluginのように特定のパスのみをコピーすることをお勧めします。