Commit 8a2ff3a9 authored by Dom Sekotill's avatar Dom Sekotill
Browse files

Switch tests to package TempDir

parent 1f59f720
Loading
Loading
Loading
Loading

tests/temp.py

deleted100644 → 0
+0 −62
Original line number Diff line number Diff line
#  Copyright 2022 Dominik Sekotill <dom.sekotill@kodo.org.uk>
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

"""
Temporary file and directory helper module
"""

from __future__ import annotations

import tempfile
from pathlib import Path
from typing import TypeVar

TEMP_DIR = Path(tempfile.gettempdir())


class TempDir(Path):
	"""
	A temporary directory context manager Path subclass

	This class implements almost identical behaviour to tempfile.TemporaryDirectory, but as
	a pathlib.Path subclass.

	Note: The "name" attribute is from Path; it is the base name of the directory, not the
	full path as in tempfile.TemporaryDirectory.
	"""

	_flavour = type(Path())._flavour  # type: ignore

	P = TypeVar("P", bound="TempDir")

	def __new__(cls: type[P]) -> P:  # noqa: D102 - https://github.com/PyCQA/pydocstyle/issues/515
		return Path.__new__(cls, tempfile.mkdtemp())

	def __enter__(self: P) -> P:
		return self

	def __exit__(self, *_: object) -> None:
		self.cleanup()

	def cleanup(self) -> None:
		"""
		Remove the directory and all its contents
		"""
		if TEMP_DIR not in self.parents:
			raise RuntimeError(f"not removing {self} as it's not in {TEMP_DIR}")
		if not self.exists():
			return
		for path in reversed([*self.glob("**/*")]):
			path.rmdir() if path.is_dir() else path.unlink()
		self.rmdir()
+1 −1
Original line number Diff line number Diff line
@@ -23,7 +23,7 @@ import subprocess
from pathlib import Path
from typing import NewType

from tests.temp import TempDir
from project_templates.resources import TempDir

Ref = NewType("Ref", str)
Sha = NewType("Sha", str)