├── src └── pytest_servers │ ├── py.typed │ ├── __init__.py │ ├── local.py │ ├── exceptions.py │ ├── s3.py │ ├── utils.py │ ├── gcs.py │ ├── azure.py │ ├── fixtures.py │ └── factory.py ├── .gitattributes ├── tests ├── __init__.py ├── test_utils.py ├── test_memory.py ├── test_fixtures.py └── test_factory.py ├── .github ├── dependabot.yml └── workflows │ ├── update-template.yaml │ ├── release.yml │ └── tests.yml ├── renovate.json ├── .cruft.json ├── .pre-commit-config.yaml ├── noxfile.py ├── .gitignore ├── CONTRIBUTING.rst ├── pyproject.toml ├── README.rst ├── CODE_OF_CONDUCT.rst └── LICENSE /src/pytest_servers/py.typed: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | -------------------------------------------------------------------------------- /src/pytest_servers/__init__.py: -------------------------------------------------------------------------------- 1 | """pytest servers.""" 2 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | """Test suite for the pytest_servers package.""" 2 | -------------------------------------------------------------------------------- /tests/test_utils.py: -------------------------------------------------------------------------------- 1 | from pytest_servers.fixtures import _version_aware 2 | 3 | 4 | def test_version_aware(request): 5 | assert not _version_aware(request) 6 | request.getfixturevalue("versioning") 7 | assert _version_aware(request) 8 | -------------------------------------------------------------------------------- /src/pytest_servers/local.py: -------------------------------------------------------------------------------- 1 | import pathlib 2 | 3 | from fsspec.implementations.local import LocalFileSystem 4 | 5 | 6 | class LocalPath(type(pathlib.Path())): # type: ignore[misc] 7 | fs = LocalFileSystem() 8 | 9 | @property 10 | def path(self) -> str: 11 | return str(self) 12 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | updates: 4 | - directory: "/" 5 | package-ecosystem: "pip" 6 | schedule: 7 | interval: "weekly" 8 | labels: 9 | - "maintenance" 10 | 11 | - directory: "/" 12 | package-ecosystem: "github-actions" 13 | schedule: 14 | interval: "weekly" 15 | labels: 16 | - "maintenance" 17 | -------------------------------------------------------------------------------- /.github/workflows/update-template.yaml: -------------------------------------------------------------------------------- 1 | name: Update template 2 | 3 | on: 4 | schedule: 5 | - cron: '5 1 * * *' # every day at 01:05 6 | workflow_dispatch: 7 | 8 | jobs: 9 | update: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Check out the repository 13 | uses: actions/checkout@v4 14 | 15 | - name: Update template 16 | uses: iterative/py-template@main 17 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["group:all", ":dependencyDashboard"], 3 | "enabledManagers": ["regex"], 4 | "regexManagers": [ 5 | { 6 | "fileMatch": [ 7 | "^src/pytest_servers/gcs.py$", 8 | "^src/pytest_servers/azure.py$" 9 | ], 10 | "matchStrings": [ 11 | "\"(?.*?):(?.*)\".*?#\\s+renovate" 12 | ], 13 | "datasourceTemplate": "docker" 14 | } 15 | ] 16 | } 17 | -------------------------------------------------------------------------------- /tests/test_memory.py: -------------------------------------------------------------------------------- 1 | def test_memory_fs_clean(tmp_upath_factory): 2 | mempath1 = tmp_upath_factory.mktemp("memory") 3 | mempath2 = tmp_upath_factory.mktemp("memory") 4 | 5 | foo = mempath1 / "foo" 6 | foo.write_text("foo") 7 | bar = mempath2 / "bar" 8 | bar.write_text("bar") 9 | 10 | assert (mempath1 / "foo").exists() 11 | assert (mempath2 / "bar").exists() 12 | assert not (mempath1 / "bar").exists() 13 | assert not (mempath2 / "foo").exists() 14 | -------------------------------------------------------------------------------- /src/pytest_servers/exceptions.py: -------------------------------------------------------------------------------- 1 | class PytestServersException(Exception): # noqa: N818 2 | """Base class for all pytest-servers exceptions.""" 3 | 4 | def __init__(self, msg: str, *args): 5 | assert msg 6 | self.msg = msg 7 | super().__init__(msg, *args) 8 | 9 | 10 | class RemoteUnavailable(PytestServersException): 11 | """Raise when the given remote is not available.""" 12 | 13 | 14 | class HealthcheckTimeout(PytestServersException): 15 | """Raise when the healthcheck probe for a container fails.""" 16 | 17 | def __init__(self, container_name: str, container_logs: str): 18 | super().__init__(container_name) 19 | self.logs = container_logs 20 | 21 | def __str__(self): 22 | return f"Healthcheck timeout: Logs for {self.msg}:\n{self.logs}" 23 | -------------------------------------------------------------------------------- /tests/test_fixtures.py: -------------------------------------------------------------------------------- 1 | def test_gcs_versioning(tmp_gcs_path, versioning): 2 | assert tmp_gcs_path.fs.version_aware 3 | 4 | 5 | def test_gcs_versioning_disabled(tmp_gcs_path): 6 | assert not tmp_gcs_path.fs.version_aware 7 | 8 | 9 | def test_s3_versioning(tmp_s3_path, versioning): 10 | assert tmp_s3_path.fs.version_aware 11 | 12 | 13 | def test_s3_versioning_disabled(tmp_s3_path): 14 | assert not tmp_s3_path.fs.version_aware 15 | 16 | 17 | def test_s3_server_default_config(s3_server): 18 | assert "endpoint_url" in s3_server 19 | assert s3_server["aws_access_key_id"] == "pytest-servers" 20 | assert s3_server["aws_secret_access_key"] == "pytest-servers" 21 | assert s3_server["aws_session_token"] == "pytest-servers" 22 | assert s3_server["region_name"] == "pytest-servers-region" 23 | -------------------------------------------------------------------------------- /.cruft.json: -------------------------------------------------------------------------------- 1 | { 2 | "template": "https://github.com/iterative/py-template", 3 | "commit": "5533e6330b505e7037948207c1c6755597a82f84", 4 | "checkout": null, 5 | "context": { 6 | "cookiecutter": { 7 | "project_name": "pytest-servers", 8 | "package_name": "pytest_servers", 9 | "friendly_name": "pytest servers", 10 | "author": "Iterative", 11 | "email": "support@dvc.org", 12 | "github_user": "iterative", 13 | "version": "0.0.0", 14 | "copyright_year": "2022", 15 | "license": "Apache-2.0", 16 | "docs": "False", 17 | "short_description": "pytest-servers", 18 | "development_status": "Development Status :: 3 - Alpha", 19 | "_template": "https://github.com/iterative/py-template", 20 | "_commit": "5533e6330b505e7037948207c1c6755597a82f84" 21 | } 22 | }, 23 | "directory": null, 24 | "skip": [ 25 | ".git" 26 | ] 27 | } 28 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | release: 5 | types: [published] 6 | workflow_dispatch: 7 | 8 | env: 9 | FORCE_COLOR: "1" 10 | 11 | jobs: 12 | release: 13 | environment: pypi 14 | permissions: 15 | contents: read 16 | id-token: write 17 | runs-on: ubuntu-latest 18 | steps: 19 | - name: Check out the repository 20 | uses: actions/checkout@v4 21 | with: 22 | fetch-depth: 0 23 | 24 | - name: Set up Python 3.12 25 | uses: actions/setup-python@v5 26 | with: 27 | python-version: '3.12' 28 | 29 | - name: Upgrade pip and nox 30 | run: | 31 | pip install --upgrade pip nox 32 | pip --version 33 | nox --version 34 | 35 | - name: Build package 36 | run: nox -s build 37 | 38 | - name: Upload package 39 | if: github.event_name == 'release' 40 | uses: pypa/gh-action-pypi-publish@release/v1 41 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | default_language_version: 2 | python: python3 3 | repos: 4 | - repo: https://github.com/pre-commit/pre-commit-hooks 5 | rev: v5.0.0 6 | hooks: 7 | - id: check-added-large-files 8 | - id: check-case-conflict 9 | - id: check-docstring-first 10 | - id: check-executables-have-shebangs 11 | - id: check-json 12 | - id: check-merge-conflict 13 | args: ['--assume-in-merge'] 14 | - id: check-toml 15 | - id: check-yaml 16 | - id: end-of-file-fixer 17 | - id: mixed-line-ending 18 | args: ['--fix=lf'] 19 | - id: sort-simple-yaml 20 | - id: trailing-whitespace 21 | - repo: https://github.com/astral-sh/ruff-pre-commit 22 | rev: 'v0.12.7' 23 | hooks: 24 | - id: ruff 25 | args: [--fix, --exit-non-zero-on-fix] 26 | - id: ruff-format 27 | - repo: https://github.com/codespell-project/codespell 28 | rev: v2.4.1 29 | hooks: 30 | - id: codespell 31 | additional_dependencies: ["tomli"] 32 | - repo: https://github.com/macisamuele/language-formatters-pre-commit-hooks 33 | rev: v2.15.0 34 | hooks: 35 | - id: pretty-format-toml 36 | args: [--autofix, --no-sort] 37 | - id: pretty-format-yaml 38 | args: [--autofix, --indent, '2', '--offset', '2', --preserve-quotes] 39 | -------------------------------------------------------------------------------- /src/pytest_servers/s3.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import pytest 4 | 5 | 6 | class MockedS3Server: 7 | def __init__( 8 | self, 9 | ip_address: str = "127.0.0.1", 10 | port: int = 0, 11 | *, 12 | verbose: bool = True, 13 | ): 14 | from moto.server import ThreadedMotoServer 15 | 16 | self._server = ThreadedMotoServer(ip_address, port=port, verbose=verbose) 17 | 18 | @property 19 | def endpoint_url(self) -> str: 20 | return f"http://{self.ip_address}:{self.port}" 21 | 22 | @property 23 | def port(self) -> int: 24 | # grab the port from the _server attribute, which has the bound port 25 | assert self._server._server # noqa: SLF001 26 | return self._server._server.port # noqa: SLF001 27 | 28 | @property 29 | def ip_address(self) -> str: 30 | return self._server._ip_address # noqa: SLF001 31 | 32 | def __enter__(self): 33 | self._server.start() 34 | return self 35 | 36 | def __exit__(self, *exc_args): 37 | self._server.stop() 38 | 39 | 40 | @pytest.fixture(scope="session") 41 | def s3_server_config() -> dict: 42 | """Override to change default config of the moto server.""" 43 | return {} 44 | 45 | 46 | @pytest.fixture(scope="session") 47 | def s3_server( # type: ignore[misc] 48 | monkeypatch_session: pytest.MonkeyPatch, 49 | s3_server_config: dict, 50 | ) -> dict[str, str | None]: 51 | """Spins up a moto s3 server. 52 | 53 | Returns a client_kwargs dict that can be used with a boto client. 54 | """ 55 | assert isinstance(s3_server_config, dict) 56 | monkeypatch_session.setenv("MOTO_ALLOW_NONEXISTENT_REGION", "true") 57 | 58 | with MockedS3Server(**s3_server_config) as server: 59 | yield { 60 | "endpoint_url": server.endpoint_url, 61 | "aws_access_key_id": "pytest-servers", 62 | "aws_secret_access_key": "pytest-servers", 63 | "aws_session_token": "pytest-servers", 64 | "region_name": "pytest-servers-region", 65 | } 66 | -------------------------------------------------------------------------------- /noxfile.py: -------------------------------------------------------------------------------- 1 | """Automation using nox.""" 2 | 3 | import glob 4 | import os 5 | from pathlib import Path 6 | 7 | import nox 8 | 9 | nox.options.reuse_existing_virtualenvs = True 10 | nox.options.sessions = "lint", "tests" 11 | 12 | 13 | @nox.session( 14 | python=["3.9", "3.10", "3.11", "3.12", "3.13", "pypy3.10"], 15 | ) 16 | def tests(session: nox.Session) -> None: 17 | session.install(".[dev]") 18 | 19 | env = { 20 | "COVERAGE_FILE": f".coverage.{session.python}", 21 | "COVERAGE_PROCESS_START": os.fspath(Path.cwd() / "pyproject.toml"), 22 | } 23 | # pytest loads plugin before the test is run, so we have to start coverage 24 | # before pytest loads. 25 | session.run("coverage", "run", "-m", "pytest", *session.posargs, env=env) 26 | session.run("coverage", "combine", env=env) 27 | session.run("coverage", "report", env=env) 28 | if os.getenv("COVERAGE_XML"): 29 | session.run("coverage", "xml", "-o", "coverage.xml", env=env) 30 | 31 | 32 | @nox.session 33 | def lint(session: nox.Session) -> None: 34 | session.install("pre-commit") 35 | session.install("-e", ".[dev]") 36 | 37 | args = *(session.posargs or ("--show-diff-on-failure",)), "--all-files" 38 | session.run("pre-commit", "run", *args) 39 | session.run("python", "-m", "mypy") 40 | 41 | 42 | @nox.session 43 | def build(session: nox.Session) -> None: 44 | session.install("build", "setuptools", "twine") 45 | session.run("python", "-m", "build") 46 | dists = glob.glob("dist/*") 47 | session.run("twine", "check", *dists, silent=True) 48 | 49 | 50 | @nox.session 51 | def dev(session: nox.Session) -> None: 52 | """Sets up a python development environment for the project.""" 53 | args = session.posargs or ("venv",) 54 | venv_dir = os.fsdecode(os.path.abspath(args[0])) 55 | 56 | session.log(f"Setting up virtual environment in {venv_dir}") 57 | session.install("virtualenv") 58 | session.run("virtualenv", venv_dir, silent=True) 59 | 60 | python = os.path.join(venv_dir, "bin/python") 61 | session.run(python, "-m", "pip", "install", "-e", ".[all,dev]", external=True) 62 | -------------------------------------------------------------------------------- /tests/test_factory.py: -------------------------------------------------------------------------------- 1 | import importlib 2 | 3 | import pytest 4 | import upath.implementations.cloud 5 | import upath.implementations.memory 6 | 7 | from pytest_servers.local import LocalPath 8 | 9 | for module in ["s3fs", "adlfs", "gcsfs"]: 10 | importlib.import_module(module) 11 | 12 | 13 | implementations = [ 14 | pytest.param("local", LocalPath), 15 | pytest.param( 16 | "memory", 17 | upath.implementations.memory.MemoryPath, 18 | ), 19 | pytest.param( 20 | "s3", 21 | upath.implementations.cloud.S3Path, 22 | ), 23 | pytest.param( 24 | "azure", 25 | upath.implementations.cloud.AzurePath, 26 | ), 27 | pytest.param( 28 | "gcs", 29 | upath.implementations.cloud.GCSPath, 30 | ), 31 | pytest.param( 32 | "gs", 33 | upath.implementations.cloud.GCSPath, 34 | ), 35 | ] 36 | 37 | 38 | with_versioning = [ 39 | param for param in implementations if param.values[0] in ("s3", "gcs", "gs") 40 | ] 41 | 42 | 43 | @pytest.mark.parametrize( 44 | ("fs", "cls"), 45 | implementations, 46 | ids=[param.values[0] for param in implementations], # type: ignore[misc] 47 | ) 48 | class TestTmpUPathFactory: 49 | def test_init(self, tmp_upath_factory, fs, cls): 50 | if fs in ("gcs", "gs"): 51 | pytest.skip("gcsfs does not support .exists() on a bucket") 52 | path = tmp_upath_factory.mktemp(fs) 53 | assert isinstance(path, cls) 54 | assert path.exists() 55 | 56 | def test_is_empty(self, tmp_upath_factory, fs, cls): 57 | path = tmp_upath_factory.mktemp(fs) 58 | assert list(path.iterdir()) == [] 59 | 60 | def test_write_text(self, tmp_upath_factory, fs, cls): 61 | file = tmp_upath_factory.mktemp(fs) / "foo" 62 | assert file.write_text("bar") 63 | assert file.read_text() == "bar" 64 | 65 | def test_multiple_paths(self, tmp_upath_factory, fs, cls): 66 | path_1 = tmp_upath_factory.mktemp(fs) 67 | path_2 = tmp_upath_factory.mktemp(fs) 68 | assert str(path_1) != str(path_2) 69 | 70 | 71 | @pytest.mark.parametrize( 72 | ("fs", "cls"), 73 | with_versioning, 74 | ids=[param.values[0] for param in with_versioning], # type: ignore[misc] 75 | ) 76 | class TestTmpUPathFactoryVersioning: 77 | def test_mktemp(self, tmp_upath_factory, fs, cls): 78 | path = tmp_upath_factory.mktemp(fs, version_aware=True) 79 | assert path.fs.version_aware 80 | -------------------------------------------------------------------------------- /src/pytest_servers/utils.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import random 3 | import socket 4 | import string 5 | import time 6 | from typing import TYPE_CHECKING, Callable, NamedTuple, TypeVar 7 | 8 | import pytest 9 | 10 | if TYPE_CHECKING: 11 | from docker import DockerClient 12 | from docker.models.containers import Container 13 | 14 | 15 | logger = logging.getLogger(__name__) 16 | 17 | _T = TypeVar("_T") 18 | 19 | 20 | def wait_until(pred: Callable[..., _T], timeout: float, pause: float = 0.1) -> _T: 21 | start = time.perf_counter() 22 | exc = None 23 | while (time.perf_counter() - start) < timeout: 24 | try: 25 | value = pred() 26 | except Exception as e: # noqa: BLE001 27 | exc = e 28 | else: 29 | return value 30 | time.sleep(pause) 31 | 32 | msg = "timed out waiting" 33 | raise TimeoutError(msg) from exc 34 | 35 | 36 | def random_string(n: int = 6) -> str: 37 | return "".join( 38 | random.choices( # nosec B311 # noqa: S311 39 | string.ascii_lowercase, 40 | k=n, 41 | ), 42 | ) 43 | 44 | 45 | @pytest.fixture(scope="session") 46 | def monkeypatch_session() -> pytest.MonkeyPatch: # type: ignore[misc] 47 | """Session-scoped monkeypatch.""" 48 | m = pytest.MonkeyPatch() 49 | yield m 50 | m.undo() 51 | 52 | 53 | @pytest.fixture(scope="session") 54 | def docker_client() -> "DockerClient": 55 | """Run docker commands using the python API.""" 56 | import docker 57 | 58 | client = docker.from_env() 59 | 60 | yield client 61 | 62 | client.close() 63 | 64 | 65 | def wait_until_running( 66 | container: "Container", 67 | timeout: int = 30, 68 | pause: float = 0.5, 69 | ) -> None: 70 | def check() -> bool: 71 | container.reload() 72 | return container.status == "running" 73 | 74 | wait_until(check, timeout=timeout, pause=pause) 75 | 76 | 77 | def get_free_port() -> int: 78 | retries = 3 79 | while retries >= 0: 80 | try: 81 | with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: 82 | s.listen() 83 | free_port = s.getsockname()[1] 84 | except OSError as exc: # noqa: PERF203 85 | retries -= 1 86 | exception = exc 87 | else: 88 | return free_port 89 | 90 | msg = "Could not get a free port" 91 | raise SystemError(msg) from exception 92 | 93 | 94 | class MockRemote(NamedTuple): 95 | fixture_name: str 96 | config_attribute_name: str 97 | requires_docker: bool 98 | -------------------------------------------------------------------------------- /src/pytest_servers/gcs.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import logging 4 | from typing import TYPE_CHECKING 5 | 6 | import pytest 7 | import requests 8 | from filelock import FileLock 9 | 10 | from .exceptions import HealthcheckTimeout 11 | from .utils import get_free_port, wait_until, wait_until_running 12 | 13 | if TYPE_CHECKING: 14 | from docker import DockerClient 15 | from docker.models import Container 16 | 17 | 18 | logger = logging.getLogger(__name__) 19 | 20 | GCS_DEFAULT_PORT = 4443 21 | 22 | 23 | @pytest.fixture(scope="session") 24 | def fake_gcs_server( 25 | docker_client: DockerClient, 26 | tmp_path_factory: pytest.TempPathFactory, 27 | ) -> str: 28 | """Spins up a fake-gcs-server container. Returns the endpoint URL.""" 29 | from docker.errors import NotFound 30 | 31 | container_name = "pytest-servers-fake-gcs-server" 32 | 33 | root_tmp_dir = tmp_path_factory.getbasetemp().parent 34 | fake_gcs_server_lock = root_tmp_dir / "fake_gcs_server.lock" 35 | 36 | with FileLock(fake_gcs_server_lock): 37 | container: Container 38 | try: 39 | container = docker_client.containers.get(container_name) 40 | port = container.ports.get(f"{GCS_DEFAULT_PORT}/tcp")[0]["HostPort"] 41 | url = f"http://localhost:{port}" 42 | except NotFound: 43 | # Some features, such as signed URLs and resumable uploads, require 44 | # `fake-gcs-server` to know the actual url it will be accessed 45 | # with. We can provide that with -public-host and -external-url. 46 | port = get_free_port() 47 | url = f"http://localhost:{port}" 48 | command = ( 49 | "-backend memory -scheme http " 50 | f"-public-host localhost:{port} -external-url {url} " 51 | ) 52 | container = docker_client.containers.run( 53 | "fsouza/fake-gcs-server:1.52.2", # renovate 54 | name=container_name, 55 | command=command, 56 | stdout=True, 57 | stderr=True, 58 | detach=True, 59 | remove=True, 60 | ports={f"{GCS_DEFAULT_PORT}/tcp": port}, 61 | ) 62 | 63 | wait_until_running(container) 64 | 65 | try: 66 | wait_until( 67 | lambda: requests.get(f"{url}/storage/v1/b", timeout=10).ok, 68 | timeout=30, 69 | ) 70 | except TimeoutError: 71 | raise HealthcheckTimeout( 72 | container.name, 73 | container.logs().decode(), 74 | ) from None 75 | 76 | return url 77 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 98 | __pypackages__/ 99 | 100 | # Celery stuff 101 | celerybeat-schedule 102 | celerybeat.pid 103 | 104 | # SageMath parsed files 105 | *.sage.py 106 | 107 | # Environments 108 | .env 109 | .venv 110 | env/ 111 | venv/ 112 | ENV/ 113 | env.bak/ 114 | venv.bak/ 115 | 116 | # Spyder project settings 117 | .spyderproject 118 | .spyproject 119 | 120 | # Rope project settings 121 | .ropeproject 122 | 123 | # mkdocs documentation 124 | /site 125 | 126 | # mypy 127 | .mypy_cache/ 128 | .dmypy.json 129 | dmypy.json 130 | 131 | # Pyre type checker 132 | .pyre/ 133 | 134 | # pytype static type analyzer 135 | .pytype/ 136 | 137 | # Cython debug symbols 138 | cython_debug/ 139 | -------------------------------------------------------------------------------- /src/pytest_servers/azure.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import logging 4 | from typing import TYPE_CHECKING 5 | 6 | import pytest 7 | import requests 8 | from filelock import FileLock 9 | 10 | from .exceptions import HealthcheckTimeout 11 | from .utils import wait_until, wait_until_running 12 | 13 | if TYPE_CHECKING: 14 | from docker import DockerClient 15 | from docker.models import Container 16 | 17 | AZURITE_PORT = 10000 18 | AZURITE_URL = "http://localhost:{port}" 19 | AZURITE_ACCOUNT_NAME = "devstoreaccount1" 20 | AZURITE_KEY = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==" # noqa: E501 21 | AZURITE_ENDPOINT = f"{AZURITE_URL}/{AZURITE_ACCOUNT_NAME}" 22 | AZURITE_CONNECTION_STRING = f"DefaultEndpointsProtocol=http;AccountName={AZURITE_ACCOUNT_NAME};AccountKey={AZURITE_KEY};BlobEndpoint={AZURITE_ENDPOINT};" # noqa: E501 23 | 24 | logger = logging.getLogger(__name__) 25 | 26 | 27 | @pytest.fixture(scope="session") 28 | def azurite( 29 | docker_client: DockerClient, 30 | tmp_path_factory: pytest.TempPathFactory, 31 | ) -> str: 32 | """Spins up an azurite container. Returns the connection string.""" 33 | from docker.errors import NotFound 34 | 35 | container_name = "pytest-servers-azurite" 36 | 37 | root_tmp_dir = tmp_path_factory.getbasetemp().parent 38 | azurite_lock = root_tmp_dir / "azurite.lock" 39 | 40 | with FileLock(azurite_lock): 41 | try: 42 | container: Container = docker_client.containers.get(container_name) 43 | except NotFound: 44 | container = docker_client.containers.run( 45 | "mcr.microsoft.com/azure-storage/azurite:3.35.0", # renovate 46 | command="azurite-blob --loose --blobHost 0.0.0.0", 47 | name=container_name, 48 | stdout=True, 49 | stderr=True, 50 | detach=True, 51 | remove=True, 52 | ports={f"{AZURITE_PORT}/tcp": None}, # assign a random port 53 | ) 54 | 55 | wait_until_running(container) 56 | port = container.ports.get(f"{AZURITE_PORT}/tcp")[0]["HostPort"] 57 | 58 | def is_healthy() -> bool: 59 | r = requests.get(AZURITE_URL.format(port=port), timeout=3) 60 | return ( 61 | r.status_code == 400 62 | and "Server" in r.headers 63 | and "Azurite" in r.headers["Server"] 64 | ) 65 | 66 | try: 67 | wait_until( 68 | is_healthy, 69 | timeout=30, 70 | ) 71 | except TimeoutError: 72 | raise HealthcheckTimeout( 73 | container.name, 74 | container.logs().decode(), 75 | ) from None 76 | 77 | return AZURITE_CONNECTION_STRING.format(port=port) 78 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | pull_request: 7 | schedule: 8 | - cron: "5 1 * * *" # every day at 01:05 9 | workflow_dispatch: 10 | 11 | env: 12 | FORCE_COLOR: "1" 13 | 14 | concurrency: 15 | group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} 16 | cancel-in-progress: true 17 | 18 | jobs: 19 | tests: 20 | timeout-minutes: 30 21 | runs-on: ${{ matrix.os }} 22 | strategy: 23 | fail-fast: false 24 | matrix: 25 | os: [ubuntu-latest, windows-latest, macos-latest] 26 | pyv: ["3.9", "3.10", "3.11", "3.12", "3.13"] 27 | include: 28 | - {os: ubuntu-latest, pyv: "pypy3.10"} 29 | 30 | steps: 31 | - name: Check out the repository 32 | uses: actions/checkout@v4 33 | with: 34 | fetch-depth: 0 35 | 36 | - name: Set up Python ${{ matrix.pyv }} 37 | uses: actions/setup-python@v5 38 | with: 39 | python-version: ${{ matrix.pyv }} 40 | 41 | - name: Upgrade pip and nox 42 | run: | 43 | python -m pip install --upgrade pip nox 44 | pip --version 45 | nox --version 46 | 47 | - name: Lint code 48 | if: matrix.pyv != 'pypy3.10' 49 | run: nox -s lint 50 | 51 | # https://github.com/iterative/pytest-servers/pull/122 52 | # https://github.com/abiosoft/colima/issues/468 53 | # https://github.com/abiosoft/colima/blob/main/docs/FAQ.md#cannot-connect-to-the-docker-daemon-at-unixvarrundockersock-is-the-docker-daemon-running 54 | # colima v0.5.6 seems to run more stable than the latest - that has occasional network failures (ports are not open) 55 | # see: https://github.com/abiosoft/colima/issues/962 56 | - name: Use colima as default docker host on MacOS 57 | if: matrix.os == 'macos-latest' 58 | run: | 59 | brew install qemu 60 | brew install lima-additional-guestagents 61 | brew install docker lima || true # avoid non-zero exit code if brew link fails 62 | sudo curl -L -o /usr/local/bin/colima https://github.com/abiosoft/colima/releases/download/v0.5.6/colima-Darwin-x86_64 63 | sudo chmod +x /usr/local/bin/colima 64 | colima start 65 | sudo ln -vsf "${HOME}"/.colima/default/docker.sock /var/run/docker.sock 66 | env: 67 | HOMEBREW_NO_AUTO_UPDATE: true 68 | HOMEBREW_NO_INSTALL_CLEANUP: true 69 | HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK: true 70 | HOMEBREW_NO_INSTALL_UPGRADE: true 71 | 72 | - name: Run tests 73 | id: tests 74 | run: nox -s tests-${{ matrix.pyv }} 75 | continue-on-error: ${{ matrix.os == 'macos-latest' }} 76 | env: 77 | COVERAGE_XML: true 78 | 79 | - name: Upload coverage report 80 | if: steps.tests.outcome == 'success' 81 | uses: codecov/codecov-action@v5 82 | 83 | - name: Build package 84 | run: nox -s build 85 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | Contributor Guide 2 | ================= 3 | 4 | Thank you for your interest in improving this project. 5 | This project is open-source under the `Apache 2.0 license`_ and 6 | welcomes contributions in the form of bug reports, feature requests, and pull requests. 7 | 8 | Here is a list of important resources for contributors: 9 | 10 | - `Source Code`_ 11 | - `Issue Tracker`_ 12 | - `Code of Conduct`_ 13 | 14 | .. _Apache 2.0 license: https://opensource.org/licenses/Apache-2.0 15 | .. _Source Code: https://github.com/iterative/pytest-servers 16 | .. _Issue Tracker: https://github.com/iterative/pytest-servers/issues 17 | 18 | How to report a bug 19 | ------------------- 20 | 21 | Report bugs on the `Issue Tracker`_. 22 | 23 | When filing an issue, make sure to answer these questions: 24 | 25 | - Which operating system and Python version are you using? 26 | - Which version of this project are you using? 27 | - What did you do? 28 | - What did you expect to see? 29 | - What did you see instead? 30 | 31 | The best way to get your bug fixed is to provide a test case, 32 | and/or steps to reproduce the issue. 33 | 34 | 35 | How to request a feature 36 | ------------------------ 37 | 38 | Request features on the `Issue Tracker`_. 39 | 40 | 41 | How to set up your development environment 42 | ------------------------------------------ 43 | 44 | You need Python 3.9+ and the following tools: 45 | 46 | - Nox_ 47 | 48 | Install the package with development requirements: 49 | 50 | .. code:: console 51 | 52 | $ pip install nox 53 | 54 | .. _Nox: https://nox.thea.codes/ 55 | 56 | 57 | How to test the project 58 | ----------------------- 59 | 60 | Run the full test suite: 61 | 62 | .. code:: console 63 | 64 | $ nox 65 | 66 | List the available Nox sessions: 67 | 68 | .. code:: console 69 | 70 | $ nox --list-sessions 71 | 72 | You can also run a specific Nox session. 73 | For example, invoke the unit test suite like this: 74 | 75 | .. code:: console 76 | 77 | $ nox --session=tests 78 | 79 | Unit tests are located in the ``tests`` directory, 80 | and are written using the pytest_ testing framework. 81 | 82 | .. _pytest: https://pytest.readthedocs.io/ 83 | 84 | 85 | How to submit changes 86 | --------------------- 87 | 88 | Open a `pull request`_ to submit changes to this project. 89 | 90 | Your pull request needs to meet the following guidelines for acceptance: 91 | 92 | - The Nox test suite must pass without errors and warnings. 93 | - Include unit tests. This project maintains 100% code coverage. 94 | - If your changes add functionality, update the documentation accordingly. 95 | 96 | Feel free to submit early, though—we can always iterate on this. 97 | 98 | To run linting and code formatting checks, you can invoke a `lint` session in nox: 99 | 100 | .. code:: console 101 | 102 | $ nox -s lint 103 | 104 | It is recommended to open an issue before starting work on anything. 105 | This will allow a chance to talk it over with the owners and validate your approach. 106 | 107 | .. _pull request: https://github.com/iterative/pytest-servers/pulls 108 | .. github-only 109 | .. _Code of Conduct: CODE_OF_CONDUCT.rst 110 | -------------------------------------------------------------------------------- /src/pytest_servers/fixtures.py: -------------------------------------------------------------------------------- 1 | from typing import TYPE_CHECKING 2 | 3 | import pytest 4 | from upath import UPath 5 | 6 | from .azure import azurite # noqa: F401 7 | from .factory import TempUPathFactory 8 | from .gcs import fake_gcs_server # noqa: F401 9 | from .s3 import MockedS3Server, s3_server, s3_server_config # noqa: F401 10 | from .utils import docker_client, monkeypatch_session # noqa: F401 11 | 12 | if TYPE_CHECKING: 13 | from pytest import MonkeyPatch # noqa: PT013 14 | 15 | 16 | def _version_aware(request: pytest.FixtureRequest) -> bool: 17 | return "versioning" in request.fixturenames 18 | 19 | 20 | @pytest.fixture 21 | def versioning(): # noqa: ANN201 22 | """Enable versioning for supported remotes.""" 23 | 24 | 25 | @pytest.fixture(scope="session") 26 | def tmp_upath_factory( 27 | request: pytest.FixtureRequest, 28 | tmp_path_factory: pytest.TempPathFactory, 29 | ) -> TempUPathFactory: 30 | """Return a TempUPathFactory instance for the test session.""" 31 | return TempUPathFactory.from_request(request, tmp_path_factory) 32 | 33 | 34 | @pytest.fixture 35 | def tmp_s3_path( 36 | tmp_upath_factory: TempUPathFactory, 37 | request: pytest.FixtureRequest, 38 | ) -> UPath: 39 | """Temporary path on a mocked S3 remote.""" 40 | return tmp_upath_factory.mktemp("s3", version_aware=_version_aware(request)) 41 | 42 | 43 | @pytest.fixture 44 | def tmp_local_path( 45 | tmp_upath_factory: TempUPathFactory, 46 | monkeypatch: "MonkeyPatch", 47 | ) -> UPath: 48 | """Return a temporary path.""" 49 | ret = tmp_upath_factory.mktemp() 50 | monkeypatch.chdir(ret) 51 | return ret 52 | 53 | 54 | @pytest.fixture 55 | def tmp_azure_path(tmp_upath_factory: TempUPathFactory) -> UPath: 56 | """Return a temporary path.""" 57 | return tmp_upath_factory.mktemp("azure") 58 | 59 | 60 | @pytest.fixture 61 | def tmp_memory_path(tmp_upath_factory: TempUPathFactory) -> UPath: 62 | """Return a temporary path in a MemoryFileSystem.""" 63 | return tmp_upath_factory.mktemp("memory") 64 | 65 | 66 | @pytest.fixture 67 | def tmp_gcs_path( 68 | tmp_upath_factory: TempUPathFactory, 69 | request: pytest.FixtureRequest, 70 | ) -> UPath: 71 | """Return a temporary path.""" 72 | return tmp_upath_factory.mktemp( 73 | "gcs", 74 | version_aware=_version_aware(request), 75 | ) 76 | 77 | 78 | @pytest.fixture 79 | def tmp_upath( 80 | tmp_upath_factory: TempUPathFactory, 81 | request: pytest.FixtureRequest, 82 | ) -> UPath: 83 | """Temporary directory on different filesystems. 84 | 85 | Usage: 86 | >>> @pytest.mark.parametrize("tmp_upath", ["local", "s3", "azure"], indirect=True) 87 | >>> def test_something(tmp_upath): 88 | >>> pass 89 | """ 90 | param = getattr(request, "param", "local") 91 | version_aware = _version_aware(request) 92 | if version_aware and param not in ("gcs", "s3"): 93 | msg = f"Versioning is not supported for {param}" 94 | raise NotImplementedError(msg) 95 | if param == "local": 96 | return tmp_upath_factory.mktemp() 97 | if param == "memory": 98 | return tmp_upath_factory.mktemp("memory") 99 | if param == "s3": 100 | return tmp_upath_factory.mktemp("s3", version_aware=version_aware) 101 | if param == "azure": 102 | return tmp_upath_factory.mktemp("azure") 103 | if param == "gcs": 104 | return tmp_upath_factory.mktemp("gcs", version_aware=version_aware) 105 | if param == "gs": 106 | return tmp_upath_factory.mktemp("gs", version_aware=version_aware) 107 | msg = f"unknown {param=}" 108 | raise ValueError(msg) 109 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools>=48", "setuptools_scm[toml]>=6.3.1"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [project] 6 | name = "pytest-servers" 7 | description = "pytest servers" 8 | readme = "README.rst" 9 | license = {text = "Apache-2.0"} 10 | authors = [{name = "Iterative", email = "support@dvc.org"}] 11 | classifiers = [ 12 | "Programming Language :: Python :: 3", 13 | "Programming Language :: Python :: 3.9", 14 | "Programming Language :: Python :: 3.10", 15 | "Programming Language :: Python :: 3.11", 16 | "Programming Language :: Python :: 3.12", 17 | "Programming Language :: Python :: 3.13", 18 | "Development Status :: 3 - Alpha", 19 | "Framework :: Pytest", 20 | "Intended Audience :: Developers" 21 | ] 22 | requires-python = ">=3.9" 23 | dynamic = ["version"] 24 | dependencies = [ 25 | "pytest>=6.2", 26 | "requests", 27 | "fsspec", 28 | "universal-pathlib>=0.2.0", 29 | "filelock>=3.3.2" 30 | ] 31 | 32 | [project.entry-points.pytest11] 33 | pytest-servers = "pytest_servers.fixtures" 34 | 35 | [project.urls] 36 | Issues = "https://github.com/iterative/pytest-servers/issues" 37 | Source = "https://github.com/iterative/pytest-servers" 38 | 39 | [project.optional-dependencies] 40 | docker = ["docker>6"] 41 | s3 = [ 42 | "moto[server]>=4", 43 | "s3fs[boto3]>=2022.02.0", 44 | "botocore>=1.31.17", # Temporary: explicitly define this to avoid pip backtracking while installing moto[server] 45 | "PyYAML>=6.0.2" 46 | ] 47 | azure = [ 48 | "adlfs>=2022.02.22", 49 | "pytest-servers[docker]" 50 | ] 51 | gcs = [ 52 | "gcsfs>=2022.02.22", 53 | "pytest-servers[docker]" 54 | ] 55 | all = ["pytest-servers[s3,azure,gcs]"] 56 | tests = [ 57 | # see https://github.com/nedbat/coveragepy/issues/1341#issuecomment-1228942657 58 | "coverage-enable-subprocess", 59 | "coverage[toml]>6", 60 | "pytest-sugar==1.0.0", 61 | "pytest-xdist==3.8.0", 62 | "mypy==1.17.0", 63 | "types-requests" 64 | ] 65 | dev = [ 66 | "pytest-servers[all]", 67 | "pytest-servers[tests]" 68 | ] 69 | 70 | [tool.setuptools_scm] 71 | 72 | [tool.setuptools.packages.find] 73 | where = ["src"] 74 | namespaces = false 75 | 76 | [tool.pytest.ini_options] 77 | addopts = "-ra -n=auto" 78 | 79 | [tool.coverage.run] 80 | branch = true 81 | parallel = true 82 | concurrency = ["multiprocessing", "thread"] 83 | source = ["pytest_servers", "tests"] 84 | 85 | [tool.coverage.paths] 86 | source = ["src", "*/site-packages"] 87 | 88 | [tool.coverage.report] 89 | show_missing = true 90 | exclude_lines = [ 91 | "pragma: no cover", 92 | "if __name__ == .__main__.:", 93 | "if typing.TYPE_CHECKING:", 94 | "if TYPE_CHECKING:", 95 | "raise NotImplementedError", 96 | "raise AssertionError", 97 | "@overload" 98 | ] 99 | 100 | [tool.mypy] 101 | # Error output 102 | show_column_numbers = true 103 | show_error_codes = true 104 | show_error_context = true 105 | show_traceback = true 106 | pretty = true 107 | check_untyped_defs = false 108 | # Warnings 109 | warn_no_return = true 110 | warn_redundant_casts = true 111 | warn_unreachable = true 112 | ignore_missing_imports = true 113 | files = ["src", "tests"] 114 | 115 | [tool.codespell] 116 | ignore-words-list = " " 117 | skip = "CODE_OF_CONDUCT.rst" 118 | 119 | [tool.ruff] 120 | line-length = 88 121 | target-version = "py38" 122 | output-format = "full" 123 | show-fixes = true 124 | 125 | [tool.ruff.lint] 126 | ignore = [ 127 | "S101", # assert 128 | "PLR2004", # magic-value-comparison 129 | "PLW2901", # redefined-loop-name 130 | "ISC001", # single-line-implicit-string-concatenation 131 | "SIM105", # suppressible-exception 132 | "SIM108", # if-else-block-instead-of-if-exp 133 | "D203", # one blank line before class 134 | "D213", # multi-line-summary-second-line 135 | "D100", # missing docstring in public module 136 | "D101", # missing docstring in public class 137 | "D102", # missing docstring in public method 138 | "D103", # missing docstring in public function 139 | "D104", # missing docstring in public package 140 | "D105", # missing docstring in magic method 141 | "D107", # missing docstring in method 142 | "ANN002", # missing type annotation 143 | "ANN101", # missing type annotation 144 | "ANN204", # missing return type annotation 145 | "PT004", # pytest-missing-fixture-name-underscore 146 | "PLC0415" # top level imports 147 | ] 148 | select = ["ALL"] 149 | 150 | [tool.ruff.lint.per-file-ignores] 151 | "noxfile.py" = ["D", "PTH"] 152 | "tests/**" = [ 153 | "S", 154 | "ARG001", 155 | "ARG002", 156 | "ANN", 157 | "D", 158 | "PD011" 159 | ] 160 | "src/pytest_servers/fixtures.py" = [ 161 | "PT001" # pytest-fixture-incorrect-parentheses-style 162 | ] 163 | "src/pytest_servers/factory.py" = [ 164 | "ANN003" # missing type kwargs 165 | ] 166 | "docs/**" = ["INP"] 167 | 168 | [tool.ruff.lint.flake8-type-checking] 169 | strict = true 170 | 171 | [tool.ruff.lint.isort] 172 | known-first-party = ["pytest_servers"] 173 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | pytest servers 2 | -------------- 3 | 4 | |PyPI| |Status| |Python Version| |License| 5 | 6 | |Tests| |Codecov| |pre-commit| |Black| 7 | 8 | .. |PyPI| image:: https://img.shields.io/pypi/v/pytest-servers.svg 9 | :target: https://pypi.org/project/pytest-servers/ 10 | :alt: PyPI 11 | .. |Status| image:: https://img.shields.io/pypi/status/pytest-servers.svg 12 | :target: https://pypi.org/project/pytest-servers/ 13 | :alt: Status 14 | .. |Python Version| image:: https://img.shields.io/pypi/pyversions/pytest-servers 15 | :target: https://pypi.org/project/pytest-servers 16 | :alt: Python Version 17 | .. |License| image:: https://img.shields.io/pypi/l/pytest-servers 18 | :target: https://opensource.org/licenses/Apache-2.0 19 | :alt: License 20 | .. |Tests| image:: https://github.com/iterative/pytest-servers/workflows/Tests/badge.svg 21 | :target: https://github.com/iterative/pytest-servers/actions?workflow=Tests 22 | :alt: Tests 23 | .. |Codecov| image:: https://codecov.io/gh/iterative/pytest-servers/branch/main/graph/badge.svg 24 | :target: https://app.codecov.io/gh/iterative/pytest-servers 25 | :alt: Codecov 26 | .. |pre-commit| image:: https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white 27 | :target: https://github.com/pre-commit/pre-commit 28 | :alt: pre-commit 29 | .. |Black| image:: https://img.shields.io/badge/code%20style-black-000000.svg 30 | :target: https://github.com/psf/black 31 | :alt: Black 32 | 33 | 34 | Features 35 | -------- 36 | 37 | Create temporary directories on the following filesystems: 38 | 39 | - Local fs 40 | - In-memory fs 41 | - S3, both using mock S3 remotes (https://github.com/spulec/moto) and real S3 remotes 42 | - Azure, both using mock Azure remotes (https://github.com/Azure/Azurite) via docker and using real Azure Storage remotes 43 | - Google Cloud Storage, both using mock GCS remote (https://github.com/fsouza/fake-gcs-server) via docker and using real Google Storage Remotes 44 | 45 | Installation 46 | ------------ 47 | 48 | You can install *pytest servers* via pip_ from PyPI_: 49 | 50 | .. code:: console 51 | 52 | $ pip install pytest-servers 53 | 54 | To use temporary S3 paths: 55 | 56 | .. code:: console 57 | 58 | $ pip install pytest-servers[s3] 59 | 60 | To use temporary Azure paths 61 | 62 | .. code:: console 63 | 64 | $ pip install pytest-servers[azure] 65 | 66 | To use temporary Google Cloud Storage paths 67 | 68 | .. code:: console 69 | 70 | $ pip install pytest-servers[gcs] 71 | 72 | To install all extras: 73 | 74 | .. code:: console 75 | 76 | $ pip install pytest-servers[all] 77 | 78 | Usage 79 | ------------ 80 | 81 | The main fixture provided by `pytest-servers` provides is `tmp_upath_factory`, which can be used 82 | to generate temporary paths on different (mocked) filesystems: 83 | 84 | .. code:: python 85 | 86 | def test_something_on_s3(tmp_upath_factory): 87 | path = tmp_upath_factory.mktemp("s3") 88 | foo = path / "foo" 89 | foo.write_text("foo") 90 | ... 91 | 92 | `mktemp` supports the following filesystem types: 93 | 94 | - ``local`` (local filesystem) 95 | - ``memory`` (in-memory filesystem) 96 | - ``s3`` (Amazon S3) 97 | - ``gcs`` (Google Cloud Storage) 98 | - ``azure`` (Azure Storage) 99 | 100 | Some convenience fixtures that wrap `tmp_upath_factory.mktemp` and return a paths on these filesystems are also available: 101 | 102 | - ``tmp_local_path`` 103 | - ``tmp_memory_path`` 104 | - ``tmp_s3_path`` 105 | - ``tmp_gcs_path`` 106 | - ``tmp_azure_path`` 107 | 108 | The `tmp_upath` fixture can be used for parametrizing paths with pytest's indirect parametrization: 109 | 110 | .. code:: python 111 | 112 | @pytest.mark.parametrize("tmp_upath", ["local", "s3", "gcs", "gs"], indirect=True) 113 | def test_something(tmp_upath): 114 | pass 115 | 116 | In order to use real remotes instead of mocked ones, use `tmp_upath_factory` with the following methods 117 | 118 | - ``tmp_upath_factory.s3(region_name, client_kwargs)`` where client_kwargs are passed to the underlying S3FileSystem/boto client 119 | - ``tmp_upath_factory.gcs(endpoint_url)`` 120 | - ``tmp_upath_factory.azure(connection_string)`` 121 | 122 | 123 | Versioning support can be used by using the `versioning` fixture. This is currently supported for s3 and gcs remotes 124 | 125 | .. code:: python 126 | 127 | # using mktemp 128 | def test_something_on_s3_versioned(tmp_upath_factory): 129 | path = tmp_upath_factory.mktemp("s3", version_aware=True) 130 | assert path.fs.version_aware # bucket has versioning enabled 131 | 132 | # or, using remote-specific fixtures 133 | def test_something_on_s3_versioned(tmp_s3_path, versioning): 134 | assert tmp_s3_path.fs.version_aware # bucket has versioning enabled 135 | 136 | 137 | Contributing 138 | ------------ 139 | 140 | Contributions are very welcome. 141 | To learn more, see the `Contributor Guide`_. 142 | 143 | License 144 | -------------- 145 | Distributed under the terms of the `Apache 2.0 license`_, 146 | *pytest servers* is free and open source software. 147 | 148 | Issues 149 | ------------- 150 | 151 | If you encounter any problems, 152 | please `file an issue`_ along with a detailed description. 153 | 154 | 155 | .. _Apache 2.0 license: https://opensource.org/licenses/Apache-2.0 156 | .. _PyPI: https://pypi.org/ 157 | .. _file an issue: https://github.com/iterative/pytest-servers/issues 158 | .. _pip: https://pip.pypa.io/ 159 | .. github-only 160 | .. _Contributor Guide: CONTRIBUTING.rst 161 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.rst: -------------------------------------------------------------------------------- 1 | Contributor Covenant Code of Conduct 2 | ==================================== 3 | 4 | Our Pledge 5 | ---------- 6 | 7 | We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. 8 | 9 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. 10 | 11 | 12 | Our Standards 13 | ------------- 14 | 15 | Examples of behavior that contributes to a positive environment for our community include: 16 | 17 | - Demonstrating empathy and kindness toward other people 18 | - Being respectful of differing opinions, viewpoints, and experiences 19 | - Giving and gracefully accepting constructive feedback 20 | - Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience 21 | - Focusing on what is best not just for us as individuals, but for the overall community 22 | 23 | Examples of unacceptable behavior include: 24 | 25 | - The use of sexualized language or imagery, and sexual attention or 26 | advances of any kind 27 | - Trolling, insulting or derogatory comments, and personal or political attacks 28 | - Public or private harassment 29 | - Publishing others' private information, such as a physical or email 30 | address, without their explicit permission 31 | - Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | Enforcement Responsibilities 35 | ---------------------------- 36 | 37 | Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. 38 | 39 | Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. 40 | 41 | 42 | Scope 43 | ----- 44 | 45 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. 46 | 47 | 48 | Enforcement 49 | ----------- 50 | 51 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at support@dvc.org. All complaints will be reviewed and investigated promptly and fairly. 52 | 53 | All community leaders are obligated to respect the privacy and security of the reporter of any incident. 54 | 55 | 56 | Enforcement Guidelines 57 | ---------------------- 58 | 59 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: 60 | 61 | 62 | 1. Correction 63 | ~~~~~~~~~~~~~ 64 | 65 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. 66 | 67 | **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. 68 | 69 | 70 | 2. Warning 71 | ~~~~~~~~~~ 72 | 73 | **Community Impact**: A violation through a single incident or series of actions. 74 | 75 | **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. 76 | 77 | 78 | 3. Temporary Ban 79 | ~~~~~~~~~~~~~~~~ 80 | 81 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. 82 | 83 | **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. 84 | 85 | 86 | 4. Permanent Ban 87 | ~~~~~~~~~~~~~~~~ 88 | 89 | **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. 90 | 91 | **Consequence**: A permanent ban from any sort of public interaction within the community. 92 | 93 | 94 | Attribution 95 | ----------- 96 | 97 | This Code of Conduct is adapted from the `Contributor Covenant `__, version 2.0, 98 | available at https://www.contributor-covenant.org/version/2/0/code_of_conduct/. 99 | 100 | Community Impact Guidelines were inspired by `Mozilla’s code of conduct enforcement ladder `__. 101 | 102 | .. _homepage: https://www.contributor-covenant.org 103 | 104 | For answers to common questions about this code of conduct, see the FAQ at 105 | https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. 106 | -------------------------------------------------------------------------------- /src/pytest_servers/factory.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import os 4 | import sys 5 | import tempfile 6 | from typing import Any, ClassVar 7 | 8 | import pytest 9 | from upath import UPath 10 | 11 | from pytest_servers.exceptions import RemoteUnavailable 12 | from pytest_servers.local import LocalPath 13 | from pytest_servers.utils import random_string 14 | 15 | from .utils import MockRemote 16 | 17 | 18 | class TempUPathFactory: 19 | """Factory for temporary directories with universal-pathlib and mocked servers.""" 20 | 21 | mock_remotes: ClassVar[dict[str, MockRemote]] = { 22 | "azure": MockRemote( 23 | "azurite", 24 | "_azure_connection_string", 25 | requires_docker=True, 26 | ), 27 | "gcs": MockRemote( 28 | "fake_gcs_server", 29 | "_gcs_endpoint_url", 30 | requires_docker=True, 31 | ), 32 | "gs": MockRemote( 33 | "fake_gcs_server", 34 | "_gcs_endpoint_url", 35 | requires_docker=True, 36 | ), 37 | "s3": MockRemote( 38 | "s3_server", 39 | "_s3_client_kwargs", 40 | requires_docker=False, 41 | ), 42 | } 43 | 44 | def __init__( 45 | self, 46 | s3_client_kwargs: dict[str, str] | None = None, 47 | azure_connection_string: str | None = None, 48 | gcs_endpoint_url: str | None = None, 49 | ) -> None: 50 | self._request: pytest.FixtureRequest | None = None 51 | 52 | self._local_path_factory: pytest.TempPathFactory | None = None 53 | self._azure_connection_string = azure_connection_string 54 | self._gcs_endpoint_url = gcs_endpoint_url 55 | self._s3_client_kwargs = s3_client_kwargs 56 | 57 | @classmethod 58 | def from_request( 59 | cls: type[TempUPathFactory], 60 | request: pytest.FixtureRequest, 61 | tmp_path_factory: pytest.TempPathFactory, 62 | *args, 63 | **kwargs, 64 | ) -> TempUPathFactory: 65 | """Create a factory according to pytest configuration.""" 66 | tmp_upath_factory = cls(*args, **kwargs) 67 | tmp_upath_factory._local_path_factory = tmp_path_factory 68 | tmp_upath_factory._request = request 69 | 70 | return tmp_upath_factory 71 | 72 | def _mock_remote_setup(self, fs: str) -> None: 73 | try: 74 | fixture, config_attr, needs_docker = self.mock_remotes[fs] 75 | except KeyError: 76 | msg = f"No mock remote available for fs: {fs}" 77 | raise RemoteUnavailable(msg) from None 78 | 79 | if getattr(self, config_attr): 80 | # remote is already configured 81 | return 82 | 83 | if needs_docker and os.environ.get("CI") and sys.platform == "win32": 84 | pytest.skip( 85 | "disabled for Windows on Github Actions: " 86 | "https://github.com/actions/runner-images/issues/1143", 87 | ) 88 | 89 | assert self._request 90 | remote_config = self._request.getfixturevalue(fixture) 91 | 92 | setattr(self, config_attr, remote_config) 93 | 94 | def mktemp( # noqa: C901 # complex-structure 95 | self, 96 | fs: str = "local", 97 | *, 98 | mock: bool = True, 99 | version_aware: bool = False, 100 | **kwargs, 101 | ) -> UPath: 102 | """Create a new temporary directory managed by the factory. 103 | 104 | :param fs: 105 | Filesystem type, one of 106 | - local (default) 107 | - memory 108 | - s3 109 | - azure 110 | - gcs 111 | - gs (alias for gcs) 112 | 113 | :param mock: 114 | Set to False to use real remotes 115 | 116 | :returns: 117 | :class:`upath.Upath` to the new directory. 118 | """ 119 | if fs == "local": 120 | if version_aware: 121 | msg = f"not implemented for {fs=}" 122 | raise NotImplementedError(msg) 123 | return self.local() 124 | if fs == "memory": 125 | if version_aware: 126 | msg = f"not implemented for {fs=}" 127 | raise NotImplementedError(msg) 128 | return self.memory(**kwargs) 129 | 130 | if mock: 131 | try: 132 | self._mock_remote_setup(fs) 133 | except Exception as exc: # noqa: BLE001 134 | assert self._request 135 | from_exc = exc if self._request.config.option.verbose >= 1 else None 136 | msg = f"{fs}: Failed to setup mock remote: {exc}" + ( 137 | "" if from_exc else "\nRun `pytest -v` for more details" 138 | ) 139 | raise RemoteUnavailable(msg) from from_exc 140 | 141 | if fs == "s3": 142 | return self.s3( 143 | client_kwargs=self._s3_client_kwargs, 144 | version_aware=version_aware, 145 | **kwargs, 146 | ) 147 | if fs == "azure": 148 | if version_aware and mock: 149 | msg = f"not implemented for {fs=}" 150 | raise NotImplementedError(msg) 151 | if not self._azure_connection_string: 152 | msg = "missing connection string" 153 | raise RemoteUnavailable(msg) 154 | return self.azure(connection_string=self._azure_connection_string, **kwargs) 155 | 156 | if fs == "gcs": 157 | return self.gcs( 158 | endpoint_url=self._gcs_endpoint_url, 159 | version_aware=version_aware, 160 | **kwargs, 161 | ) 162 | 163 | if fs == "gs": 164 | return self.gs( 165 | endpoint_url=self._gcs_endpoint_url, 166 | version_aware=version_aware, 167 | **kwargs, 168 | ) 169 | raise ValueError(fs) 170 | 171 | def local(self) -> LocalPath: 172 | """Create a local temporary path.""" 173 | mktemp = ( 174 | self._local_path_factory.mktemp 175 | if self._local_path_factory is not None 176 | else tempfile.mktemp 177 | ) 178 | return LocalPath(mktemp("pytest-servers")) # type: ignore[operator] 179 | 180 | def s3( 181 | self, 182 | client_kwargs: dict[str, Any] | None = None, 183 | *, 184 | version_aware: bool = False, 185 | **kwargs, 186 | ) -> UPath: 187 | """Create a new S3 bucket and returns an UPath instance. 188 | 189 | `client_kwargs` can be used to configure the underlying boto client 190 | """ 191 | bucket_name = f"pytest-servers-{random_string()}" 192 | path = UPath( 193 | f"s3://{bucket_name}", 194 | endpoint_url=client_kwargs.get("endpoint_url") if client_kwargs else None, 195 | client_kwargs=client_kwargs, 196 | version_aware=version_aware, 197 | **kwargs, 198 | ) 199 | if version_aware: 200 | from botocore.session import Session 201 | 202 | session = Session() 203 | client = session.create_client("s3", **client_kwargs) 204 | client.create_bucket( 205 | Bucket=bucket_name, 206 | ACL="public-read", 207 | CreateBucketConfiguration={ 208 | "LocationConstraint": client_kwargs.get("region_name"), 209 | } 210 | if client_kwargs 211 | else None, 212 | ) 213 | 214 | client.put_bucket_versioning( 215 | Bucket=bucket_name, 216 | VersioningConfiguration={"Status": "Enabled"}, 217 | ) 218 | else: 219 | path.mkdir() 220 | 221 | return path 222 | 223 | def azure( 224 | self, 225 | connection_string: str, 226 | **kwargs, 227 | ) -> UPath: 228 | """Create a new container and return an UPath instance.""" 229 | from azure.storage.blob import BlobServiceClient 230 | 231 | container_name = f"pytest-servers-{random_string()}" 232 | client = BlobServiceClient.from_connection_string(conn_str=connection_string) 233 | client.create_container(container_name) 234 | 235 | return UPath( 236 | f"az://{container_name}", 237 | connection_string=connection_string, 238 | **kwargs, 239 | ) 240 | 241 | def memory( 242 | self, 243 | **kwargs, 244 | ) -> UPath: 245 | """Create a new temporary in-memory path returns an UPath instance.""" 246 | path = UPath( 247 | f"memory:/{random_string()}", 248 | **kwargs, 249 | ) 250 | path.mkdir() 251 | return path 252 | 253 | def gs( 254 | self, 255 | endpoint_url: str | None = None, 256 | *, 257 | version_aware: bool = False, 258 | **kwargs, 259 | ) -> UPath: 260 | return self._gs( 261 | "gs", 262 | endpoint_url=endpoint_url, 263 | version_aware=version_aware, 264 | **kwargs, 265 | ) 266 | 267 | def gcs( 268 | self, 269 | endpoint_url: str | None = None, 270 | *, 271 | version_aware: bool = False, 272 | **kwargs, 273 | ) -> UPath: 274 | return self._gs( 275 | "gcs", 276 | endpoint_url=endpoint_url, 277 | version_aware=version_aware, 278 | **kwargs, 279 | ) 280 | 281 | def _gs( 282 | self, 283 | scheme: str, 284 | endpoint_url: str | None = None, 285 | *, 286 | version_aware: bool = False, 287 | **kwargs, 288 | ) -> UPath: 289 | """Create a new gcs bucket and return an UPath instance. 290 | 291 | `endpoint_url` can be used to use custom servers 292 | (e.g. fake-gcs-server). 293 | """ 294 | client_kwargs: dict[str, Any] = {} 295 | if endpoint_url: 296 | client_kwargs["endpoint_url"] = endpoint_url 297 | 298 | bucket_name = f"pytest-servers-{random_string()}" 299 | 300 | path = UPath( 301 | f"{scheme}://{bucket_name}", 302 | version_aware=version_aware, 303 | **client_kwargs, 304 | **kwargs, 305 | ) 306 | path.fs.mkdir(bucket_name, enable_versioning=version_aware, exist_ok=False) 307 | return path 308 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2022 Iterative. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------