freemarker-notifications mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ddek...@apache.org
Subject [1/4] incubator-freemarker-online-tester git commit: initial commit
Date Sat, 01 Apr 2017 19:47:16 GMT
Repository: incubator-freemarker-online-tester
Updated Branches:
  refs/heads/master 0fb645b28 -> fc99d2b4f


http://git-wip-us.apache.org/repos/asf/incubator-freemarker-online-tester/blob/abb26297/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
new file mode 100644
index 0000000..ea30902
--- /dev/null
+++ b/src/test/java/com/kenshoo/freemarker/resources/FreeMarkerOnlineResourceTest.java
@@ -0,0 +1,72 @@
+/*
+ * 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.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;
+
+/**
+ * Created with IntelliJ IDEA.
+ * User: nir
+ * Date: 4/12/14
+ * Time: 11:23 PM
+ */
+@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/abb26297/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
new file mode 100644
index 0000000..d30bdec
--- /dev/null
+++ b/src/test/java/com/kenshoo/freemarker/services/FreeMarkerServiceResponseBuilderTest.java
@@ -0,0 +1,63 @@
+/*
+ * 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.services;
+
+import static org.hamcrest.Matchers.*;
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+
+/**
+ * Created with IntelliJ IDEA.
+ * User: nir
+ * Date: 4/13/14
+ * Time: 7:30 AM
+ */
+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/abb26297/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
new file mode 100644
index 0000000..5bd19dd
--- /dev/null
+++ b/src/test/java/com/kenshoo/freemarker/services/FreeMarkerServiceTest.java
@@ -0,0 +1,310 @@
+/*
+ * 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.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;
+
+/**
+ * Created with IntelliJ IDEA.
+ * User: nir
+ * Date: 4/12/14
+ * Time: 11:15 AM
+ */
+@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("&amp;"));
+        }
+    }
+
+    @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/abb26297/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
new file mode 100644
index 0000000..08f389c
--- /dev/null
+++ b/src/test/java/com/kenshoo/freemarker/util/DataModelParserTest.java
@@ -0,0 +1,277 @@
+/*
+ * 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.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/abb26297/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
new file mode 100644
index 0000000..169b39e
--- /dev/null
+++ b/src/test/java/com/kenshoo/freemarker/util/LengthLimitedWriterTest.java
@@ -0,0 +1,73 @@
+/*
+ * 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.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/abb26297/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
new file mode 100644
index 0000000..b73410f
--- /dev/null
+++ b/src/test/java/com/kenshoo/freemarker/view/FreeMarkerOnlineViewTest.java
@@ -0,0 +1,70 @@
+/*
+ * 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.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;
+
+/**
+ * Created with IntelliJ IDEA.
+ * User: nir
+ * Date: 4/12/14
+ * Time: 11:13 PM
+ */
+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/abb26297/src/test/resources/spring/test-context.xml
----------------------------------------------------------------------
diff --git a/src/test/resources/spring/test-context.xml b/src/test/resources/spring/test-context.xml
new file mode 100644
index 0000000..2ca10e6
--- /dev/null
+++ b/src/test/resources/spring/test-context.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:context="http://www.springframework.org/schema/context"
+       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
+
+</beans>
\ No newline at end of file



Mime
View raw message