Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: create config.isolate_data_folder() method #2139

Merged
merged 2 commits into from
Jun 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion src/ape/managers/config.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import os
from collections.abc import Iterator
from contextlib import contextmanager
from functools import cached_property
from pathlib import Path
from typing import Any, Optional
Expand All @@ -8,7 +10,7 @@
from ape.api import PluginConfig
from ape.api.config import ApeConfig
from ape.managers.base import BaseManager
from ape.utils import log_instead_of_fail
from ape.utils import create_tempdir, in_tempdir, log_instead_of_fail
from ape.utils.basemodel import (
ExtraAttributesMixin,
ExtraModelAttributes,
Expand Down Expand Up @@ -120,6 +122,27 @@ def get_config(self, plugin_name: str) -> PluginConfig:
# Empty config.
return PluginConfig()

@contextmanager
def isolate_data_folder(self) -> Iterator[Path]:
"""
Change Ape's DATA_FOLDER to point a temporary path,
in a context, for testing purposes. Any data
cached to disk will not persist.
"""
original_data_folder = self.DATA_FOLDER
if in_tempdir(original_data_folder):
# Already isolated.
yield original_data_folder

else:
try:
with create_tempdir() as temp_data_folder:
self.DATA_FOLDER = temp_data_folder
yield temp_data_folder

finally:
self.DATA_FOLDER = original_data_folder


def merge_configs(*cfgs: dict) -> dict:
if len(cfgs) == 0:
Expand Down
7 changes: 4 additions & 3 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import shutil
import subprocess
import sys
import tempfile
import time
from collections.abc import Callable, Sequence
from contextlib import contextmanager
Expand All @@ -30,7 +29,9 @@
explorer_test = pytest.mark.xdist_group(name="explorer-tests")

# Ensure we don't persist any .ape data or using existing.
DATA_FOLDER = Path(tempfile.mkdtemp()).resolve()

_DATA_FOLDER_CTX = ape.config.isolate_data_folder()
DATA_FOLDER = _DATA_FOLDER_CTX.__enter__()
ape.config.DATA_FOLDER = DATA_FOLDER


Expand Down Expand Up @@ -59,7 +60,7 @@ def setenviron(monkeypatch):
@pytest.fixture(scope="session", autouse=True)
def clean_temp_data_folder():
yield
shutil.rmtree(DATA_FOLDER)
_DATA_FOLDER_CTX.__exit__(None, None, None)


@pytest.fixture(scope="session", autouse=True)
Expand Down
Loading