From 866720ab56040513ce6753296fb6ab48a75bad70 Mon Sep 17 00:00:00 2001 From: Daniel D'Avella Date: Tue, 19 Mar 2024 16:19:41 -0400 Subject: [PATCH] Handle case where autoescape setting can't be known --- src/core_codemods/enable_jinja2_autoescape.py | 2 + .../codemods/test_enable_jinja2_autoescape.py | 43 +++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/src/core_codemods/enable_jinja2_autoescape.py b/src/core_codemods/enable_jinja2_autoescape.py index cdaa1b33..1fbc2864 100644 --- a/src/core_codemods/enable_jinja2_autoescape.py +++ b/src/core_codemods/enable_jinja2_autoescape.py @@ -24,6 +24,8 @@ class EnableJinja2Autoescape(SimpleCodemod): - pattern: jinja2.Environment(...) - pattern-not: jinja2.Environment(..., autoescape=True, ...) - pattern-not: jinja2.Environment(..., autoescape=jinja2.select_autoescape(...), ...) + # Exclude cases where the arguments can't be precisely determined + - pattern-not: jinja2.Environment(**$KWARGS) - pattern-inside: | import jinja2 ... diff --git a/tests/codemods/test_enable_jinja2_autoescape.py b/tests/codemods/test_enable_jinja2_autoescape.py index d5596c23..3d2614fa 100644 --- a/tests/codemods/test_enable_jinja2_autoescape.py +++ b/tests/codemods/test_enable_jinja2_autoescape.py @@ -117,6 +117,42 @@ def test_autoescape_enabled(self, tmpdir): def test_autoescape_callable(self, tmpdir, code): self.run_and_assert(tmpdir, code, code) + def test_kwargs_unpacked(self, tmpdir): + input_code = ( + expexted_output + ) = """ + import jinja2 + env = jinja2.Environment(**kwargs) + var = "hello" + """ + self.run_and_assert(tmpdir, input_code, expexted_output) + + def test_kwargs_unpacked_with_autoescape(self, tmpdir): + input_code = """ + import jinja2 + env = jinja2.Environment(**kwargs, autoescape=False) + var = "hello" + """ + expexted_output = """ + import jinja2 + env = jinja2.Environment(**kwargs, autoescape=True) + var = "hello" + """ + self.run_and_assert(tmpdir, input_code, expexted_output) + + def test_kwargs_unpacked_with_autoescape_before(self, tmpdir): + input_code = """ + import jinja2 + env = jinja2.Environment(autoescape=False, **kwargs) + var = "hello" + """ + expexted_output = """ + import jinja2 + env = jinja2.Environment(autoescape=True, **kwargs) + var = "hello" + """ + self.run_and_assert(tmpdir, input_code, expexted_output) + def test_aiohttp_import_setup(self, tmpdir): input_code = """ import aiohttp_jinja2 @@ -180,3 +216,10 @@ def test_aiohttp_autoescape_callable(self, tmpdir): aiohttp_jinja2.setup(app, autoescape=jinja2.select_autoescape()) """ self.run_and_assert(tmpdir, input_code, input_code) + + def test_aiohttp_autoescape_kwargs(self, tmpdir): + input_code = """ + import aiohttp_jinja2 + aiohttp_jinja2.setup(app, **kwargs) + """ + self.run_and_assert(tmpdir, input_code, input_code)