http://git-wip-us.apache.org/repos/asf/incubator-freemarker-online-tester/blob/2f0c0424/src/main/java/org/apache/freemarker/onlinetester/util/LengthLimitedWriter.java ---------------------------------------------------------------------- diff --git a/src/main/java/org/apache/freemarker/onlinetester/util/LengthLimitedWriter.java b/src/main/java/org/apache/freemarker/onlinetester/util/LengthLimitedWriter.java new file mode 100644 index 0000000..bb2650d --- /dev/null +++ b/src/main/java/org/apache/freemarker/onlinetester/util/LengthLimitedWriter.java @@ -0,0 +1,87 @@ +/* + * 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.onlinetester.util; + +import java.io.FilterWriter; +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; + +/** + * A {@link StringWriter} that limits its buffer size, and throws {@link LengthLimitExceededException} when that's + * exceeded. + */ +public class LengthLimitedWriter extends FilterWriter { + + private int lengthLeft; + + public LengthLimitedWriter(Writer writer, int lengthLimit) { + super(writer); + this.lengthLeft = lengthLimit; + } + + @Override + public void write(int c) throws IOException { + if (lengthLeft < 1) { + throw new LengthLimitExceededException(); + } + + super.write(c); + + lengthLeft--; + } + + @Override + public void write(char[] cbuf, int off, int len) throws IOException { + final boolean lengthExceeded; + if (lengthLeft < len) { + len = lengthLeft; + lengthExceeded = true; + } else { + lengthExceeded = false; + } + + super.write(cbuf, off, len); + lengthLeft -= len; + + if (lengthExceeded) { + throw new LengthLimitExceededException(); + } + } + + @Override + public void write(String str, int off, int len) throws IOException { + final boolean lengthExceeded; + if (lengthLeft < len) { + len = lengthLeft; + lengthExceeded = true; + } else { + lengthExceeded = false; + } + + super.write(str, off, len); + lengthLeft -= len; + + if (lengthExceeded) { + throw new LengthLimitExceededException(); + } + } + +}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker-online-tester/blob/2f0c0424/src/main/java/org/apache/freemarker/onlinetester/view/FreeMarkerOnlineView.java ---------------------------------------------------------------------- diff --git a/src/main/java/org/apache/freemarker/onlinetester/view/FreeMarkerOnlineView.java b/src/main/java/org/apache/freemarker/onlinetester/view/FreeMarkerOnlineView.java new file mode 100644 index 0000000..3aecbb5 --- /dev/null +++ b/src/main/java/org/apache/freemarker/onlinetester/view/FreeMarkerOnlineView.java @@ -0,0 +1,157 @@ +/* + * 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.onlinetester.view; + +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; + +import org.apache.freemarker.onlinetester.model.SelectionOption; +import org.apache.freemarker.onlinetester.services.AllowedSettingValuesMaps; +import com.yammer.dropwizard.views.View; + +import freemarker.template.Configuration; + +public class FreeMarkerOnlineView extends View { + + private static final List<SelectionOption> LOCALE_SELECTION_OPTIONS = toLocaleSelectionOptions(AllowedSettingValuesMaps.LOCALE_MAP); + private static final List<SelectionOption> TIME_ZONE_SELECTION_OPTIONS = toSelectionOptions(AllowedSettingValuesMaps.TIME_ZONE_MAP); + private static final List<SelectionOption> OUTPUT_FORMAT_SELECTION_OPTIONS = toSelectionOptions(AllowedSettingValuesMaps.OUTPUT_FORMAT_MAP); + + private String template = ""; + private String dataModel = ""; + private String outputFormat = AllowedSettingValuesMaps.DEFAULT_OUTPUT_FORMAT_KEY; + private String locale = AllowedSettingValuesMaps.DEFAULT_LOCALE_KEY; + private String timeZone = AllowedSettingValuesMaps.DEFAULT_TIME_ZONE_KEY; + + private boolean execute; + + private static List<SelectionOption> toSelectionOptions(Map<String, ?> settingValueMap) { + ArrayList<SelectionOption> selectionOptions = new ArrayList<SelectionOption>(settingValueMap.size()); + for (String key : settingValueMap.keySet()) { + selectionOptions.add(new SelectionOption(key, truncate(key, 25))); + } + Collections.sort(selectionOptions); + return selectionOptions; + } + + private static List<SelectionOption> toLocaleSelectionOptions(Map<String, Locale> localeMap) { + ArrayList<SelectionOption> selectionOptions = new ArrayList<SelectionOption>(localeMap.size()); + for (Map.Entry<String, Locale> ent : localeMap.entrySet()) { + Locale locale = ent.getValue(); + selectionOptions.add( + new SelectionOption(ent.getKey(), + truncate(locale.getDisplayName(Locale.US), 18) + "; " + locale.toString())); + } + Collections.sort(selectionOptions); + return selectionOptions; + } + + private static String truncate(String s, int maxLength) { + if (s == null) { + return null; + } + return s.length() <= maxLength ? s : s.substring(0, Math.max(maxLength - 3, 0)) + "[...]"; + } + + /** + * + * @param template + * @param dataModel + * @param execute set to true if the execution should be triggered on page load. + */ + public FreeMarkerOnlineView() { + super("/view/freemarker-online.ftl", Charset.forName("utf-8")); + } + + public String getTemplate() { + return template; + } + + public void setTemplate(String template) { + this.template = withDefault(template, ""); + } + + public String getDataModel() { + return dataModel; + } + + public void setDataModel(String dataModel) { + this.dataModel = withDefault(dataModel, ""); + } + + public String getFreeMarkerVersion() { + return Configuration.getVersion().toString(); + } + + public List<SelectionOption> getOutputFormats() { + return OUTPUT_FORMAT_SELECTION_OPTIONS; + } + + public List<SelectionOption> getLocales() { + return LOCALE_SELECTION_OPTIONS; + } + + public List<SelectionOption> getTimeZones() { + return TIME_ZONE_SELECTION_OPTIONS; + } + + public String getOutputFormat() { + return outputFormat; + } + + public void setOutputFormat(String outputFormat) { + this.outputFormat = withDefault(outputFormat, AllowedSettingValuesMaps.DEFAULT_OUTPUT_FORMAT_KEY); + } + + public String getLocale() { + return locale; + } + + public void setLocale(String locale) { + this.locale = withDefault(locale, AllowedSettingValuesMaps.DEFAULT_LOCALE_KEY); + } + + public String getTimeZone() { + return timeZone; + } + + public void setTimeZone(String timeZone) { + this.timeZone = withDefault(timeZone, AllowedSettingValuesMaps.DEFAULT_TIME_ZONE_KEY); + } + + public boolean isExecute() { + return execute; + } + + public void setExecute(boolean executeImmediately) { + this.execute = executeImmediately; + } + + private static String withDefault(String value, String defaultValue) { + return !StringUtils.isBlank(value) ? value : defaultValue; + } + +} http://git-wip-us.apache.org/repos/asf/incubator-freemarker-online-tester/blob/2f0c0424/src/main/resources/spring/bootstrap-context.xml ---------------------------------------------------------------------- diff --git a/src/main/resources/spring/bootstrap-context.xml b/src/main/resources/spring/bootstrap-context.xml index db4bf9b..8d8e518 100644 --- a/src/main/resources/spring/bootstrap-context.xml +++ b/src/main/resources/spring/bootstrap-context.xml @@ -24,7 +24,7 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> - <context:component-scan base-package="com.kenshoo"/> + <context:component-scan base-package="org.apache.freemarker.onlinetester"/> <context:annotation-config/> http://git-wip-us.apache.org/repos/asf/incubator-freemarker-online-tester/blob/2f0c0424/src/test/java/com/kenshoo/freemarker/platform/DropWizardServiceTest.java ---------------------------------------------------------------------- diff --git a/src/test/java/com/kenshoo/freemarker/platform/DropWizardServiceTest.java b/src/test/java/com/kenshoo/freemarker/platform/DropWizardServiceTest.java deleted file mode 100644 index 312ed0b..0000000 --- a/src/test/java/com/kenshoo/freemarker/platform/DropWizardServiceTest.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2014 Kenshoo.com - * - * Licensed 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 com.kenshoo.freemarker.platform; - -import com.google.common.io.Resources; -import com.kenshoo.freemarker.dropwizard.ApplicationStartup; -import com.yammer.dropwizard.testing.junit.DropwizardServiceRule; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.rules.TestRule; - -public class DropWizardServiceTest { - @ClassRule - public static TestRule testRule = new DropwizardServiceRule<>(ApplicationStartup.class, - Resources.getResource("freemarker-online.yml").getPath()); - - - @Test - public void testServerIsUp() throws Exception { - ((DropwizardServiceRule) testRule).getService(); - } -} http://git-wip-us.apache.org/repos/asf/incubator-freemarker-online-tester/blob/2f0c0424/src/test/java/com/kenshoo/freemarker/platform/YamlPropertiesPersister.java ---------------------------------------------------------------------- diff --git a/src/test/java/com/kenshoo/freemarker/platform/YamlPropertiesPersister.java b/src/test/java/com/kenshoo/freemarker/platform/YamlPropertiesPersister.java deleted file mode 100644 index 1299581..0000000 --- a/src/test/java/com/kenshoo/freemarker/platform/YamlPropertiesPersister.java +++ /dev/null @@ -1,91 +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 com.kenshoo.freemarker.platform; - -import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml; -import org.springframework.util.PropertiesPersister; -import org.springframework.util.StringUtils; - -import java.io.*; -import java.util.Map; -import java.util.Properties; - -public class YamlPropertiesPersister implements PropertiesPersister { - @Override - public void load(Properties props, InputStream is) throws IOException { - load(props, new InputStreamReader(is)); - } - - /** - * We want to traverse map representing Yaml object and each time we find String=String pair we want to - * save it as Property. As we are going deeper into map we generate compound key as path-like String - * - * @see org.springframework.util.PropertiesPersister#load(java.util.Properties, java.io.Reader) - */ - @Override - public void load(Properties props, Reader reader) throws IOException { - Yaml yaml = new Yaml(); - @SuppressWarnings("unchecked") - Map<String, Object> map = (Map<String, Object>) yaml.load(reader); - // now we can populate supplied props - assignProperties(props, map, null); - } - - @SuppressWarnings("unchecked") - public void assignProperties(Properties props, Map<String, Object> map, String path) { - for (Map.Entry<String, Object> entry : map.entrySet()) { - String key = entry.getKey(); - if (!StringUtils.isEmpty(path)) - key = path + "." + key; - Object val = entry.getValue(); - if (val instanceof String) { - // see if we need to create a compound key - props.put(key, val); - } else if (val instanceof Map) { - assignProperties(props, (Map<String, Object>) val, key); - } - } - } - - @Override - public void store(Properties props, OutputStream os, String header) throws IOException { - throw new IllegalStateException("Current implementation is a read-only"); - } - - @Override - public void store(Properties props, Writer writer, String header) throws IOException { - throw new IllegalStateException("Current implementation is a read-only"); - } - - @Override - public void loadFromXml(Properties props, InputStream is) throws IOException { - throw new IllegalStateException("Use DefaultPropertiesPersister if you want to read/write XML"); - } - - @Override - public void storeToXml(Properties props, OutputStream os, String header) throws IOException { - throw new IllegalStateException("Use DefaultPropertiesPersister if you want to load/store to XML"); - } - - @Override - public void storeToXml(Properties props, OutputStream os, String header, String encoding) throws IOException { - throw new IllegalStateException("Use DefaultPropertiesPersister if you want to read/write XML"); - } -} http://git-wip-us.apache.org/repos/asf/incubator-freemarker-online-tester/blob/2f0c0424/src/test/java/com/kenshoo/freemarker/resources/FreeMarkerOnlineExecuteResourceTest.java ---------------------------------------------------------------------- diff --git a/src/test/java/com/kenshoo/freemarker/resources/FreeMarkerOnlineExecuteResourceTest.java b/src/test/java/com/kenshoo/freemarker/resources/FreeMarkerOnlineExecuteResourceTest.java deleted file mode 100644 index e7ca204..0000000 --- a/src/test/java/com/kenshoo/freemarker/resources/FreeMarkerOnlineExecuteResourceTest.java +++ /dev/null @@ -1,159 +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 com.kenshoo.freemarker.resources; - -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.springframework.web.context.ContextLoaderListener; -import org.springframework.web.context.request.RequestContextListener; - -import com.kenshoo.freemarker.model.ExecuteRequest; -import com.kenshoo.freemarker.model.ExecuteResourceField; -import com.kenshoo.freemarker.model.ExecuteResourceProblem; -import com.kenshoo.freemarker.model.ExecuteResponse; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.spi.spring.container.servlet.SpringServlet; -import com.sun.jersey.test.framework.AppDescriptor; -import com.sun.jersey.test.framework.JerseyTest; -import com.sun.jersey.test.framework.WebAppDescriptor; - -public class FreeMarkerOnlineExecuteResourceTest extends JerseyTest { - private static final String DATA_MODEL = "user=John"; - private static final String TEMPLATE_WITH_VARIABLE = "Welcome ${user}"; - private static final String TEMPLATE_PLAIN = "Welcome John"; - private static final String MALFORMED_DATA_MODEL = "userJohn"; - private static final String EXECUTE_API = "api/execute"; - @Override - protected AppDescriptor configure() { - return new WebAppDescriptor.Builder("com.kenshoo.freemarker.resources") - .contextPath("/") - .contextListenerClass(ContextLoaderListener.class) - .contextParam("contextConfigLocation", "classpath:spring/bootstrap-context.xml") - .servletClass(SpringServlet.class) - .requestListenerClass(RequestContextListener.class) - .build(); - } - - @Test - public void testSuccessRequest() throws Exception { - ExecuteRequest req = new ExecuteRequest(TEMPLATE_WITH_VARIABLE, DATA_MODEL); - ClientResponse resp = client().resource(getBaseURI().toString() + EXECUTE_API) - .header("Content-Type", "application/json").entity(req).post(ClientResponse.class); - assertEquals(200, resp.getStatus()); - ExecuteResponse response = resp.getEntity(ExecuteResponse.class); - assertNull(response.getProblems()); - } - - @Test - public void testMalformedDataModel() throws Exception { - ExecuteRequest req = new ExecuteRequest(TEMPLATE_PLAIN, MALFORMED_DATA_MODEL); - ClientResponse resp = client().resource(getBaseURI().toString() + EXECUTE_API) - .header("Content-Type", "application/json").entity(req).post(ClientResponse.class); - assertEquals(200, resp.getStatus()); - ExecuteResponse response = resp.getEntity(ExecuteResponse.class); - assertNotNull(response.getProblems()); - assertTrue(containsProblem(response, ExecuteResourceField.DATA_MODEL)); - } - - @Test - public void testLongDataModel() throws Exception { - ExecuteRequest req = new ExecuteRequest(TEMPLATE_PLAIN, create30KString()); - ClientResponse resp = client().resource(getBaseURI().toString() + EXECUTE_API) - .header("Content-Type", "application/json").entity(req).post(ClientResponse.class); - assertEquals(200, resp.getStatus()); - ExecuteResponse response = resp.getEntity(ExecuteResponse.class); - assertNotNull(response.getProblems()); - assertTrue(containsProblem(response, ExecuteResourceField.DATA_MODEL)); - String problemMessage = getProblemMessage(response, ExecuteResourceField.DATA_MODEL); - assertThat(problemMessage, containsString("data model")); - assertThat(problemMessage, containsString("limit")); - } - - @Test - public void testLongTemplate() throws Exception { - ExecuteRequest req = new ExecuteRequest(create30KString(), DATA_MODEL); - ClientResponse resp = client().resource(getBaseURI().toString() + EXECUTE_API) - .header("Content-Type", "application/json").entity(req).post(ClientResponse.class); - assertEquals(200, resp.getStatus()); - ExecuteResponse response = resp.getEntity(ExecuteResponse.class); - assertNotNull(response.getProblems()); - assertTrue(containsProblem(response, ExecuteResourceField.TEMPLATE)); - String problemMessage = getProblemMessage(response, ExecuteResourceField.TEMPLATE); - assertThat(problemMessage, containsString("template")); - assertThat(problemMessage, containsString("limit")); - } - - @Test - public void testMultipleErrorsDataModel() throws Exception { - ExecuteRequest req = new ExecuteRequest(create30KString(), create30KString()); - req.setOutputFormat("wrongOutputFormat"); - req.setLocale("wrongLocale"); - req.setTimeZone("wrongTimeZone"); - - ClientResponse resp = client().resource(getBaseURI() + EXECUTE_API) - .header("Content-Type", "application/json").entity(req).post(ClientResponse.class); - - assertEquals(200, resp.getStatus()); - ExecuteResponse response = resp.getEntity(ExecuteResponse.class); - assertNotNull(response.getProblems()); - assertThat(getProblemMessage(response, ExecuteResourceField.TEMPLATE), containsString("limit")); - assertThat(getProblemMessage(response, ExecuteResourceField.DATA_MODEL), containsString("limit")); - assertThat(getProblemMessage(response, ExecuteResourceField.OUTPUT_FORMAT), containsString("wrongOutputFormat")); - assertThat(getProblemMessage(response, ExecuteResourceField.LOCALE), containsString("wrongLocale")); - assertThat(getProblemMessage(response, ExecuteResourceField.TIME_ZONE), containsString("wrongTimeZone")); - } - - private String create30KString() { - final String veryLongString; - { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < 30000 / 10; i++) { - sb.append("0123456789"); - } - veryLongString = sb.toString(); - } - return veryLongString; - } - - private boolean containsProblem(ExecuteResponse response, ExecuteResourceField field) { - for (ExecuteResourceProblem problem : response.getProblems()) { - if (problem.getField() == field) { - return true; - } - } - return false; - } - - private String getProblemMessage(ExecuteResponse response, ExecuteResourceField field) { - for (ExecuteResourceProblem problem : response.getProblems()) { - if (problem.getField() == field) { - return problem.getMessage(); - } - } - return null; - } - -} http://git-wip-us.apache.org/repos/asf/incubator-freemarker-online-tester/blob/2f0c0424/src/test/java/com/kenshoo/freemarker/resources/FreeMarkerOnlineResourceTest.java ---------------------------------------------------------------------- diff --git a/src/test/java/com/kenshoo/freemarker/resources/FreeMarkerOnlineResourceTest.java b/src/test/java/com/kenshoo/freemarker/resources/FreeMarkerOnlineResourceTest.java deleted file mode 100644 index 6b3df76..0000000 --- a/src/test/java/com/kenshoo/freemarker/resources/FreeMarkerOnlineResourceTest.java +++ /dev/null @@ -1,70 +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 com.kenshoo.freemarker.resources; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyMap; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.when; - -import java.util.Locale; -import java.util.TimeZone; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - -import com.kenshoo.freemarker.services.FreeMarkerService; -import com.kenshoo.freemarker.view.FreeMarkerOnlineView; - -import freemarker.core.OutputFormat; - -@RunWith(MockitoJUnitRunner.class) -public class FreeMarkerOnlineResourceTest { - - @InjectMocks - FreeMarkerOnlineResource freeMarkerOnlineResultResource; - - @Mock - FreeMarkerService freeMarkerService; - - @Test - public void testInitialForm() { - when(freeMarkerService.calculateTemplateOutput( - anyString(), anyMap(), any(OutputFormat.class), any(Locale.class), any(TimeZone.class))) - .thenThrow(new AssertionError()); - FreeMarkerOnlineView view = freeMarkerOnlineResultResource.blankForm(); - assertEquals(view.getTemplate(), ""); - assertEquals(view.getDataModel(), ""); - } - - @Test - public void testPostedBlankForm() { - when(freeMarkerService.calculateTemplateOutput( - anyString(), anyMap(), any(OutputFormat.class), any(Locale.class), any(TimeZone.class))) - .thenThrow(new AssertionError()); - FreeMarkerOnlineView view = freeMarkerOnlineResultResource.formResult(null, null, null, null, null); - assertEquals(view.getTemplate(), ""); - assertEquals(view.getDataModel(), ""); - } -} http://git-wip-us.apache.org/repos/asf/incubator-freemarker-online-tester/blob/2f0c0424/src/test/java/com/kenshoo/freemarker/services/FreeMarkerServiceResponseBuilderTest.java ---------------------------------------------------------------------- diff --git a/src/test/java/com/kenshoo/freemarker/services/FreeMarkerServiceResponseBuilderTest.java b/src/test/java/com/kenshoo/freemarker/services/FreeMarkerServiceResponseBuilderTest.java deleted file mode 100644 index caf5ca4..0000000 --- a/src/test/java/com/kenshoo/freemarker/services/FreeMarkerServiceResponseBuilderTest.java +++ /dev/null @@ -1,61 +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 com.kenshoo.freemarker.services; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import org.junit.Test; - -public class FreeMarkerServiceResponseBuilderTest { - - private static final String RESULT = "Result"; - - private final FreeMarkerServiceResponse.Builder builder = new FreeMarkerServiceResponse.Builder(); - - @Test - public void testSuccessResult() { - FreeMarkerServiceResponse result = builder.buildForSuccess(RESULT, false); - assertThat(result.getTemplateOutput(), equalTo(RESULT)); - assertThat(result.isTemplateOutputTruncated(), is(false)); - assertThat(result.isSuccesful(), is(true)); - assertThat(result.getFailureReason(), nullValue()); - } - - @Test - public void testSuccessTruncatedResult() { - FreeMarkerServiceResponse result = builder.buildForSuccess(RESULT, true); - assertThat(result.getTemplateOutput(), equalTo(RESULT)); - assertThat(result.isTemplateOutputTruncated(), is(true)); - assertThat(result.isSuccesful(), is(true)); - assertThat(result.getFailureReason(), nullValue()); - } - - @Test - public void testErrorResult() { - Throwable failureReason = new Exception(); - FreeMarkerServiceResponse result = builder.buildForFailure(failureReason); - assertThat(result.getTemplateOutput(), nullValue()); - assertThat(result.isTemplateOutputTruncated(), is(false)); - assertThat(result.isSuccesful(), is(false)); - assertThat(result.getFailureReason(), sameInstance(failureReason)); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-freemarker-online-tester/blob/2f0c0424/src/test/java/com/kenshoo/freemarker/services/FreeMarkerServiceTest.java ---------------------------------------------------------------------- diff --git a/src/test/java/com/kenshoo/freemarker/services/FreeMarkerServiceTest.java b/src/test/java/com/kenshoo/freemarker/services/FreeMarkerServiceTest.java deleted file mode 100644 index 6608d52..0000000 --- a/src/test/java/com/kenshoo/freemarker/services/FreeMarkerServiceTest.java +++ /dev/null @@ -1,308 +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 com.kenshoo.freemarker.services; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.util.Collections; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.TimeZone; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.runners.MockitoJUnitRunner; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import freemarker.core.Environment; -import freemarker.core.HTMLOutputFormat; -import freemarker.core.ParseException; -import freemarker.template.TemplateDirectiveBody; -import freemarker.template.TemplateDirectiveModel; -import freemarker.template.TemplateException; -import freemarker.template.TemplateModel; - -@RunWith(MockitoJUnitRunner.class) -public class FreeMarkerServiceTest { - - private static final Logger LOG = LoggerFactory.getLogger(FreeMarkerServiceTest.class); - - private static final int MAX_THREADS = 3; - private static final int MAX_QUEUE_LENGTH = 2; - private static final int MAX_TEMPLATE_EXECUTION_TIME = 1500; - - private static final int BLOCKING_TEST_TIMEOUT = 5000; - - private static final String TRUNCATION_TEST_TEMPLATE = "12345"; - - @InjectMocks - private FreeMarkerService freeMarkerService; - - @Before - public void initializeSpringBeans() { - freeMarkerService.setMaxQueueLength(MAX_QUEUE_LENGTH); - freeMarkerService.setMaxThreads(MAX_THREADS); - freeMarkerService.postConstruct(); - freeMarkerService.setMaxTemplateExecutionTime(MAX_TEMPLATE_EXECUTION_TIME); - } - - @Test - public void testCalculationOfATemplateWithNoDataModel() { - FreeMarkerServiceResponse serviceResponse = freeMarkerService.calculateTemplateOutput( - "test", Collections.<String, Object>emptyMap(), null, null, null); - assertThat(serviceResponse.isSuccesful(), is(true)); - assertThat(serviceResponse.getTemplateOutput(), is("test")); - } - - @Test - public void testSimpleTemplate() { - HashMap<String, Object> dataModel = new HashMap<>(); - dataModel.put("var1", "val1"); - String templateSourceCode = "${var1}"; - FreeMarkerServiceResponse serviceResponse = freeMarkerService.calculateTemplateOutput( - templateSourceCode, dataModel, null, null, null); - assertThat(serviceResponse.getTemplateOutput(), equalTo("val1")); - } - - @Test - public void testTemplateWithFewArgsAndOperators() { - HashMap<String, Object> dataModel = new HashMap<>(); - dataModel.put("var1", "val1"); - dataModel.put("var2", "val2"); - String template = "${var1?capitalize} ${var2?cap_first}"; - FreeMarkerServiceResponse serviceResponse = freeMarkerService.calculateTemplateOutput( - template, dataModel, null, null, null); - assertThat(serviceResponse.getTemplateOutput(), equalTo("Val1 Val2")); - } - - @Test - public void testOutputFormatParamterMatters() { - String template = "${'&'}"; - { - FreeMarkerServiceResponse serviceResponse = freeMarkerService.calculateTemplateOutput( - template, null, null, null, null); - assertThat(serviceResponse.getTemplateOutput(), equalTo("&")); - } - { - FreeMarkerServiceResponse serviceResponse = freeMarkerService.calculateTemplateOutput( - template, null, HTMLOutputFormat.INSTANCE, null, null); - assertThat(serviceResponse.getTemplateOutput(), equalTo("&")); - } - } - - @Test - public void testLocaleParameterMatters() { - String template = "${.locale}"; - { - FreeMarkerServiceResponse serviceResponse = freeMarkerService.calculateTemplateOutput( - template, null, null, new Locale("en", "US"), null); - assertThat(serviceResponse.getTemplateOutput(), equalTo("en_US")); - } - { - FreeMarkerServiceResponse serviceResponse = freeMarkerService.calculateTemplateOutput( - template, null, null, new Locale("ru", "RU"), null); - assertThat(serviceResponse.getTemplateOutput(), equalTo("ru_RU")); - } - } - - @Test - public void testTimeZoneParameterMatters() { - String template = "${" + System.currentTimeMillis() + "?numberToDatetime}"; - - String gmt1Result; - { - FreeMarkerServiceResponse serviceResponse = freeMarkerService.calculateTemplateOutput( - template, null, null, null, TimeZone.getTimeZone("GMT+01")); - gmt1Result = serviceResponse.getTemplateOutput(); - } - - String gmt2Result; - { - FreeMarkerServiceResponse serviceResponse = freeMarkerService.calculateTemplateOutput( - template, null, null, new Locale("ru", "RU"), null); - gmt2Result = serviceResponse.getTemplateOutput(); - } - - assertThat(gmt1Result, not(equalTo(gmt2Result))); - } - - @Test - public void testTemplateWithSyntaxError() { - FreeMarkerServiceResponse serviceResponse = freeMarkerService.calculateTemplateOutput( - "test ${xx", Collections.<String, Object>emptyMap(), null, null, null); - assertThat(serviceResponse.isSuccesful(), is(false)); - assertThat(serviceResponse.getFailureReason(), instanceOf(ParseException.class)); - } - - @Test - public void testTemplateWithEvaluationError() { - FreeMarkerServiceResponse serviceResponse = freeMarkerService.calculateTemplateOutput( - "test ${x}", Collections.<String, Object>emptyMap(), null, null, null); - assertThat(serviceResponse.isSuccesful(), is(false)); - assertThat(serviceResponse.getFailureReason(), instanceOf(TemplateException.class)); - } - - @Test - public void testResultAlmostTruncation() { - freeMarkerService.setMaxOutputLength(5); - FreeMarkerServiceResponse serviceResponse = freeMarkerService.calculateTemplateOutput( - TRUNCATION_TEST_TEMPLATE, Collections.<String, Object>emptyMap(), null, null, null); - assertThat(serviceResponse.isSuccesful(), is(true)); - assertThat(serviceResponse.isTemplateOutputTruncated(), is(false)); - assertThat(serviceResponse.getTemplateOutput(), equalTo(TRUNCATION_TEST_TEMPLATE)); - } - - @Test - public void testResultTruncation() { - freeMarkerService.setMaxOutputLength(4); - FreeMarkerServiceResponse serviceResponse = freeMarkerService.calculateTemplateOutput( - TRUNCATION_TEST_TEMPLATE, Collections.<String, Object>emptyMap(), null, null, null); - assertThat(serviceResponse.isSuccesful(), is(true)); - assertThat(serviceResponse.isTemplateOutputTruncated(), is(true)); - assertThat(serviceResponse.getTemplateOutput(), - startsWith(TRUNCATION_TEST_TEMPLATE.substring(0, freeMarkerService.getMaxOutputLength()))); - assertThat(serviceResponse.getTemplateOutput().charAt(freeMarkerService.getMaxOutputLength()), - not(equalTo(TRUNCATION_TEST_TEMPLATE.charAt(freeMarkerService.getMaxOutputLength())))); - } - - @Test - public void testTemplateExecutionTimeout() throws InterruptedException, ExecutionException { - freeMarkerService.setMaxTemplateExecutionTime(200); - - // To avoid blocking the CI server forever without giving error: - Future<FreeMarkerServiceResponse> future = Executors.newSingleThreadExecutor().submit( - new Callable<FreeMarkerServiceResponse>() { - - @Override - public FreeMarkerServiceResponse call() throws Exception { - return freeMarkerService.calculateTemplateOutput( - "<#list 1.. as _></#list>", Collections.<String, Object>emptyMap(), null, null, null); - } - - }); - FreeMarkerServiceResponse serviceResponse; - try { - serviceResponse = future.get(BLOCKING_TEST_TIMEOUT, TimeUnit.MILLISECONDS); - } catch (TimeoutException e) { - throw new AssertionError("The template execution wasn't aborted (within the timeout)."); - } - assertThat(serviceResponse.isSuccesful(), is(false)); - assertThat(serviceResponse.getFailureReason(), instanceOf(TimeoutException.class)); - } - - @Test - public void testServiceOverburden() throws InterruptedException { - final BlockerDirective blocker = new BlockerDirective(); - final Map<String, BlockerDirective> blockerDataModel = Collections.singletonMap("blocker", blocker); - try { - // Fill all available task "slots": - for (int i = 0; i < MAX_THREADS + MAX_QUEUE_LENGTH; i++) { - new Thread(new Runnable() { - @Override - public void run() { - freeMarkerService.calculateTemplateOutput("<@blocker/>", blockerDataModel, null, null, null); - } - }).start(); - } - - // Wait until all template executions has started: - synchronized (blocker) { - final long startTime = System.currentTimeMillis(); - while (blocker.getEntered() < MAX_THREADS) { - // To avoid blocking the CI server forever is something goes wrong: - if (System.currentTimeMillis() - startTime > BLOCKING_TEST_TIMEOUT) { - fail("JUnit test timed out"); - } - blocker.wait(1000); - } - } - Thread.sleep(200); - // Because the others are waiting in the queue, and weren't started: - assertThat(blocker.getEntered(), not(greaterThan(MAX_THREADS))); - - // Souldn't accept on more tasks: - try { - freeMarkerService.calculateTemplateOutput("<@blocker/>", blockerDataModel, null, null, null); - fail("Expected RejectedExecutionException, but nothing was thrown."); - } catch (RejectedExecutionException e) { - // Expected - } - } finally { - // Ensure that the started threads will end: - blocker.release(); - } - } - - private static final class BlockerDirective implements TemplateDirectiveModel { - - private int entered; - private boolean released; - - public synchronized void release() { - released = true; - notifyAll(); - } - - @Override - public synchronized void execute(Environment env, @SuppressWarnings("rawtypes") Map params, - TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { - entered++; - notifyAll(); - final long startTime = System.currentTimeMillis(); - while (!released) { - // To avoid blocking the CI server forever is something goes wrong: - if (System.currentTimeMillis() - startTime > BLOCKING_TEST_TIMEOUT) { - LOG.error("JUnit test timed out"); - } - try { - wait(1000); - } catch (InterruptedException e) { - LOG.error("JUnit test was interrupted"); - } - } - LOG.debug("Blocker released"); - } - - public synchronized int getEntered() { - return entered; - } - - } - -} http://git-wip-us.apache.org/repos/asf/incubator-freemarker-online-tester/blob/2f0c0424/src/test/java/com/kenshoo/freemarker/util/DataModelParserTest.java ---------------------------------------------------------------------- diff --git a/src/test/java/com/kenshoo/freemarker/util/DataModelParserTest.java b/src/test/java/com/kenshoo/freemarker/util/DataModelParserTest.java deleted file mode 100644 index f651fb8..0000000 --- a/src/test/java/com/kenshoo/freemarker/util/DataModelParserTest.java +++ /dev/null @@ -1,281 +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 com.kenshoo.freemarker.util; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import java.math.BigDecimal; -import java.sql.Time; -import java.sql.Timestamp; -import java.util.GregorianCalendar; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Test; -import org.w3c.dom.Document; -import org.w3c.dom.Node; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; - -import freemarker.template.utility.DateUtil; - -public class DataModelParserTest { - - @Test - public void testEmpty() throws DataModelParsingException { - assertTrue(DataModelParser.parse("", DateUtil.UTC).isEmpty()); - assertTrue(DataModelParser.parse(" \n ", DateUtil.UTC).isEmpty()); - } - - @Test - public void testSingleAssignment() throws DataModelParsingException { - assertEquals(ImmutableMap.of("n", "v"), DataModelParser.parse("n=v", DateUtil.UTC)); - assertEquals(ImmutableMap.of("n", "v"), DataModelParser.parse("\n\n\tn\t= v", DateUtil.UTC)); - assertEquals(ImmutableMap.of("longerN", "longer v"), DataModelParser.parse("longerN=longer v", DateUtil.UTC)); - assertEquals(ImmutableMap.of("a:b.c-d$@", "foo bar\nbaaz"), DataModelParser.parse("a:b.c-d$@ = foo bar\nbaaz", DateUtil.UTC)); - } - - @Test - public void testNotBlankButHasNoAssignment() { - try { - DataModelParser.parse("x", DateUtil.UTC); - fail(); - } catch (DataModelParsingException e) { - assertThat(e.getMessage(), containsString("must start with an assignment")); - } - } - - @Test - public void testNoLinebreakBeforeEquals() { - try { - DataModelParser.parse("x\n=y", DateUtil.UTC); - fail(); - } catch (DataModelParsingException e) { - assertThat(e.getMessage(), containsString("must start with an assignment")); - } - } - - @Test - public void testMultipleAssignments() throws DataModelParsingException { - assertEquals(ImmutableMap.of("n1", "v1", "n2", "v2", "n3", "v3"), - DataModelParser.parse("n1=v1\nn2=v2\nn3=v3", DateUtil.UTC)); - assertEquals(ImmutableMap.of("n1", "v1", "n2", "v2", "n3", "v3"), - DataModelParser.parse(" n1 = v1 \r\n\r\n\tn2=v2\nn3 = v3\n\n", DateUtil.UTC)); - assertEquals(ImmutableMap.of("n1", "=\n=v", "n2", "l1\nl2\n\nl3", "n3", "v3"), - DataModelParser.parse("n1==\n=v \n n2=l1\nl2\n\nl3\nn3=v3", DateUtil.UTC)); - } - - @Test - public void testStrings() throws DataModelParsingException { - assertEquals( - ImmutableMap.of( - "a", "C:\\x", - "b", "foo\nbar", - "c", "foo\t\"bar\"", - "d", "foo\t\"bar\"", - "e", "Foo's" - ), - DataModelParser.parse( - "a=C:\\x\n" - + "b=foo\nbar\n" - + "c=foo\t\"bar\"\n" - + "d=\"foo\\t\\\"bar\\\"\"\n" - + "e=\"Foo's\"", - DateUtil.UTC)); - try { - DataModelParser.parse("a=\"foo", DateUtil.UTC); - fail(); - } catch (DataModelParsingException e) { - assertThat(e.getMessage(), containsString("quoted")); - } - try { - DataModelParser.parse("a='foo'", DateUtil.UTC); - fail(); - } catch (DataModelParsingException e) { - assertThat(e.getMessage(), containsString("quoted")); - } - try { - DataModelParser.parse("a=\"\\x\"", DateUtil.UTC); - fail(); - } catch (DataModelParsingException e) { - assertThat(e.getMessage(), containsString("escape")); - } - } - - @Test - public void testBasicNumbers() throws DataModelParsingException { - assertEquals( - ImmutableMap.of( - "a", BigDecimal.valueOf(1), - "b", BigDecimal.valueOf(1.5), - "c", BigDecimal.valueOf(-1.5), - "d", BigDecimal.valueOf(1.5), - "e", BigDecimal.valueOf(-0.125) - ), - DataModelParser.parse("a=1\nb=1.5\nc=-1.5\nd=+1.5\ne=-12.5e-2", DateUtil.UTC)); - try { - DataModelParser.parse("a=1,5", DateUtil.UTC); - fail(); - } catch (DataModelParsingException e) { - assertThat(e.getMessage(), containsString("Malformed number")); - assertThat(e.getMessage(), not(containsString("ISO"))); - } - } - - @Test - public void testSpecialNumbers() throws DataModelParsingException { - assertEquals( - ImmutableMap.of( - "a", Double.NaN, - "b", Double.POSITIVE_INFINITY, - "c", Double.NEGATIVE_INFINITY, - "d", Double.POSITIVE_INFINITY - ), - DataModelParser.parse("a=NaN\nb=Infinity\nc=-Infinity\nd=+Infinity", DateUtil.UTC)); - } - - @Test - public void testBooleans() throws DataModelParsingException { - assertEquals(ImmutableMap.of("a", true, "b", false), DataModelParser.parse("a=true\nb=false", DateUtil.UTC)); - try { - DataModelParser.parse("a=True", DateUtil.UTC); - fail(); - } catch (DataModelParsingException e) { - assertThat(e.getMessage(), containsString("true")); - } - } - - @Test - public void testTemporals() throws DataModelParsingException { - final Map<String, Object> dm = DataModelParser.parse("a=2014-02-12T01:02:03Z\nb=2014-02-12\nc=01:02:03Z", DateUtil.UTC); - - final GregorianCalendar cal = new GregorianCalendar(DateUtil.UTC); - cal.clear(); - - cal.set(2014, 1, 12, 1, 2, 3); - Timestamp a = new Timestamp(cal.getTimeInMillis()); - assertThat(dm.get("a"), instanceOf(Timestamp.class)); - assertEquals(dm.get("a"), a); - - cal.set(2014, 1, 12, 0, 0, 0); - java.sql.Date b = new java.sql.Date(cal.getTimeInMillis()); - assertThat(dm.get("b"), instanceOf(java.sql.Date.class)); - assertEquals(dm.get("b"), b); - - cal.set(1970, 0, 1, 1, 2, 3); - Time c = new Time(cal.getTimeInMillis()); - assertThat(dm.get("c"), instanceOf(Time.class)); - assertEquals(dm.get("c"), c); - - try { - DataModelParser.parse("a=2012T123", DateUtil.UTC); - fail(); - } catch (DataModelParsingException e) { - assertThat(e.getMessage(), containsString("ISO 8601 date-time")); - } - try { - DataModelParser.parse("a=2012-0102", DateUtil.UTC); - fail(); - } catch (DataModelParsingException e) { - assertThat(e.getMessage(), containsString("ISO 8601 date")); - } - try { - DataModelParser.parse("a=25:00", DateUtil.UTC); - fail(); - } catch (DataModelParsingException e) { - assertThat(e.getMessage(), containsString("ISO 8601 time")); - } - } - - @Test - public void testMaps() throws DataModelParsingException { - final Object map = DataModelParser.parse( - "n = {\n" - + "\t\"a\": 1,\n" - + "\t\"b\": 2\n" - + "}", - DateUtil.UTC) - .get("n"); - assertEquals(ImmutableMap.of("a", 1, "b", 2), map); - assertThat(map, instanceOf(LinkedHashMap.class)); - try { - DataModelParser.parse("n={1:2}", DateUtil.UTC); - fail(); - } catch (DataModelParsingException e) { - assertThat(e.getMessage(), containsString("JSON")); - } - } - - @Test - public void testLists() throws DataModelParsingException { - final Object list = DataModelParser.parse("n=[1, 2]", DateUtil.UTC).get("n"); - assertEquals(ImmutableList.of(1, 2), list); - assertThat(list, instanceOf(List.class)); - try { - DataModelParser.parse("n=[", DateUtil.UTC); - fail(); - } catch (DataModelParsingException e) { - assertThat(e.getMessage(), containsString("JSON")); - } - } - - @Test - public void testXML() throws DataModelParsingException { - final Object doc = DataModelParser.parse("n=<e xmlns='foo:/bar' a='123'>text</e>", DateUtil.UTC).get("n"); - assertThat(doc, instanceOf(Document.class)); - final Node firstChild = ((Document) doc).getFirstChild(); - assertEquals("e", firstChild.getNodeName()); - assertEquals("foo:/bar", firstChild.getNamespaceURI()); - - try { - DataModelParser.parse("n=<ns:e />", DateUtil.UTC); - fail(); - } catch (DataModelParsingException e) { - assertThat(e.getMessage(), containsString("XML")); - } - } - - @Test - public void testNull() throws DataModelParsingException { - assertNull(DataModelParser.parse("n=null", DateUtil.UTC).get("n")); - try { - DataModelParser.parse("a=NULL", DateUtil.UTC); - fail(); - } catch (DataModelParsingException e) { - assertThat(e.getMessage(), containsString("null")); - } - } - - @Test - public void testEmptyValue() throws DataModelParsingException { - try { - DataModelParser.parse("n=", DateUtil.UTC); - fail(); - } catch (DataModelParsingException e) { - assertThat(e.getMessage(), containsString("Empty")); - } - - assertEquals("", DataModelParser.parse("n=\"\"", DateUtil.UTC).get("n")); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-freemarker-online-tester/blob/2f0c0424/src/test/java/com/kenshoo/freemarker/util/LengthLimitedWriterTest.java ---------------------------------------------------------------------- diff --git a/src/test/java/com/kenshoo/freemarker/util/LengthLimitedWriterTest.java b/src/test/java/com/kenshoo/freemarker/util/LengthLimitedWriterTest.java deleted file mode 100644 index c56d52e..0000000 --- a/src/test/java/com/kenshoo/freemarker/util/LengthLimitedWriterTest.java +++ /dev/null @@ -1,77 +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 com.kenshoo.freemarker.util; - -import static org.junit.Assert.*; - -import java.io.IOException; -import java.io.StringWriter; - -import org.junit.Test; - -public class LengthLimitedWriterTest { - - private StringWriter wrappedW = new StringWriter(); - private LengthLimitedWriter w = new LengthLimitedWriter(wrappedW, 5); - - @Test - public void testLimitNotExceeded() throws IOException { - w.write("123"); - w.write("45"); - } - - @Test - public void testLimitExceededWithString() throws IOException { - w.write("123"); - try { - w.write("456"); - fail(); - } catch (LengthLimitExceededException e) { - assertEquals("12345", wrappedW.toString()); - } - } - - @Test - public void testLimitExceededWithCharArray() throws IOException { - w.write(new char[] { '1', '2', '3' }); - try { - w.write(new char[] { '4', '5', '6' }); - fail(); - } catch (LengthLimitExceededException e) { - assertEquals("12345", wrappedW.toString()); - } - } - - @Test - public void testLimitExceededWithChar() throws IOException { - w.write('1'); - w.write('2'); - w.write('3'); - w.write('4'); - w.write('5'); - try { - w.write('6'); - fail(); - } catch (LengthLimitExceededException e) { - assertEquals("12345", wrappedW.toString()); - } - } - -} http://git-wip-us.apache.org/repos/asf/incubator-freemarker-online-tester/blob/2f0c0424/src/test/java/com/kenshoo/freemarker/view/FreeMarkerOnlineViewTest.java ---------------------------------------------------------------------- diff --git a/src/test/java/com/kenshoo/freemarker/view/FreeMarkerOnlineViewTest.java b/src/test/java/com/kenshoo/freemarker/view/FreeMarkerOnlineViewTest.java deleted file mode 100644 index c67b44c..0000000 --- a/src/test/java/com/kenshoo/freemarker/view/FreeMarkerOnlineViewTest.java +++ /dev/null @@ -1,69 +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 com.kenshoo.freemarker.view; - -import static org.junit.Assert.assertEquals; - -import java.util.Locale; -import java.util.TimeZone; - -import org.junit.Test; - -import com.kenshoo.freemarker.services.AllowedSettingValuesMaps; - -import freemarker.core.HTMLOutputFormat; - - -public class FreeMarkerOnlineViewTest { - - private static final String TEMPLATE = "Template"; - private static final String DATA_MODEL = "DataModel"; - - @Test - public void testVieEmptyConstrucotr() { - FreeMarkerOnlineView view = new FreeMarkerOnlineView(); - assertEquals(view.getTemplate(), ""); - assertEquals(view.getDataModel(), ""); - assertEquals(view.getOutputFormat(), AllowedSettingValuesMaps.DEFAULT_OUTPUT_FORMAT_KEY); - assertEquals(view.getLocale(), AllowedSettingValuesMaps.DEFAULT_LOCALE_KEY); - assertEquals(view.getTimeZone(), AllowedSettingValuesMaps.DEFAULT_TIME_ZONE_KEY); - } - - @Test - public void testViewWhenAllOK() { - FreeMarkerOnlineView view = new FreeMarkerOnlineView(); - - view.setTemplate(TEMPLATE); - view.setDataModel(DATA_MODEL); - String outputFormatStr = HTMLOutputFormat.INSTANCE.getName(); - view.setOutputFormat(outputFormatStr); - String localeStr = Locale.GERMAN.toString(); - view.setLocale(localeStr); - String timeZoneStr = TimeZone.getTimeZone("GMT+01").getID(); - view.setTimeZone(timeZoneStr); - - assertEquals(view.getTemplate(), TEMPLATE); - assertEquals(view.getDataModel(), DATA_MODEL); - assertEquals(view.getOutputFormat(), outputFormatStr); - assertEquals(view.getLocale(), localeStr); - assertEquals(view.getTimeZone(), timeZoneStr); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-freemarker-online-tester/blob/2f0c0424/src/test/java/org/apache/freemarker/onlinetester/platform/DropWizardServiceTest.java ---------------------------------------------------------------------- diff --git a/src/test/java/org/apache/freemarker/onlinetester/platform/DropWizardServiceTest.java b/src/test/java/org/apache/freemarker/onlinetester/platform/DropWizardServiceTest.java new file mode 100644 index 0000000..f23672c --- /dev/null +++ b/src/test/java/org/apache/freemarker/onlinetester/platform/DropWizardServiceTest.java @@ -0,0 +1,39 @@ +/* + * 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.onlinetester.platform; + +import com.google.common.io.Resources; +import org.apache.freemarker.onlinetester.dropwizard.ApplicationStartup; +import com.yammer.dropwizard.testing.junit.DropwizardServiceRule; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.rules.TestRule; + +public class DropWizardServiceTest { + @ClassRule + public static TestRule testRule = new DropwizardServiceRule<>(ApplicationStartup.class, + Resources.getResource("freemarker-online.yml").getPath()); + + + @Test + public void testServerIsUp() throws Exception { + ((DropwizardServiceRule) testRule).getService(); + } +} http://git-wip-us.apache.org/repos/asf/incubator-freemarker-online-tester/blob/2f0c0424/src/test/java/org/apache/freemarker/onlinetester/platform/YamlPropertiesPersister.java ---------------------------------------------------------------------- diff --git a/src/test/java/org/apache/freemarker/onlinetester/platform/YamlPropertiesPersister.java b/src/test/java/org/apache/freemarker/onlinetester/platform/YamlPropertiesPersister.java new file mode 100644 index 0000000..4257e40 --- /dev/null +++ b/src/test/java/org/apache/freemarker/onlinetester/platform/YamlPropertiesPersister.java @@ -0,0 +1,91 @@ +/* + * 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.onlinetester.platform; + +import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml; +import org.springframework.util.PropertiesPersister; +import org.springframework.util.StringUtils; + +import java.io.*; +import java.util.Map; +import java.util.Properties; + +public class YamlPropertiesPersister implements PropertiesPersister { + @Override + public void load(Properties props, InputStream is) throws IOException { + load(props, new InputStreamReader(is)); + } + + /** + * We want to traverse map representing Yaml object and each time we find String=String pair we want to + * save it as Property. As we are going deeper into map we generate compound key as path-like String + * + * @see org.springframework.util.PropertiesPersister#load(java.util.Properties, java.io.Reader) + */ + @Override + public void load(Properties props, Reader reader) throws IOException { + Yaml yaml = new Yaml(); + @SuppressWarnings("unchecked") + Map<String, Object> map = (Map<String, Object>) yaml.load(reader); + // now we can populate supplied props + assignProperties(props, map, null); + } + + @SuppressWarnings("unchecked") + public void assignProperties(Properties props, Map<String, Object> map, String path) { + for (Map.Entry<String, Object> entry : map.entrySet()) { + String key = entry.getKey(); + if (!StringUtils.isEmpty(path)) + key = path + "." + key; + Object val = entry.getValue(); + if (val instanceof String) { + // see if we need to create a compound key + props.put(key, val); + } else if (val instanceof Map) { + assignProperties(props, (Map<String, Object>) val, key); + } + } + } + + @Override + public void store(Properties props, OutputStream os, String header) throws IOException { + throw new IllegalStateException("Current implementation is a read-only"); + } + + @Override + public void store(Properties props, Writer writer, String header) throws IOException { + throw new IllegalStateException("Current implementation is a read-only"); + } + + @Override + public void loadFromXml(Properties props, InputStream is) throws IOException { + throw new IllegalStateException("Use DefaultPropertiesPersister if you want to read/write XML"); + } + + @Override + public void storeToXml(Properties props, OutputStream os, String header) throws IOException { + throw new IllegalStateException("Use DefaultPropertiesPersister if you want to load/store to XML"); + } + + @Override + public void storeToXml(Properties props, OutputStream os, String header, String encoding) throws IOException { + throw new IllegalStateException("Use DefaultPropertiesPersister if you want to read/write XML"); + } +} http://git-wip-us.apache.org/repos/asf/incubator-freemarker-online-tester/blob/2f0c0424/src/test/java/org/apache/freemarker/onlinetester/resources/FreeMarkerOnlineExecuteResourceTest.java ---------------------------------------------------------------------- diff --git a/src/test/java/org/apache/freemarker/onlinetester/resources/FreeMarkerOnlineExecuteResourceTest.java b/src/test/java/org/apache/freemarker/onlinetester/resources/FreeMarkerOnlineExecuteResourceTest.java new file mode 100644 index 0000000..d0f81cb --- /dev/null +++ b/src/test/java/org/apache/freemarker/onlinetester/resources/FreeMarkerOnlineExecuteResourceTest.java @@ -0,0 +1,159 @@ +/* + * 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.onlinetester.resources; + +import static org.hamcrest.Matchers.containsString; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import org.apache.freemarker.onlinetester.model.ExecuteRequest; +import org.apache.freemarker.onlinetester.model.ExecuteResourceField; +import org.apache.freemarker.onlinetester.model.ExecuteResourceProblem; +import org.apache.freemarker.onlinetester.model.ExecuteResponse; +import org.junit.Test; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.request.RequestContextListener; + +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.spi.spring.container.servlet.SpringServlet; +import com.sun.jersey.test.framework.AppDescriptor; +import com.sun.jersey.test.framework.JerseyTest; +import com.sun.jersey.test.framework.WebAppDescriptor; + +public class FreeMarkerOnlineExecuteResourceTest extends JerseyTest { + private static final String DATA_MODEL = "user=John"; + private static final String TEMPLATE_WITH_VARIABLE = "Welcome ${user}"; + private static final String TEMPLATE_PLAIN = "Welcome John"; + private static final String MALFORMED_DATA_MODEL = "userJohn"; + private static final String EXECUTE_API = "api/execute"; + @Override + protected AppDescriptor configure() { + return new WebAppDescriptor.Builder("org.apache.freemarker.onlinetester.resources") + .contextPath("/") + .contextListenerClass(ContextLoaderListener.class) + .contextParam("contextConfigLocation", "classpath:spring/bootstrap-context.xml") + .servletClass(SpringServlet.class) + .requestListenerClass(RequestContextListener.class) + .build(); + } + + @Test + public void testSuccessRequest() throws Exception { + ExecuteRequest req = new ExecuteRequest(TEMPLATE_WITH_VARIABLE, DATA_MODEL); + ClientResponse resp = client().resource(getBaseURI().toString() + EXECUTE_API) + .header("Content-Type", "application/json").entity(req).post(ClientResponse.class); + assertEquals(200, resp.getStatus()); + ExecuteResponse response = resp.getEntity(ExecuteResponse.class); + assertNull(response.getProblems()); + } + + @Test + public void testMalformedDataModel() throws Exception { + ExecuteRequest req = new ExecuteRequest(TEMPLATE_PLAIN, MALFORMED_DATA_MODEL); + ClientResponse resp = client().resource(getBaseURI().toString() + EXECUTE_API) + .header("Content-Type", "application/json").entity(req).post(ClientResponse.class); + assertEquals(200, resp.getStatus()); + ExecuteResponse response = resp.getEntity(ExecuteResponse.class); + assertNotNull(response.getProblems()); + assertTrue(containsProblem(response, ExecuteResourceField.DATA_MODEL)); + } + + @Test + public void testLongDataModel() throws Exception { + ExecuteRequest req = new ExecuteRequest(TEMPLATE_PLAIN, create30KString()); + ClientResponse resp = client().resource(getBaseURI().toString() + EXECUTE_API) + .header("Content-Type", "application/json").entity(req).post(ClientResponse.class); + assertEquals(200, resp.getStatus()); + ExecuteResponse response = resp.getEntity(ExecuteResponse.class); + assertNotNull(response.getProblems()); + assertTrue(containsProblem(response, ExecuteResourceField.DATA_MODEL)); + String problemMessage = getProblemMessage(response, ExecuteResourceField.DATA_MODEL); + assertThat(problemMessage, containsString("data model")); + assertThat(problemMessage, containsString("limit")); + } + + @Test + public void testLongTemplate() throws Exception { + ExecuteRequest req = new ExecuteRequest(create30KString(), DATA_MODEL); + ClientResponse resp = client().resource(getBaseURI().toString() + EXECUTE_API) + .header("Content-Type", "application/json").entity(req).post(ClientResponse.class); + assertEquals(200, resp.getStatus()); + ExecuteResponse response = resp.getEntity(ExecuteResponse.class); + assertNotNull(response.getProblems()); + assertTrue(containsProblem(response, ExecuteResourceField.TEMPLATE)); + String problemMessage = getProblemMessage(response, ExecuteResourceField.TEMPLATE); + assertThat(problemMessage, containsString("template")); + assertThat(problemMessage, containsString("limit")); + } + + @Test + public void testMultipleErrorsDataModel() throws Exception { + ExecuteRequest req = new ExecuteRequest(create30KString(), create30KString()); + req.setOutputFormat("wrongOutputFormat"); + req.setLocale("wrongLocale"); + req.setTimeZone("wrongTimeZone"); + + ClientResponse resp = client().resource(getBaseURI() + EXECUTE_API) + .header("Content-Type", "application/json").entity(req).post(ClientResponse.class); + + assertEquals(200, resp.getStatus()); + ExecuteResponse response = resp.getEntity(ExecuteResponse.class); + assertNotNull(response.getProblems()); + assertThat(getProblemMessage(response, ExecuteResourceField.TEMPLATE), containsString("limit")); + assertThat(getProblemMessage(response, ExecuteResourceField.DATA_MODEL), containsString("limit")); + assertThat(getProblemMessage(response, ExecuteResourceField.OUTPUT_FORMAT), containsString("wrongOutputFormat")); + assertThat(getProblemMessage(response, ExecuteResourceField.LOCALE), containsString("wrongLocale")); + assertThat(getProblemMessage(response, ExecuteResourceField.TIME_ZONE), containsString("wrongTimeZone")); + } + + private String create30KString() { + final String veryLongString; + { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < 30000 / 10; i++) { + sb.append("0123456789"); + } + veryLongString = sb.toString(); + } + return veryLongString; + } + + private boolean containsProblem(ExecuteResponse response, ExecuteResourceField field) { + for (ExecuteResourceProblem problem : response.getProblems()) { + if (problem.getField() == field) { + return true; + } + } + return false; + } + + private String getProblemMessage(ExecuteResponse response, ExecuteResourceField field) { + for (ExecuteResourceProblem problem : response.getProblems()) { + if (problem.getField() == field) { + return problem.getMessage(); + } + } + return null; + } + +} http://git-wip-us.apache.org/repos/asf/incubator-freemarker-online-tester/blob/2f0c0424/src/test/java/org/apache/freemarker/onlinetester/resources/FreeMarkerOnlineResourceTest.java ---------------------------------------------------------------------- diff --git a/src/test/java/org/apache/freemarker/onlinetester/resources/FreeMarkerOnlineResourceTest.java b/src/test/java/org/apache/freemarker/onlinetester/resources/FreeMarkerOnlineResourceTest.java new file mode 100644 index 0000000..4f6ef7c --- /dev/null +++ b/src/test/java/org/apache/freemarker/onlinetester/resources/FreeMarkerOnlineResourceTest.java @@ -0,0 +1,70 @@ +/* + * 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.onlinetester.resources; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyMap; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.when; + +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import org.apache.freemarker.onlinetester.services.FreeMarkerService; +import org.apache.freemarker.onlinetester.view.FreeMarkerOnlineView; + +import freemarker.core.OutputFormat; + +@RunWith(MockitoJUnitRunner.class) +public class FreeMarkerOnlineResourceTest { + + @InjectMocks + FreeMarkerOnlineResource freeMarkerOnlineResultResource; + + @Mock + FreeMarkerService freeMarkerService; + + @Test + public void testInitialForm() { + when(freeMarkerService.calculateTemplateOutput( + anyString(), anyMap(), any(OutputFormat.class), any(Locale.class), any(TimeZone.class))) + .thenThrow(new AssertionError()); + FreeMarkerOnlineView view = freeMarkerOnlineResultResource.blankForm(); + assertEquals(view.getTemplate(), ""); + assertEquals(view.getDataModel(), ""); + } + + @Test + public void testPostedBlankForm() { + when(freeMarkerService.calculateTemplateOutput( + anyString(), anyMap(), any(OutputFormat.class), any(Locale.class), any(TimeZone.class))) + .thenThrow(new AssertionError()); + FreeMarkerOnlineView view = freeMarkerOnlineResultResource.formResult(null, null, null, null, null); + assertEquals(view.getTemplate(), ""); + assertEquals(view.getDataModel(), ""); + } +} http://git-wip-us.apache.org/repos/asf/incubator-freemarker-online-tester/blob/2f0c0424/src/test/java/org/apache/freemarker/onlinetester/services/FreeMarkerServiceResponseBuilderTest.java ---------------------------------------------------------------------- diff --git a/src/test/java/org/apache/freemarker/onlinetester/services/FreeMarkerServiceResponseBuilderTest.java b/src/test/java/org/apache/freemarker/onlinetester/services/FreeMarkerServiceResponseBuilderTest.java new file mode 100644 index 0000000..f83a1b4 --- /dev/null +++ b/src/test/java/org/apache/freemarker/onlinetester/services/FreeMarkerServiceResponseBuilderTest.java @@ -0,0 +1,61 @@ +/* + * 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.onlinetester.services; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import org.junit.Test; + +public class FreeMarkerServiceResponseBuilderTest { + + private static final String RESULT = "Result"; + + private final FreeMarkerServiceResponse.Builder builder = new FreeMarkerServiceResponse.Builder(); + + @Test + public void testSuccessResult() { + FreeMarkerServiceResponse result = builder.buildForSuccess(RESULT, false); + assertThat(result.getTemplateOutput(), equalTo(RESULT)); + assertThat(result.isTemplateOutputTruncated(), is(false)); + assertThat(result.isSuccesful(), is(true)); + assertThat(result.getFailureReason(), nullValue()); + } + + @Test + public void testSuccessTruncatedResult() { + FreeMarkerServiceResponse result = builder.buildForSuccess(RESULT, true); + assertThat(result.getTemplateOutput(), equalTo(RESULT)); + assertThat(result.isTemplateOutputTruncated(), is(true)); + assertThat(result.isSuccesful(), is(true)); + assertThat(result.getFailureReason(), nullValue()); + } + + @Test + public void testErrorResult() { + Throwable failureReason = new Exception(); + FreeMarkerServiceResponse result = builder.buildForFailure(failureReason); + assertThat(result.getTemplateOutput(), nullValue()); + assertThat(result.isTemplateOutputTruncated(), is(false)); + assertThat(result.isSuccesful(), is(false)); + assertThat(result.getFailureReason(), sameInstance(failureReason)); + } + +}
