Skip to content

Instantly share code, notes, and snippets.

@object-Object
Created September 4, 2023 23:53
Show Gist options
  • Save object-Object/e981b4a717f716914e3d02ab4d5258d2 to your computer and use it in GitHub Desktop.
Save object-Object/e981b4a717f716914e3d02ab4d5258d2 to your computer and use it in GitHub Desktop.
from typing import Any
from hatchling.plugin import hookimpl
from hatchling.version.source.plugin.interface import VersionSourceInterface
class BrokenException(Exception):
def __new__(cls, *args: object):
raise TypeError("This hides the real error message") from None
@classmethod
def new(cls, *args: object):
return super().__new__(cls, *args)
class PluginVersionSource(VersionSourceInterface):
PLUGIN_NAME = "plugin"
def get_version_data(self) -> dict[str, Any]:
message = "This message should be displayed"
if self.config.get("use_broken_exception"):
raise BrokenException.new(message)
else:
raise Exception(message)
def set_version(self, version: str, version_data: dict[str, Any]) -> None:
pass
@hookimpl
def hatch_register_version_source():
return PluginVersionSource
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "hatch-plugin"
version = "0.1.0"
dependencies = ["pytest", "build"]
[tool.hatch.build]
only_include = ["hatch_plugin.py"]
[project.entry-points.hatch]
plugin = "hatch_plugin"
import shutil
import subprocess
import sys
from pathlib import Path
from tempfile import TemporaryDirectory
from textwrap import dedent
import pytest
@pytest.mark.parametrize("use_broken_exception", ["true", "false"])
def test_build(
new_project: Path,
monkeypatch: pytest.MonkeyPatch,
capfd: pytest.CaptureFixture[str],
use_broken_exception: str,
):
append_text(
new_project / "pyproject.toml",
dedent(
f"""
[tool.hatch.version]
source = "plugin"
use_broken_exception = {use_broken_exception}
"""
),
)
monkeypatch.chdir(new_project)
subprocess.run([sys.executable, "-m", "build"])
captured = capfd.readouterr()
print(captured.err)
assert "This message should be displayed" in captured.err
@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", "venv"),
)
yield directory.resolve()
@pytest.fixture
def new_project(tmp_path: Path, plugin_dir: Path):
project_dir = tmp_path / "my-app"
project_dir.mkdir()
project_file = project_dir / "pyproject.toml"
project_file.write_text(
dedent(
f"""\
[build-system]
requires = ["hatchling", "hatch-plugin @ {plugin_dir.as_uri()}"]
build-backend = "hatchling.build"
[project]
name = "my-app"
dynamic = ["version"]
"""
),
encoding="utf-8",
)
return project_dir
def append_text(path: Path, data: str):
with path.open("a") as f:
f.write(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment