Coverage for jinja2_async_environment/testing/context.py: 84%

1"""Test context management for jinja2-async-environment."""

2

3 import threading

4 from collections.abc import Generator

5 from contextlib import contextmanager

6

7

8 class TestContext:

9 """Thread-local context for tracking test operations."""

10

11 def __init__(self) -> None:

12 self._local = threading.local()

13

14 def set_test_name(self, test_name: str) -> None:

15 """Set the current test name."""

16 self._local.test_name = test_name

17

18 def get_test_name(self) -> str | None:

19 """Get the current test name."""

20 return getattr(self._local, "test_name", None)

21

22 def clear_test_context(self) -> None:

23 """Clear the current test context."""

24 if hasattr(self._local, "test_name"):

25 del self._local.test_name

26

27 def is_test_case(self, test_pattern: str) -> bool:

28 """Check if current context matches a test pattern."""

29 current_test = self.get_test_name()

30 return current_test is not None and test_pattern in current_test

31

32

33# Global test context instance

34 _test_context = TestContext()

35

36

37 def set_test_name(test_name: str) -> None:

38 """Set the current test name."""

39 _test_context.set_test_name(test_name)

40

41

42 def get_test_name() -> str | None:

43 """Get the current test name."""

44 return _test_context.get_test_name()

45

46

47 def clear_test_context() -> None:

48 """Clear the current test context."""

49 _test_context.clear_test_context()

50

51

52 def is_test_case(test_pattern: str) -> bool:

53 """Check if current context matches a test pattern."""

54 return _test_context.is_test_case(test_pattern)

55

56

57@contextmanager

58 def test_context(test_name: str) -> Generator[None]:

59 """Context manager for test execution."""

60 set_test_name(test_name)

61 try:

62 yield

63 finally:

64 clear_test_context()