Skip to content

Commit

Permalink
feat: create config.isolate_data_folder() method (#2139)
Browse files Browse the repository at this point in the history
  • Loading branch information
antazoey authored Jun 14, 2024
1 parent 114781d commit ff3754e
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
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

0 comments on commit ff3754e

Please sign in to comment.