From 89c244e77b21d623b95df0586a9b7d3a50ea13b8 Mon Sep 17 00:00:00 2001 From: Bastien Jansen Date: Wed, 9 Dec 2020 16:23:30 +0100 Subject: [PATCH] Throw an error when an import alias references an invalid macro (#558) --- .../pebble/template/PebbleTemplateImpl.java | 6 ++++++ .../pebble/macro/TestMacroCalls.java | 18 ++++++++++++++++++ .../macros/invalid.from.unknownMacro.peb | 4 ++++ 3 files changed, 28 insertions(+) create mode 100644 pebble/src/test/resources/templates/macros/invalid.from.unknownMacro.peb diff --git a/pebble/src/main/java/com/mitchellbosecke/pebble/template/PebbleTemplateImpl.java b/pebble/src/main/java/com/mitchellbosecke/pebble/template/PebbleTemplateImpl.java index d0255ab64..04bdd9b7e 100644 --- a/pebble/src/main/java/com/mitchellbosecke/pebble/template/PebbleTemplateImpl.java +++ b/pebble/src/main/java/com/mitchellbosecke/pebble/template/PebbleTemplateImpl.java @@ -244,6 +244,12 @@ public void importNamedMacrosFromTemplate(String name, List .getTemplate(this.resolveRelativePath(name)); for (Pair pair : namedMacros) { Macro m = templateImpl.macros.get(pair.getRight()); + + if (m == null) { + throw new PebbleException(null, "Function or Macro [" + pair.getRight() + "] referenced by alias [" + + pair.getLeft() + "] does not exist."); + } + this.registerMacro(pair.getLeft(), m); } } diff --git a/pebble/src/test/java/com/mitchellbosecke/pebble/macro/TestMacroCalls.java b/pebble/src/test/java/com/mitchellbosecke/pebble/macro/TestMacroCalls.java index b9054334f..074e518eb 100644 --- a/pebble/src/test/java/com/mitchellbosecke/pebble/macro/TestMacroCalls.java +++ b/pebble/src/test/java/com/mitchellbosecke/pebble/macro/TestMacroCalls.java @@ -161,4 +161,22 @@ void testInvalidSameAliasMacroWithImportAsToken() throws IOException { .startsWith("More than one named template can not share the same name")); } } + + @Test + void testInvalidAliasReferencingUnknownMacro() throws IOException { + PebbleEngine pebble = new PebbleEngine.Builder().build(); + + try { + PebbleTemplate template = pebble + .getTemplate("templates/macros/invalid.from.unknownMacro.peb"); + Writer writer = new StringWriter(); + template.evaluate(writer); + fail("expected PebbleException"); + } catch (PebbleException e) { + assertEquals( + "Function or Macro [iDontExist] referenced by alias [macro_test] does not exist.", + e.getPebbleMessage() + ); + } + } } diff --git a/pebble/src/test/resources/templates/macros/invalid.from.unknownMacro.peb b/pebble/src/test/resources/templates/macros/invalid.from.unknownMacro.peb new file mode 100644 index 000000000..07b950c98 --- /dev/null +++ b/pebble/src/test/resources/templates/macros/invalid.from.unknownMacro.peb @@ -0,0 +1,4 @@ +Hello + +{% from "templates/macros/macro.peb" import iDontExist as macro_test %} +Call 1: {{ macro_test() }}