1515from langchain_core .prompts .few_shot_with_templates import FewShotPromptWithTemplates
1616from langchain_core .prompts .image import ImagePromptTemplate
1717
18+ jinja2 = pytest .importorskip ("jinja2" )
19+
1820
1921@pytest .mark .requires ("jinja2" )
2022class TestPromptTemplateJinja2Unrestricted :
@@ -54,8 +56,6 @@ def __init__(self, value: str) -> None:
5456
5557 def test_dangerous_patterns_blocked (self ) -> None :
5658 """Test that dangerous patterns are still blocked by SandboxedEnvironment."""
57- import jinja2
58-
5959 # Test blocking access to __class__.__bases__
6060 template = "{{ ''.__class__.__bases__[0] }}"
6161 prompt = PromptTemplate .from_template (
@@ -84,7 +84,8 @@ def test_complex_jinja2_features(self) -> None:
8484 template , template_format = "jinja2_unrestricted"
8585 )
8686 result = prompt .format (items = ["apple" , "banana" , "cherry" ])
87- # Jinja2 preserves the newlines in the template, including the one after each item
87+ # Jinja2 preserves the newlines in the template,
88+ # including the one after each item
8889 expected = "\n - APPLE\n \n - BANANA\n \n - CHERRY\n "
8990 assert result == expected
9091
@@ -319,8 +320,6 @@ def __init__(self, content: str) -> None:
319320
320321 def test_dangerous_patterns_blocked (self ) -> None :
321322 """Test that dangerous patterns are blocked in chat templates."""
322- import jinja2
323-
324323 prompt = ChatPromptTemplate .from_messages (
325324 [("human" , "{{ ''.__class__.__bases__ }}" )],
326325 template_format = "jinja2_unrestricted" ,
@@ -463,8 +462,6 @@ class TestJinja2UnrestrictedComparison:
463462
464463 def test_jinja2_blocks_attributes_unrestricted_allows (self ) -> None :
465464 """Test that jinja2 blocks attributes but jinja2_unrestricted allows them."""
466- import jinja2
467-
468465 # jinja2 (restricted) blocks attribute access
469466 restricted_prompt = PromptTemplate .from_template (
470467 "{{ text.upper() }}" , template_format = "jinja2"
@@ -481,8 +478,6 @@ def test_jinja2_blocks_attributes_unrestricted_allows(self) -> None:
481478
482479 def test_both_block_dangerous_patterns (self ) -> None :
483480 """Test that both formats block dangerous patterns."""
484- import jinja2
485-
486481 dangerous_template = "{{ ''.__class__.__bases__ }}"
487482
488483 # jinja2 blocks it
@@ -537,4 +532,3 @@ def test_correct_variables_no_warning(self) -> None:
537532 validate_template = True ,
538533 )
539534 assert prompt .input_variables == ["foo" ]
540-
0 commit comments