http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/28a276c8/freemarker-core/src/test/java/org/apache/freemarker/manualtest/Product.java ---------------------------------------------------------------------- diff --git a/freemarker-core/src/test/java/org/apache/freemarker/manualtest/Product.java b/freemarker-core/src/test/java/org/apache/freemarker/manualtest/Product.java deleted file mode 100644 index fcb34e8..0000000 --- a/freemarker-core/src/test/java/org/apache/freemarker/manualtest/Product.java +++ /dev/null @@ -1,49 +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.manualtest; - -/** - * Product bean; note that it must be a public class! - */ -public class Product { - - private String url; - private String name; - - // As per the JavaBeans spec., this defines the "url" bean property - // It must be public! - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - // As per the JavaBean spec., this defines the "name" bean property - // It must be public! - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - -} \ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/28a276c8/freemarker-core/src/test/java/org/apache/freemarker/manualtest/TemplateConfigurationExamples.java ---------------------------------------------------------------------- diff --git a/freemarker-core/src/test/java/org/apache/freemarker/manualtest/TemplateConfigurationExamples.java b/freemarker-core/src/test/java/org/apache/freemarker/manualtest/TemplateConfigurationExamples.java deleted file mode 100644 index 8c515bd..0000000 --- a/freemarker-core/src/test/java/org/apache/freemarker/manualtest/TemplateConfigurationExamples.java +++ /dev/null @@ -1,191 +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.manualtest; - -import static org.junit.Assert.*; - -import java.nio.charset.StandardCharsets; -import java.util.Date; - -import org.apache.freemarker.core.Configuration; -import org.apache.freemarker.core.Template; -import org.apache.freemarker.core.TemplateConfiguration; -import org.apache.freemarker.core.outputformat.impl.HTMLOutputFormat; -import org.apache.freemarker.core.outputformat.impl.PlainTextOutputFormat; -import org.apache.freemarker.core.outputformat.impl.UndefinedOutputFormat; -import org.apache.freemarker.core.outputformat.impl.XMLOutputFormat; -import org.apache.freemarker.core.templateresolver.ConditionalTemplateConfigurationFactory; -import org.apache.freemarker.core.templateresolver.FileExtensionMatcher; -import org.apache.freemarker.core.templateresolver.FileNameGlobMatcher; -import org.apache.freemarker.core.templateresolver.FirstMatchTemplateConfigurationFactory; -import org.apache.freemarker.core.templateresolver.MergingTemplateConfigurationFactory; -import org.apache.freemarker.core.templateresolver.OrMatcher; -import org.apache.freemarker.core.templateresolver.PathGlobMatcher; -import org.apache.freemarker.core.util._DateUtil; -import org.apache.freemarker.test.TemplateTest; -import org.apache.freemarker.test.TestConfigurationBuilder; -import org.junit.Test; - -public class TemplateConfigurationExamples extends TemplateTest { - - @Test - public void example1JavaCfg() throws Exception { - example1(true); - } - - @Test - public void example1PropertiesCfg() throws Exception { - example1(false); - } - - private void example1(boolean javaCfg) throws Exception { - TestConfigurationBuilder cfgB = new TestConfigurationBuilder(this.getClass()); - if (javaCfg) { - cfgB.setTemplateConfigurations(new ConditionalTemplateConfigurationFactory( - new FileExtensionMatcher("xml"), - new TemplateConfiguration.Builder() - .sourceEncoding(StandardCharsets.UTF_8) - .outputFormat(XMLOutputFormat.INSTANCE) - .build())); - - } else { - cfgB.setTemplateConfigurations(null); - cfgB.setSettings(loadPropertiesFile("TemplateConfigurationExamples1.properties")); - } - setConfiguration(cfgB.build()); - - addTemplate("t.xml", ""); - - Template t = getConfiguration().getTemplate("t.xml"); - assertEquals(StandardCharsets.UTF_8, t.getActualSourceEncoding()); - assertEquals(XMLOutputFormat.INSTANCE, t.getOutputFormat()); - } - - @Test - public void example2JavaCfg() throws Exception { - example2(true); - } - - @Test - public void example2PropertiesCfg() throws Exception { - example2(false); - } - - private void example2(boolean javaCfg) throws Exception { - TestConfigurationBuilder cfgB = new TestConfigurationBuilder(this.getClass()); - if (javaCfg) { - cfgB.setTemplateConfigurations( - new ConditionalTemplateConfigurationFactory( - new PathGlobMatcher("mail/**"), - new FirstMatchTemplateConfigurationFactory( - new ConditionalTemplateConfigurationFactory( - new FileNameGlobMatcher("*.subject.*"), - new TemplateConfiguration.Builder() - .outputFormat(PlainTextOutputFormat.INSTANCE) - .build()), - new ConditionalTemplateConfigurationFactory( - new FileNameGlobMatcher("*.body.*"), - new TemplateConfiguration.Builder() - .outputFormat(HTMLOutputFormat.INSTANCE) - .build()) - ) - .noMatchErrorDetails( - "Mail template names must contain \".subject.\" or \".body.\"!"))); - } else{ - cfgB.setSettings(loadPropertiesFile("TemplateConfigurationExamples2.properties")); - } - setConfiguration(cfgB.build()); - - addTemplate("t.subject.ftl", ""); - addTemplate("mail/t.subject.ftl", ""); - addTemplate("mail/t.body.ftl", ""); - - Configuration cfg = getConfiguration(); - assertEquals(UndefinedOutputFormat.INSTANCE, cfg.getTemplate("t.subject.ftl").getOutputFormat()); - assertEquals(PlainTextOutputFormat.INSTANCE, cfg.getTemplate("mail/t.subject.ftl").getOutputFormat()); - assertEquals(HTMLOutputFormat.INSTANCE, cfg.getTemplate("mail/t.body.ftl").getOutputFormat()); - } - - @Test - public void example3JavaCfg() throws Exception { - example3(true); - } - - @Test - public void example3PropertiesCfg() throws Exception { - example3(false); - } - - private void example3(boolean javaCfg) throws Exception { - TestConfigurationBuilder cfgB = new TestConfigurationBuilder(this.getClass()) - .sourceEncoding(StandardCharsets.ISO_8859_1); - if (javaCfg) { - cfgB.setTemplateConfigurations( - new MergingTemplateConfigurationFactory( - new ConditionalTemplateConfigurationFactory( - new FileNameGlobMatcher("*.stats.*"), - new TemplateConfiguration.Builder() - .dateTimeFormat("iso") - .dateFormat("iso") - .timeFormat("iso") - .timeZone(_DateUtil.UTC) - .build()), - new ConditionalTemplateConfigurationFactory( - new PathGlobMatcher("mail/**"), - new TemplateConfiguration.Builder() - .sourceEncoding(StandardCharsets.UTF_8) - .build()), - new FirstMatchTemplateConfigurationFactory( - new ConditionalTemplateConfigurationFactory( - new FileExtensionMatcher("xml"), - new TemplateConfiguration.Builder() - .outputFormat(XMLOutputFormat.INSTANCE) - .build()), - new ConditionalTemplateConfigurationFactory( - new OrMatcher( - new FileExtensionMatcher("html"), - new FileExtensionMatcher("htm")), - new TemplateConfiguration.Builder() - .outputFormat(HTMLOutputFormat.INSTANCE) - .build()) - ).allowNoMatch(true))); - } else { - cfgB.setSettings(loadPropertiesFile("TemplateConfigurationExamples3.properties")); - } - setConfiguration(cfgB.build()); - - addTemplate("t.stats.html", "${ts?datetime} ${ts?date} ${ts?time}"); - addTemplate("t.html", ""); - addTemplate("t.htm", ""); - addTemplate("t.xml", ""); - addTemplate("mail/t.html", ""); - - addToDataModel("ts", new Date(1440431606011L)); - - Configuration cfg = getConfiguration(); - assertEquals(HTMLOutputFormat.INSTANCE, cfg.getTemplate("t.html").getOutputFormat()); - assertEquals(StandardCharsets.ISO_8859_1, cfg.getTemplate("t.html").getActualSourceEncoding()); - assertEquals(HTMLOutputFormat.INSTANCE, cfg.getTemplate("t.htm").getOutputFormat()); - assertEquals(XMLOutputFormat.INSTANCE, cfg.getTemplate("t.xml").getOutputFormat()); - assertEquals(HTMLOutputFormat.INSTANCE, cfg.getTemplate("t.stats.html").getOutputFormat()); - assertOutputForNamed("t.stats.html", "2015-08-24T15:53:26.011Z 2015-08-24 15:53:26.011Z"); - assertEquals(StandardCharsets.UTF_8, cfg.getTemplate("mail/t.html").getActualSourceEncoding()); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/28a276c8/freemarker-core/src/test/java/org/apache/freemarker/manualtest/UnitAwareTemplateNumberFormatFactory.java ---------------------------------------------------------------------- diff --git a/freemarker-core/src/test/java/org/apache/freemarker/manualtest/UnitAwareTemplateNumberFormatFactory.java b/freemarker-core/src/test/java/org/apache/freemarker/manualtest/UnitAwareTemplateNumberFormatFactory.java deleted file mode 100644 index 89f20fa..0000000 --- a/freemarker-core/src/test/java/org/apache/freemarker/manualtest/UnitAwareTemplateNumberFormatFactory.java +++ /dev/null @@ -1,80 +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.manualtest; - -import java.util.Locale; - -import org.apache.freemarker.core.Environment; -import org.apache.freemarker.core.model.TemplateModelException; -import org.apache.freemarker.core.model.TemplateNumberModel; -import org.apache.freemarker.core.valueformat.TemplateNumberFormat; -import org.apache.freemarker.core.valueformat.TemplateNumberFormatFactory; -import org.apache.freemarker.core.valueformat.TemplateValueFormatException; - -/** - * A number format that takes any other number format as parameter (specified as a string, as - * usual in FreeMarker), then if the model is a {@link UnitAwareTemplateNumberModel}, it shows - * the unit after the number formatted with the other format, otherwise it just shows the formatted - * number without unit. - */ -public class UnitAwareTemplateNumberFormatFactory extends TemplateNumberFormatFactory { - - public static final UnitAwareTemplateNumberFormatFactory INSTANCE - = new UnitAwareTemplateNumberFormatFactory(); - - private UnitAwareTemplateNumberFormatFactory() { - // Defined to decrease visibility - } - - @Override - public TemplateNumberFormat get(String params, Locale locale, Environment env) - throws TemplateValueFormatException { - return new UnitAwareNumberFormat(env.getTemplateNumberFormat(params, locale)); - } - - private static class UnitAwareNumberFormat extends TemplateNumberFormat { - - private final TemplateNumberFormat innerFormat; - - private UnitAwareNumberFormat(TemplateNumberFormat innerFormat) { - this.innerFormat = innerFormat; - } - - @Override - public String formatToPlainText(TemplateNumberModel numberModel) - throws TemplateModelException, TemplateValueFormatException { - String innerResult = innerFormat.formatToPlainText(numberModel); - return numberModel instanceof UnitAwareTemplateNumberModel - ? innerResult + " " + ((UnitAwareTemplateNumberModel) numberModel).getUnit() - : innerResult; - } - - @Override - public boolean isLocaleBound() { - return innerFormat.isLocaleBound(); - } - - @Override - public String getDescription() { - return "unit-aware " + innerFormat.getDescription(); - } - - } - -} http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/28a276c8/freemarker-core/src/test/java/org/apache/freemarker/manualtest/UnitAwareTemplateNumberModel.java ---------------------------------------------------------------------- diff --git a/freemarker-core/src/test/java/org/apache/freemarker/manualtest/UnitAwareTemplateNumberModel.java b/freemarker-core/src/test/java/org/apache/freemarker/manualtest/UnitAwareTemplateNumberModel.java deleted file mode 100644 index 1e54254..0000000 --- a/freemarker-core/src/test/java/org/apache/freemarker/manualtest/UnitAwareTemplateNumberModel.java +++ /dev/null @@ -1,43 +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.manualtest; - -import org.apache.freemarker.core.model.TemplateModelException; -import org.apache.freemarker.core.model.TemplateNumberModel; - -public class UnitAwareTemplateNumberModel implements TemplateNumberModel { - - private final Number value; - private final String unit; - - public UnitAwareTemplateNumberModel(Number value, String unit) { - this.value = value; - this.unit = unit; - } - - @Override - public Number getAsNumber() throws TemplateModelException { - return value; - } - - public String getUnit() { - return unit; - } - -} http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/28a276c8/freemarker-core/src/test/java/org/apache/freemarker/test/CopyrightCommentRemoverTemplateLoader.java ---------------------------------------------------------------------- diff --git a/freemarker-core/src/test/java/org/apache/freemarker/test/CopyrightCommentRemoverTemplateLoader.java b/freemarker-core/src/test/java/org/apache/freemarker/test/CopyrightCommentRemoverTemplateLoader.java deleted file mode 100644 index 3b1f1ee..0000000 --- a/freemarker-core/src/test/java/org/apache/freemarker/test/CopyrightCommentRemoverTemplateLoader.java +++ /dev/null @@ -1,104 +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.test; - -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.io.Serializable; -import java.io.StringReader; -import java.nio.charset.StandardCharsets; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.io.input.ReaderInputStream; -import org.apache.freemarker.core.templateresolver.TemplateLoader; -import org.apache.freemarker.core.templateresolver.TemplateLoaderSession; -import org.apache.freemarker.core.templateresolver.TemplateLoadingResult; -import org.apache.freemarker.core.templateresolver.TemplateLoadingResultStatus; -import org.apache.freemarker.core.templateresolver.TemplateLoadingSource; - -/** - * Removes the Apache copyright boiler plate from the beginning of the template, so that they don't mess up the expected - * template output. This can interfere with tests that try to test I/O errors and such low level things, so use with - * care. - */ -public class CopyrightCommentRemoverTemplateLoader implements TemplateLoader { - - private final TemplateLoader innerTemplateLoader; - - public CopyrightCommentRemoverTemplateLoader(TemplateLoader innerTemplateLoader) { - this.innerTemplateLoader = innerTemplateLoader; - } - - @Override - public TemplateLoaderSession createSession() { - return null; - } - - @Override - public TemplateLoadingResult load(String name, TemplateLoadingSource ifSourceDiffersFrom, - Serializable ifVersionDiffersFrom, TemplateLoaderSession session) throws IOException { - TemplateLoadingResult result = innerTemplateLoader.load(name, ifSourceDiffersFrom, ifVersionDiffersFrom, session); - if (result.getStatus() != TemplateLoadingResultStatus.OPENED) { - return result; - } - if (result.getInputStream() != null) { - return new TemplateLoadingResult( - result.getSource(), result.getVersion(), getWithoutCopyrightHeader(result.getInputStream()), - result.getTemplateConfiguration()); - } else { - return new TemplateLoadingResult( - result.getSource(), result.getVersion(), getWithoutCopyrightHeader(result.getReader()), - result.getTemplateConfiguration()); - } - } - - @Override - public void resetState() { - // Do nothing - } - - private Reader getWithoutCopyrightHeader(Reader reader) throws IOException { - if (reader == null) { - return null; - } - try { - String content = IOUtils.toString(reader); - return new StringReader(TestUtil.removeFTLCopyrightComment(content)); - } finally { - reader.close(); - } - } - - private InputStream getWithoutCopyrightHeader(InputStream in) throws IOException { - if (in == null) { - return null; - } - try { - // Encoding then decosing in ISO-8859-1 is binary loseless - String content = IOUtils.toString(in, StandardCharsets.ISO_8859_1.name()); - return new ReaderInputStream( - new StringReader(TestUtil.removeFTLCopyrightComment(content)), - StandardCharsets.ISO_8859_1); - } finally { - in.close(); - } - } - -} http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/28a276c8/freemarker-core/src/test/java/org/apache/freemarker/test/MonitoredTemplateLoader.java ---------------------------------------------------------------------- diff --git a/freemarker-core/src/test/java/org/apache/freemarker/test/MonitoredTemplateLoader.java b/freemarker-core/src/test/java/org/apache/freemarker/test/MonitoredTemplateLoader.java deleted file mode 100644 index 0ab2922..0000000 --- a/freemarker-core/src/test/java/org/apache/freemarker/test/MonitoredTemplateLoader.java +++ /dev/null @@ -1,325 +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.test; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.Serializable; -import java.io.StringReader; -import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.apache.freemarker.core.templateresolver.TemplateLoader; -import org.apache.freemarker.core.templateresolver.TemplateLoaderSession; -import org.apache.freemarker.core.templateresolver.TemplateLoadingResult; -import org.apache.freemarker.core.templateresolver.TemplateLoadingResultStatus; -import org.apache.freemarker.core.templateresolver.TemplateLoadingSource; - -import com.google.common.base.Objects; - -public class MonitoredTemplateLoader implements TemplateLoader { - - private final List<AbstractTemplateLoader2Event> events - = Collections.synchronizedList(new ArrayList<AbstractTemplateLoader2Event>()); - - private Map<String, StoredTemplate> templates - = new ConcurrentHashMap<>(); - - @Override - public TemplateLoaderSession createSession() { - events.add(CreateSessionEvent.INSTANCE); - return new MonitoredTemplateLoader2Session(); - } - - @Override - public TemplateLoadingResult load(String name, TemplateLoadingSource ifSourceDiffersFrom, Serializable ifVersionDiffersFrom, - TemplateLoaderSession session) - throws IOException { - TemplateLoadingResult result = loadInner(name, ifSourceDiffersFrom, ifVersionDiffersFrom, session); - events.add(new LoadEvent(name, result.getStatus())); - return result; - } - - private TemplateLoadingResult loadInner(String name, TemplateLoadingSource ifSourceDiffersFrom, - Serializable ifVersionDiffersFrom, TemplateLoaderSession session) throws UnsupportedEncodingException { - if (session.isClosed()) { - throw new IllegalArgumentException("Template loader session is already closed."); - } - - StoredTemplate storedTemplate = templates.get(name); - if (storedTemplate == null) { - return TemplateLoadingResult.NOT_FOUND; - } - - TemplateLoadingSource source = storedTemplate.getSource(); - Serializable version = storedTemplate.getVersion(); - if (ifSourceDiffersFrom != null - && ifSourceDiffersFrom.equals(source) - && Objects.equal(ifVersionDiffersFrom, version)) { - return TemplateLoadingResult.NOT_MODIFIED; - } - - String content = storedTemplate.getContent(); - return storedTemplate.inputStreamEncoding == null - ? new TemplateLoadingResult(source, version, new StringReader(content), null) - : new TemplateLoadingResult(source, version, - new ByteArrayInputStream(content.getBytes(storedTemplate.inputStreamEncoding)), null); - } - - @Override - public void resetState() { - events.add(ResetStateEvent.INSTANCE); - } - - public StoredTemplate putTextTemplate(String name, String content) { - return putTextTemplate(name, "v1", content); - } - - public StoredTemplate putTextTemplate(String name, Serializable version, String content) { - StoredTemplate storedTemplate = new StoredTemplate(name, version, content, null); - templates.put(name, storedTemplate); - return storedTemplate; - } - - public StoredTemplate putBinaryTemplate(String name, String content) { - return putBinaryTemplate(name, content, "v1"); - } - - public StoredTemplate putBinaryTemplate(String name, String content, Serializable version) { - return putBinaryTemplate(name, content, null, version); - } - - public StoredTemplate putBinaryTemplate(String name, String content, - Charset inputStreamEncoding, Serializable version) { - StoredTemplate storedTemplate = new StoredTemplate(name, version, content, - inputStreamEncoding != null ? inputStreamEncoding : StandardCharsets.UTF_8); - templates.put(name, storedTemplate); - return storedTemplate; - } - - public List<AbstractTemplateLoader2Event> getEvents() { - return events; - } - - /** - * Gets a filtered event list. - */ - @SuppressWarnings("unchecked") - public <E extends AbstractTemplateLoader2Event> List<E> getEvents(Class<E> eventClass) { - List<E> result = new ArrayList<>(); - for (AbstractTemplateLoader2Event event : events) { - if (eventClass.isInstance(event)) { - result.add((E) event); - } - } - return result; - } - - /** - * Extract from the {@link #getEvents()} the template names for which {@link TemplateLoader#load} was called. - */ - public List<String> getLoadNames() { - List<String> result = new ArrayList<>(); - for (AbstractTemplateLoader2Event event : events) { - if (event instanceof LoadEvent) { - result.add(((LoadEvent) event).name); - } - } - return result; - } - - public void clearEvents() { - events.clear(); - } - - @SuppressWarnings("serial") - public static class StoredTemplate implements TemplateLoadingSource { - private String name; - private Serializable version; - private String content; - private Charset inputStreamEncoding; - - private StoredTemplate(String name, Serializable version, String content, Charset inputStreamEncoding) { - this.name = name; - this.version = version; - this.content = content; - this.inputStreamEncoding = inputStreamEncoding; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public TemplateLoadingSource getSource() { - return this; - } - - public Serializable getVersion() { - return version; - } - - public void setVersion(Serializable version) { - this.version = version; - } - - public String getContent() { - return content; - } - - public void setContent(String content) { - this.content = content; - } - - public Charset getInputStreamEncoding() { - return inputStreamEncoding; - } - - public void setInputStreamEncoding(Charset inputStreamEncoding) { - this.inputStreamEncoding = inputStreamEncoding; - } - - } - - public abstract static class AbstractTemplateLoader2Event { - // empty - } - - public static class LoadEvent extends AbstractTemplateLoader2Event { - private final String name; - private final TemplateLoadingResultStatus resultStatus; - - public LoadEvent(String name, TemplateLoadingResultStatus resultStatus) { - this.name = name; - this.resultStatus = resultStatus; - } - - public String getName() { - return name; - } - - public TemplateLoadingResultStatus getResultStatus() { - return resultStatus; - } - - @Override - public String toString() { - return "LoadEvent [name=" + name + ", resultStatus=" + resultStatus + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((resultStatus == null) ? 0 : resultStatus.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - LoadEvent other = (LoadEvent) obj; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return resultStatus == other.resultStatus; - } - - } - - public static class ResetStateEvent extends AbstractTemplateLoader2Event { - - public static ResetStateEvent INSTANCE = new ResetStateEvent(); - - private ResetStateEvent() { - // - } - - @Override - public String toString() { - return "ResetStateEvent []"; - } - - } - - public static class CreateSessionEvent extends AbstractTemplateLoader2Event { - - public static CreateSessionEvent INSTANCE = new CreateSessionEvent(); - - private CreateSessionEvent() { - // - } - - @Override - public String toString() { - return "CreateSessionEvent []"; - } - - } - - public static class CloseSessionEvent extends AbstractTemplateLoader2Event { - - public static CloseSessionEvent INSTANCE = new CloseSessionEvent(); - - private CloseSessionEvent() { - // - } - - @Override - public String toString() { - return "CloseSessionEvent []"; - } - - } - - public class MonitoredTemplateLoader2Session implements TemplateLoaderSession { - - private boolean closed; - - @Override - public void close() { - closed = true; - events.add(CloseSessionEvent.INSTANCE); - } - - @Override - public boolean isClosed() { - return closed; - } - - } - -} http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/28a276c8/freemarker-core/src/test/java/org/apache/freemarker/test/TemplateTest.java ---------------------------------------------------------------------- diff --git a/freemarker-core/src/test/java/org/apache/freemarker/test/TemplateTest.java b/freemarker-core/src/test/java/org/apache/freemarker/test/TemplateTest.java deleted file mode 100644 index 566cc90..0000000 --- a/freemarker-core/src/test/java/org/apache/freemarker/test/TemplateTest.java +++ /dev/null @@ -1,341 +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.test; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; -import java.nio.charset.StandardCharsets; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import org.apache.commons.io.IOUtils; -import org.apache.freemarker.core.Configuration; -import org.apache.freemarker.core.ParseException; -import org.apache.freemarker.core.Template; -import org.apache.freemarker.core.TemplateException; -import org.apache.freemarker.core.templateresolver.TemplateLoader; -import org.apache.freemarker.core.templateresolver.impl.ByteArrayTemplateLoader; -import org.apache.freemarker.core.templateresolver.impl.MultiTemplateLoader; -import org.apache.freemarker.core.util._NullArgumentException; -import org.apache.freemarker.core.util._StringUtil; -import org.apache.freemarker.test.templatesuite.TemplateTestSuite; -import org.junit.Ignore; - -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; - -/** - * Superclass of JUnit tests that process templates but aren't practical to implement via {@link TemplateTestSuite}. - */ -@Ignore -public abstract class TemplateTest { - - private Configuration configuration; - private boolean dataModelCreated; - private Object dataModel; - private Map<String, String> addedTemplates = new HashMap<>(); - - /** - * Gets the {@link Configuration} used, automaticlly creating and setting if it wasn't yet. - */ - protected final Configuration getConfiguration() { - if (configuration == null) { - try { - setConfiguration(createDefaultConfiguration()); - } catch (Exception e) { - throw new RuntimeException("Failed to create configuration", e); - } - } - return configuration; - } - - /** - * @param configuration Usually should be built using {@link TestConfigurationBuilder}; not {@code null}. - */ - protected final void setConfiguration(Configuration configuration) { - _NullArgumentException.check("configuration", configuration); - if (this.configuration == configuration) { - return; - } - - this.configuration = configuration; - afterConfigurationSet(); - } - - protected void assertOutput(String ftl, String expectedOut) throws IOException, TemplateException { - assertOutput(createTemplate(ftl), expectedOut, false); - } - - private Template createTemplate(String ftl) throws IOException { - return new Template(null, ftl, getConfiguration()); - } - - protected void assertOutputForNamed(String name, String expectedOut) throws IOException, TemplateException { - assertOutput(getConfiguration().getTemplate(name), expectedOut, false); - } - - @SuppressFBWarnings(value="UI_INHERITANCE_UNSAFE_GETRESOURCE", justification="By design relative to subclass") - protected void assertOutputForNamed(String name) throws IOException, TemplateException { - String expectedOut; - { - String resName = name + ".out"; - InputStream in = getClass().getResourceAsStream(resName); - if (in == null) { - throw new IOException("Reference output resource not found: " + getClass() + ", " + resName); - } - try { - expectedOut = TestUtil.removeTxtCopyrightComment(IOUtils.toString(in, StandardCharsets.UTF_8.name())); - } finally { - in.close(); - } - } - assertOutput(getConfiguration().getTemplate(name), expectedOut, true); - } - - protected void assertOutput(Template t, String expectedOut) throws TemplateException, IOException { - assertOutput(t, expectedOut, false); - } - - protected void assertOutput(Template t, String expectedOut, boolean normalizeNewlines) - throws TemplateException, IOException { - String actualOut = getOutput(t); - - if (normalizeNewlines) { - expectedOut = normalizeNewLines(expectedOut); - actualOut = normalizeNewLines(actualOut); - } - assertEquals(expectedOut, actualOut); - } - - protected String getOutput(String ftl) throws IOException, TemplateException { - return getOutput(createTemplate(ftl)); - } - - protected String getOutput(Template t) throws TemplateException, IOException { - StringWriter out = new StringWriter(); - t.process(getDataModel(), out); - return out.toString(); - } - - protected Configuration createDefaultConfiguration() throws Exception { - return new TestConfigurationBuilder().build(); - } - - private void afterConfigurationSet() { - ensureAddedTemplatesPresent(); - addCommonTemplates(); - } - - private void ensureAddedTemplatesPresent() { - for (Map.Entry<String, String> ent : addedTemplates.entrySet()) { - addTemplate(ent.getKey(), ent.getValue()); - } - } - - protected void addCommonTemplates() { - // - } - - protected Object getDataModel() { - if (!dataModelCreated) { - dataModel = createDataModel(); - dataModelCreated = true; - } - return dataModel; - } - - protected Object createDataModel() { - return null; - } - - @SuppressWarnings("boxing") - protected Map<String, Object> createCommonTestValuesDataModel() { - Map<String, Object> dataModel = new HashMap<>(); - dataModel.put("map", Collections.singletonMap("key", "value")); - dataModel.put("list", Collections.singletonList("item")); - dataModel.put("s", "text"); - dataModel.put("n", 1); - dataModel.put("b", true); - dataModel.put("bean", new TestBean()); - return dataModel; - } - - protected void addTemplate(String name, String content) { - Configuration cfg = getConfiguration(); - TemplateLoader tl = cfg.getTemplateLoader(); - ByteArrayTemplateLoader btl; - btl = extractByteArrayTemplateLoader(tl); - btl.putTemplate(name, content.getBytes(StandardCharsets.UTF_8)); - addedTemplates.put(name, content); - } - - private ByteArrayTemplateLoader extractByteArrayTemplateLoader(TemplateLoader tl) { - if (tl instanceof MultiTemplateLoader) { - MultiTemplateLoader mtl = (MultiTemplateLoader) tl; - for (int i = 0; i < mtl.getTemplateLoaderCount(); i++) { - TemplateLoader tli = mtl.getTemplateLoader(i); - if (tli instanceof ByteArrayTemplateLoader) { - return (ByteArrayTemplateLoader) tli; - } - } - throw new IllegalStateException( - "The template loader was a MultiTemplateLoader that didn't contain ByteArrayTemplateLoader: " - + tl); - } else if (tl instanceof ByteArrayTemplateLoader) { - return (ByteArrayTemplateLoader) tl; - } else if (tl == null) { - throw new IllegalStateException("The templateLoader was null in the configuration"); - } else { - throw new IllegalStateException( - "The template loader was already set to a non-ByteArrayTemplateLoader non-MultiTemplateLoader: " - + tl); - } - } - - protected void addToDataModel(String name, Object value) { - Object dm = getDataModel(); - if (dm == null) { - dm = new HashMap<String, Object>(); - dataModel = dm; - } - if (dm instanceof Map) { - ((Map) dm).put(name, value); - } else { - throw new IllegalStateException("Can't add to non-Map data-model: " + dm); - } - } - - protected Properties loadPropertiesFile(String name) throws IOException { - Properties props = new Properties(); - InputStream in = getClass().getResourceAsStream(name); - try { - props.load(in); - } finally { - in.close(); - } - return props; - } - - protected Throwable assertErrorContains(String ftl, String... expectedSubstrings) { - return assertErrorContains(null, ftl, null, expectedSubstrings); - } - - protected Throwable assertErrorContains(String ftl, Class<? extends Throwable> exceptionClass, - String... expectedSubstrings) { - return assertErrorContains(null, ftl, exceptionClass, expectedSubstrings); - } - - protected void assertErrorContainsForNamed(String name, String... expectedSubstrings) { - assertErrorContains(name, null, null, expectedSubstrings); - } - - protected void assertErrorContainsForNamed(String name, Class<? extends Throwable> exceptionClass, - String... expectedSubstrings) { - assertErrorContains(name, null, exceptionClass, expectedSubstrings); - } - - private Throwable assertErrorContains(String name, String ftl, Class<? extends Throwable> exceptionClass, - String... expectedSubstrings) { - try { - Template t; - if (ftl == null) { - t = getConfiguration().getTemplate(name); - } else { - t = new Template("adhoc", ftl, getConfiguration()); - } - t.process(getDataModel(), new StringWriter()); - fail("The tempalte had to fail"); - return null; - } catch (TemplateException e) { - if (exceptionClass != null) { - assertThat(e, instanceOf(exceptionClass)); - } - assertContainsAll(e.getMessageWithoutStackTop(), expectedSubstrings); - return e; - } catch (ParseException e) { - if (exceptionClass != null) { - assertThat(e, instanceOf(exceptionClass)); - } - assertContainsAll(e.getEditorMessage(), expectedSubstrings); - return e; - } catch (Exception e) { - if (exceptionClass != null) { - assertThat(e, instanceOf(exceptionClass)); - return e; - } else { - throw new RuntimeException("Unexpected exception class: " + e.getClass().getName(), e); - } - } - } - - private void assertContainsAll(String msg, String... expectedSubstrings) { - for (String needle: expectedSubstrings) { - if (needle.startsWith("\\!")) { - String netNeedle = needle.substring(2); - if (msg.contains(netNeedle)) { - fail("The message shouldn't contain substring " + _StringUtil.jQuote(netNeedle) + ":\n" + msg); - } - } else if (!msg.contains(needle)) { - fail("The message didn't contain substring " + _StringUtil.jQuote(needle) + ":\n" + msg); - } - } - } - - private String normalizeNewLines(String s) { - return _StringUtil.replace(s, "\r\n", "\n").replace('\r', '\n'); - } - - public static class TestBean { - private int x; - private boolean b; - - public int getX() { - return x; - } - public void setX(int x) { - this.x = x; - } - public boolean isB() { - return b; - } - public void setB(boolean b) { - this.b = b; - } - - public int intM() { - return 1; - } - - public int intMP(int x) { - return x; - } - - public void voidM() { - - } - - } - -} http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/28a276c8/freemarker-core/src/test/java/org/apache/freemarker/test/TestConfigurationBuilder.java ---------------------------------------------------------------------- diff --git a/freemarker-core/src/test/java/org/apache/freemarker/test/TestConfigurationBuilder.java b/freemarker-core/src/test/java/org/apache/freemarker/test/TestConfigurationBuilder.java deleted file mode 100644 index 7f869db..0000000 --- a/freemarker-core/src/test/java/org/apache/freemarker/test/TestConfigurationBuilder.java +++ /dev/null @@ -1,92 +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.test; - -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.Locale; -import java.util.TimeZone; - -import org.apache.freemarker.core.Configuration; -import org.apache.freemarker.core.Configuration.Builder; -import org.apache.freemarker.core.Version; -import org.apache.freemarker.core.templateresolver.TemplateLoader; -import org.apache.freemarker.core.templateresolver.impl.ByteArrayTemplateLoader; -import org.apache.freemarker.core.templateresolver.impl.ClassTemplateLoader; -import org.apache.freemarker.core.templateresolver.impl.MultiTemplateLoader; - -/** - * Configuration builder you should use instead of {@link Builder} in unit tests. - * It tries to make the behavior of the tests independent of the environment where we run them. For convenience, it - * has a {@link ByteArrayTemplateLoader} as the default template loader. - */ -public class TestConfigurationBuilder extends Configuration.ExtendableBuilder<TestConfigurationBuilder> { - - private static final TimeZone DEFAULT_TIME_ZONE = TimeZone.getTimeZone("GMT+1"); - private final Class<?> classTemplateLoaderBase; - private TemplateLoader defaultTemplateLoader; - - public TestConfigurationBuilder() { - this((Version) null); - } - - public TestConfigurationBuilder(Class<?> classTemplateLoaderBase) { - this(null, classTemplateLoaderBase); - } - - public TestConfigurationBuilder(Version incompatibleImprovements) { - this(incompatibleImprovements, null); - } - - public TestConfigurationBuilder(Version incompatibleImprovements, Class<?> classTemplateLoaderBase) { - super(incompatibleImprovements != null ? incompatibleImprovements : Configuration.VERSION_3_0_0); - this.classTemplateLoaderBase = classTemplateLoaderBase; - } - - @Override - protected Locale getDefaultLocale() { - return Locale.US; - } - - @Override - protected Charset getDefaultSourceEncoding() { - return StandardCharsets.UTF_8; - } - - @Override - protected TimeZone getDefaultTimeZone() { - return DEFAULT_TIME_ZONE; - } - - @Override - protected TemplateLoader getDefaultTemplateLoader() { - if (defaultTemplateLoader == null) { - if (classTemplateLoaderBase == null) { - defaultTemplateLoader = new ByteArrayTemplateLoader(); - } else { - defaultTemplateLoader = new MultiTemplateLoader( - new ByteArrayTemplateLoader(), - new ClassTemplateLoader(classTemplateLoaderBase, "")); - } - } - return defaultTemplateLoader; - } - -} http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/28a276c8/freemarker-core/src/test/java/org/apache/freemarker/test/hamcerst/Matchers.java ---------------------------------------------------------------------- diff --git a/freemarker-core/src/test/java/org/apache/freemarker/test/hamcerst/Matchers.java b/freemarker-core/src/test/java/org/apache/freemarker/test/hamcerst/Matchers.java deleted file mode 100644 index 7552a8d..0000000 --- a/freemarker-core/src/test/java/org/apache/freemarker/test/hamcerst/Matchers.java +++ /dev/null @@ -1,34 +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.test.hamcerst; - -import org.hamcrest.Matcher; - -public final class Matchers { - - private Matchers() { - // Not meant to be instantiated - } - - public static Matcher<String> containsStringIgnoringCase(String substring) { - return StringContainsIgnoringCase.containsStringIgnoringCase(substring); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/28a276c8/freemarker-core/src/test/java/org/apache/freemarker/test/hamcerst/StringContainsIgnoringCase.java ---------------------------------------------------------------------- diff --git a/freemarker-core/src/test/java/org/apache/freemarker/test/hamcerst/StringContainsIgnoringCase.java b/freemarker-core/src/test/java/org/apache/freemarker/test/hamcerst/StringContainsIgnoringCase.java deleted file mode 100644 index 914bbd1..0000000 --- a/freemarker-core/src/test/java/org/apache/freemarker/test/hamcerst/StringContainsIgnoringCase.java +++ /dev/null @@ -1,47 +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.test.hamcerst; - -import org.hamcrest.Factory; -import org.hamcrest.Matcher; -import org.hamcrest.core.SubstringMatcher; - -public class StringContainsIgnoringCase extends SubstringMatcher { - - public StringContainsIgnoringCase(String substring) { - super(substring); - } - - @Override - protected boolean evalSubstringOf(String s) { - return s.toLowerCase().contains(substring.toLowerCase()); - } - - @Override - protected String relationship() { - return "containing ignoring case"; - } - - @Factory - public static Matcher<String> containsStringIgnoringCase(String substring) { - return new StringContainsIgnoringCase(substring); - } - -} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/28a276c8/freemarker-core/src/test/java/org/apache/freemarker/test/package.html ---------------------------------------------------------------------- diff --git a/freemarker-core/src/test/java/org/apache/freemarker/test/package.html b/freemarker-core/src/test/java/org/apache/freemarker/test/package.html deleted file mode 100644 index 3dbb3fb..0000000 --- a/freemarker-core/src/test/java/org/apache/freemarker/test/package.html +++ /dev/null @@ -1,28 +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. ---> -<html> -<head> -</head> -<body> -<p>Testing-related classes that don't fit into the normal packages. -Normally you put the test classes into the same package where the -tested classes are, but under <tt>src/test/java/<tt> instead of -under <tt>src/main/java/<tt>.</p> -</body> -</html> http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/28a276c8/freemarker-core/src/test/java/org/apache/freemarker/test/templatesuite/TemplateTestCase.java ---------------------------------------------------------------------- diff --git a/freemarker-core/src/test/java/org/apache/freemarker/test/templatesuite/TemplateTestCase.java b/freemarker-core/src/test/java/org/apache/freemarker/test/templatesuite/TemplateTestCase.java deleted file mode 100644 index 07bf0ca..0000000 --- a/freemarker-core/src/test/java/org/apache/freemarker/test/templatesuite/TemplateTestCase.java +++ /dev/null @@ -1,515 +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.test.templatesuite; - -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.ResourceBundle; -import java.util.Set; -import java.util.StringTokenizer; -import java.util.TimeZone; -import java.util.TreeSet; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - -import org.apache.freemarker.core.ASTPrinter; -import org.apache.freemarker.core.Configuration; -import org.apache.freemarker.core.ConfigurationException; -import org.apache.freemarker.core.Template; -import org.apache.freemarker.core.TemplateException; -import org.apache.freemarker.core.Version; -import org.apache.freemarker.core.model.TemplateBooleanModel; -import org.apache.freemarker.core.model.TemplateDateModel; -import org.apache.freemarker.core.model.TemplateMethodModel; -import org.apache.freemarker.core.model.TemplateNodeModel; -import org.apache.freemarker.core.model.TemplateScalarModel; -import org.apache.freemarker.core.model.TemplateSequenceModel; -import org.apache.freemarker.core.model.impl.DefaultNonListCollectionAdapter; -import org.apache.freemarker.core.model.impl.DefaultObjectWrapper; -import org.apache.freemarker.core.model.impl.ResourceBundleModel; -import org.apache.freemarker.core.model.impl.SimpleCollection; -import org.apache.freemarker.core.model.impl.SimpleDate; -import org.apache.freemarker.core.model.impl.SimpleNumber; -import org.apache.freemarker.core.templateresolver.impl.ClassTemplateLoader; -import org.apache.freemarker.core.util._NullArgumentException; -import org.apache.freemarker.core.util._NullWriter; -import org.apache.freemarker.core.util._StringUtil; -import org.apache.freemarker.dom.NodeModel; -import org.apache.freemarker.test.CopyrightCommentRemoverTemplateLoader; -import org.apache.freemarker.test.TestConfigurationBuilder; -import org.apache.freemarker.test.templatesuite.models.BooleanAndStringTemplateModel; -import org.apache.freemarker.test.templatesuite.models.BooleanHash1; -import org.apache.freemarker.test.templatesuite.models.BooleanHash2; -import org.apache.freemarker.test.templatesuite.models.BooleanList1; -import org.apache.freemarker.test.templatesuite.models.BooleanList2; -import org.apache.freemarker.test.templatesuite.models.BooleanVsStringMethods; -import org.apache.freemarker.test.templatesuite.models.JavaObjectInfo; -import org.apache.freemarker.test.templatesuite.models.Listables; -import org.apache.freemarker.test.templatesuite.models.MultiModel1; -import org.apache.freemarker.test.templatesuite.models.OverloadedMethods2; -import org.apache.freemarker.test.templatesuite.models.VarArgTestModel; -import org.apache.freemarker.test.util.AssertDirective; -import org.apache.freemarker.test.util.AssertEqualsDirective; -import org.apache.freemarker.test.util.AssertFailsDirective; -import org.apache.freemarker.test.util.FileTestCase; -import org.apache.freemarker.test.util.NoOutputDirective; -import org.apache.freemarker.test.util.XMLLoader; -import org.junit.Ignore; -import org.xml.sax.InputSource; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; - -import junit.framework.AssertionFailedError; - -/** - * Instances of this are created and called by {@link TemplateTestSuite}. (It's on "Ignore" so that Eclipse doesn't try - * to run this alone.) - */ -@Ignore -public class TemplateTestCase extends FileTestCase { - - // Name of variables exposed to all test FTL-s: - private static final String ICI_INT_VALUE_VAR_NAME = "iciIntValue"; - private static final String TEST_NAME_VAR_NAME = "testName"; - private static final String JAVA_OBJECT_INFO_VAR_NAME = "javaObjectInfo"; - private static final String NO_OUTPUT_VAR_NAME = "noOutput"; - private static final String ASSERT_FAILS_VAR_NAME = "assertFails"; - private static final String ASSERT_EQUALS_VAR_NAME = "assertEquals"; - private static final String ASSERT_VAR_NAME = "assert"; - - private final String simpleTestName; - private final String templateName; - private final String expectedFileName; - private final boolean noOutput; - - private final Configuration.ExtendableBuilder confB; - private final HashMap<String, Object> dataModel = new HashMap<>(); - - public TemplateTestCase(String testName, String simpleTestName, String templateName, String expectedFileName, boolean noOutput, - Version incompatibleImprovements) { - super(testName); - _NullArgumentException.check("testName", testName); - - _NullArgumentException.check("simpleTestName", simpleTestName); - this.simpleTestName = simpleTestName; - - _NullArgumentException.check("templateName", templateName); - this.templateName = templateName; - - _NullArgumentException.check("expectedFileName", expectedFileName); - this.expectedFileName = expectedFileName; - - this.noOutput = noOutput; - - confB = new TestConfigurationBuilder(incompatibleImprovements); - } - - public void setSetting(String param, String value) throws IOException { - if ("auto_import".equals(param)) { - StringTokenizer st = new StringTokenizer(value); - if (!st.hasMoreTokens()) fail("Expecting libname"); - String libname = st.nextToken(); - if (!st.hasMoreTokens()) fail("Expecting 'as <alias>' in autoimport"); - String as = st.nextToken(); - if (!as.equals("as")) fail("Expecting 'as <alias>' in autoimport"); - if (!st.hasMoreTokens()) fail("Expecting alias after 'as' in autoimport"); - String alias = st.nextToken(); - confB.addAutoImport(alias, libname); - } else if ("source_encoding".equals(param)) { - confB.setSourceEncoding(Charset.forName(value)); - // INCOMPATIBLE_IMPROVEMENTS is a list here, and was already set in the constructor. - } else if (!Configuration.ExtendableBuilder.INCOMPATIBLE_IMPROVEMENTS_KEY.equals(param)) { - try { - confB.setSetting(param, value); - } catch (ConfigurationException e) { - throw new RuntimeException( - "Failed to set setting " + - _StringUtil.jQuote(param) + " to " + - _StringUtil.jQuote(value) + "; see cause exception.", - e); - } - } - } - - /* - * This method just contains all the code to seed the data model - * ported over from the individual classes. This seems ugly and unnecessary. - * We really might as well just expose pretty much - * the same tree to all our tests. (JR) - */ - @Override - @SuppressWarnings("boxing") - public void setUp() throws Exception { - confB.setTemplateLoader( - new CopyrightCommentRemoverTemplateLoader( - new ClassTemplateLoader(TemplateTestCase.class, "templates"))); - - DefaultObjectWrapper dow = new DefaultObjectWrapper.Builder(Configuration.VERSION_3_0_0).build(); - - dataModel.put(ASSERT_VAR_NAME, AssertDirective.INSTANCE); - dataModel.put(ASSERT_EQUALS_VAR_NAME, AssertEqualsDirective.INSTANCE); - dataModel.put(ASSERT_FAILS_VAR_NAME, AssertFailsDirective.INSTANCE); - dataModel.put(NO_OUTPUT_VAR_NAME, NoOutputDirective.INSTANCE); - - dataModel.put(JAVA_OBJECT_INFO_VAR_NAME, JavaObjectInfo.INSTANCE); - dataModel.put(TEST_NAME_VAR_NAME, simpleTestName); - dataModel.put(ICI_INT_VALUE_VAR_NAME, confB.getIncompatibleImprovements().intValue()); - - dataModel.put("message", "Hello, world!"); - - if (simpleTestName.startsWith("api-builtin")) { - dataModel.put("map", ImmutableMap.of(1, "a", 2, "b", 3, "c")); - dataModel.put("list", ImmutableList.of(1, 2, 3)); - dataModel.put("set", ImmutableSet.of("a", "b", "c")); - dataModel.put("s", "test"); - } else if (simpleTestName.equals("default-object-wrapper")) { - dataModel.put("array", new String[] { "array-0", "array-1"}); - dataModel.put("list", Arrays.asList("list-0", "list-1", "list-2")); - Map<Object, Object> tmap = new HashMap<>(); - tmap.put("key", "value"); - Object objKey = new Object(); - tmap.put(objKey, "objValue"); - dataModel.put("map", tmap); - dataModel.put("objKey", objKey); - dataModel.put("obj", new org.apache.freemarker.test.templatesuite.models.BeanTestClass()); - dataModel.put("resourceBundle", - new ResourceBundleModel(ResourceBundle.getBundle( - "org.apache.freemarker.test.templatesuite.models.BeansTestResources"), dow)); - dataModel.put("date", new GregorianCalendar(1974, 10, 14).getTime()); - dataModel.put("statics", dow.getStaticModels()); - dataModel.put("enums", dow.getEnumModels()); - } else if (simpleTestName.equals("boolean")) { - dataModel.put( "boolean1", TemplateBooleanModel.FALSE); - dataModel.put( "boolean2", TemplateBooleanModel.TRUE); - dataModel.put( "boolean3", TemplateBooleanModel.TRUE); - dataModel.put( "boolean4", TemplateBooleanModel.TRUE); - dataModel.put( "boolean5", TemplateBooleanModel.FALSE); - - dataModel.put( "list1", new BooleanList1(dow) ); - dataModel.put( "list2", new BooleanList2(dow) ); - - dataModel.put( "hash1", new BooleanHash1() ); - dataModel.put( "hash2", new BooleanHash2() ); - } else if (simpleTestName.startsWith("dateformat")) { - GregorianCalendar cal = new GregorianCalendar(2002, 10, 15, 14, 54, 13); - cal.setTimeZone(TimeZone.getTimeZone("GMT")); - dataModel.put("date", new SimpleDate(cal.getTime(), TemplateDateModel.DATETIME)); - dataModel.put("unknownDate", new SimpleDate(cal.getTime(), TemplateDateModel.UNKNOWN)); - dataModel.put("javaGMT02", TimeZone.getTimeZone("GMT+02")); - dataModel.put("javaUTC", TimeZone.getTimeZone("UTC")); - dataModel.put("adaptedToStringScalar", new Object() { - @Override - public String toString() { - return "GMT+02"; - } - }); - dataModel.put("sqlDate", new java.sql.Date(1273955885023L)); - dataModel.put("sqlTime", new java.sql.Time(74285023L)); - } else if ( - templateName.equals("list.ftl") || templateName.equals("list2.ftl") || templateName.equals("list3.ftl") - || simpleTestName.equals("listhash")) { - dataModel.put("listables", new Listables()); - } else if (simpleTestName.startsWith("number-format")) { - dataModel.put("int", new SimpleNumber(Integer.valueOf(1))); - dataModel.put("double", new SimpleNumber(Double.valueOf(1.0))); - dataModel.put("double2", new SimpleNumber(Double.valueOf(1 + 1e-15))); - dataModel.put("double3", new SimpleNumber(Double.valueOf(1e-16))); - dataModel.put("double4", new SimpleNumber(Double.valueOf(-1e-16))); - dataModel.put("bigDecimal", new SimpleNumber(java.math.BigDecimal.valueOf(1))); - dataModel.put("bigDecimal2", new SimpleNumber(java.math.BigDecimal.valueOf(1, 16))); - } else if (simpleTestName.equals("simplehash-char-key")) { - HashMap<String, String> mStringC = new HashMap<>(); - mStringC.put("c", "string"); - dataModel.put("mStringC", mStringC); - - HashMap<String, String> mStringCNull = new HashMap<>(); - mStringCNull.put("c", null); - dataModel.put("mStringCNull", mStringCNull); - - HashMap<Character, String> mCharC = new HashMap<>(); - mCharC.put(Character.valueOf('c'), "char"); - dataModel.put("mCharC", mCharC); - - HashMap<String, String> mCharCNull = new HashMap<>(); - mCharCNull.put("c", null); - dataModel.put("mCharCNull", mCharCNull); - - HashMap<Object, String> mMixed = new HashMap<>(); - mMixed.put(Character.valueOf('c'), "char"); - mMixed.put("s", "string"); - mMixed.put("s2", "string2"); - mMixed.put("s2n", null); - dataModel.put("mMixed", mMixed); - } else if (simpleTestName.equals("default-xmlns")) { - InputSource is = new InputSource(getClass().getResourceAsStream("models/defaultxmlns1.xml")); - NodeModel nm = XMLLoader.toModel(is); - dataModel.put("doc", nm); - } else if (simpleTestName.equals("multimodels")) { - dataModel.put("test", "selftest"); - dataModel.put("self", "self"); - dataModel.put("zero", Integer.valueOf(0)); - dataModel.put("data", new MultiModel1()); - } else if (simpleTestName.equals("stringbimethods")) { - dataModel.put("multi", new TestBoolean()); - } else if (simpleTestName.startsWith("type-builtins")) { - dataModel.put("testmethod", new TestMethod()); - dataModel.put("testnode", new TestNode()); - dataModel.put("testcollection", new SimpleCollection(new ArrayList<>(), dow)); - dataModel.put("testcollectionEx", DefaultNonListCollectionAdapter.adapt(new HashSet<>(), dow)); - dataModel.put("bean", new TestBean()); - } else if (simpleTestName.equals("date-type-builtins")) { - GregorianCalendar cal = new GregorianCalendar(2003, 4 - 1, 5, 6, 7, 8); - cal.setTimeZone(TimeZone.getTimeZone("UTC")); - Date d = cal.getTime(); - dataModel.put("unknown", d); - dataModel.put("timeOnly", new java.sql.Time(d.getTime())); - dataModel.put("dateOnly", new java.sql.Date(d.getTime())); - dataModel.put("dateTime", new java.sql.Timestamp(d.getTime())); - } else if (simpleTestName.equals("var-layers")) { - dataModel.put("x", Integer.valueOf(4)); - dataModel.put("z", Integer.valueOf(4)); - confB.setSharedVariable("y", Integer.valueOf(7)); - } else if (simpleTestName.equals("xml-fragment")) { - DocumentBuilderFactory f = DocumentBuilderFactory.newInstance(); - f.setNamespaceAware(true); - DocumentBuilder db = f.newDocumentBuilder(); - org.w3c.dom.Document doc = db.parse(new InputSource(getClass().getResourceAsStream("models/xmlfragment.xml"))); - NodeModel.simplify(doc); - dataModel.put("node", NodeModel.wrap(doc.getDocumentElement().getFirstChild().getFirstChild())); - } else if (simpleTestName.equals("xmlns1")) { - InputSource is = new InputSource(getClass().getResourceAsStream("models/xmlns.xml")); - NodeModel nm = XMLLoader.toModel(is); - dataModel.put("doc", nm); - } else if (simpleTestName.equals("xmlns2")) { - InputSource is = new InputSource(getClass().getResourceAsStream("models/xmlns2.xml")); - NodeModel nm = XMLLoader.toModel(is); - dataModel.put("doc", nm); - } else if (simpleTestName.equals("xmlns3") || simpleTestName.equals("xmlns4")) { - InputSource is = new InputSource(getClass().getResourceAsStream("models/xmlns3.xml")); - NodeModel nm = XMLLoader.toModel(is); - dataModel.put("doc", nm); - } else if (simpleTestName.equals("xmlns5")) { - InputSource is = new InputSource(getClass().getResourceAsStream("models/defaultxmlns1.xml")); - NodeModel nm = XMLLoader.toModel(is); - dataModel.put("doc", nm); - } else if (simpleTestName.equals("xml-ns_prefix-scope")) { - InputSource is = new InputSource(getClass().getResourceAsStream("models/xml-ns_prefix-scope.xml")); - NodeModel nm = XMLLoader.toModel(is); - dataModel.put("doc", nm); - } else if (simpleTestName.startsWith("sequence-builtins")) { - Set<String> abcSet = new TreeSet<>(); - abcSet.add("a"); - abcSet.add("b"); - abcSet.add("c"); - dataModel.put("abcSet", abcSet); - dataModel.put("abcSetNonSeq", DefaultNonListCollectionAdapter.adapt(abcSet, dow)); - - List<String> listWithNull = new ArrayList<>(); - listWithNull.add("a"); - listWithNull.add(null); - listWithNull.add("c"); - dataModel.put("listWithNull", listWithNull); - - List<String> listWithNullsOnly = new ArrayList<>(); - listWithNull.add(null); - listWithNull.add(null); - listWithNull.add(null); - dataModel.put("listWithNullsOnly", listWithNullsOnly); - - dataModel.put("abcCollection", new SimpleCollection(abcSet, dow)); - - Set<String> set = new HashSet<>(); - set.add("a"); - set.add("b"); - set.add("c"); - dataModel.put("set", set); - } else if (simpleTestName.equals("number-to-date")) { - dataModel.put("bigInteger", new BigInteger("1305575275540")); - dataModel.put("bigDecimal", new BigDecimal("1305575275539.5")); - } else if (simpleTestName.equals("varargs")) { - dataModel.put("m", new VarArgTestModel()); - } else if (simpleTestName.startsWith("boolean-formatting")) { - dataModel.put("booleanAndString", new BooleanAndStringTemplateModel()); - dataModel.put("booleanVsStringMethods", new BooleanVsStringMethods()); - } else if (simpleTestName.startsWith("number-math-builtins")) { - dataModel.put("fNan", Float.valueOf(Float.NaN)); - dataModel.put("dNan", Double.valueOf(Double.NaN)); - dataModel.put("fNinf", Float.valueOf(Float.NEGATIVE_INFINITY)); - dataModel.put("dPinf", Double.valueOf(Double.POSITIVE_INFINITY)); - - dataModel.put("fn", Float.valueOf(-0.05f)); - dataModel.put("dn", Double.valueOf(-0.05)); - dataModel.put("ineg", Integer.valueOf(-5)); - dataModel.put("ln", Long.valueOf(-5)); - dataModel.put("sn", Short.valueOf((short) -5)); - dataModel.put("bn", Byte.valueOf((byte) -5)); - dataModel.put("bin", BigInteger.valueOf(5)); - dataModel.put("bdn", BigDecimal.valueOf(-0.05)); - - dataModel.put("fp", Float.valueOf(0.05f)); - dataModel.put("dp", Double.valueOf(0.05)); - dataModel.put("ip", Integer.valueOf(5)); - dataModel.put("lp", Long.valueOf(5)); - dataModel.put("sp", Short.valueOf((short) 5)); - dataModel.put("bp", Byte.valueOf((byte) 5)); - dataModel.put("bip", BigInteger.valueOf(5)); - dataModel.put("bdp", BigDecimal.valueOf(0.05)); - } else if (simpleTestName.startsWith("overloaded-methods")) { - dataModel.put("obj", new OverloadedMethods2()); - } - } - - @Override - public void runTest() throws IOException, ConfigurationException { - Template template; - try { - template = confB.build().getTemplate(templateName); - } catch (IOException e) { - throw new AssertionFailedError( - "Could not load template " + _StringUtil.jQuote(templateName) + ":\n" + getStackTrace(e)); - } - ASTPrinter.validateAST(template); - - StringWriter out = noOutput ? null : new StringWriter(); - try { - template.process(dataModel, out != null ? out : _NullWriter.INSTANCE); - } catch (TemplateException e) { - throw new AssertionFailedError("Template " + _StringUtil.jQuote(templateName) + " has stopped with error:\n" - + getStackTrace(e)); - } - - if (out != null) { - assertExpectedFileEqualsString(expectedFileName, out.toString()); - } - } - - private String getStackTrace(Throwable e) { - StringWriter sw = new StringWriter(); - e.printStackTrace(new PrintWriter(sw)); - return sw.toString(); - } - - @Override - protected String getExpectedContentFileDirectoryResourcePath() throws IOException { - return joinResourcePaths(super.getExpectedContentFileDirectoryResourcePath(), "expected"); - } - - @Override - protected Charset getTestResourceDefaultCharset() { - return confB.getOutputEncoding() != null ? confB.getOutputEncoding() : StandardCharsets.UTF_8; - } - - static class TestBoolean implements TemplateBooleanModel, TemplateScalarModel { - @Override - public boolean getAsBoolean() { - return true; - } - - @Override - public String getAsString() { - return "de"; - } - } - - static class TestMethod implements TemplateMethodModel { - @Override - public Object exec(List arguments) { - return "x"; - } - } - - static class TestNode implements TemplateNodeModel { - - @Override - public String getNodeName() { - return "name"; - } - - @Override - public TemplateNodeModel getParentNode() { - return null; - } - - @Override - public String getNodeType() { - return "element"; - } - - @Override - public TemplateSequenceModel getChildNodes() { - return null; - } - - @Override - public String getNodeNamespace() { - return null; - } - } - - public Object getTestMapBean() { - Map<String, Object> testBean = new TestMapBean(); - testBean.put("name", "Chris"); - testBean.put("location", "San Francisco"); - testBean.put("age", Integer.valueOf(27)); - return testBean; - } - - public static class TestMapBean extends HashMap<String, Object> { - public String getName() { - return "Christopher"; - } - public int getLuckyNumber() { - return 7; - } - } - - public static class TestBean { - - public int m(int n) { - return n * 10; - } - - public int mOverloaded(int n) { - return n * 10; - } - - public String mOverloaded(String s) { - return s.toUpperCase(); - } - - } - -}
