Removed namingConvention setting, and made directive names, built-in names, special variable names, and setting names, camel case. (Other naming conventions, if needed, are planned to be handled with custom dialects.)
Along the way had fixed some String setting name keys to match the setter/getter methids: "autoInclude" to "autoIncludes", "autoImport" to "autoImports", "datetimeFormat" to "dateTimeFormat". Also, clarified which configuration scopes do "incompatibleImprovements" belong, also added isXxxSet method for this setting. Project: http://git-wip-us.apache.org/repos/asf/incubator-freemarker/repo Commit: http://git-wip-us.apache.org/repos/asf/incubator-freemarker/commit/51dba882 Tree: http://git-wip-us.apache.org/repos/asf/incubator-freemarker/tree/51dba882 Diff: http://git-wip-us.apache.org/repos/asf/incubator-freemarker/diff/51dba882 Branch: refs/heads/3 Commit: 51dba88295cfc6d9d0ef5d64f583b848591dcde2 Parents: aaa100c Author: ddekany <ddek...@apache.org> Authored: Sat Jul 15 23:57:40 2017 +0200 Committer: ddekany <ddek...@apache.org> Committed: Sat Jul 15 23:59:20 2017 +0200 ---------------------------------------------------------------------- FM3-CHANGE-LOG.txt | 24 +- .../freemarker/converter/FM2ToFM3Converter.java | 2 - .../core/ActualNamingConvetionTest.java | 67 --- .../apache/freemarker/core/CamelCaseTest.java | 486 ------------------- .../freemarker/core/ConfigurationTest.java | 206 +++----- .../core/CustomTemplateResolverTest.java | 4 +- .../apache/freemarker/core/DateFormatTest.java | 14 +- .../core/InterpretAndEvalTemplateNameTest.java | 4 +- ...leParsingAndProcessingConfigurationTest.java | 102 +--- .../MutableProcessingConfigurationTest.java | 156 +----- .../core/ObjectBuilderSettingsTest.java | 2 +- .../core/OptInTemplateClassResolverTest.java | 18 +- .../freemarker/core/OutputFormatTest.java | 102 ++-- .../core/ParsingErrorMessagesTest.java | 3 +- .../apache/freemarker/core/SQLTimeZoneTest.java | 46 +- .../freemarker/core/SpecialVariableTest.java | 4 +- .../core/TagSyntaxVariationsTest.java | 2 +- .../core/TemplateConfigurationTest.java | 67 +-- .../freemarker/core/UnclosedCommentTest.java | 8 +- .../core/model/impl/ErrorMessagesTest.java | 16 +- .../org/apache/freemarker/core/ast-1.ast | 10 +- .../apache/freemarker/core/ast-assignments.ast | 2 +- .../org/apache/freemarker/core/ast-builtins.ast | 2 +- .../apache/freemarker/core/ast-locations.ast | 16 +- .../core/ast-multipleignoredchildren.ast | 2 +- .../core/ast-nestedignoredchildren.ast | 2 +- .../org/apache/freemarker/core/ast-range.ast | 2 +- .../freemarker/core/ast-strlitinterpolation.ast | 2 +- .../freemarker/core/ast-whitespacestripping.ast | 2 +- .../core/templatesuite/expected/noparse.txt | 10 +- .../templatesuite/expected/string-builtins1.txt | 24 +- .../core/templatesuite/templates/comment.ftl | 2 +- .../templates/dateformat-iso-like.ftl | 14 +- .../templatesuite/templates/dateformat-java.ftl | 14 +- .../templatesuite/templates/dateparsing.ftl | 6 +- .../core/templatesuite/templates/if.ftl | 8 +- .../core/templatesuite/templates/noparse.ftl | 10 +- .../core/templatesuite/templates/setting.ftl | 2 +- .../templates/string-builtins1.ftl | 26 +- .../freemarker/core/templatesuite/testcases.xml | 72 +-- .../apache/freemarker/core/ASTDebugBreak.java | 2 +- .../apache/freemarker/core/ASTDirAutoEsc.java | 2 +- .../core/ASTDirCapturingAssignment.java | 2 +- .../core/ASTDirIfElseIfElseContainer.java | 4 +- .../freemarker/core/ASTDirIfOrElseOrElseIf.java | 6 +- .../apache/freemarker/core/ASTDirNoAutoEsc.java | 4 +- .../apache/freemarker/core/ASTDirNoEscape.java | 4 +- .../freemarker/core/ASTDirOutputFormat.java | 4 +- .../apache/freemarker/core/ASTDirSetting.java | 52 +- .../apache/freemarker/core/ASTDirective.java | 106 ++-- .../apache/freemarker/core/ASTExpBuiltIn.java | 251 +++++----- .../freemarker/core/ASTExpBuiltInVariable.java | 95 ++-- .../freemarker/core/ASTExpStringLiteral.java | 4 +- .../freemarker/core/ASTImplicitParent.java | 2 +- .../apache/freemarker/core/ASTStaticText.java | 2 +- .../freemarker/core/BuiltInsForSequences.java | 8 +- .../core/BuiltInsForStringsBasic.java | 4 +- .../core/BuiltInsForStringsEncoding.java | 2 +- .../apache/freemarker/core/Configuration.java | 349 ++++--------- .../org/apache/freemarker/core/Environment.java | 2 +- ...utableParsingAndProcessingConfiguration.java | 225 +++------ .../core/MutableProcessingConfiguration.java | 477 ++++++------------ .../freemarker/core/NamingConvention.java | 29 -- .../core/NonSequenceOrCollectionException.java | 2 +- .../apache/freemarker/core/ParseException.java | 6 +- .../freemarker/core/ParsingConfiguration.java | 61 +-- .../core/ParsingConfigurationWithFallback.java | 142 ++++++ .../core/ProcessingConfiguration.java | 24 +- .../org/apache/freemarker/core/Template.java | 17 +- .../freemarker/core/TemplateBooleanFormat.java | 2 +- .../freemarker/core/TemplateConfiguration.java | 33 +- .../core/TemplateExceptionHandler.java | 2 +- ...emplateParsingConfigurationWithFallback.java | 146 ------ .../core/_ObjectBuilderSettingEvaluator.java | 3 +- .../core/model/impl/SimpleMethod.java | 2 +- .../core/templateresolver/TemplateResolver.java | 9 +- .../apache/freemarker/core/util/FTLUtil.java | 6 +- .../freemarker/core/util/_SortedArraySet.java | 2 +- .../freemarker/core/util/_StringUtil.java | 21 +- freemarker-core/src/main/javacc/FTL.jj | 206 +++----- .../misc/overloadedNumberRules/generator.ftl | 2 +- .../apache/freemarker/dom/DOMSiblingTest.java | 2 - .../java/org/apache/freemarker/dom/DOMTest.java | 4 +- .../freemarker/dom/templatesuite/testcases.xml | 24 +- .../freemarker/servlet/FreemarkerServlet.java | 16 +- .../servlet/jsp/webapps/basic/WEB-INF/web.xml | 18 +- .../servlet/jsp/webapps/config/WEB-INF/web.xml | 2 +- .../servlet/jsp/webapps/errors/WEB-INF/web.xml | 8 +- .../jsp/webapps/multipleLoaders/WEB-INF/web.xml | 6 +- .../jsp/webapps/tldDiscovery/WEB-INF/web.xml | 20 +- .../spring/ConfigurationFactoryBeanTest.java | 13 +- .../freemarker/test/TemplateTestCase.java | 4 +- .../org/apache/freemarker/test/TestUtil.java | 2 +- 93 files changed, 1220 insertions(+), 2782 deletions(-) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/51dba882/FM3-CHANGE-LOG.txt ---------------------------------------------------------------------- diff --git a/FM3-CHANGE-LOG.txt b/FM3-CHANGE-LOG.txt index 1791868..b5544cb 100644 --- a/FM3-CHANGE-LOG.txt +++ b/FM3-CHANGE-LOG.txt @@ -20,6 +20,12 @@ Because the Manual won't be updated for a good while, we will lead the FreeMarer 3 changelog here: +- Switched to camel case as the only supported naming convention. This is as if in FM2 you set the "namingConvention" + configuration setting to "camelCase", however the "namingConvention" setting was removed, as no other convention will + be supported (for the default dialect at least). Also, configuration setting names and values must use camel case + too (FM2 was forgiving there). This means `#elseif` becomes to ``#elseIf`, ``?upper_case`, `?upperCase`, and + if you configure FreeMarker with Properties, then `template_loader` becomes to `templateLoader`. + Note that the template converter tool takes care of this conversion. - Increased version number to 3.0.0 (nightly aka. SNAPSHOT) - Removed legacy extensions: rhyno, jython, xml (not to be confused with dom), jdom, ant. - Servlet 3.0 and JSP 2.2 and is the minimum requirement now (if Serlvet/JSP features are used at all). @@ -171,9 +177,9 @@ the FreeMarer 3 changelog here: Also added a new setting, "templateLanguage", which decides this; the two available values are TemplateLanguage.FTL and TemplateLanguage.STATIC_TEXT. - Configuration.getTemplate has no "encoding" parameter anymore. Similarly #include has no "encoding" parameter either. The charset - of templates can be specified via Configuration.defaultEncoding and Configuration.templateConfigurations (for example based on the - directory it is in), or wirh the #ftl directive inside the template. Thus, a given template always has the same charset, no mater how - it's accessed. + of templates can be specified via Configuration.sourceEncoding and Configuration.templateConfigurations (for example + based on the directory it is in), or with the #ftl directive inside the template. Thus, a given template always has + the same charset, no mater how it's accessed. - #include-d/#import-ed templates don't inheirit the charset (encoding) of the #include-ing/#import-ing template. (Because, again, the charset of a template file is independent of how you access it.) - Removed Configuration.setEncoding(java.util.Locale, String) and the related other methods. Because of the new logic of template @@ -260,18 +266,20 @@ the FreeMarer 3 changelog here: .build()) - Configuration-related int constants were replaced with enums: - - FM2 Configuration.${c}_NAMING_CONVENTION with NamingConvention.${c} - FM2 Configuration.${c}_TAG_SYNTAX with TagSyntax.${c} - FM2 Configuration.${c}_AUTO_ESCAPING_POLICY with AutoEscapingPolicy.${c} - TemplateClassResolver.UNRESTRICTED_RESOLVER and ALLOWS_NOTHING_RESOLVER was renamed to UNRESTRICTED and ALLOW_NOTHING. Also the String setting name "allows_nothing" and - "allowsNothing" were renamed to "allow_nothing" and "allowNothing". + "allowsNothing" were renamed to "allowNothing". - TemplateExceptionHandler.IGNORE_HANDLER, RETHROW_HANDLER, DEBUG_HANDLER and HTLM_DEBUG_HANDLER was renamed to IGNORE, RETHROW, DEBUG and HTML_DEBUG - AttemptExceptionReporter.LOG_ERROR_REPORTER and LOG_WARN_REPORTER was renamed to LOG_ERROR and LOG_WARN (to be consistent with the new TemplateExceptionHandler names) - Renamed the `cacheStorage` Configuration setting to `templateCacheStorage`. - Renamed the `localizedLookup` Configuration setting to `localizedLookup`. +- Renamed the `datetimeFormat` Configuration setting to `dateTimeFormat` (following Java 8 convention). +- Renamed the String key for the historically incorrect `autoInclude` Configuration setting to `autoIncludes`. +- Renamed the String key for the historically incorrect `autoImport` Configuration setting to `autoImports`. - Changed the defaults of some Configuration settings: - Changed the default of sourceEncoding ("encoding" earlier) to UTF-8 from the platform default charset. Using the platform default charset was proven to be fragile in practice, @@ -279,9 +287,9 @@ the FreeMarer 3 changelog here: was unwillingly relying on the default. - Changed the default of templateExceptionHandler (template_exception_hander) to TemplateExceptionHandler.RETHROW from DEBUG - - Changed the default of sqlDateAndTimeTimeZone (sql_date_and_time_time_zone) to + - Changed the default of sqlDateAndTimeTimeZone (sqlDateAndTimeTimeZone) to TimeZone.default() from null (where null meant falling back to the timeZone setting value) - - Changed the default of templateNameFormat (template_name_format) to what's equivalent to + - Changed the default of templateNameFormat (templateNameFormat) to what's equivalent to FM2 DefaultTemplateNameFormat24. The old DefaultTemplateNameFormat was removed, and DefaultTemplateNameFormat24 was renamed to DefaultTemplateNameFormat. - Removed the logTemplateExceptions (log_template_exceptions) setting. FreeMarker now @@ -299,5 +307,5 @@ the FreeMarer 3 changelog here: tool does this conversion.) - Inside a #switch, #case can't be after #default anymore (this is actually a bug in FM2) (The template converter can't fix this automatically, but reports it as an error.) -- #else and #elseif tags must be ended without "/", for example, <#else/> is illegal now, <#else> is legal. +- #else and #elseIf tags must be ended without "/", for example, <#else/> is illegal now, <#else> is legal. (The template converter tool does this conversion.) \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/51dba882/freemarker-converter/src/main/java/org/apache/freemarker/converter/FM2ToFM3Converter.java ---------------------------------------------------------------------- diff --git a/freemarker-converter/src/main/java/org/apache/freemarker/converter/FM2ToFM3Converter.java b/freemarker-converter/src/main/java/org/apache/freemarker/converter/FM2ToFM3Converter.java index e233ccd..e9d7df3 100644 --- a/freemarker-converter/src/main/java/org/apache/freemarker/converter/FM2ToFM3Converter.java +++ b/freemarker-converter/src/main/java/org/apache/freemarker/converter/FM2ToFM3Converter.java @@ -24,7 +24,6 @@ import java.util.Map; import java.util.Properties; import java.util.regex.Pattern; -import org.apache.freemarker.core.NamingConvention; import org.apache.freemarker.core.util._NullArgumentException; import com.google.common.collect.ImmutableMap; @@ -173,7 +172,6 @@ public class FM2ToFM3Converter extends Converter { try { org.apache.freemarker.core.Configuration fm3Config = new org.apache.freemarker.core.Configuration .Builder(org.apache.freemarker.core.Configuration.getVersion() /* highest possible by design */) - .namingConvention(NamingConvention.CAMEL_CASE) .outputFormat(converOutputFormat(result.getFM2Template().getOutputFormat())) .build(); new org.apache.freemarker.core.Template(null, result.getFM3Content(), fm3Config); http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/51dba882/freemarker-core-test/src/test/java/org/apache/freemarker/core/ActualNamingConvetionTest.java ---------------------------------------------------------------------- diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/ActualNamingConvetionTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/ActualNamingConvetionTest.java deleted file mode 100644 index 69a95c9..0000000 --- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/ActualNamingConvetionTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.freemarker.core; - -import static org.junit.Assert.*; - -import java.io.IOException; - -import org.apache.freemarker.test.TestConfigurationBuilder; -import org.junit.Test; - -public class ActualNamingConvetionTest { - - @Test - public void testUndetectable() throws IOException { - final String ftl = "<#if true>${x?size}</#if>"; - assertEquals(getActualNamingConvention(ftl, - NamingConvention.AUTO_DETECT), NamingConvention.AUTO_DETECT); - assertEquals(getActualNamingConvention(ftl, - NamingConvention.LEGACY), NamingConvention.LEGACY); - assertEquals(getActualNamingConvention(ftl, - NamingConvention.CAMEL_CASE), NamingConvention.CAMEL_CASE); - } - - @Test - public void testLegacyDetected() throws IOException { - final String ftl = "${x?upper_case}"; - assertEquals(getActualNamingConvention(ftl, - NamingConvention.AUTO_DETECT), NamingConvention.LEGACY); - assertEquals(getActualNamingConvention(ftl, - NamingConvention.LEGACY), NamingConvention.LEGACY); - } - - @Test - public void testCamelCaseDetected() throws IOException { - final String ftl = "${x?upperCase}"; - assertEquals(getActualNamingConvention(ftl, - NamingConvention.AUTO_DETECT), NamingConvention.CAMEL_CASE); - assertEquals(getActualNamingConvention(ftl, - NamingConvention.CAMEL_CASE), NamingConvention.CAMEL_CASE); - } - - private NamingConvention getActualNamingConvention(String ftl, NamingConvention namingConvention) - throws IOException { - return new Template(null, ftl, - new TestConfigurationBuilder().namingConvention(namingConvention).build()) - .getActualNamingConvention(); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/51dba882/freemarker-core-test/src/test/java/org/apache/freemarker/core/CamelCaseTest.java ---------------------------------------------------------------------- diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/CamelCaseTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/CamelCaseTest.java deleted file mode 100644 index d2f3fa0..0000000 --- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/CamelCaseTest.java +++ /dev/null @@ -1,486 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.freemarker.core; - -import static org.junit.Assert.*; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Locale; -import java.util.Set; - -import org.apache.freemarker.core.outputformat.impl.HTMLOutputFormat; -import org.apache.freemarker.core.outputformat.impl.UndefinedOutputFormat; -import org.apache.freemarker.core.util._StringUtil; -import org.apache.freemarker.test.TemplateTest; -import org.apache.freemarker.test.TestConfigurationBuilder; -import org.junit.Test; - -public class CamelCaseTest extends TemplateTest { - - @Test - public void camelCaseSpecialVars() throws IOException, TemplateException { - setConfiguration(new TestConfigurationBuilder() - .outputEncoding(StandardCharsets.UTF_8) - .urlEscapingCharset(StandardCharsets.ISO_8859_1) - .locale(Locale.GERMANY) - .build()); - assertOutput("${.dataModel?isHash?c}", "true"); - assertOutput("${.data_model?is_hash?c}", "true"); - assertOutput("${.localeObject.toString()}", "de_DE"); - assertOutput("${.locale_object.toString()}", "de_DE"); - assertOutput("${.templateName!'null'}", "null"); - assertOutput("${.template_name!'null'}", "null"); - assertOutput("${.currentTemplateName!'null'}", "null"); - assertOutput("${.current_template_name!'null'}", "null"); - assertOutput("${.mainTemplateName!'null'}", "null"); - assertOutput("${.main_template_name!'null'}", "null"); - assertOutput("${.outputEncoding}", StandardCharsets.UTF_8.name()); - assertOutput("${.output_encoding}", StandardCharsets.UTF_8.name()); - assertOutput("${.outputFormat}", UndefinedOutputFormat.INSTANCE.getName()); - assertOutput("${.output_format}", UndefinedOutputFormat.INSTANCE.getName()); - assertOutput("${.urlEscapingCharset}", StandardCharsets.ISO_8859_1.name()); - assertOutput("${.url_escaping_charset}", StandardCharsets.ISO_8859_1.name()); - assertOutput("${.currentNode!'-'}", "-"); - assertOutput("${.current_node!'-'}", "-"); - } - - @Test - public void camelCaseSpecialVarsInErrorMessage() throws IOException, TemplateException { - assertErrorContains("${.fooBar}", "dataModel", "\\!data_model"); - assertErrorContains("${.foo_bar}", "data_model", "\\!dataModel"); - // [2.4] If camel case will be the recommended style, then this need to be inverted: - assertErrorContains("${.foo}", "data_model", "\\!dataModel"); - - assertErrorContains("<#if x><#elseIf y></#if>${.foo}", "dataModel", "\\!data_model"); - assertErrorContains("<#if x><#elseif y></#if>${.foo}", "data_model", "\\!dataModel"); - - setConfigurationToCamelCaseNamingConvention(); - assertErrorContains("${.foo}", "dataModel", "\\!data_model"); - - setConfigurationToLegacyCaseNamingConvention(); - assertErrorContains("${.foo}", "data_model", "\\!dataModel"); - } - - @Test - public void camelCaseSettingNames() throws IOException, TemplateException { - assertOutput("<#setting booleanFormat='Y,N'>${true} <#setting booleanFormat='+,-'>${true}", "Y +"); - assertOutput("<#setting boolean_format='Y,N'>${true} <#setting boolean_format='+,-'>${true}", "Y +"); - - // Still works inside ?interpret - assertOutput("<@r\"<#setting booleanFormat='Y,N'>${true}\"?interpret />", "Y"); - } - - @Test - public void camelCaseFtlHeaderParameters() throws IOException, TemplateException { - assertOutput( - "<#ftl " - + "stripWhitespace=false " - + "stripText=true " - + "outputFormat='" + HTMLOutputFormat.INSTANCE.getName() + "' " - + "autoEsc=true " - + "nsPrefixes={} " - + ">\nx\n<#if true>\n${.outputFormat}\n</#if>\n", - "\nHTML\n"); - - assertOutput( - "<#ftl " - + "strip_whitespace=false " - + "strip_text=true " - + "output_format='" + HTMLOutputFormat.INSTANCE.getName() + "' " - + "auto_esc=true " - + "ns_prefixes={} " - + ">\nx\n<#if true>\n${.output_format}\n</#if>\n", - "\nHTML\n"); - - assertErrorContains("<#ftl strip_text=true xmlns={}>", "ns_prefixes", "\\!nsPrefixes"); - assertErrorContains("<#ftl stripText=true xmlns={}>", "nsPrefixes"); - - assertErrorContains("<#ftl stripWhitespace=true strip_text=true>", "naming convention"); - assertErrorContains("<#ftl strip_whitespace=true stripText=true>", "naming convention"); - assertErrorContains("<#ftl stripWhitespace=true>${.foo_bar}", "naming convention"); - assertErrorContains("<#ftl strip_whitespace=true>${.fooBar}", "naming convention"); - - setConfiguration(new TestConfigurationBuilder() - .namingConvention(NamingConvention.CAMEL_CASE) - .outputEncoding(StandardCharsets.UTF_8) - .build()); - assertErrorContains("<#ftl strip_whitespace=true>", "naming convention"); - assertOutput("<#ftl stripWhitespace=true>${.outputEncoding}", StandardCharsets.UTF_8.name()); - - setConfiguration(new TestConfigurationBuilder() - .namingConvention(NamingConvention.LEGACY) - .outputEncoding(StandardCharsets.UTF_8) - .build()); - assertErrorContains("<#ftl stripWhitespace=true>", "naming convention"); - assertOutput("<#ftl strip_whitespace=true>${.output_encoding}", StandardCharsets.UTF_8.name()); - - setConfiguration(new TestConfigurationBuilder() - .namingConvention(NamingConvention.AUTO_DETECT) - .outputEncoding(StandardCharsets.UTF_8) - .build()); - assertOutput("<#ftl stripWhitespace=true>${.outputEncoding}", StandardCharsets.UTF_8.name()); - assertOutput("<#ftl encoding='iso-8859-1' stripWhitespace=true>${.outputEncoding}", StandardCharsets.UTF_8.name()); - assertOutput("<#ftl stripWhitespace=true encoding='iso-8859-1'>${.outputEncoding}", StandardCharsets.UTF_8.name()); - assertOutput("<#ftl encoding='iso-8859-1' strip_whitespace=true>${.output_encoding}", StandardCharsets.UTF_8.name()); - assertOutput("<#ftl strip_whitespace=true encoding='iso-8859-1'>${.output_encoding}", StandardCharsets.UTF_8.name()); - } - - @Test - public void camelCaseSettingNamesInErrorMessages() throws IOException, TemplateException { - assertErrorContains("<#setting fooBar=1>", "booleanFormat", "\\!boolean_format"); - assertErrorContains("<#setting foo_bar=1>", "boolean_format", "\\!booleanFormat"); - // [2.4] If camel case will be the recommended style, then this need to be inverted: - assertErrorContains("<#setting foo=1>", "boolean_format", "\\!booleanFormat"); - - assertErrorContains("<#if x><#elseIf y></#if><#setting foo=1>", "booleanFormat", "\\!boolean_format"); - assertErrorContains("<#if x><#elseif y></#if><#setting foo=1>", "boolean_format", "\\!booleanFormat"); - - setConfigurationToCamelCaseNamingConvention(); - assertErrorContains("<#setting foo=1>", "booleanFormat", "\\!boolean_format"); - - setConfigurationToLegacyCaseNamingConvention(); - assertErrorContains("<#setting foo=1>", "boolean_format", "\\!booleanFormat"); - } - - @Test - public void camelCaseIncludeParameters() throws IOException, TemplateException { - assertOutput("<#ftl stripWhitespace=true>[<#include 'noSuchTemplate' ignoreMissing=true>]", "[]"); - assertOutput("<#ftl strip_whitespace=true>[<#include 'noSuchTemplate' ignore_missing=true>]", "[]"); - assertErrorContains("<#ftl stripWhitespace=true>[<#include 'noSuchTemplate' ignore_missing=true>]", - "naming convention", "ignore_missing"); - assertErrorContains("<#ftl strip_whitespace=true>[<#include 'noSuchTemplate' ignoreMissing=true>]", - "naming convention", "ignoreMissing"); - } - - @Test - public void specialVarsHasBothNamingStyle() throws IOException, TemplateException { - assertContainsBothNamingStyles( - new HashSet(Arrays.asList(ASTExpBuiltInVariable.SPEC_VAR_NAMES)), - new NamePairAssertion() { @Override - public void assertPair(String name1, String name2) { } }); - } - - @Test - public void camelCaseBuiltIns() throws IOException, TemplateException { - assertOutput("${'x'?upperCase}", "X"); - assertOutput("${'x'?upper_case}", "X"); - } - - @Test - public void stringLiteralInterpolation() throws IOException, TemplateException { - assertEquals(NamingConvention.AUTO_DETECT, getConfiguration().getNamingConvention()); - addToDataModel("x", "x"); - - assertOutput("${'-${x?upperCase}-'} ${x?upperCase}", "-X- X"); - assertOutput("${x?upperCase} ${'-${x?upperCase}-'}", "X -X-"); - assertOutput("${'-${x?upper_case}-'} ${x?upper_case}", "-X- X"); - assertOutput("${x?upper_case} ${'-${x?upper_case}-'}", "X -X-"); - - assertErrorContains("${'-${x?upper_case}-'} ${x?upperCase}", - "naming convention", "legacy", "upperCase", "detection", "9"); - assertErrorContains("${x?upper_case} ${'-${x?upperCase}-'}", - "naming convention", "legacy", "upperCase", "detection", "5"); - assertErrorContains("${'-${x?upperCase}-'} ${x?upper_case}", - "naming convention", "camel", "upper_case"); - assertErrorContains("${x?upperCase} ${'-${x?upper_case}-'}", - "naming convention", "camel", "upper_case"); - - setConfigurationToCamelCaseNamingConvention(); - assertOutput("${'-${x?upperCase}-'} ${x?upperCase}", "-X- X"); - assertErrorContains("${'-${x?upper_case}-'}", - "naming convention", "camel", "upper_case", "\\!detection"); - - setConfigurationToLegacyCaseNamingConvention(); - assertOutput("${'-${x?upper_case}-'} ${x?upper_case}", "-X- X"); - assertErrorContains("${'-${x?upperCase}-'}", - "naming convention", "legacy", "upperCase", "\\!detection"); - } - - @Test - public void evalAndInterpret() throws IOException, TemplateException { - assertEquals(NamingConvention.AUTO_DETECT, getConfiguration().getNamingConvention()); - // The naming convention detected doesn't affect the enclosing template's naming convention. - // - ?eval: - assertOutput("${\"'x'?upperCase\"?eval}${'x'?upper_case}", "XX"); - assertOutput("${\"'x'?upper_case\"?eval}${'x'?upperCase}", "XX"); - assertOutput("${'x'?upperCase}${\"'x'?upper_case\"?eval}", "XX"); - assertErrorContains("${\"'x'\n?upperCase\n?is_string\"?eval}", - "naming convention", "camel", "upperCase", "is_string", "line 2", "line 3"); - // - ?interpret: - assertOutput("<@r\"${'x'?upperCase}\"?interpret />${'x'?upper_case}", "XX"); - assertOutput("<@r\"${'x'?upper_case}\"?interpret />${'x'?upperCase}", "XX"); - assertOutput("${'x'?upper_case}<@r\"${'x'?upperCase}\"?interpret />", "XX"); - assertErrorContains("<@r\"${'x'\n?upperCase\n?is_string}\"?interpret />", - "naming convention", "camel", "upperCase", "is_string", "line 2", "line 3"); - - // Will be inherited by ?eval-ed/?interpreted fragments: - setConfigurationToCamelCaseNamingConvention(); - // - ?eval: - assertErrorContains("${\"'x'?upper_case\"?eval}", "naming convention", "camel", "upper_case"); - assertOutput("${\"'x'?upperCase\"?eval}", "X"); - // - ?interpret: - assertErrorContains("<@r\"${'x'?upper_case}\"?interpret />", "naming convention", "camel", "upper_case"); - assertOutput("<@r\"${'x'?upperCase}\"?interpret />", "X"); - - // Again, will be inherited by ?eval-ed/?interpreted fragments: - setConfigurationToLegacyCaseNamingConvention(); - // - ?eval: - assertErrorContains("${\"'x'?upperCase\"?eval}", "naming convention", "legacy", "upperCase"); - assertOutput("${\"'x'?upper_case\"?eval}", "X"); - // - ?interpret: - assertErrorContains("<@r\"${'x'?upperCase}\"?interpret />", "naming convention", "legacy", "upperCase"); - assertOutput("<@r\"${'x'?upper_case}\"?interpret />", "X"); - } - - private void setConfigurationToLegacyCaseNamingConvention() { - setConfiguration(new TestConfigurationBuilder() - .namingConvention(NamingConvention.LEGACY) - .build()); - } - - @Test - public void camelCaseBuiltInErrorMessage() throws IOException, TemplateException { - assertErrorContains("${'x'?upperCasw}", "upperCase", "\\!upper_case"); - assertErrorContains("${'x'?upper_casw}", "upper_case", "\\!upperCase"); - // [2.4] If camel case will be the recommended style, then this need to be inverted: - assertErrorContains("${'x'?foo}", "upper_case", "\\!upperCase"); - - assertErrorContains("<#if x><#elseIf y></#if> ${'x'?foo}", "upperCase", "\\!upper_case"); - assertErrorContains("<#if x><#elseif y></#if>${'x'?foo}", "upper_case", "\\!upperCase"); - - setConfigurationToCamelCaseNamingConvention(); - assertErrorContains("${'x'?foo}", "upperCase", "\\!upper_case"); - setConfigurationToLegacyCaseNamingConvention(); - assertErrorContains("${'x'?foo}", "upper_case", "\\!upperCase"); - } - - private void setConfigurationToCamelCaseNamingConvention() { - setConfiguration(new TestConfigurationBuilder() - .namingConvention(NamingConvention.CAMEL_CASE) - .build()); - } - - @Test - public void builtInsHasBothNamingStyle() throws IOException, TemplateException { - assertContainsBothNamingStyles(getConfiguration().getSupportedBuiltInNames(), new NamePairAssertion() { - - @Override - public void assertPair(String name1, String name2) { - ASTExpBuiltIn bi1 = ASTExpBuiltIn.BUILT_INS_BY_NAME.get(name1); - ASTExpBuiltIn bi2 = ASTExpBuiltIn.BUILT_INS_BY_NAME.get(name2); - assertTrue("\"" + name1 + "\" and \"" + name2 + "\" doesn't belong to the same BI object.", - bi1 == bi2); - } - - }); - } - - private void assertContainsBothNamingStyles(Set<String> names, NamePairAssertion namePairAssertion) { - Set<String> underscoredNamesWithCamelCasePair = new HashSet<>(); - for (String name : names) { - if (_StringUtil.getIdentifierNamingConvention(name) == NamingConvention.CAMEL_CASE) { - String underscoredName = correctIsoBIExceptions(_StringUtil.camelCaseToUnderscored(name)); - assertTrue( - "Missing underscored variation \"" + underscoredName + "\" for \"" + name + "\".", - names.contains(underscoredName)); - assertTrue(underscoredNamesWithCamelCasePair.add(underscoredName)); - - namePairAssertion.assertPair(name, underscoredName); - } - } - for (String name : names) { - if (_StringUtil.getIdentifierNamingConvention(name) == NamingConvention.LEGACY) { - assertTrue("Missing camel case variation for \"" + name + "\".", - underscoredNamesWithCamelCasePair.contains(name)); - } - } - } - - private String correctIsoBIExceptions(String underscoredName) { - return underscoredName.replace("_n_z", "_nz").replace("_f_z", "_fz"); - } - - @Test - public void camelCaseDirectives() throws IOException, TemplateException { - camelCaseDirectives(false); - setConfiguration(new TestConfigurationBuilder() - .tagSyntax(TagSyntax.AUTO_DETECT) - .build()); - camelCaseDirectives(true); - } - - private void camelCaseDirectives(boolean squared) throws IOException, TemplateException { - assertOutput( - squared("<#list 1..4 as x><#if x == 1>one <#elseIf x == 2>two <#elseIf x == 3>three " - + "<#else>more</#if></#list>", squared), - "one two three more"); - assertOutput( - squared("<#list 1..4 as x><#if x == 1>one <#elseif x == 2>two <#elseif x == 3>three " - + "<#else>more</#if></#list>", squared), - "one two three more"); - - assertOutput( - squared("<#escape x as x?upperCase>${'a'}<#noEscape>${'b'}</#noEscape></#escape>", squared), - "Ab"); - assertOutput( - squared("<#escape x as x?upper_case>${'a'}<#noescape>${'b'}</#noescape></#escape>", squared), - "Ab"); - - assertOutput( - squared("<#noParse></#noparse></#noParse>", squared), - squared("</#noparse>", squared)); - assertOutput( - squared("<#noparse></#noParse></#noparse>", squared), - squared("</#noParse>", squared)); - } - - private String squared(String ftl, boolean squared) { - return squared ? ftl.replace('<', '[').replace('>', ']') : ftl; - } - - @Test - public void explicitNamingConvention() throws IOException, TemplateException { - explicitNamingConvention(false); - explicitNamingConvention(true); - } - - private void explicitNamingConvention(boolean squared) throws IOException, TemplateException { - TagSyntax tagSyntax = squared ? TagSyntax.AUTO_DETECT - : TagSyntax.ANGLE_BRACKET; - setConfiguration(new TestConfigurationBuilder() - .tagSyntax(tagSyntax) - .namingConvention(NamingConvention.CAMEL_CASE) - .build()); - - assertErrorContains( - squared("<#if true>t<#elseif false>f</#if>", squared), - "naming convention", "camel", "#elseif"); - assertOutput( - squared("<#if true>t<#elseIf false>f</#if>", squared), - "t"); - - assertErrorContains( - squared("<#noparse>${x}</#noparse>", squared), - "naming convention", "camel", "#noparse"); - assertOutput( - squared("<#noParse>${x}</#noParse>", squared), - "${x}"); - - assertErrorContains( - squared("<#escape x as -x><#noescape>${1}</#noescape></#escape>", squared), - "naming convention", "camel", "#noescape"); - assertOutput( - squared("<#escape x as -x><#noEscape>${1}</#noEscape></#escape>", squared), - "1"); - - // --- - - setConfiguration(new TestConfigurationBuilder() - .tagSyntax(tagSyntax) - .namingConvention(NamingConvention.LEGACY) - .build()); - - assertErrorContains( - squared("<#if true>t<#elseIf false>f</#if>", squared), - "naming convention", "legacy", "#elseIf"); - assertOutput( - squared("<#if true>t<#elseif false>f</#if>", squared), - "t"); - - assertErrorContains( - squared("<#noParse>${x}</#noParse>", squared), - "naming convention", "legacy", "#noParse"); - assertOutput( - squared("<#noparse>${x}</#noparse>", squared), - "${x}"); - - assertErrorContains( - squared("<#escape x as -x><#noEscape>${1}</#noEscape></#escape>", squared), - "naming convention", "legacy", "#noEscape"); - assertOutput( - squared("<#escape x as -x><#noescape>${1}</#noescape></#escape>", squared), - "1"); - } - - @Test - public void inconsistentAutoDetectedNamingConvention() { - assertErrorContains( - "<#if x><#elseIf y><#elseif z></#if>", - "naming convention", "camel"); - assertErrorContains( - "<#if x><#elseif y><#elseIf z></#if>", - "naming convention", "legacy"); - assertErrorContains( - "<#if x><#elseIf y></#if><#noparse></#noparse>", - "naming convention", "camel"); - assertErrorContains( - "<#if x><#elseif y></#if><#noParse></#noParse>", - "naming convention", "legacy"); - assertErrorContains( - "<#if x><#elseif y><#elseIf z></#if>", - "naming convention", "legacy"); - assertErrorContains( - "<#escape x as x + 1><#noEscape></#noescape></#escape>", - "naming convention", "camel"); - assertErrorContains( - "<#escape x as x + 1><#noEscape></#noEscape><#noescape></#noescape></#escape>", - "naming convention", "camel"); - assertErrorContains( - "<#escape x as x + 1><#noescape></#noEscape></#escape>", - "naming convention", "legacy"); - assertErrorContains( - "<#escape x as x + 1><#noescape></#noescape><#noEscape></#noEscape></#escape>", - "naming convention", "legacy"); - - assertErrorContains("${x?upperCase?is_string}", - "naming convention", "camel", "upperCase", "is_string"); - assertErrorContains("${x?upper_case?isString}", - "naming convention", "legacy", "upper_case", "isString"); - - assertErrorContains("<#setting outputEncoding='utf-8'>${x?is_string}", - "naming convention", "camel", "outputEncoding", "is_string"); - assertErrorContains("<#setting output_encoding='utf-8'>${x?isString}", - "naming convention", "legacy", "output_encoding", "isString"); - - assertErrorContains("${x?isString}<#setting output_encoding='utf-8'>", - "naming convention", "camel", "isString", "output_encoding"); - assertErrorContains("${x?is_string}<#setting outputEncoding='utf-8'>", - "naming convention", "legacy", "is_string", "outputEncoding"); - - assertErrorContains("${.outputEncoding}${x?is_string}", - "naming convention", "camel", "outputEncoding", "is_string"); - assertErrorContains("${.output_encoding}${x?isString}", - "naming convention", "legacy", "output_encoding", "isString"); - - assertErrorContains("${x?upperCase}<#noparse></#noparse>", - "naming convention", "camel", "upperCase", "noparse"); - assertErrorContains("${x?upper_case}<#noParse></#noParse>", - "naming convention", "legacy", "upper_case", "noParse"); - } - - private interface NamePairAssertion { - - void assertPair(String name1, String name2); - - } - -} http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/51dba882/freemarker-core-test/src/test/java/org/apache/freemarker/core/ConfigurationTest.java ---------------------------------------------------------------------- diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/ConfigurationTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/ConfigurationTest.java index 8882a3c..2f7af7b 100644 --- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/ConfigurationTest.java +++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/ConfigurationTest.java @@ -29,16 +29,21 @@ import java.io.IOException; import java.io.Serializable; import java.io.StringWriter; import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; +import java.util.TreeSet; import org.apache.freemarker.core.model.TemplateModelException; import org.apache.freemarker.core.model.TemplateScalarModel; @@ -80,7 +85,6 @@ import org.apache.freemarker.core.userpkg.SeldomEscapedOutputFormat; import org.apache.freemarker.core.util._CollectionUtil; import org.apache.freemarker.core.util._DateUtil; import org.apache.freemarker.core.util._NullWriter; -import org.apache.freemarker.core.util._StringUtil; import org.apache.freemarker.core.valueformat.TemplateDateFormatFactory; import org.apache.freemarker.core.valueformat.TemplateNumberFormatFactory; import org.junit.Test; @@ -594,7 +598,7 @@ public class ConfigurationTest { assertTrue(cfg.getRegisteredCustomOutputFormats().isEmpty()); - cfg.setSetting(REGISTERED_CUSTOM_OUTPUT_FORMATS_KEY_CAMEL_CASE, + cfg.setSetting(REGISTERED_CUSTOM_OUTPUT_FORMATS_KEY, "[org.apache.freemarker.core.userpkg.CustomHTMLOutputFormat(), " + "org.apache.freemarker.core.userpkg.DummyOutputFormat()]"); assertEquals( @@ -602,7 +606,7 @@ public class ConfigurationTest { new ArrayList(cfg.getRegisteredCustomOutputFormats())); try { - cfg.setSetting(REGISTERED_CUSTOM_OUTPUT_FORMATS_KEY_SNAKE_CASE, "[TemplateConfiguration()]"); + cfg.setSetting(REGISTERED_CUSTOM_OUTPUT_FORMATS_KEY, "[TemplateConfiguration()]"); fail(); } catch (InvalidSettingValueException e) { assertThat(e.getMessage(), containsString(OutputFormat.class.getSimpleName())); @@ -623,7 +627,7 @@ public class ConfigurationTest { Configuration.Builder cfgB = new Configuration.Builder(Configuration.VERSION_3_0_0); assertEquals(AttemptExceptionReporter.LOG_ERROR, cfgB.getAttemptExceptionReporter()); assertFalse(cfgB.isAttemptExceptionReporterSet()); - cfgB.setSetting(MutableProcessingConfiguration.ATTEMPT_EXCEPTION_REPORTER_KEY, "log_warn"); + cfgB.setSetting(MutableProcessingConfiguration.ATTEMPT_EXCEPTION_REPORTER_KEY, "logWarn"); assertEquals(AttemptExceptionReporter.LOG_WARN, cfgB.getAttemptExceptionReporter()); assertTrue(cfgB.isAttemptExceptionReporterSet()); cfgB.setSetting(MutableProcessingConfiguration.ATTEMPT_EXCEPTION_REPORTER_KEY, "default"); @@ -726,138 +730,91 @@ public class ConfigurationTest { @Test public void testGetSettingNamesAreSorted() throws Exception { - for (boolean camelCase : new boolean[] { false, true }) { - List<String> names = new ArrayList<>(Builder.getSettingNames(camelCase)); - List<String> inheritedNames = new ArrayList<>( - MutableParsingAndProcessingConfiguration.getSettingNames(camelCase)); - assertStartsWith(names, inheritedNames); - - String prevName = null; - for (int i = inheritedNames.size(); i < names.size(); i++) { - String name = names.get(i); - if (prevName != null) { - assertThat(name, greaterThan(prevName)); - } - prevName = name; + List<String> names = new ArrayList<>(Builder.getSettingNames()); + List<String> inheritedNames = new ArrayList<>( + MutableParsingAndProcessingConfiguration.getSettingNames()); + assertStartsWith(names, inheritedNames); + + String prevName = null; + for (int i = inheritedNames.size(); i < names.size(); i++) { + String name = names.get(i); + if (prevName != null) { + assertThat(name, greaterThan(prevName)); } + prevName = name; } } @Test - public void testGetSettingNamesNameConventionsContainTheSame() throws Exception { - MutableProcessingConfigurationTest.testGetSettingNamesNameConventionsContainTheSame( - new ArrayList<>(Builder.getSettingNames(false)), - new ArrayList<>(Builder.getSettingNames(true))); - } - - @Test - public void testStaticFieldKeysCoverAllGetSettingNames() throws Exception { - List<String> names = new ArrayList<>(Builder.getSettingNames(false)); - for (String name : names) { - assertTrue("No field was found for " + name, keyFieldExists(name)); - } - } - - @Test - public void testGetSettingNamesCoversAllStaticKeyFields() throws Exception { - Collection<String> names = Builder.getSettingNames(false); - - for (Class<?> cfgableClass : new Class[] { - Configuration.class, - MutableParsingAndProcessingConfiguration.class, - MutableProcessingConfiguration.class }) { - for (Field f : cfgableClass.getFields()) { - if (f.getName().endsWith("_KEY")) { - final Object name = f.get(null); - assertTrue("Missing setting name: " + name, names.contains(name)); + public void testAllSettingsAreCoveredByMutableSettingsObject() throws Exception { + testAllSettingsAreCoveredByMutableSettingsObject(TopLevelConfiguration.class, Configuration.Builder.class); + } + + @SuppressWarnings("rawtypes") + public static void testAllSettingsAreCoveredByMutableSettingsObject( + Class<?> settingsInterface, Class<?> settingsMutableObjectClass) throws Exception { + Set<String> beanSettingNames = new TreeSet<>(); + Set<String> isSetSettingNames = new TreeSet<>(); + for (Method method : settingsInterface.getMethods()) { + String name = method.getName(); + if (method.getParameterTypes().length == 0 && method.getReturnType() != void.class + && (method.getModifiers() & Modifier.PUBLIC) != 0) { + if (name.startsWith("is") && name.endsWith("Set") && method.getReturnType() == boolean.class) { + isSetSettingNames.add(toGetterNameToSettingNameCase(name.substring(2, name.length() - 3))); + } else if (name.startsWith("get")) { + String settingName = toGetterNameToSettingNameCase(name.substring(3)); + beanSettingNames.add(settingName); } } } - } - - @Test - public void testKeyStaticFieldsHasAllVariationsAndCorrectFormat() throws IllegalArgumentException, IllegalAccessException { - MutableProcessingConfigurationTest.testKeyStaticFieldsHasAllVariationsAndCorrectFormat(ExtendableBuilder.class); + + assertEquals("Not all getXxx have isXxxSet pair", beanSettingNames, isSetSettingNames); + + Method method = settingsMutableObjectClass.getMethod("getSettingNames"); + assertTrue((method.getModifiers() & Modifier.STATIC) != 0); + assertEquals("Names deduced from getXxx methods and getSettingNames() result differs", + beanSettingNames, new TreeSet<>((Set) method.invoke(null))); + + // TODO [FM3] Check if all has setXxx, unsetXxx, etc. } - @Test - public void testSetSettingSupportsBothNamingConventions() throws Exception { - Builder cfgB = new Builder(VERSION_3_0_0); - - cfgB.setSetting(SOURCE_ENCODING_KEY_CAMEL_CASE, StandardCharsets.UTF_16LE.name()); - assertEquals(StandardCharsets.UTF_16LE, cfgB.getSourceEncoding()); - cfgB.setSetting(SOURCE_ENCODING_KEY_SNAKE_CASE, StandardCharsets.UTF_8.name()); - assertEquals(StandardCharsets.UTF_8, cfgB.getSourceEncoding()); - - for (String nameCC : cfgB.getSettingNames(true)) { - for (String value : new String[] { "1", "default", "true" }) { - Exception resultCC = null; - try { - cfgB.setSetting(nameCC, value); - } catch (Exception e) { - assertThat(e, not(instanceOf(InvalidSettingNameException.class))); - resultCC = e; - } - - String nameSC = _StringUtil.camelCaseToUnderscored(nameCC); - Exception resultSC = null; - try { - cfgB.setSetting(nameSC, value); - } catch (Exception e) { - assertThat(e, not(instanceOf(InvalidSettingNameException.class))); - resultSC = e; - } - - if (resultCC == null) { - assertNull(resultSC); - } else { - assertNotNull(resultSC); - assertEquals(resultCC.getClass(), resultSC.getClass()); - } - } + private static String toGetterNameToSettingNameCase(String name) { + int idx = 0; + while (idx < name.length() && Character.isUpperCase(name.charAt(idx))) { + idx++; } - } - - @Test - public void testGetSupportedBuiltInDirectiveNames() { - Configuration cfg = new Builder(VERSION_3_0_0).build(); - - Set<String> allNames = cfg.getSupportedBuiltInDirectiveNames(NamingConvention.AUTO_DETECT); - Set<String> lNames = cfg.getSupportedBuiltInDirectiveNames(NamingConvention.LEGACY); - Set<String> cNames = cfg.getSupportedBuiltInDirectiveNames(NamingConvention.CAMEL_CASE); - - checkNamingConventionNameSets(allNames, lNames, cNames); - - for (String name : cNames) { - assertThat(name.toLowerCase(), isIn(lNames)); + String result = + idx == 0 ? name + : idx == 1 ? Character.toLowerCase(name.charAt(0)) + name.substring(1) + : name.substring(0, idx - 1).toLowerCase() + name.substring(idx - 1); // "FOOBar" -> "fooBar" + if (result.equals("templateUpdateDelayMilliseconds")) { + result = "templateUpdateDelay"; } - } - @Test - public void testGetSupportedBuiltInNames() { - Configuration cfg = new Builder(VERSION_3_0_0).build(); - - Set<String> allNames = cfg.getSupportedBuiltInNames(NamingConvention.AUTO_DETECT); - Set<String> lNames = cfg.getSupportedBuiltInNames(NamingConvention.LEGACY); - Set<String> cNames = cfg.getSupportedBuiltInNames(NamingConvention.CAMEL_CASE); - - checkNamingConventionNameSets(allNames, lNames, cNames); + return result; } - private void checkNamingConventionNameSets(Set<String> allNames, Set<String> lNames, Set<String> cNames) { - for (String name : lNames) { - assertThat(allNames, hasItem(name)); - assertTrue("Should be all-lowercase: " + name, name.equals(name.toLowerCase())); - } - for (String name : cNames) { - assertThat(allNames, hasItem(name)); - } - for (String name : allNames) { - assertThat(name, anyOf(isIn(lNames), isIn(cNames))); + @Test + public void testGetSettingNamesCorrespondToStaticKeyFields() throws Exception { + testGetSettingNamesCorrespondToStaticKeyFields( + Configuration.Builder.getSettingNames(), + Configuration.Builder.class); + } + + public static void testGetSettingNamesCorrespondToStaticKeyFields(Set<String> names, Class<?> cfgClass) throws + Exception { + Set<String> uncoveredNames = new HashSet<>(names); + for (Field f : cfgClass.getFields()) { + if (f.getName().endsWith("_KEY")) { + final String name = (String) f.get(null); + assertTrue("Missing setting name: " + name, names.contains(name)); + uncoveredNames.remove(name); + } } - assertEquals(lNames.size(), cNames.size()); + assertEquals("Some setting names aren't covered by the ..._KEY constants.", + Collections.emptySet(), uncoveredNames); } - + @Test public void testRemovedSettings() { Builder cfgB = new Builder(VERSION_3_0_0); @@ -978,17 +935,6 @@ public class ConfigurationTest { } } - private boolean keyFieldExists(String name) throws Exception { - Field field; - try { - field = ExtendableBuilder.class.getField(name.toUpperCase() + "_KEY"); - } catch (NoSuchFieldException e) { - return false; - } - assertEquals(name, field.get(null)); - return true; - } - private static class MyScalarModel implements TemplateScalarModel { @Override http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/51dba882/freemarker-core-test/src/test/java/org/apache/freemarker/core/CustomTemplateResolverTest.java ---------------------------------------------------------------------- diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/CustomTemplateResolverTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/CustomTemplateResolverTest.java index 640dd71..426a96b 100644 --- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/CustomTemplateResolverTest.java +++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/CustomTemplateResolverTest.java @@ -79,7 +79,6 @@ public class CustomTemplateResolverTest { assertNotNull(cfg.getLocalizedTemplateLookup()); assertNotNull(cfg.getTemplateCacheStorage()); assertNotNull(cfg.getTemplateUpdateDelayMilliseconds()); - assertNotNull(cfg.getNamingConvention()); assertNull(cfg.getTemplateLoader()); assertNull(cfg.getTemplateConfigurations()); @@ -111,14 +110,13 @@ public class CustomTemplateResolverTest { @Test public void testConfigurationDefaultForCustomTemplateResolver2() { Configuration cfg = new Configuration.Builder(Configuration.VERSION_3_0_0) - .templateResolver(new CustomTemplateResolver(NAMING_CONVENTION_KEY)) + .templateResolver(new CustomTemplateResolver(null)) .build(); assertNull(cfg.getTemplateLookupStrategy()); assertNull(cfg.getLocalizedTemplateLookup()); assertNull(cfg.getTemplateCacheStorage()); assertNull(cfg.getTemplateUpdateDelayMilliseconds()); - assertNotNull(cfg.getNamingConvention()); //! assertNull(cfg.getTemplateLoader()); assertNull(cfg.getTemplateConfigurations()); http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/51dba882/freemarker-core-test/src/test/java/org/apache/freemarker/core/DateFormatTest.java ---------------------------------------------------------------------- diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/DateFormatTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/DateFormatTest.java index 4ad5937..9cd835b 100644 --- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/DateFormatTest.java +++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/DateFormatTest.java @@ -162,9 +162,9 @@ public class DateFormatTest extends TemplateTest { .dateTimeFormat("[wrong dt]") .timeFormat("[wrong t]") .build()); - assertErrorContains("${.now?date}", "\"date_format\"", "[wrong d]"); - assertErrorContains("${.now?datetime}", "\"datetime_format\"", "[wrong dt]"); - assertErrorContains("${.now?time}", "\"time_format\"", "[wrong t]"); + assertErrorContains("${.now?date}", "\"dateFormat\"", "[wrong d]"); + assertErrorContains("${.now?datetime}", "\"dateTimeFormat\"", "[wrong dt]"); + assertErrorContains("${.now?time}", "\"timeFormat\"", "[wrong t]"); } @Test @@ -178,7 +178,7 @@ public class DateFormatTest extends TemplateTest { assertErrorContains("${d?string.@div_xyz}", "\"@div_xyz\"", "\"xyz\""); setConfigurationWithDateTimeFormat("@div"); - assertErrorContains("${d}", "\"datetime_format\"", "\"@div\"", "format parameter is required"); + assertErrorContains("${d}", "\"dateTimeFormat\"", "\"@div\"", "format parameter is required"); } @Test @@ -187,7 +187,7 @@ public class DateFormatTest extends TemplateTest { setConfigurationWithDateTimeFormat("@noSuchFormat"); Throwable exc = assertErrorContains( "${.now}", - "\"@noSuchFormat\"", "\"noSuchFormat\"", "\"datetime_format\""); + "\"@noSuchFormat\"", "\"noSuchFormat\"", "\"dateTimeFormat\""); assertThat(exc.getCause(), instanceOf(UndefinedCustomFormatException.class)); } @@ -195,13 +195,13 @@ public class DateFormatTest extends TemplateTest { setConfiguration(createConfigurationBuilder().dateFormat("@noSuchFormatD").build()); assertErrorContains( "${.now?date}", - "\"@noSuchFormatD\"", "\"noSuchFormatD\"", "\"date_format\""); + "\"@noSuchFormatD\"", "\"noSuchFormatD\"", "\"dateFormat\""); } { setConfiguration(createConfigurationBuilder().timeFormat("@noSuchFormatT").build()); assertErrorContains( "${.now?time}", - "\"@noSuchFormatT\"", "\"noSuchFormatT\"", "\"time_format\""); + "\"@noSuchFormatT\"", "\"noSuchFormatT\"", "\"timeFormat\""); } { http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/51dba882/freemarker-core-test/src/test/java/org/apache/freemarker/core/InterpretAndEvalTemplateNameTest.java ---------------------------------------------------------------------- diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/InterpretAndEvalTemplateNameTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/InterpretAndEvalTemplateNameTest.java index ff5897f..8b4b2d5 100644 --- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/InterpretAndEvalTemplateNameTest.java +++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/InterpretAndEvalTemplateNameTest.java @@ -34,8 +34,8 @@ public class InterpretAndEvalTemplateNameTest extends TemplateTest { @Test public void testInterpret() throws IOException, TemplateException { for (String getTemplateNames : new String[] { - "c=${.current_template_name}, m=${.main_template_name}", - "c=${\".current_template_name\"?eval}, m=${\".main_template_name\"?eval}" + "c=${.currentTemplateName}, m=${.mainTemplateName}", + "c=${\".currentTemplateName\"?eval}, m=${\".mainTemplateName\"?eval}" }) { StringTemplateLoader tl = new StringTemplateLoader(); tl.putTemplate( http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/51dba882/freemarker-core-test/src/test/java/org/apache/freemarker/core/MutableParsingAndProcessingConfigurationTest.java ---------------------------------------------------------------------- diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/MutableParsingAndProcessingConfigurationTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/MutableParsingAndProcessingConfigurationTest.java index 2e96c18..54ce6b1 100644 --- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/MutableParsingAndProcessingConfigurationTest.java +++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/MutableParsingAndProcessingConfigurationTest.java @@ -22,11 +22,9 @@ package org.apache.freemarker.core; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; -import java.lang.reflect.Field; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import java.util.Locale; import java.util.TimeZone; @@ -55,19 +53,13 @@ public class MutableParsingAndProcessingConfigurationTest { cfgB.setAutoEscapingPolicy(AutoEscapingPolicy.DISABLE); assertEquals(AutoEscapingPolicy.DISABLE, cfgB.getAutoEscapingPolicy()); - cfgB.setSetting(Configuration.ExtendableBuilder.AUTO_ESCAPING_POLICY_KEY_CAMEL_CASE, "enableIfSupported"); + cfgB.setSetting(Configuration.ExtendableBuilder.AUTO_ESCAPING_POLICY_KEY, "enableIfSupported"); assertEquals(AutoEscapingPolicy.ENABLE_IF_SUPPORTED, cfgB.getAutoEscapingPolicy()); - cfgB.setSetting(Configuration.ExtendableBuilder.AUTO_ESCAPING_POLICY_KEY_CAMEL_CASE, "enable_if_supported"); - assertEquals(AutoEscapingPolicy.ENABLE_IF_SUPPORTED, cfgB.getAutoEscapingPolicy()); - - cfgB.setSetting(Configuration.ExtendableBuilder.AUTO_ESCAPING_POLICY_KEY_CAMEL_CASE, "enableIfDefault"); - assertEquals(AutoEscapingPolicy.ENABLE_IF_DEFAULT, cfgB.getAutoEscapingPolicy()); - - cfgB.setSetting(Configuration.ExtendableBuilder.AUTO_ESCAPING_POLICY_KEY_CAMEL_CASE, "enable_if_default"); + cfgB.setSetting(Configuration.ExtendableBuilder.AUTO_ESCAPING_POLICY_KEY, "enableIfDefault"); assertEquals(AutoEscapingPolicy.ENABLE_IF_DEFAULT, cfgB.getAutoEscapingPolicy()); - cfgB.setSetting(Configuration.ExtendableBuilder.AUTO_ESCAPING_POLICY_KEY_CAMEL_CASE, "disable"); + cfgB.setSetting(Configuration.ExtendableBuilder.AUTO_ESCAPING_POLICY_KEY, "disable"); assertEquals(AutoEscapingPolicy.DISABLE, cfgB.getAutoEscapingPolicy()); } @@ -87,10 +79,10 @@ public class MutableParsingAndProcessingConfigurationTest { assertFalse(cfgB.isOutputFormatSet()); - cfgB.setSetting(Configuration.ExtendableBuilder.OUTPUT_FORMAT_KEY_CAMEL_CASE, XMLOutputFormat.class.getSimpleName()); + cfgB.setSetting(Configuration.ExtendableBuilder.OUTPUT_FORMAT_KEY, XMLOutputFormat.class.getSimpleName()); assertEquals(XMLOutputFormat.INSTANCE, cfgB.getOutputFormat()); - cfgB.setSetting(Configuration.ExtendableBuilder.OUTPUT_FORMAT_KEY_SNAKE_CASE, HTMLOutputFormat.class.getSimpleName()); + cfgB.setSetting(Configuration.ExtendableBuilder.OUTPUT_FORMAT_KEY, HTMLOutputFormat.class.getSimpleName()); assertEquals(HTMLOutputFormat.INSTANCE, cfgB.getOutputFormat()); cfgB.unsetOutputFormat(); @@ -99,7 +91,7 @@ public class MutableParsingAndProcessingConfigurationTest { cfgB.setOutputFormat(UndefinedOutputFormat.INSTANCE); assertTrue(cfgB.isOutputFormatSet()); - cfgB.setSetting(Configuration.ExtendableBuilder.OUTPUT_FORMAT_KEY_CAMEL_CASE, "default"); + cfgB.setSetting(Configuration.ExtendableBuilder.OUTPUT_FORMAT_KEY, "default"); assertFalse(cfgB.isOutputFormatSet()); try { @@ -128,11 +120,11 @@ public class MutableParsingAndProcessingConfigurationTest { assertTrue(cfgB.getRecognizeStandardFileExtensions()); assertTrue(cfgB.isRecognizeStandardFileExtensionsSet()); - cfgB.setSetting(Configuration.ExtendableBuilder.RECOGNIZE_STANDARD_FILE_EXTENSIONS_KEY_CAMEL_CASE, "false"); + cfgB.setSetting(Configuration.ExtendableBuilder.RECOGNIZE_STANDARD_FILE_EXTENSIONS_KEY, "false"); assertFalse(cfgB.getRecognizeStandardFileExtensions()); assertTrue(cfgB.isRecognizeStandardFileExtensionsSet()); - cfgB.setSetting(Configuration.ExtendableBuilder.RECOGNIZE_STANDARD_FILE_EXTENSIONS_KEY_SNAKE_CASE, "default"); + cfgB.setSetting(Configuration.ExtendableBuilder.RECOGNIZE_STANDARD_FILE_EXTENSIONS_KEY, "default"); assertTrue(cfgB.getRecognizeStandardFileExtensions()); assertFalse(cfgB.isRecognizeStandardFileExtensionsSet()); } @@ -176,13 +168,13 @@ public class MutableParsingAndProcessingConfigurationTest { public void testTabSizeSetting() throws Exception { Configuration.Builder cfgB = new Configuration.Builder(Configuration.VERSION_3_0_0); assertEquals(8, cfgB.getTabSize()); - cfgB.setSetting(Configuration.ExtendableBuilder.TAB_SIZE_KEY_CAMEL_CASE, "4"); + cfgB.setSetting(Configuration.ExtendableBuilder.TAB_SIZE_KEY, "4"); assertEquals(4, cfgB.getTabSize()); - cfgB.setSetting(Configuration.ExtendableBuilder.TAB_SIZE_KEY_SNAKE_CASE, "1"); + cfgB.setSetting(Configuration.ExtendableBuilder.TAB_SIZE_KEY, "1"); assertEquals(1, cfgB.getTabSize()); try { - cfgB.setSetting(Configuration.ExtendableBuilder.TAB_SIZE_KEY_SNAKE_CASE, "x"); + cfgB.setSetting(Configuration.ExtendableBuilder.TAB_SIZE_KEY, "x"); fail(); } catch (ConfigurationException e) { assertThat(e.getCause(), instanceOf(NumberFormatException.class)); @@ -190,28 +182,12 @@ public class MutableParsingAndProcessingConfigurationTest { } @Test - public void testNamingConventionSetSetting() throws ConfigurationException { - Configuration.Builder cfg = new Configuration.Builder(Configuration.VERSION_3_0_0); - - assertEquals(NamingConvention.AUTO_DETECT, cfg.getNamingConvention()); - - cfg.setSetting("naming_convention", "legacy"); - assertEquals(NamingConvention.LEGACY, cfg.getNamingConvention()); - - cfg.setSetting("naming_convention", "camel_case"); - assertEquals(NamingConvention.CAMEL_CASE, cfg.getNamingConvention()); - - cfg.setSetting("naming_convention", "auto_detect"); - assertEquals(NamingConvention.AUTO_DETECT, cfg.getNamingConvention()); - } - - @Test public void testLazyImportsSetSetting() throws ConfigurationException { Configuration.Builder cfgB = new Configuration.Builder(Configuration.VERSION_3_0_0); assertFalse(cfgB.getLazyImports()); assertFalse(cfgB.isLazyImportsSet()); - cfgB.setSetting("lazy_imports", "true"); + cfgB.setSetting("lazyImports", "true"); assertTrue(cfgB.getLazyImports()); cfgB.setSetting("lazyImports", "false"); assertFalse(cfgB.getLazyImports()); @@ -224,7 +200,7 @@ public class MutableParsingAndProcessingConfigurationTest { assertNull(cfgB.getLazyAutoImports()); assertFalse(cfgB.isLazyAutoImportsSet()); - cfgB.setSetting("lazy_auto_imports", "true"); + cfgB.setSetting("lazyAutoImports", "true"); assertEquals(Boolean.TRUE, cfgB.getLazyAutoImports()); assertTrue(cfgB.isLazyAutoImportsSet()); cfgB.setSetting("lazyAutoImports", "false"); @@ -304,8 +280,8 @@ public class MutableParsingAndProcessingConfigurationTest { @Test public void testGetSettingNamesAreSorted() throws Exception { for (boolean camelCase : new boolean[] { false, true }) { - List<String> names = new ArrayList<>(MutableParsingAndProcessingConfiguration.getSettingNames(camelCase)); - List<String> inheritedNames = new ArrayList<>(MutableProcessingConfiguration.getSettingNames(camelCase)); + List<String> names = new ArrayList<>(MutableParsingAndProcessingConfiguration.getSettingNames()); + List<String> inheritedNames = new ArrayList<>(MutableProcessingConfiguration.getSettingNames()); assertStartsWith(names, inheritedNames); String prevName = null; @@ -320,39 +296,16 @@ public class MutableParsingAndProcessingConfigurationTest { } @Test - public void testGetSettingNamesNameConventionsContainTheSame() throws Exception { - MutableProcessingConfigurationTest.testGetSettingNamesNameConventionsContainTheSame( - new ArrayList<>(MutableParsingAndProcessingConfiguration.getSettingNames(false)), - new ArrayList<>(MutableParsingAndProcessingConfiguration.getSettingNames(true))); - } - - @Test - public void testStaticFieldKeysCoverAllGetSettingNames() throws Exception { - List<String> names = new ArrayList<>(MutableParsingAndProcessingConfiguration.getSettingNames(false)); - for (String name : names) { - assertTrue("No field was found for " + name, keyFieldExists(name)); - } - } - - @Test - public void testGetSettingNamesCoversAllStaticKeyFields() throws Exception { - Collection<String> names = MutableParsingAndProcessingConfiguration.getSettingNames(false); - - for (Class<?> cfgableClass : new Class[] { - MutableParsingAndProcessingConfiguration.class, - MutableProcessingConfiguration.class }) { - for (Field f : cfgableClass.getFields()) { - if (f.getName().endsWith("_KEY")) { - final String name = (String) f.get(null); - assertTrue("Missing setting name: " + name, names.contains(name)); - } - } - } + public void testAllSettingsAreCoveredByMutableSettingsObject() throws Exception { + ConfigurationTest.testAllSettingsAreCoveredByMutableSettingsObject( + ParsingAndProcessingConfiguration.class, + MutableParsingAndProcessingConfiguration.class); } @Test - public void testKeyStaticFieldsHasAllVariationsAndCorrectFormat() throws IllegalArgumentException, IllegalAccessException { - MutableProcessingConfigurationTest.testKeyStaticFieldsHasAllVariationsAndCorrectFormat( + public void testGetSettingNamesCorrespondToStaticKeyFields() throws Exception { + ConfigurationTest.testGetSettingNamesCorrespondToStaticKeyFields( + MutableParsingAndProcessingConfiguration.getSettingNames(), MutableParsingAndProcessingConfiguration.class); } @@ -366,15 +319,4 @@ public class MutableParsingAndProcessingConfigurationTest { } } - private boolean keyFieldExists(String name) throws Exception { - Field field; - try { - field = MutableParsingAndProcessingConfiguration.class.getField(name.toUpperCase() + "_KEY"); - } catch (NoSuchFieldException e) { - return false; - } - assertEquals(name, field.get(null)); - return true; - } - } http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/51dba882/freemarker-core-test/src/test/java/org/apache/freemarker/core/MutableProcessingConfigurationTest.java ---------------------------------------------------------------------- diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/MutableProcessingConfigurationTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/MutableProcessingConfigurationTest.java index 4295e17..5db5dd9 100644 --- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/MutableProcessingConfigurationTest.java +++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/MutableProcessingConfigurationTest.java @@ -24,15 +24,12 @@ import static org.junit.Assert.*; import java.io.IOException; import java.io.StringWriter; -import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Set; import java.util.TimeZone; import org.apache.freemarker.core.userpkg.BaseNTemplateNumberFormatFactory; @@ -42,7 +39,6 @@ import org.apache.freemarker.core.userpkg.HexTemplateNumberFormatFactory; import org.apache.freemarker.core.util._CollectionUtil; import org.apache.freemarker.core.util._DateUtil; import org.apache.freemarker.core.util._NullWriter; -import org.apache.freemarker.core.util._StringUtil; import org.apache.freemarker.core.valueformat.TemplateDateFormatFactory; import org.apache.freemarker.core.valueformat.TemplateNumberFormatFactory; import org.junit.Test; @@ -55,140 +51,28 @@ public class MutableProcessingConfigurationTest { @Test public void testGetSettingNamesAreSorted() throws Exception { - MutableProcessingConfiguration mpc = createMutableProcessingConfiguration(); - for (boolean camelCase : new boolean[] { false, true }) { - Collection<String> names = mpc.getSettingNames(camelCase); - String prevName = null; - for (String name : names) { - if (prevName != null) { - assertThat(name, greaterThan(prevName)); - } - prevName = name; - } - } - } - - @Test - public void testStaticFieldKeysCoverAllGetSettingNames() throws Exception { - MutableProcessingConfiguration mpc = createMutableProcessingConfiguration(); - Collection<String> names = mpc.getSettingNames(false); + Collection<String> names = MutableProcessingConfiguration.getSettingNames(); + String prevName = null; for (String name : names) { - assertTrue("No field was found for " + name, keyFieldExists(name)); - } - } - - @Test - public void testGetSettingNamesCoversAllStaticKeyFields() throws Exception { - MutableProcessingConfiguration mpc = createMutableProcessingConfiguration(); - Collection<String> names = mpc.getSettingNames(false); - - for (Field f : MutableProcessingConfiguration.class.getFields()) { - if (f.getName().endsWith("_KEY")) { - final Object name = f.get(null); - assertTrue("Missing setting name: " + name, names.contains(name)); + if (prevName != null) { + assertThat(name, greaterThan(prevName)); } + prevName = name; } } @Test - public void testKeyStaticFieldsHasAllVariationsAndCorrectFormat() throws IllegalArgumentException, IllegalAccessException { - MutableProcessingConfigurationTest.testKeyStaticFieldsHasAllVariationsAndCorrectFormat(MutableProcessingConfiguration.class); - } - - @Test - public void testGetSettingNamesNameConventionsContainTheSame() throws Exception { - MutableProcessingConfiguration mpc = createMutableProcessingConfiguration(); - MutableProcessingConfigurationTest.testGetSettingNamesNameConventionsContainTheSame( - new ArrayList<>(mpc.getSettingNames(false)), - new ArrayList<>(mpc.getSettingNames(true))); - } - - public static void testKeyStaticFieldsHasAllVariationsAndCorrectFormat( - Class<? extends MutableProcessingConfiguration> confClass) throws IllegalArgumentException, IllegalAccessException { - // For all _KEY fields there must be a _KEY_CAMEL_CASE and a _KEY_SNAKE_CASE field. - // Their content must not contradict the expected naming convention. - // They _KEY filed value must be deducable from the field name - // The _KEY value must be the same as _KEY_SNAKE_CASE field. - // The _KEY_CAMEL_CASE converted to snake case must give the value of the _KEY_SNAKE_CASE. - for (Field field : confClass.getFields()) { - String fieldName = field.getName(); - if (fieldName.endsWith("_KEY")) { - String keyFieldValue = (String) field.get(null); - assertNotEquals(NamingConvention.CAMEL_CASE, - _StringUtil.getIdentifierNamingConvention(keyFieldValue)); - assertEquals(fieldName.substring(0, fieldName.length() - 4).toLowerCase(), keyFieldValue); - - try { - String keySCFieldValue = (String) confClass.getField(fieldName + "_SNAKE_CASE").get(null); - assertEquals(keyFieldValue, keySCFieldValue); - } catch (NoSuchFieldException e) { - fail("Missing ..._SNAKE_CASE field for " + fieldName); - } - - try { - String keyCCFieldValue = (String) confClass.getField(fieldName + "_CAMEL_CASE").get(null); - assertNotEquals(NamingConvention.LEGACY, - _StringUtil.getIdentifierNamingConvention(keyCCFieldValue)); - assertEquals(keyFieldValue, _StringUtil.camelCaseToUnderscored(keyCCFieldValue)); - } catch (NoSuchFieldException e) { - fail("Missing ..._CAMEL_CASE field for " + fieldName); - } - } - } - - // For each _KEY_SNAKE_CASE field there must be a _KEY field. - for (Field field : confClass.getFields()) { - String fieldName = field.getName(); - if (fieldName.endsWith("_KEY_SNAKE_CASE")) { - try { - confClass.getField(fieldName.substring(0, fieldName.length() - 11)).get(null); - } catch (NoSuchFieldException e) { - fail("Missing ..._KEY field for " + fieldName); - } - } - } - - // For each _KEY_CAMEL_CASE field there must be a _KEY field. - for (Field field : confClass.getFields()) { - String fieldName = field.getName(); - if (fieldName.endsWith("_KEY_CAMEL_CASE")) { - try { - confClass.getField(fieldName.substring(0, fieldName.length() - 11)).get(null); - } catch (NoSuchFieldException e) { - fail("Missing ..._KEY field for " + fieldName); - } - } - } - } - - public static void testGetSettingNamesNameConventionsContainTheSame(List<String> namesSCList, List<String> namesCCList) { - Set<String> namesSC = new HashSet<>(namesSCList); - assertEquals(namesSCList.size(), namesSC.size()); - - Set<String> namesCC = new HashSet<>(namesCCList); - assertEquals(namesCCList.size(), namesCC.size()); - - assertEquals(namesSC.size(), namesCC.size()); - - for (String nameCC : namesCC) { - final String nameSC = _StringUtil.camelCaseToUnderscored(nameCC); - if (!namesSC.contains(nameSC)) { - fail("\"" + nameCC + "\" misses corresponding snake case name, \"" + nameSC + "\"."); - } - } - } - - private MutableProcessingConfiguration createMutableProcessingConfiguration() throws IOException { - return new TemplateConfiguration.Builder(); + public void testAllSettingsAreCoveredByMutableSettingsObject() throws Exception { + ConfigurationTest.testAllSettingsAreCoveredByMutableSettingsObject( + ProcessingConfiguration.class, + MutableProcessingConfiguration.class); } - private boolean keyFieldExists(String name) throws Exception { - try { - MutableProcessingConfiguration.class.getField(name.toUpperCase() + "_KEY"); - } catch (NoSuchFieldException e) { - return false; - } - return true; + @Test + public void testGetSettingNamesCorrespondToStaticKeyFields() throws Exception { + ConfigurationTest.testGetSettingNamesCorrespondToStaticKeyFields( + MutableProcessingConfiguration.getSettingNames(), + MutableProcessingConfiguration.class); } @Test @@ -443,13 +327,13 @@ public class MutableProcessingConfigurationTest { assertThat(e.getMessage(), containsString("@wrong")); } - cfgB.setSetting(MutableProcessingConfiguration.CUSTOM_NUMBER_FORMATS_KEY_CAMEL_CASE, + cfgB.setSetting(MutableProcessingConfiguration.CUSTOM_NUMBER_FORMATS_KEY, "{ 'base': " + BaseNTemplateNumberFormatFactory.class.getName() + "() }"); assertEquals( Collections.singletonMap("base", BaseNTemplateNumberFormatFactory.INSTANCE), cfgB.getCustomNumberFormats()); - cfgB.setSetting(MutableProcessingConfiguration.CUSTOM_NUMBER_FORMATS_KEY_SNAKE_CASE, + cfgB.setSetting(MutableProcessingConfiguration.CUSTOM_NUMBER_FORMATS_KEY, "{ " + "'base': " + BaseNTemplateNumberFormatFactory.class.getName() + "(), " + "'hex': " + HexTemplateNumberFormatFactory.class.getName() + "()" @@ -464,7 +348,7 @@ public class MutableProcessingConfigurationTest { assertEquals(Collections.emptyMap(), cfgB.getCustomNumberFormats()); try { - cfgB.setSetting(MutableProcessingConfiguration.CUSTOM_NUMBER_FORMATS_KEY_CAMEL_CASE, + cfgB.setSetting(MutableProcessingConfiguration.CUSTOM_NUMBER_FORMATS_KEY, "{ 'x': " + EpochMillisTemplateDateFormatFactory.class.getName() + "() }"); fail(); } catch (ConfigurationException e) { @@ -519,13 +403,13 @@ public class MutableProcessingConfigurationTest { assertThat(e.getMessage(), containsString("@wrong")); } - cfgB.setSetting(MutableProcessingConfiguration.CUSTOM_DATE_FORMATS_KEY_CAMEL_CASE, + cfgB.setSetting(MutableProcessingConfiguration.CUSTOM_DATE_FORMATS_KEY, "{ 'epoch': " + EpochMillisTemplateDateFormatFactory.class.getName() + "() }"); assertEquals( Collections.singletonMap("epoch", EpochMillisTemplateDateFormatFactory.INSTANCE), cfgB.getCustomDateFormats()); - cfgB.setSetting(MutableProcessingConfiguration.CUSTOM_DATE_FORMATS_KEY_SNAKE_CASE, + cfgB.setSetting(MutableProcessingConfiguration.CUSTOM_DATE_FORMATS_KEY, "{ " + "'epoch': " + EpochMillisTemplateDateFormatFactory.class.getName() + "(), " + "'epochDiv': " + EpochMillisDivTemplateDateFormatFactory.class.getName() + "()" @@ -540,7 +424,7 @@ public class MutableProcessingConfigurationTest { assertEquals(Collections.emptyMap(), cfgB.getCustomDateFormats()); try { - cfgB.setSetting(MutableProcessingConfiguration.CUSTOM_DATE_FORMATS_KEY_CAMEL_CASE, + cfgB.setSetting(MutableProcessingConfiguration.CUSTOM_DATE_FORMATS_KEY, "{ 'x': " + HexTemplateNumberFormatFactory.class.getName() + "() }"); fail(); } catch (ConfigurationException e) { http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/51dba882/freemarker-core-test/src/test/java/org/apache/freemarker/core/ObjectBuilderSettingsTest.java ---------------------------------------------------------------------- diff --git a/freemarker-core-test/src/test/java/org/apache/freemarker/core/ObjectBuilderSettingsTest.java b/freemarker-core-test/src/test/java/org/apache/freemarker/core/ObjectBuilderSettingsTest.java index b02a736..f93d9ce 100644 --- a/freemarker-core-test/src/test/java/org/apache/freemarker/core/ObjectBuilderSettingsTest.java +++ b/freemarker-core-test/src/test/java/org/apache/freemarker/core/ObjectBuilderSettingsTest.java @@ -395,7 +395,7 @@ public class ObjectBuilderSettingsTest { props.setProperty(Configuration.ExtendableBuilder.TEMPLATE_CACHE_STORAGE_KEY, "soft: 500, strong: 100"); props.setProperty(MutableProcessingConfiguration.NEW_BUILTIN_CLASS_RESOLVER_KEY, - "allow_nothing"); + "allowNothing"); cfgB.setSettings(props); assertEquals(DefaultObjectWrapper.class, cfgB.getObjectWrapper().getClass()); assertEquals(1, ((DummyArithmeticEngine) cfgB.getArithmeticEngine()).getX());