Coverage for jinja2_async_environment/compiler_modules/dependencies.py: 98%

1"""Dependency resolution for template filters and tests."""

2

3 import typing as t

4

5 if t.TYPE_CHECKING:

6 from .codegen import AsyncCodeGenerator

7

8

9 class DependencyResolver:

10 """Utility class for resolving template dependencies like filters and tests."""

11

12 def __init__(self, code_generator: "AsyncCodeGenerator") -> None:

13 self.code_generator = code_generator

14

15 def setup_filter_dependency(self, name: str) -> None:

16 """Set up a single filter dependency with error handling."""

17 if name in self.code_generator.filters:

18 return

19

20 self.code_generator.filters[name] = self.code_generator.temporary_identifier()

21 filter_var = self.code_generator.filters[name]

22

23 self.code_generator.writeline("try:")

24 self.code_generator.indent()

25 self.code_generator.writeline(f"{filter_var} = environment.filters[{name! r}]")

26 self.code_generator.outdent()

27 self.code_generator.writeline("except KeyError:")

28 self.code_generator.indent()

29 self.code_generator.writeline("@internalcode")

30 self.code_generator.writeline(f"def {filter_var}(*unused):")

31 self.code_generator.indent()

32 self.code_generator.writeline(

33 f'raise TemplateRuntimeError("No filter named {name! r} found.")'

34 )

35 self.code_generator.outdent()

36 self.code_generator.outdent()

37

38 def setup_test_dependency(self, name: str) -> None:

39 """Set up a single test dependency with error handling."""

40 if name in self.code_generator.tests:

41 return

42

43 self.code_generator.tests[name] = self.code_generator.temporary_identifier()

44 test_var = self.code_generator.tests[name]

45

46 self.code_generator.writeline("try:")

47 self.code_generator.indent()

48 self.code_generator.writeline(f"{test_var} = environment.tests[{name! r}]")

49 self.code_generator.outdent()

50 self.code_generator.writeline("except KeyError:")

51 self.code_generator.indent()

52 self.code_generator.writeline("@internalcode")

53 self.code_generator.writeline(f"def {test_var}(*unused):")

54 self.code_generator.indent()

55 self.code_generator.writeline(

56 f'raise TemplateRuntimeError("No test named {name! r} found.")'

57 )

58 self.code_generator.outdent()

59 self.code_generator.outdent()