Coverage for jinja2_async_environment/testing/fixtures.py: 100%

1"""Testing fixtures for jinja2-async-environment."""

2

3 from collections.abc import Generator

4 from contextlib import contextmanager

5 from typing import Any

6

7 from .context import TestContext, clear_test_context, set_test_name

8

9# Aliases for backward compatibility

10 LoaderContext = TestContext

11

12

13 class UnifiedCache:

14 """Unified cache for backward compatibility."""

15

16 def __init__(self) -> None:

17 self._cache: dict[str, Any] = {}

18

19 def clear_all(self) -> None:

20 """Clear all cache entries."""

21 self._cache.clear()

22

23 def get(self, key: str, default: Any = None) -> Any:

24 """Get value from cache."""

25 return self._cache.get(key, default)

26

27 def set(self, key: str, value: Any) -> None:

28 """Set value in cache."""

29 self._cache[key] = value

30

31

32# Global unified cache instance

33 _unified_cache = UnifiedCache()

34

35

36 def _clear_expired_cache() -> None:

37 """Clear expired cache entries (backward compatibility)."""

38 pass

39

40

41@contextmanager

42 def isolated_test_context(test_name: str) -> Generator[None]:

43 """Context manager for isolated test execution with proper cleanup."""

44 import gc

45

46 # Set test context

47 set_test_name(test_name)

48

49 # Force garbage collection to clear any lingering references

50 gc.collect()

51

52 try:

53 yield

54 finally:

55 # Always cleanup after test

56 clear_test_context()

57 # Force garbage collection after test

58 gc.collect()

59

60

61# Backward compatibility exports

62 _loader_context = None

63 set_test_context = set_test_name

64

65

66 __all__ = [

67 "isolated_test_context",

68 "LoaderContext",

69 "TestContext",

70 "UnifiedCache",

71 "_loader_context",

72 "_unified_cache",

73 "_clear_expired_cache",

74 "set_test_context",

75 "clear_test_context",

76]