From 32a5d8f3827fbf0ba2c0c3102f0d818d7b7a3873 Mon Sep 17 00:00:00 2001 From: Artur Signell Date: Mon, 29 Dec 2014 14:11:12 +0200 Subject: Reformat project using Eclipse Luna SR1 Change-Id: I58748499c87d470e70304d882d3227cda5803481 --- .../client/metadata/ConnectorBundleLoader.java | 2 +- client/src/com/vaadin/client/ui/VPopupView.java | 7 ++++--- client/src/com/vaadin/client/ui/VTabsheet.java | 23 ++++++++++++---------- 3 files changed, 18 insertions(+), 14 deletions(-) (limited to 'client') diff --git a/client/src/com/vaadin/client/metadata/ConnectorBundleLoader.java b/client/src/com/vaadin/client/metadata/ConnectorBundleLoader.java index dca5931640..e67fee96cf 100644 --- a/client/src/com/vaadin/client/metadata/ConnectorBundleLoader.java +++ b/client/src/com/vaadin/client/metadata/ConnectorBundleLoader.java @@ -161,7 +161,7 @@ public abstract class ConnectorBundleLoader { private HTML notice; // Not using Vaadin notifications (#14597) - private void notice(String productName) { + private void notice(String productName) { if (notice == null) { notice = new HTML(); notice.addClickHandler(new ClickHandler() { diff --git a/client/src/com/vaadin/client/ui/VPopupView.java b/client/src/com/vaadin/client/ui/VPopupView.java index 5b37a90915..1923fc55e6 100644 --- a/client/src/com/vaadin/client/ui/VPopupView.java +++ b/client/src/com/vaadin/client/ui/VPopupView.java @@ -92,7 +92,7 @@ public class VPopupView extends HTML implements HasEnabled, Iterable, addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { - if(isEnabled()) { + if (isEnabled()) { preparePopup(popup); showPopup(popup); center(); @@ -206,8 +206,9 @@ public class VPopupView extends HTML implements HasEnabled, Iterable, /** * Sets whether this popup is enabled. * - * @param enabled true to enable the popup, false - * to disable it + * @param enabled + * true to enable the popup, false to + * disable it * @since 7.3.4 */ @Override diff --git a/client/src/com/vaadin/client/ui/VTabsheet.java b/client/src/com/vaadin/client/ui/VTabsheet.java index 2d34897986..96af09bb32 100644 --- a/client/src/com/vaadin/client/ui/VTabsheet.java +++ b/client/src/com/vaadin/client/ui/VTabsheet.java @@ -735,9 +735,10 @@ public class VTabsheet extends VTabsheetBase implements Focusable, SubPartAware /** * The id of the tab at position scrollerIndex. This is used for keeping the * scroll position unchanged when a tab is removed from the server side and - * the removed tab lies to the left of the current scroll position. For other - * cases scrollerIndex alone would be sufficient. Since the tab at the current - * scroll position can be removed, scrollerIndex is required in addition to this variable. + * the removed tab lies to the left of the current scroll position. For + * other cases scrollerIndex alone would be sufficient. Since the tab at the + * current scroll position can be removed, scrollerIndex is required in + * addition to this variable. */ private String scrollerPositionTabId; @@ -1081,7 +1082,8 @@ public class VTabsheet extends VTabsheetBase implements Focusable, SubPartAware } private boolean isScrollerPrevDisabled() { - return scrollerPrev.getClassName().contains(PREV_SCROLLER_DISABLED_CLASSNAME); + return scrollerPrev.getClassName().contains( + PREV_SCROLLER_DISABLED_CLASSNAME); } private boolean isIndexSkippingHiddenTabs() { @@ -1103,9 +1105,9 @@ public class VTabsheet extends VTabsheetBase implements Focusable, SubPartAware // Should not set tabs visible if they are scrolled out of view tab.setVisible(false); } else { - //reset the scroller index back to zero if tab is visible - //again and tab is in view - if(isIndexSkippingHiddenTabs() && tabState.visible) { + // reset the scroller index back to zero if tab is visible + // again and tab is in view + if (isIndexSkippingHiddenTabs() && tabState.visible) { scrollerIndex = 0; } tab.setVisible(tabState.visible); @@ -1247,7 +1249,9 @@ public class VTabsheet extends VTabsheetBase implements Focusable, SubPartAware if (tb.getTabCount() > 0 && tb.isVisible() && (scrolled || clipped)) { scroller.getStyle().clearDisplay(); DOM.setElementProperty(scrollerPrev, "className", - SCROLLER_CLASSNAME + (scrolled ? "Prev" : PREV_SCROLLER_DISABLED_CLASSNAME)); + SCROLLER_CLASSNAME + + (scrolled ? "Prev" + : PREV_SCROLLER_DISABLED_CLASSNAME)); DOM.setElementProperty(scrollerNext, "className", SCROLLER_CLASSNAME + (clipped ? "Next" : "Next-disabled")); @@ -1861,8 +1865,7 @@ public class VTabsheet extends VTabsheetBase implements Focusable, SubPartAware } if (scrollerIndex >= 0 && scrollerIndex < tb.getTabCount()) { scrollerPositionTabId = tb.getTab(scrollerIndex).id; - } - else{ + } else { scrollerPositionTabId = null; } } -- cgit v1.2.3 From 26832b6947266ce5cffd92558c23e6556278038d Mon Sep 17 00:00:00 2001 From: Artur Signell Date: Fri, 19 Dec 2014 01:50:32 +0200 Subject: Option for rendering Calendar event captions as HTML (#9030) Change-Id: Ib7f6e67c242449e58a10359c596489fea2f679f6 --- WebContent/release-notes.html | 3 +- client/src/com/vaadin/client/ui/VCalendar.java | 30 ++++++ .../client/ui/calendar/CalendarConnector.java | 2 + .../ui/calendar/schedule/DateCellDayEvent.java | 14 ++- .../ui/calendar/schedule/MonthEventLabel.java | 15 ++- .../ui/calendar/schedule/WeeklyLongEvents.java | 6 +- server/src/com/vaadin/ui/Calendar.java | 37 +++++++- .../vaadin/shared/ui/calendar/CalendarState.java | 1 + .../components/calendar/CalendarHtmlInEvents.java | 101 ++++++++++++++++++++ .../calendar/CalendarHtmlInEventsTest.java | 103 +++++++++++++++++++++ 10 files changed, 302 insertions(+), 10 deletions(-) create mode 100644 uitest/src/com/vaadin/tests/components/calendar/CalendarHtmlInEvents.java create mode 100644 uitest/src/com/vaadin/tests/components/calendar/CalendarHtmlInEventsTest.java (limited to 'client') diff --git a/WebContent/release-notes.html b/WebContent/release-notes.html index a060372580..7be74ee1ed 100644 --- a/WebContent/release-notes.html +++ b/WebContent/release-notes.html @@ -112,7 +112,7 @@
  • Declarative layout support for initializing a component hierarchy from an HTML file.
  • Uses GWT 2.7 for improved compilation times when using Super Dev Mode.
  • @Viewport annotation for declaratively defining a mobile viewport definition for a UI.
  • -
  • Captions can be configured to be displayed as HTML.
  • +
  • Component captions, TabSheet/Accordion tab captions and Calendar event captions can be configured to be displayed as HTML.
  • Selects use converters when presenting itemids.
  • Improved performance when server response contains no visual changing (e.g. empty polling responses).
  • Unified JSON library for using the same API in both server-side and client-side code.
  • @@ -134,6 +134,7 @@

    Raw JSON values passed to AbstractJavaScriptComponent.callFunction and AbstractJavaScriptExtension.callFunction should be changed to use elemental.json types.

  • The semantics of empty and required for Field classes has been made more consistent. This mainly affects Checkbox which is now considered to be empty when it is not checked.
  • +
  • The previously inconsistent behavior in HTML vs plain text rendering of Calendar event captions has been made consistent.
  • Support for Opera 12 has been dropped. Newer versions based on the Blink rendering engine are still supported.
  • Known issues

    diff --git a/client/src/com/vaadin/client/ui/VCalendar.java b/client/src/com/vaadin/client/ui/VCalendar.java index c59a78108c..08d4351931 100644 --- a/client/src/com/vaadin/client/ui/VCalendar.java +++ b/client/src/com/vaadin/client/ui/VCalendar.java @@ -1342,6 +1342,7 @@ public class VCalendar extends Composite implements VHasDropHandler { private MouseEventListener mouseEventListener; private boolean forwardNavigationEnabled = true; private boolean backwardNavigationEnabled = true; + private boolean eventCaptionAsHtml = false; /** * Get the listener that listen to mouse events @@ -1467,4 +1468,33 @@ public class VCalendar extends Composite implements VHasDropHandler { public void setDropHandler(CalendarDropHandler dropHandler) { this.dropHandler = dropHandler; } + + /** + * Sets whether the event captions are rendered as HTML. + *

    + * If set to true, the captions are rendered in the browser as HTML and the + * developer is responsible for ensuring no harmful HTML is used. If set to + * false, the caption is rendered in the browser as plain text. + *

    + * The default is false, i.e. to render that caption as plain text. + * + * @param captionAsHtml + * true if the captions are rendered as HTML, false if rendered + * as plain text + */ + public void setEventCaptionAsHtml(boolean eventCaptionAsHtml) { + this.eventCaptionAsHtml = eventCaptionAsHtml; + } + + /** + * Checks whether event captions are rendered as HTML + *

    + * The default is false, i.e. to render that caption as plain text. + * + * @return true if the captions are rendered as HTML, false if rendered as + * plain text + */ + public boolean isEventCaptionAsHtml() { + return eventCaptionAsHtml; + } } diff --git a/client/src/com/vaadin/client/ui/calendar/CalendarConnector.java b/client/src/com/vaadin/client/ui/calendar/CalendarConnector.java index 8f5e9d9a59..8c92ef1233 100644 --- a/client/src/com/vaadin/client/ui/calendar/CalendarConnector.java +++ b/client/src/com/vaadin/client/ui/calendar/CalendarConnector.java @@ -345,6 +345,8 @@ public class CalendarConnector extends AbstractComponentConnector implements widget.setEventMoveAllowed(hasEventListener(CalendarEventId.EVENTMOVE)); widget.setEventResizeAllowed(hasEventListener(CalendarEventId.EVENTRESIZE)); + widget.setEventCaptionAsHtml(state.eventCaptionAsHtml); + List days = state.days; List events = state.events; diff --git a/client/src/com/vaadin/client/ui/calendar/schedule/DateCellDayEvent.java b/client/src/com/vaadin/client/ui/calendar/schedule/DateCellDayEvent.java index 3b168b636c..8b08e9bc7a 100644 --- a/client/src/com/vaadin/client/ui/calendar/schedule/DateCellDayEvent.java +++ b/client/src/com/vaadin/client/ui/calendar/schedule/DateCellDayEvent.java @@ -184,14 +184,20 @@ public class DateCellDayEvent extends FocusableHTML implements */ private void updateCaptions(boolean bigMode) { String innerHtml; - String escapedCaption = Util.escapeHTML(calendarEvent.getCaption()); String timeAsText = calendarEvent.getTimeAsText(); + String htmlOrText; + + if (dateCell.weekgrid.getCalendar().isEventCaptionAsHtml()) { + htmlOrText = calendarEvent.getCaption(); + } else { + htmlOrText = Util.escapeHTML(calendarEvent.getCaption()); + } + if (bigMode) { - innerHtml = "" + timeAsText + "
    " - + escapedCaption; + innerHtml = "" + timeAsText + "
    " + htmlOrText; } else { innerHtml = "" + timeAsText + ": " - + escapedCaption; + + htmlOrText; } caption.setInnerHTML(innerHtml); eventContent.setInnerHTML(""); diff --git a/client/src/com/vaadin/client/ui/calendar/schedule/MonthEventLabel.java b/client/src/com/vaadin/client/ui/calendar/schedule/MonthEventLabel.java index 6fc2e430cd..31e600c8f9 100644 --- a/client/src/com/vaadin/client/ui/calendar/schedule/MonthEventLabel.java +++ b/client/src/com/vaadin/client/ui/calendar/schedule/MonthEventLabel.java @@ -20,6 +20,7 @@ import java.util.Date; import com.google.gwt.event.dom.client.ContextMenuEvent; import com.google.gwt.event.dom.client.ContextMenuHandler; import com.google.gwt.user.client.ui.HTML; +import com.vaadin.client.Util; import com.vaadin.client.ui.VCalendar; /** @@ -75,7 +76,8 @@ public class MonthEventLabel extends HTML implements HasTooltipKey { * Set the caption of the event label * * @param caption - * The caption string, can be HTML + * The caption string, can be HTML if + * {@link VCalendar#isEventCaptionAsHtml()} is true */ public void setCaption(String caption) { this.caption = caption; @@ -87,13 +89,20 @@ public class MonthEventLabel extends HTML implements HasTooltipKey { */ private void renderCaption() { StringBuilder html = new StringBuilder(); + String textOrHtml; + if (calendar.isEventCaptionAsHtml()) { + textOrHtml = caption; + } else { + textOrHtml = Util.escapeHTML(caption); + } + if (caption != null && time != null) { html.append(""); html.append(calendar.getTimeFormat().format(time)); html.append(" "); - html.append(caption); + html.append(textOrHtml); } else if (caption != null) { - html.append(caption); + html.append(textOrHtml); } else if (time != null) { html.append(""); html.append(calendar.getTimeFormat().format(time)); diff --git a/client/src/com/vaadin/client/ui/calendar/schedule/WeeklyLongEvents.java b/client/src/com/vaadin/client/ui/calendar/schedule/WeeklyLongEvents.java index bd833e06a0..9488c8835a 100644 --- a/client/src/com/vaadin/client/ui/calendar/schedule/WeeklyLongEvents.java +++ b/client/src/com/vaadin/client/ui/calendar/schedule/WeeklyLongEvents.java @@ -102,7 +102,11 @@ public class WeeklyLongEvents extends HorizontalPanel implements HasTooltipKey { eventLabel.addStyleDependentName(extraStyle + "-all-day"); } if (!started) { - eventLabel.setText(calendarEvent.getCaption()); + if (calendar.isEventCaptionAsHtml()) { + eventLabel.setHTML(calendarEvent.getCaption()); + } else { + eventLabel.setText(calendarEvent.getCaption()); + } started = true; } } diff --git a/server/src/com/vaadin/ui/Calendar.java b/server/src/com/vaadin/ui/Calendar.java index 5b5c390fa1..206cc01d1a 100644 --- a/server/src/com/vaadin/ui/Calendar.java +++ b/server/src/com/vaadin/ui/Calendar.java @@ -296,6 +296,11 @@ public class Calendar extends AbstractComponent implements return (CalendarState) super.getState(); } + @Override + protected CalendarState getState(boolean markAsDirty) { + return (CalendarState) super.getState(markAsDirty); + } + @Override public void beforeClientResponse(boolean initial) { super.beforeClientResponse(initial); @@ -1667,7 +1672,7 @@ public class Calendar extends AbstractComponent implements * weekly mode */ public boolean isMonthlyMode() { - CalendarState state = (CalendarState) getState(false); + CalendarState state = getState(false); if (state.days != null) { return state.days.size() > 7; } else { @@ -1895,4 +1900,34 @@ public class Calendar extends AbstractComponent implements dropHandler.getAcceptCriterion().paint(target); } } + + /** + * Sets whether the event captions are rendered as HTML. + *

    + * If set to true, the captions are rendered in the browser as HTML and the + * developer is responsible for ensuring no harmful HTML is used. If set to + * false, the caption is rendered in the browser as plain text. + *

    + * The default is false, i.e. to render that caption as plain text. + * + * @param captionAsHtml + * true if the captions are rendered as HTML, false if rendered + * as plain text + */ + public void setEventCaptionAsHtml(boolean eventCaptionAsHtml) { + getState().eventCaptionAsHtml = eventCaptionAsHtml; + } + + /** + * Checks whether event captions are rendered as HTML + *

    + * The default is false, i.e. to render that caption as plain text. + * + * @return true if the captions are rendered as HTML, false if rendered as + * plain text + */ + public boolean isEventCaptionAsHtml() { + return getState(false).eventCaptionAsHtml; + } + } diff --git a/shared/src/com/vaadin/shared/ui/calendar/CalendarState.java b/shared/src/com/vaadin/shared/ui/calendar/CalendarState.java index 93bd05bc1e..c26c4ead16 100644 --- a/shared/src/com/vaadin/shared/ui/calendar/CalendarState.java +++ b/shared/src/com/vaadin/shared/ui/calendar/CalendarState.java @@ -38,6 +38,7 @@ public class CalendarState extends AbstractComponentState { public List days; public List events; public List actions; + public boolean eventCaptionAsHtml; public static class Day implements java.io.Serializable { public String date; diff --git a/uitest/src/com/vaadin/tests/components/calendar/CalendarHtmlInEvents.java b/uitest/src/com/vaadin/tests/components/calendar/CalendarHtmlInEvents.java new file mode 100644 index 0000000000..15cde71838 --- /dev/null +++ b/uitest/src/com/vaadin/tests/components/calendar/CalendarHtmlInEvents.java @@ -0,0 +1,101 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.components.calendar; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import com.vaadin.data.Property.ValueChangeEvent; +import com.vaadin.data.Property.ValueChangeListener; +import com.vaadin.data.util.MethodProperty; +import com.vaadin.server.VaadinRequest; +import com.vaadin.tests.components.AbstractTestUIWithLog; +import com.vaadin.ui.Alignment; +import com.vaadin.ui.Calendar; +import com.vaadin.ui.CheckBox; +import com.vaadin.ui.HorizontalLayout; +import com.vaadin.ui.NativeSelect; +import com.vaadin.ui.components.calendar.event.BasicEvent; +import com.vaadin.ui.components.calendar.event.CalendarEvent; +import com.vaadin.ui.components.calendar.event.CalendarEventProvider; + +public class CalendarHtmlInEvents extends AbstractTestUIWithLog { + + private Calendar calendar = new Calendar(); + + @Override + protected void setup(VaadinRequest request) { + final NativeSelect ns = new NativeSelect("Period"); + ns.addItems("Day", "Week", "Month"); + ns.addValueChangeListener(new ValueChangeListener() { + @Override + public void valueChange(ValueChangeEvent event) { + if ("Day".equals(ns.getValue())) { + calendar.setStartDate(new Date(2014 - 1900, 1 - 1, 1)); + calendar.setEndDate(new Date(2014 - 1900, 1 - 1, 1)); + } else if ("Week".equals(ns.getValue())) { + calendar.setStartDate(new Date(2014 - 1900, 1 - 1, 1)); + calendar.setEndDate(new Date(2014 - 1900, 1 - 1, 7)); + } else if ("Month".equals(ns.getValue())) { + calendar.setStartDate(new Date(2014 - 1900, 1 - 1, 1)); + calendar.setEndDate(new Date(2014 - 1900, 2 - 1, 1)); + } + } + }); + ns.setValue("Month"); + final CheckBox allowHtml = new CheckBox("Allow HTML in event caption", + new MethodProperty(calendar, "eventCaptionAsHtml")); + allowHtml.addValueChangeListener(new ValueChangeListener() { + @Override + public void valueChange(ValueChangeEvent event) { + log("HTML in event caption: " + allowHtml.getValue()); + } + }); + HorizontalLayout hl = new HorizontalLayout(); + hl.setDefaultComponentAlignment(Alignment.BOTTOM_LEFT); + hl.addComponents(ns, allowHtml); + hl.setSpacing(true); + hl.setMargin(true); + calendar.setEventProvider(new CalendarEventProvider() { + + @Override + public List getEvents(Date startDate, Date endDate) { + Date d = startDate; + ArrayList events = new ArrayList(); + while (d.before(endDate)) { + BasicEvent ce = new BasicEvent(); + ce.setAllDay(false); + ce.setCaption("Hello world!"); + ce.setDescription("Nothing really important"); + Date start = new Date(d.getTime()); + start.setHours(d.getDay()); + Date end = new Date(d.getTime()); + end.setHours(d.getDay() + 3); + ce.setStart(start); + ce.setEnd(end); + events.add(ce); + d.setTime(d.getTime() + 1000 * 60 * 60 * 24); + } + + return events; + } + + }); + addComponent(hl); + addComponent(calendar); + } +} diff --git a/uitest/src/com/vaadin/tests/components/calendar/CalendarHtmlInEventsTest.java b/uitest/src/com/vaadin/tests/components/calendar/CalendarHtmlInEventsTest.java new file mode 100644 index 0000000000..31e3f754e3 --- /dev/null +++ b/uitest/src/com/vaadin/tests/components/calendar/CalendarHtmlInEventsTest.java @@ -0,0 +1,103 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.components.calendar; + +import org.junit.Assert; +import org.junit.Test; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; + +import com.vaadin.testbench.elements.CalendarElement; +import com.vaadin.testbench.elements.CheckBoxElement; +import com.vaadin.testbench.elements.NativeSelectElement; +import com.vaadin.tests.tb3.SingleBrowserTest; + +public class CalendarHtmlInEventsTest extends SingleBrowserTest { + + private NativeSelectElement periodSelect; + private CheckBoxElement htmlAllowed; + private CalendarElement calendar; + + @Override + public void setup() throws Exception { + super.setup(); + openTestURL(); + periodSelect = $(NativeSelectElement.class).first(); + htmlAllowed = $(CheckBoxElement.class).first(); + calendar = $(CalendarElement.class).first(); + } + + @Test + public void monthViewEventCaptions() { + Assert.assertEquals(getMonthEvent(0).getText(), + "12:00 AM Hello world!"); + + // Switch to HTML mode + click(htmlAllowed); + Assert.assertEquals("1. HTML in event caption: true", getLogRow(0)); + + Assert.assertEquals(getMonthEvent(0).getText(), "12:00 AM Hello world!"); + } + + @Test + public void weekViewEventCaptions() { + periodSelect.selectByText("Week"); + Assert.assertEquals("4:00 AM\nHello world!", + getWeekEvent(1).getText()); + + // Switch to HTML mode + click(htmlAllowed); + Assert.assertEquals("1. HTML in event caption: true", getLogRow(0)); + + Assert.assertEquals("4:00 AM\nHello world!", getWeekEvent(1).getText()); + } + + @Test + public void dayViewEventCaptions() { + periodSelect.selectByText("Day"); + Assert.assertEquals("3:00 AM\nHello world!", + getWeekEvent(0).getText()); + + // Switch to HTML mode + click(htmlAllowed); + Assert.assertEquals("1. HTML in event caption: true", getLogRow(0)); + Assert.assertEquals("3:00 AM\nHello world!", getWeekEvent(0).getText()); + } + + private WebElement getMonthEvent(int dayInCalendar) { + return getMonthDay(dayInCalendar).findElement( + By.className("v-calendar-event")); + } + + private WebElement getWeekEvent(int dayInCalendar) { + return getWeekDay(dayInCalendar).findElement( + By.className("v-calendar-event")); + } + + private void click(CheckBoxElement htmlAllowed2) { + htmlAllowed2.findElement(By.xpath("input")).click(); + } + + private WebElement getMonthDay(int i) { + return calendar.findElements(By.className("v-calendar-month-day")).get( + i); + } + + private WebElement getWeekDay(int i) { + return calendar.findElements(By.className("v-calendar-day-times")).get( + i); + } +} -- cgit v1.2.3 From 0c9625d05c829a66b2b42fb5c3f14384d8c0f4a8 Mon Sep 17 00:00:00 2001 From: Sauli Tähkäpää Date: Fri, 2 Jan 2015 16:10:52 +0200 Subject: Unify test class naming. Unit tests are now run for *Test.java and *Tests.java. Change-Id: Iffff1d9a79c7c9b9317ffd19b5a46715b1442909 --- .../ApplicationConnectionTestURLGeneration.java | 75 --- .../ApplicationConnectionURLGenerationTest.java | 75 +++ .../client/TestVBrowserDetailsUserAgentParser.java | 588 ------------------ .../client/VBrowserDetailsUserAgentParserTest.java | 588 ++++++++++++++++++ common.xml | 10 +- .../com/vaadin/data/fieldgroup/FieldGroupDate.java | 97 --- .../vaadin/data/fieldgroup/FieldGroupDateTest.java | 97 +++ .../data/util/AbstractBeanContainerTest.java | 77 --- .../data/util/AbstractBeanContainerTestBase.java | 77 +++ .../vaadin/data/util/AbstractContainerTest.java | 679 --------------------- .../data/util/AbstractContainerTestBase.java | 679 +++++++++++++++++++++ .../util/AbstractHierarchicalContainerTest.java | 256 -------- .../AbstractHierarchicalContainerTestBase.java | 256 ++++++++ .../data/util/AbstractInMemoryContainerTest.java | 6 - .../util/AbstractInMemoryContainerTestBase.java | 6 + .../com/vaadin/data/util/BeanContainerTest.java | 4 +- .../data/util/BeanItemContainerGenerator.java | 3 - .../vaadin/data/util/BeanItemContainerTest.java | 2 +- .../util/ContainerHierarchicalWrapperTest.java | 42 ++ .../com/vaadin/data/util/ContainerSortingTest.java | 224 +++++++ .../data/util/HierarchicalContainerTest.java | 270 ++++++++ .../com/vaadin/data/util/IndexedContainerTest.java | 395 ++++++++++++ .../data/util/MethodPropertyMemoryConsumption.java | 145 ----- .../util/MethodPropertyMemoryConsumptionTest.java | 145 +++++ .../data/util/PerformanceTestIndexedContainer.java | 116 ---- .../util/PerformanceTestIndexedContainerTest.java | 116 ++++ .../data/util/ReflectToolsGetSuperField.java | 35 -- .../data/util/ReflectToolsGetSuperFieldTest.java | 35 ++ .../util/TestContainerHierarchicalWrapper.java | 42 -- .../com/vaadin/data/util/TestContainerSorting.java | 224 ------- .../data/util/TestHierarchicalContainer.java | 270 -------- .../com/vaadin/data/util/TestIndexedContainer.java | 395 ------------ .../data/util/filter/AbstractFilterTest.java | 97 --- .../data/util/filter/AbstractFilterTestBase.java | 97 +++ .../vaadin/data/util/filter/AndOrFilterTest.java | 2 +- .../vaadin/data/util/filter/CompareFilterTest.java | 2 +- .../vaadin/data/util/filter/IsNullFilterTest.java | 2 +- .../vaadin/data/util/filter/LikeFilterTest.java | 2 +- .../com/vaadin/data/util/filter/NotFilterTest.java | 2 +- .../data/util/filter/SimpleStringFilterTest.java | 2 +- .../data/util/sqlcontainer/DataGenerator.java | 6 - .../data/util/sqlcontainer/FreeformQueryUtil.java | 6 - .../connection/MockInitialContextFactory.java | 6 - .../converter/AnyEnumToStringConverterTest.java | 127 ++++ .../tests/data/converter/ConverterFactory.java | 122 ---- .../tests/data/converter/ConverterFactoryTest.java | 122 ++++ .../data/converter/DateToLongConverterTest.java | 21 + .../data/converter/DateToSqlDateConverterTest.java | 25 + .../converter/DefaultConverterFactoryTest.java | 128 ++++ .../SpecificEnumToStringConverterTest.java | 125 ++++ .../converter/StringToBigDecimalConverterTest.java | 53 ++ .../converter/StringToBigIntegerConverterTest.java | 57 ++ .../converter/StringToBooleanConverterTest.java | 23 + .../data/converter/StringToByteConverterTest.java | 69 +++ .../data/converter/StringToDateConverterTest.java | 26 + .../converter/StringToDoubleConverterTest.java | 22 + .../data/converter/StringToEnumConverterTest.java | 73 +++ .../data/converter/StringToFloatConverterTest.java | 23 + .../converter/StringToIntegerConverterTest.java | 41 ++ .../data/converter/StringToLongConverterTest.java | 69 +++ .../data/converter/StringToShortConverterTest.java | 70 +++ .../converter/TestAnyEnumToStringConverter.java | 127 ---- .../data/converter/TestDateToLongConverter.java | 21 - .../data/converter/TestDateToSqlDateConverter.java | 25 - .../converter/TestDefaultConverterFactory.java | 128 ---- .../TestSpecificEnumToStringConverter.java | 125 ---- .../converter/TestStringToBigDecimalConverter.java | 53 -- .../converter/TestStringToBigIntegerConverter.java | 57 -- .../converter/TestStringToBooleanConverter.java | 23 - .../data/converter/TestStringToByteConverter.java | 69 --- .../data/converter/TestStringToDateConverter.java | 26 - .../converter/TestStringToDoubleConverter.java | 22 - .../data/converter/TestStringToEnumConverter.java | 73 --- .../data/converter/TestStringToFloatConverter.java | 23 - .../converter/TestStringToIntegerConverter.java | 41 -- .../data/converter/TestStringToLongConverter.java | 69 --- .../data/converter/TestStringToShortConverter.java | 70 --- .../validator/BigDecimalRangeValidatorTest.java | 55 ++ .../validator/BigIntegerRangeValidatorTest.java | 55 ++ .../data/validator/ByteRangeValidatorTest.java | 50 ++ .../data/validator/CompositeValidatorTest.java | 116 ++++ .../data/validator/DateRangeValidatorTest.java | 97 +++ .../data/validator/DoubleRangeValidatorTest.java | 45 ++ .../tests/data/validator/EmailValidatorTest.java | 26 + .../data/validator/FloatRangeValidatorTest.java | 45 ++ .../data/validator/IntegerRangeValidatorTest.java | 45 ++ .../data/validator/LongRangeValidatorTest.java | 45 ++ .../tests/data/validator/NullValidatorTest.java | 40 ++ .../tests/data/validator/RegexpValidatorTest.java | 44 ++ .../data/validator/ShortRangeValidatorTest.java | 52 ++ .../data/validator/StringLengthValidatorTest.java | 65 ++ .../validator/TestBigDecimalRangeValidator.java | 55 -- .../validator/TestBigIntegerRangeValidator.java | 55 -- .../data/validator/TestByteRangeValidator.java | 50 -- .../data/validator/TestCompositeValidator.java | 116 ---- .../data/validator/TestDateRangeValidator.java | 97 --- .../data/validator/TestDoubleRangeValidator.java | 45 -- .../tests/data/validator/TestEmailValidator.java | 26 - .../data/validator/TestFloatRangeValidator.java | 45 -- .../data/validator/TestIntegerRangeValidator.java | 45 -- .../data/validator/TestLongRangeValidator.java | 45 -- .../tests/data/validator/TestNullValidator.java | 40 -- .../tests/data/validator/TestRegexpValidator.java | 44 -- .../data/validator/TestShortRangeValidator.java | 52 -- .../data/validator/TestStringLengthValidator.java | 65 -- .../server/AbstractBeanContainerListenersTest.java | 16 + .../server/AbstractContainerListenersTest.java | 21 + .../AbstractInMemoryContainerListenersTest.java | 14 + .../server/AbstractPropertyListenersTest.java | 24 + .../vaadin/tests/server/AssertionsEnabledTest.java | 33 + .../vaadin/tests/server/AtmosphereVersionTest.java | 18 + .../tests/server/ClassesSerializableTest.java | 323 ++++++++++ .../server/ClientMethodSerializationTest.java | 115 ++++ .../vaadin/tests/server/CsrfTokenMissingTest.java | 253 ++++++++ .../tests/server/CsrfTokenMissingTestServer.java | 253 -------- .../com/vaadin/tests/server/EventRouterTest.java | 39 ++ .../vaadin/tests/server/FileTypeResolverTest.java | 79 +++ .../tests/server/IndexedContainerListeners.java | 20 - .../server/IndexedContainerListenersTest.java | 20 + .../src/com/vaadin/tests/server/KeyMapperTest.java | 102 ++++ .../src/com/vaadin/tests/server/MimeTypesTest.java | 17 + .../vaadin/tests/server/PropertyFormatterTest.java | 75 +++ .../tests/server/PropertysetItemListeners.java | 13 - .../tests/server/PropertysetItemListenersTest.java | 13 + .../com/vaadin/tests/server/SerializationTest.java | 139 +++++ .../server/SimpleMultiPartInputStreamTest.java | 138 +++++ .../vaadin/tests/server/StreamResourceTest.java | 55 ++ .../tests/server/StreamVariableMappingTest.java | 90 +++ .../server/TestAbstractBeanContainerListeners.java | 16 - .../server/TestAbstractContainerListeners.java | 21 - .../TestAbstractInMemoryContainerListeners.java | 14 - .../server/TestAbstractPropertyListeners.java | 24 - .../vaadin/tests/server/TestAssertionsEnabled.java | 33 - .../vaadin/tests/server/TestAtmosphereVersion.java | 18 - .../tests/server/TestClassesSerializable.java | 324 ---------- .../server/TestClientMethodSerialization.java | 115 ---- .../com/vaadin/tests/server/TestEventRouter.java | 39 -- .../vaadin/tests/server/TestFileTypeResolver.java | 79 --- .../src/com/vaadin/tests/server/TestKeyMapper.java | 102 ---- .../src/com/vaadin/tests/server/TestMimeTypes.java | 17 - .../vaadin/tests/server/TestPropertyFormatter.java | 75 --- .../com/vaadin/tests/server/TestSerialization.java | 139 ----- .../server/TestSimpleMultiPartInputStream.java | 138 ----- .../vaadin/tests/server/TestStreamResource.java | 55 -- .../tests/server/TestStreamVariableMapping.java | 90 --- .../clientconnector/AttachDetachListeners.java | 182 ------ .../clientconnector/AttachDetachListenersTest.java | 182 ++++++ .../component/AbstractListenerMethodsTest.java | 173 ------ .../component/AbstractListenerMethodsTestBase.java | 173 ++++++ .../server/component/ReadEmptyDesignTest.java | 78 +++ .../server/component/StateGetDoesNotMarkDirty.java | 100 --- .../component/StateGetDoesNotMarkDirtyTest.java | 100 +++ .../server/component/TestReadEmptyDesign.java | 78 --- .../server/component/TestWriteEmptyDesign.java | 58 -- .../server/component/WriteEmptyDesignTest.java | 58 ++ .../absolutelayout/AbsoluteLayoutListeners.java | 13 - .../AbsoluteLayoutListenersTest.java | 13 + .../absolutelayout/ComponentPosition.java | 204 ------- .../absolutelayout/ComponentPositionTest.java | 204 +++++++ .../component/absolutelayout/ReadDesignTest.java | 110 ++++ .../component/absolutelayout/TestReadDesign.java | 110 ---- .../component/absolutelayout/TestWriteDesign.java | 100 --- .../component/absolutelayout/WriteDesignTest.java | 100 +++ .../AbstractComponentStyleNamesTest.java | 61 ++ .../abstractcomponent/ReadDesignTest.java | 256 ++++++++ .../TestAbstractComponentStyleNames.java | 61 -- .../abstractcomponent/TestReadDesign.java | 256 -------- .../abstractcomponent/TestWriteDesign.java | 281 --------- .../abstractcomponent/WriteDesignTest.java | 281 +++++++++ .../AbstractComponentContainerListenersTest.java | 22 + .../AddParentAsChild.java | 64 -- .../AddParentAsChildTest.java | 64 ++ .../TestAbstractComponentContainerListeners.java | 22 - .../abstractfield/AbsFieldValidators.java | 64 -- .../abstractfield/AbsFieldValidatorsTest.java | 64 ++ .../AbsFieldValueConversionError.java | 87 --- .../AbsFieldValueConversionErrorTest.java | 87 +++ .../abstractfield/AbsFieldValueConversions.java | 266 -------- .../AbsFieldValueConversionsTest.java | 266 ++++++++ .../abstractfield/AbstractFieldListenersTest.java | 21 + .../abstractfield/DefaultConverterFactory.java | 133 ---- .../abstractfield/DefaultConverterFactoryTest.java | 133 ++++ .../component/abstractfield/ReadDesignTest.java | 71 +++ .../abstractfield/RemoveListenersOnDetach.java | 106 ---- .../abstractfield/RemoveListenersOnDetachTest.java | 106 ++++ .../abstractfield/TestAbstractFieldListeners.java | 21 - .../component/abstractfield/TestReadDesign.java | 71 --- .../component/abstractfield/TestWriteDesign.java | 77 --- .../component/abstractfield/WriteDesignTest.java | 77 +++ .../AbstractOrderedLayoutListenersTest.java | 14 + .../LayoutSettingsOnReplace.java | 85 --- .../LayoutSettingsOnReplaceTest.java | 85 +++ .../abstractorderedlayout/ReadDesignTest.java | 119 ++++ .../TestAbstractOrderedLayoutListeners.java | 14 - .../abstractorderedlayout/TestReadDesign.java | 119 ---- .../abstractorderedlayout/TestWriteDesign.java | 148 ----- .../abstractorderedlayout/WriteDesignTest.java | 148 +++++ .../AbstractSelectListenersTest.java | 20 + .../TestAbstractSelectListeners.java | 20 - .../RemoveFromParentLockingTest.java | 125 ++++ .../SetParentAsContent.java | 45 -- .../SetParentAsContentTest.java | 45 ++ .../TestRemoveFromParentLocking.java | 125 ---- .../AbstractSplitPanelListenersTest.java | 14 + .../abstractsplitpanel/ReadDesignTest.java | 158 +++++ .../TestAbstractSplitPanelListeners.java | 14 - .../abstractsplitpanel/TestReadDesign.java | 158 ----- .../abstractsplitpanel/TestWriteDesign.java | 151 ----- .../abstractsplitpanel/WriteDesignTest.java | 151 +++++ .../AbstractTextFieldListenersTest.java | 27 + .../abstracttextfield/ReadDesignTest.java | 73 +++ .../TestAbstractTextFieldListeners.java | 27 - .../abstracttextfield/TestReadDesign.java | 73 --- .../abstracttextfield/TestWriteDesign.java | 73 --- .../abstracttextfield/WriteDesignTest.java | 73 +++ .../tests/server/component/button/ButtonClick.java | 84 --- .../server/component/button/ButtonClickTest.java | 84 +++ .../server/component/button/ButtonListeners.java | 27 - .../component/button/ButtonListenersTest.java | 27 + .../server/component/button/ReadDesignTest.java | 129 ++++ .../server/component/button/TestReadDesign.java | 129 ---- .../server/component/button/TestWriteDesign.java | 103 ---- .../server/component/button/WriteDesignTest.java | 103 ++++ .../server/component/calendar/CalendarBasics.java | 236 ------- .../component/calendar/CalendarBasicsTest.java | 236 +++++++ .../component/calendar/ContainerDataSource.java | 394 ------------ .../calendar/ContainerDataSourceTest.java | 394 ++++++++++++ .../server/component/checkbox/ReadDesignTest.java | 67 ++ .../server/component/checkbox/TestReadDesign.java | 67 -- .../server/component/checkbox/TestWriteDesign.java | 57 -- .../server/component/checkbox/WriteDesignTest.java | 57 ++ .../component/colorpicker/ColorConversions.java | 57 -- .../colorpicker/ColorConversionsTest.java | 57 ++ .../component/csslayout/CssLayoutListeners.java | 13 - .../csslayout/CssLayoutListenersTest.java | 13 + .../server/component/csslayout/ReadDesignTest.java | 74 +++ .../server/component/csslayout/TestReadDesign.java | 74 --- .../component/csslayout/TestWriteDesign.java | 78 --- .../component/csslayout/WriteDesignTest.java | 78 +++ .../component/datefield/DateFieldListeners.java | 20 - .../datefield/DateFieldListenersTest.java | 20 + .../component/embedded/EmbeddedListeners.java | 13 - .../component/embedded/EmbeddedListenersTest.java | 13 + .../fieldgroup/CaseInsensitiveBinding.java | 85 --- .../fieldgroup/CaseInsensitiveBindingTest.java | 85 +++ .../fieldgroup/FieldNamedDescription.java | 53 -- .../fieldgroup/FieldNamedDescriptionTest.java | 53 ++ .../component/gridlayout/DefaultAlignment.java | 45 -- .../component/gridlayout/DefaultAlignmentTest.java | 45 ++ .../component/gridlayout/GridLayoutListeners.java | 13 - .../gridlayout/GridLayoutListenersTest.java | 13 + .../server/component/label/LabelConverters.java | 72 --- .../component/label/LabelConvertersTest.java | 72 +++ .../server/component/label/LabelListeners.java | 92 --- .../server/component/label/LabelListenersTest.java | 92 +++ .../server/component/label/ReadDesignTest.java | 102 ++++ .../server/component/label/TestReadDesign.java | 102 ---- .../server/component/label/TestWriteDesign.java | 126 ---- .../server/component/label/WriteDesignTest.java | 126 ++++ .../component/loginform/LoginFormListeners.java | 13 - .../loginform/LoginFormListenersTest.java | 13 + .../tests/server/component/menubar/MenuBarIds.java | 98 --- .../server/component/menubar/MenuBarIdsTest.java | 98 +++ .../optiongroup/OptionGroupListeners.java | 20 - .../optiongroup/OptionGroupListenersTest.java | 20 + .../component/orderedlayout/DefaultAlignment.java | 67 -- .../orderedlayout/DefaultAlignmentTest.java | 67 ++ .../component/orderedlayout/OrderedLayoutTest.java | 49 ++ .../component/orderedlayout/TestOrderedLayout.java | 49 -- .../server/component/panel/PanelListeners.java | 13 - .../server/component/panel/PanelListenersTest.java | 13 + .../server/component/panel/ReadDesignTest.java | 98 +++ .../server/component/panel/TestReadDesign.java | 98 --- .../server/component/panel/TestWriteDesign.java | 71 --- .../server/component/panel/WriteDesignTest.java | 71 +++ .../component/popupview/PopupViewListeners.java | 14 - .../popupview/PopupViewListenersTest.java | 14 + .../server/component/select/SelectListeners.java | 20 - .../component/select/SelectListenersTest.java | 20 + .../table/CacheUpdateExceptionCauses.java | 55 -- .../table/CacheUpdateExceptionCausesTest.java | 55 ++ .../tests/server/component/table/FooterTest.java | 94 +++ .../component/table/MultipleSelectionTest.java | 57 ++ .../component/table/TableColumnAlignments.java | 143 ----- .../component/table/TableColumnAlignmentsTest.java | 143 +++++ .../server/component/table/TableGenerator.java | 42 -- .../server/component/table/TableGeneratorTest.java | 42 ++ .../server/component/table/TableListeners.java | 41 -- .../server/component/table/TableListenersTest.java | 41 ++ .../table/TablePropertyValueConverter.java | 380 ------------ .../table/TablePropertyValueConverterTest.java | 380 ++++++++++++ .../server/component/table/TableSerialization.java | 25 - .../component/table/TableSerializationTest.java | 25 + .../component/table/TableVisibleColumns.java | 70 --- .../component/table/TableVisibleColumnsTest.java | 70 +++ .../tests/server/component/table/TestFooter.java | 94 --- .../component/table/TestMultipleSelection.java | 57 -- .../server/component/tabsheet/ReadDesignTest.java | 132 ++++ .../component/tabsheet/TabSheetListeners.java | 13 - .../component/tabsheet/TabSheetListenersTest.java | 13 + .../server/component/tabsheet/TabSheetTest.java | 224 +++++++ .../server/component/tabsheet/TestReadDesign.java | 132 ---- .../server/component/tabsheet/TestTabSheet.java | 224 ------- .../server/component/tabsheet/TestWriteDesign.java | 109 ---- .../server/component/tabsheet/WriteDesignTest.java | 109 ++++ .../server/component/textarea/ReadDesignTest.java | 59 ++ .../server/component/textarea/TestReadDesign.java | 59 -- .../server/component/textarea/TestWriteDesign.java | 60 -- .../server/component/textarea/WriteDesignTest.java | 60 ++ .../server/component/textfield/ReadDesignTest.java | 59 ++ .../server/component/textfield/TestReadDesign.java | 59 -- .../component/textfield/TestWriteDesign.java | 59 -- .../TextFieldWithConverterAndValidator.java | 49 -- .../TextFieldWithConverterAndValidatorTest.java | 49 ++ .../textfield/TextFieldWithPropertyFormatter.java | 106 ---- .../TextFieldWithPropertyFormatterTest.java | 106 ++++ .../textfield/TextFieldWithValidator.java | 172 ------ .../textfield/TextFieldWithValidatorTest.java | 172 ++++++ .../component/textfield/WriteDesignTest.java | 59 ++ .../tests/server/component/tree/ListenersTest.java | 137 +++++ .../tests/server/component/tree/TestListeners.java | 137 ----- .../tests/server/component/tree/TreeListeners.java | 27 - .../server/component/tree/TreeListenersTest.java | 27 + .../server/component/treetable/EmptyTreeTable.java | 13 - .../component/treetable/EmptyTreeTableTest.java | 13 + .../treetable/TreeTableSetContainerNull.java | 15 - .../treetable/TreeTableSetContainerNullTest.java | 15 + .../server/component/ui/CustomUIClassLoader.java | 124 ---- .../component/ui/CustomUIClassLoaderTest.java | 124 ++++ .../component/ui/LegacyUIAddRemoveComponents.java | 65 -- .../ui/LegacyUIAddRemoveComponentsTest.java | 65 ++ .../server/component/upload/UploadListeners.java | 41 -- .../component/upload/UploadListenersTest.java | 41 ++ .../component/window/AddRemoveSubWindow.java | 82 --- .../component/window/AddRemoveSubWindowTest.java | 82 +++ .../component/window/AttachDetachWindow.java | 314 ---------- .../component/window/AttachDetachWindowTest.java | 314 ++++++++++ .../server/component/window/WindowAttach.java | 44 -- .../server/component/window/WindowAttachTest.java | 44 ++ .../server/component/window/WindowListeners.java | 34 -- .../component/window/WindowListenersTest.java | 34 ++ .../AbstractIndexedLayoutTest.java | 84 --- .../AbstractIndexedLayoutTestBase.java | 84 +++ .../server/componentcontainer/CssLayoutTest.java | 2 +- .../server/componentcontainer/FormLayoutTest.java | 2 +- .../componentcontainer/VerticalLayoutTest.java | 2 +- .../AbstractFieldValueChangeTestBase.java | 129 ++++ .../components/AbstractTestFieldValueChange.java | 129 ---- .../server/components/ComboBoxValueChangeTest.java | 31 + .../components/GridLayoutLastRowRemovalTest.java | 40 ++ .../server/components/TestComboBoxValueChange.java | 31 - .../components/TestGridLayoutLastRowRemoval.java | 40 -- .../components/TestTextFieldValueChange.java | 125 ---- .../vaadin/tests/server/components/TestWindow.java | 92 --- .../components/TextFieldValueChangeTest.java | 125 ++++ .../vaadin/tests/server/components/WindowTest.java | 92 +++ .../server/validation/BeanValidationTest.java | 125 ++++ .../server/validation/ReadOnlyValidationTest.java | 17 + .../server/validation/TestBeanValidation.java | 125 ---- .../server/validation/TestReadOnlyValidation.java | 17 - .../vaadin/ui/AbsFieldDataSourceLocaleChange.java | 62 -- .../ui/AbsFieldDataSourceLocaleChangeTest.java | 62 ++ server/tests/src/com/vaadin/ui/AbsSelectTest.java | 147 +++++ .../src/com/vaadin/ui/AbstractSelectTest.java | 147 ----- .../tests/src/com/vaadin/ui/LabelDataSource.java | 129 ---- .../src/com/vaadin/ui/LabelDataSourceTest.java | 129 ++++ .../tests/src/com/vaadin/ui/UIThemeEscaping.java | 89 --- .../src/com/vaadin/ui/UIThemeEscapingTest.java | 89 +++ .../src/com/vaadin/util/CurrentInstanceTest.java | 194 ++++++ .../util/ReflectToolsGetFieldValueByType.java | 63 -- .../util/ReflectToolsGetFieldValueByTypeTest.java | 63 ++ .../util/ReflectToolsGetPrimitiveFieldValue.java | 26 - .../ReflectToolsGetPrimitiveFieldValueTest.java | 26 + .../src/com/vaadin/util/TestCurrentInstance.java | 194 ------ 374 files changed, 16734 insertions(+), 16762 deletions(-) delete mode 100644 client/tests/src/com/vaadin/client/ApplicationConnectionTestURLGeneration.java create mode 100644 client/tests/src/com/vaadin/client/ApplicationConnectionURLGenerationTest.java delete mode 100644 client/tests/src/com/vaadin/client/TestVBrowserDetailsUserAgentParser.java create mode 100644 client/tests/src/com/vaadin/client/VBrowserDetailsUserAgentParserTest.java delete mode 100644 server/tests/src/com/vaadin/data/fieldgroup/FieldGroupDate.java create mode 100644 server/tests/src/com/vaadin/data/fieldgroup/FieldGroupDateTest.java delete mode 100644 server/tests/src/com/vaadin/data/util/AbstractBeanContainerTest.java create mode 100644 server/tests/src/com/vaadin/data/util/AbstractBeanContainerTestBase.java delete mode 100644 server/tests/src/com/vaadin/data/util/AbstractContainerTest.java create mode 100644 server/tests/src/com/vaadin/data/util/AbstractContainerTestBase.java delete mode 100644 server/tests/src/com/vaadin/data/util/AbstractHierarchicalContainerTest.java create mode 100644 server/tests/src/com/vaadin/data/util/AbstractHierarchicalContainerTestBase.java delete mode 100644 server/tests/src/com/vaadin/data/util/AbstractInMemoryContainerTest.java create mode 100644 server/tests/src/com/vaadin/data/util/AbstractInMemoryContainerTestBase.java create mode 100644 server/tests/src/com/vaadin/data/util/ContainerHierarchicalWrapperTest.java create mode 100644 server/tests/src/com/vaadin/data/util/ContainerSortingTest.java create mode 100644 server/tests/src/com/vaadin/data/util/HierarchicalContainerTest.java create mode 100644 server/tests/src/com/vaadin/data/util/IndexedContainerTest.java delete mode 100644 server/tests/src/com/vaadin/data/util/MethodPropertyMemoryConsumption.java create mode 100644 server/tests/src/com/vaadin/data/util/MethodPropertyMemoryConsumptionTest.java delete mode 100644 server/tests/src/com/vaadin/data/util/PerformanceTestIndexedContainer.java create mode 100644 server/tests/src/com/vaadin/data/util/PerformanceTestIndexedContainerTest.java delete mode 100644 server/tests/src/com/vaadin/data/util/ReflectToolsGetSuperField.java create mode 100644 server/tests/src/com/vaadin/data/util/ReflectToolsGetSuperFieldTest.java delete mode 100644 server/tests/src/com/vaadin/data/util/TestContainerHierarchicalWrapper.java delete mode 100644 server/tests/src/com/vaadin/data/util/TestContainerSorting.java delete mode 100644 server/tests/src/com/vaadin/data/util/TestHierarchicalContainer.java delete mode 100644 server/tests/src/com/vaadin/data/util/TestIndexedContainer.java delete mode 100644 server/tests/src/com/vaadin/data/util/filter/AbstractFilterTest.java create mode 100644 server/tests/src/com/vaadin/data/util/filter/AbstractFilterTestBase.java create mode 100644 server/tests/src/com/vaadin/tests/data/converter/AnyEnumToStringConverterTest.java delete mode 100644 server/tests/src/com/vaadin/tests/data/converter/ConverterFactory.java create mode 100644 server/tests/src/com/vaadin/tests/data/converter/ConverterFactoryTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/converter/DateToLongConverterTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/converter/DateToSqlDateConverterTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/converter/DefaultConverterFactoryTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/converter/SpecificEnumToStringConverterTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/converter/StringToBigDecimalConverterTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/converter/StringToBigIntegerConverterTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/converter/StringToBooleanConverterTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/converter/StringToByteConverterTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/converter/StringToDateConverterTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/converter/StringToDoubleConverterTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/converter/StringToEnumConverterTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/converter/StringToFloatConverterTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/converter/StringToIntegerConverterTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/converter/StringToLongConverterTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/converter/StringToShortConverterTest.java delete mode 100644 server/tests/src/com/vaadin/tests/data/converter/TestAnyEnumToStringConverter.java delete mode 100644 server/tests/src/com/vaadin/tests/data/converter/TestDateToLongConverter.java delete mode 100644 server/tests/src/com/vaadin/tests/data/converter/TestDateToSqlDateConverter.java delete mode 100644 server/tests/src/com/vaadin/tests/data/converter/TestDefaultConverterFactory.java delete mode 100644 server/tests/src/com/vaadin/tests/data/converter/TestSpecificEnumToStringConverter.java delete mode 100644 server/tests/src/com/vaadin/tests/data/converter/TestStringToBigDecimalConverter.java delete mode 100644 server/tests/src/com/vaadin/tests/data/converter/TestStringToBigIntegerConverter.java delete mode 100644 server/tests/src/com/vaadin/tests/data/converter/TestStringToBooleanConverter.java delete mode 100644 server/tests/src/com/vaadin/tests/data/converter/TestStringToByteConverter.java delete mode 100644 server/tests/src/com/vaadin/tests/data/converter/TestStringToDateConverter.java delete mode 100644 server/tests/src/com/vaadin/tests/data/converter/TestStringToDoubleConverter.java delete mode 100644 server/tests/src/com/vaadin/tests/data/converter/TestStringToEnumConverter.java delete mode 100644 server/tests/src/com/vaadin/tests/data/converter/TestStringToFloatConverter.java delete mode 100644 server/tests/src/com/vaadin/tests/data/converter/TestStringToIntegerConverter.java delete mode 100644 server/tests/src/com/vaadin/tests/data/converter/TestStringToLongConverter.java delete mode 100644 server/tests/src/com/vaadin/tests/data/converter/TestStringToShortConverter.java create mode 100644 server/tests/src/com/vaadin/tests/data/validator/BigDecimalRangeValidatorTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/validator/BigIntegerRangeValidatorTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/validator/ByteRangeValidatorTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/validator/CompositeValidatorTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/validator/DateRangeValidatorTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/validator/DoubleRangeValidatorTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/validator/EmailValidatorTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/validator/FloatRangeValidatorTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/validator/IntegerRangeValidatorTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/validator/LongRangeValidatorTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/validator/NullValidatorTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/validator/RegexpValidatorTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/validator/ShortRangeValidatorTest.java create mode 100644 server/tests/src/com/vaadin/tests/data/validator/StringLengthValidatorTest.java delete mode 100644 server/tests/src/com/vaadin/tests/data/validator/TestBigDecimalRangeValidator.java delete mode 100644 server/tests/src/com/vaadin/tests/data/validator/TestBigIntegerRangeValidator.java delete mode 100644 server/tests/src/com/vaadin/tests/data/validator/TestByteRangeValidator.java delete mode 100644 server/tests/src/com/vaadin/tests/data/validator/TestCompositeValidator.java delete mode 100644 server/tests/src/com/vaadin/tests/data/validator/TestDateRangeValidator.java delete mode 100644 server/tests/src/com/vaadin/tests/data/validator/TestDoubleRangeValidator.java delete mode 100644 server/tests/src/com/vaadin/tests/data/validator/TestEmailValidator.java delete mode 100644 server/tests/src/com/vaadin/tests/data/validator/TestFloatRangeValidator.java delete mode 100644 server/tests/src/com/vaadin/tests/data/validator/TestIntegerRangeValidator.java delete mode 100644 server/tests/src/com/vaadin/tests/data/validator/TestLongRangeValidator.java delete mode 100644 server/tests/src/com/vaadin/tests/data/validator/TestNullValidator.java delete mode 100644 server/tests/src/com/vaadin/tests/data/validator/TestRegexpValidator.java delete mode 100644 server/tests/src/com/vaadin/tests/data/validator/TestShortRangeValidator.java delete mode 100644 server/tests/src/com/vaadin/tests/data/validator/TestStringLengthValidator.java create mode 100644 server/tests/src/com/vaadin/tests/server/AbstractBeanContainerListenersTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/AbstractContainerListenersTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/AbstractInMemoryContainerListenersTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/AbstractPropertyListenersTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/AssertionsEnabledTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/AtmosphereVersionTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/ClassesSerializableTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/ClientMethodSerializationTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/CsrfTokenMissingTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/CsrfTokenMissingTestServer.java create mode 100644 server/tests/src/com/vaadin/tests/server/EventRouterTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/FileTypeResolverTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/IndexedContainerListeners.java create mode 100644 server/tests/src/com/vaadin/tests/server/IndexedContainerListenersTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/KeyMapperTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/MimeTypesTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/PropertyFormatterTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/PropertysetItemListeners.java create mode 100644 server/tests/src/com/vaadin/tests/server/PropertysetItemListenersTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/SerializationTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/SimpleMultiPartInputStreamTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/StreamResourceTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/StreamVariableMappingTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/TestAbstractBeanContainerListeners.java delete mode 100644 server/tests/src/com/vaadin/tests/server/TestAbstractContainerListeners.java delete mode 100644 server/tests/src/com/vaadin/tests/server/TestAbstractInMemoryContainerListeners.java delete mode 100644 server/tests/src/com/vaadin/tests/server/TestAbstractPropertyListeners.java delete mode 100644 server/tests/src/com/vaadin/tests/server/TestAssertionsEnabled.java delete mode 100644 server/tests/src/com/vaadin/tests/server/TestAtmosphereVersion.java delete mode 100644 server/tests/src/com/vaadin/tests/server/TestClassesSerializable.java delete mode 100644 server/tests/src/com/vaadin/tests/server/TestClientMethodSerialization.java delete mode 100644 server/tests/src/com/vaadin/tests/server/TestEventRouter.java delete mode 100644 server/tests/src/com/vaadin/tests/server/TestFileTypeResolver.java delete mode 100644 server/tests/src/com/vaadin/tests/server/TestKeyMapper.java delete mode 100644 server/tests/src/com/vaadin/tests/server/TestMimeTypes.java delete mode 100644 server/tests/src/com/vaadin/tests/server/TestPropertyFormatter.java delete mode 100644 server/tests/src/com/vaadin/tests/server/TestSerialization.java delete mode 100644 server/tests/src/com/vaadin/tests/server/TestSimpleMultiPartInputStream.java delete mode 100644 server/tests/src/com/vaadin/tests/server/TestStreamResource.java delete mode 100644 server/tests/src/com/vaadin/tests/server/TestStreamVariableMapping.java delete mode 100644 server/tests/src/com/vaadin/tests/server/clientconnector/AttachDetachListeners.java create mode 100644 server/tests/src/com/vaadin/tests/server/clientconnector/AttachDetachListenersTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/AbstractListenerMethodsTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/AbstractListenerMethodsTestBase.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/ReadEmptyDesignTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/StateGetDoesNotMarkDirty.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/StateGetDoesNotMarkDirtyTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/TestReadEmptyDesign.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/TestWriteEmptyDesign.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/WriteEmptyDesignTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/absolutelayout/AbsoluteLayoutListeners.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/absolutelayout/AbsoluteLayoutListenersTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/absolutelayout/ComponentPosition.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/absolutelayout/ComponentPositionTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/absolutelayout/ReadDesignTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/absolutelayout/TestReadDesign.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/absolutelayout/TestWriteDesign.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/absolutelayout/WriteDesignTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractcomponent/AbstractComponentStyleNamesTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractcomponent/ReadDesignTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractcomponent/TestAbstractComponentStyleNames.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractcomponent/TestReadDesign.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractcomponent/TestWriteDesign.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractcomponent/WriteDesignTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractcomponentcontainer/AbstractComponentContainerListenersTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractcomponentcontainer/AddParentAsChild.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractcomponentcontainer/AddParentAsChildTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractcomponentcontainer/TestAbstractComponentContainerListeners.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractfield/AbsFieldValidators.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractfield/AbsFieldValidatorsTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractfield/AbsFieldValueConversionError.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractfield/AbsFieldValueConversionErrorTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractfield/AbsFieldValueConversions.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractfield/AbsFieldValueConversionsTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractfield/AbstractFieldListenersTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractfield/DefaultConverterFactory.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractfield/DefaultConverterFactoryTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractfield/ReadDesignTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractfield/RemoveListenersOnDetach.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractfield/RemoveListenersOnDetachTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractfield/TestAbstractFieldListeners.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractfield/TestReadDesign.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractfield/TestWriteDesign.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractfield/WriteDesignTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/AbstractOrderedLayoutListenersTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/LayoutSettingsOnReplace.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/LayoutSettingsOnReplaceTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/ReadDesignTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/TestAbstractOrderedLayoutListeners.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/TestReadDesign.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/TestWriteDesign.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/WriteDesignTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractselect/AbstractSelectListenersTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractselect/TestAbstractSelectListeners.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractsinglecomponentcontainer/RemoveFromParentLockingTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractsinglecomponentcontainer/SetParentAsContent.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractsinglecomponentcontainer/SetParentAsContentTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractsinglecomponentcontainer/TestRemoveFromParentLocking.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractsplitpanel/AbstractSplitPanelListenersTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractsplitpanel/ReadDesignTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractsplitpanel/TestAbstractSplitPanelListeners.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractsplitpanel/TestReadDesign.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractsplitpanel/TestWriteDesign.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstractsplitpanel/WriteDesignTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstracttextfield/AbstractTextFieldListenersTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstracttextfield/ReadDesignTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstracttextfield/TestAbstractTextFieldListeners.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstracttextfield/TestReadDesign.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/abstracttextfield/TestWriteDesign.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/abstracttextfield/WriteDesignTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/button/ButtonClick.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/button/ButtonClickTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/button/ButtonListeners.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/button/ButtonListenersTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/button/ReadDesignTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/button/TestReadDesign.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/button/TestWriteDesign.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/button/WriteDesignTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/calendar/CalendarBasics.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/calendar/CalendarBasicsTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/calendar/ContainerDataSource.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/calendar/ContainerDataSourceTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/checkbox/ReadDesignTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/checkbox/TestReadDesign.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/checkbox/TestWriteDesign.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/checkbox/WriteDesignTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/colorpicker/ColorConversions.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/colorpicker/ColorConversionsTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/csslayout/CssLayoutListeners.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/csslayout/CssLayoutListenersTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/csslayout/ReadDesignTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/csslayout/TestReadDesign.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/csslayout/TestWriteDesign.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/csslayout/WriteDesignTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/datefield/DateFieldListeners.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/datefield/DateFieldListenersTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/embedded/EmbeddedListeners.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/embedded/EmbeddedListenersTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/fieldgroup/CaseInsensitiveBinding.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/fieldgroup/CaseInsensitiveBindingTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/fieldgroup/FieldNamedDescription.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/fieldgroup/FieldNamedDescriptionTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/gridlayout/DefaultAlignment.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/gridlayout/DefaultAlignmentTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/gridlayout/GridLayoutListeners.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/gridlayout/GridLayoutListenersTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/label/LabelConverters.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/label/LabelConvertersTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/label/LabelListeners.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/label/LabelListenersTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/label/ReadDesignTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/label/TestReadDesign.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/label/TestWriteDesign.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/label/WriteDesignTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/loginform/LoginFormListeners.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/loginform/LoginFormListenersTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/menubar/MenuBarIds.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/menubar/MenuBarIdsTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/optiongroup/OptionGroupListeners.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/optiongroup/OptionGroupListenersTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/orderedlayout/DefaultAlignment.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/orderedlayout/DefaultAlignmentTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/orderedlayout/OrderedLayoutTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/orderedlayout/TestOrderedLayout.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/panel/PanelListeners.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/panel/PanelListenersTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/panel/ReadDesignTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/panel/TestReadDesign.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/panel/TestWriteDesign.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/panel/WriteDesignTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/popupview/PopupViewListeners.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/popupview/PopupViewListenersTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/select/SelectListeners.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/select/SelectListenersTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/table/CacheUpdateExceptionCauses.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/table/CacheUpdateExceptionCausesTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/table/FooterTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/table/MultipleSelectionTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/table/TableColumnAlignments.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/table/TableColumnAlignmentsTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/table/TableGenerator.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/table/TableGeneratorTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/table/TableListeners.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/table/TableListenersTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/table/TablePropertyValueConverter.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/table/TablePropertyValueConverterTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/table/TableSerialization.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/table/TableSerializationTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/table/TableVisibleColumns.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/table/TableVisibleColumnsTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/table/TestFooter.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/table/TestMultipleSelection.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/tabsheet/ReadDesignTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/tabsheet/TabSheetListeners.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/tabsheet/TabSheetListenersTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/tabsheet/TabSheetTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/tabsheet/TestReadDesign.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/tabsheet/TestTabSheet.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/tabsheet/TestWriteDesign.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/tabsheet/WriteDesignTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/textarea/ReadDesignTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/textarea/TestReadDesign.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/textarea/TestWriteDesign.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/textarea/WriteDesignTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/textfield/ReadDesignTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/textfield/TestReadDesign.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/textfield/TestWriteDesign.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/textfield/TextFieldWithConverterAndValidator.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/textfield/TextFieldWithConverterAndValidatorTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/textfield/TextFieldWithPropertyFormatter.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/textfield/TextFieldWithPropertyFormatterTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/textfield/TextFieldWithValidator.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/textfield/TextFieldWithValidatorTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/textfield/WriteDesignTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/tree/ListenersTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/tree/TestListeners.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/tree/TreeListeners.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/tree/TreeListenersTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/treetable/EmptyTreeTable.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/treetable/EmptyTreeTableTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/treetable/TreeTableSetContainerNull.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/treetable/TreeTableSetContainerNullTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/ui/CustomUIClassLoader.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/ui/CustomUIClassLoaderTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/ui/LegacyUIAddRemoveComponents.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/ui/LegacyUIAddRemoveComponentsTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/upload/UploadListeners.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/upload/UploadListenersTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/window/AddRemoveSubWindow.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/window/AddRemoveSubWindowTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/window/AttachDetachWindow.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/window/AttachDetachWindowTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/window/WindowAttach.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/window/WindowAttachTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/component/window/WindowListeners.java create mode 100644 server/tests/src/com/vaadin/tests/server/component/window/WindowListenersTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/componentcontainer/AbstractIndexedLayoutTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/componentcontainer/AbstractIndexedLayoutTestBase.java create mode 100644 server/tests/src/com/vaadin/tests/server/components/AbstractFieldValueChangeTestBase.java delete mode 100644 server/tests/src/com/vaadin/tests/server/components/AbstractTestFieldValueChange.java create mode 100644 server/tests/src/com/vaadin/tests/server/components/ComboBoxValueChangeTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/components/GridLayoutLastRowRemovalTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/components/TestComboBoxValueChange.java delete mode 100644 server/tests/src/com/vaadin/tests/server/components/TestGridLayoutLastRowRemoval.java delete mode 100644 server/tests/src/com/vaadin/tests/server/components/TestTextFieldValueChange.java delete mode 100644 server/tests/src/com/vaadin/tests/server/components/TestWindow.java create mode 100644 server/tests/src/com/vaadin/tests/server/components/TextFieldValueChangeTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/components/WindowTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/validation/BeanValidationTest.java create mode 100644 server/tests/src/com/vaadin/tests/server/validation/ReadOnlyValidationTest.java delete mode 100644 server/tests/src/com/vaadin/tests/server/validation/TestBeanValidation.java delete mode 100644 server/tests/src/com/vaadin/tests/server/validation/TestReadOnlyValidation.java delete mode 100644 server/tests/src/com/vaadin/ui/AbsFieldDataSourceLocaleChange.java create mode 100644 server/tests/src/com/vaadin/ui/AbsFieldDataSourceLocaleChangeTest.java create mode 100644 server/tests/src/com/vaadin/ui/AbsSelectTest.java delete mode 100644 server/tests/src/com/vaadin/ui/AbstractSelectTest.java delete mode 100644 server/tests/src/com/vaadin/ui/LabelDataSource.java create mode 100644 server/tests/src/com/vaadin/ui/LabelDataSourceTest.java delete mode 100644 server/tests/src/com/vaadin/ui/UIThemeEscaping.java create mode 100644 server/tests/src/com/vaadin/ui/UIThemeEscapingTest.java create mode 100644 server/tests/src/com/vaadin/util/CurrentInstanceTest.java delete mode 100644 server/tests/src/com/vaadin/util/ReflectToolsGetFieldValueByType.java create mode 100644 server/tests/src/com/vaadin/util/ReflectToolsGetFieldValueByTypeTest.java delete mode 100644 server/tests/src/com/vaadin/util/ReflectToolsGetPrimitiveFieldValue.java create mode 100644 server/tests/src/com/vaadin/util/ReflectToolsGetPrimitiveFieldValueTest.java delete mode 100644 server/tests/src/com/vaadin/util/TestCurrentInstance.java (limited to 'client') diff --git a/client/tests/src/com/vaadin/client/ApplicationConnectionTestURLGeneration.java b/client/tests/src/com/vaadin/client/ApplicationConnectionTestURLGeneration.java deleted file mode 100644 index cb4f1f4068..0000000000 --- a/client/tests/src/com/vaadin/client/ApplicationConnectionTestURLGeneration.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.vaadin.client; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class ApplicationConnectionTestURLGeneration { - - private static final String[] URIS = new String[] { - "http://demo.vaadin.com/", // - "https://demo.vaadin.com/", - "http://demo.vaadin.com/foo", - "http://demo.vaadin.com/foo?f", - "http://demo.vaadin.com/foo?f=1", - "http://demo.vaadin.com:1234/foo?a", - "http://demo.vaadin.com:1234/foo#frag?fakeparam", - // Jetspeed - "http://localhost:8080/jetspeed/portal/_ns:Z3RlbXBsYXRlLXRvcDJfX3BhZ2UtdGVtcGxhdGVfX2RwLTFfX1AtMTJjNTRkYjdlYjUtMTAwMDJ8YzB8ZDF8aVVJREx8Zg__", - // Liferay generated url - "http://vaadin.com/directory?p_p_id=Directory_WAR_Directory&p_p_lifecycle=2&p_p_state=normal&p_p_mode=view&p_p_resource_id=UIDL&p_p_cacheability=cacheLevelPage&p_p_col_id=row-1&p_p_col_count=1", - - }; - private static final String[] URIS_WITH_ABCD_PARAM = new String[] { - "http://demo.vaadin.com/?a=b&c=d", - "https://demo.vaadin.com/?a=b&c=d", - "http://demo.vaadin.com/foo?a=b&c=d", - "http://demo.vaadin.com/foo?f&a=b&c=d", - "http://demo.vaadin.com/foo?f=1&a=b&c=d", - "http://demo.vaadin.com:1234/foo?a&a=b&c=d", - "http://demo.vaadin.com:1234/foo?a=b&c=d#frag?fakeparam", - "http://localhost:8080/jetspeed/portal/_ns:Z3RlbXBsYXRlLXRvcDJfX3BhZ2UtdGVtcGxhdGVfX2RwLTFfX1AtMTJjNTRkYjdlYjUtMTAwMDJ8YzB8ZDF8aVVJREx8Zg__?a=b&c=d", - "http://vaadin.com/directory?p_p_id=Directory_WAR_Directory&p_p_lifecycle=2&p_p_state=normal&p_p_mode=view&p_p_resource_id=UIDL&p_p_cacheability=cacheLevelPage&p_p_col_id=row-1&p_p_col_count=1&a=b&c=d", - - }; - - private static final String[] URIS_WITH_ABCD_PARAM_AND_FRAGMENT = new String[] { - "http://demo.vaadin.com/?a=b&c=d#fragment", - "https://demo.vaadin.com/?a=b&c=d#fragment", - "http://demo.vaadin.com/foo?a=b&c=d#fragment", - "http://demo.vaadin.com/foo?f&a=b&c=d#fragment", - "http://demo.vaadin.com/foo?f=1&a=b&c=d#fragment", - "http://demo.vaadin.com:1234/foo?a&a=b&c=d#fragment", - "", - "http://localhost:8080/jetspeed/portal/_ns:Z3RlbXBsYXRlLXRvcDJfX3BhZ2UtdGVtcGxhdGVfX2RwLTFfX1AtMTJjNTRkYjdlYjUtMTAwMDJ8YzB8ZDF8aVVJREx8Zg__?a=b&c=d#fragment", - "http://vaadin.com/directory?p_p_id=Directory_WAR_Directory&p_p_lifecycle=2&p_p_state=normal&p_p_mode=view&p_p_resource_id=UIDL&p_p_cacheability=cacheLevelPage&p_p_col_id=row-1&p_p_col_count=1&a=b&c=d#fragment", - - }; - - @Test - public void testParameterAdding() { - for (int i = 0; i < URIS.length; i++) { - // Adding nothing - assertEquals(URIS[i], - ApplicationConnection.addGetParameters(URIS[i], "")); - - // Adding a=b&c=d - assertEquals(URIS_WITH_ABCD_PARAM[i], - ApplicationConnection.addGetParameters(URIS[i], "a=b&c=d")); - - // Fragments - if (URIS_WITH_ABCD_PARAM_AND_FRAGMENT[i].length() > 0) { - assertEquals( - URIS_WITH_ABCD_PARAM_AND_FRAGMENT[i], - ApplicationConnection.addGetParameters(URIS[i] - + "#fragment", "a=b&c=d")); - - // Empty fragment - assertEquals(URIS_WITH_ABCD_PARAM_AND_FRAGMENT[i].replace( - "#fragment", "#"), - ApplicationConnection.addGetParameters(URIS[i] + "#", - "a=b&c=d")); - } - } - } -} diff --git a/client/tests/src/com/vaadin/client/ApplicationConnectionURLGenerationTest.java b/client/tests/src/com/vaadin/client/ApplicationConnectionURLGenerationTest.java new file mode 100644 index 0000000000..36baa163cb --- /dev/null +++ b/client/tests/src/com/vaadin/client/ApplicationConnectionURLGenerationTest.java @@ -0,0 +1,75 @@ +package com.vaadin.client; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class ApplicationConnectionURLGenerationTest { + + private static final String[] URIS = new String[] { + "http://demo.vaadin.com/", // + "https://demo.vaadin.com/", + "http://demo.vaadin.com/foo", + "http://demo.vaadin.com/foo?f", + "http://demo.vaadin.com/foo?f=1", + "http://demo.vaadin.com:1234/foo?a", + "http://demo.vaadin.com:1234/foo#frag?fakeparam", + // Jetspeed + "http://localhost:8080/jetspeed/portal/_ns:Z3RlbXBsYXRlLXRvcDJfX3BhZ2UtdGVtcGxhdGVfX2RwLTFfX1AtMTJjNTRkYjdlYjUtMTAwMDJ8YzB8ZDF8aVVJREx8Zg__", + // Liferay generated url + "http://vaadin.com/directory?p_p_id=Directory_WAR_Directory&p_p_lifecycle=2&p_p_state=normal&p_p_mode=view&p_p_resource_id=UIDL&p_p_cacheability=cacheLevelPage&p_p_col_id=row-1&p_p_col_count=1", + + }; + private static final String[] URIS_WITH_ABCD_PARAM = new String[] { + "http://demo.vaadin.com/?a=b&c=d", + "https://demo.vaadin.com/?a=b&c=d", + "http://demo.vaadin.com/foo?a=b&c=d", + "http://demo.vaadin.com/foo?f&a=b&c=d", + "http://demo.vaadin.com/foo?f=1&a=b&c=d", + "http://demo.vaadin.com:1234/foo?a&a=b&c=d", + "http://demo.vaadin.com:1234/foo?a=b&c=d#frag?fakeparam", + "http://localhost:8080/jetspeed/portal/_ns:Z3RlbXBsYXRlLXRvcDJfX3BhZ2UtdGVtcGxhdGVfX2RwLTFfX1AtMTJjNTRkYjdlYjUtMTAwMDJ8YzB8ZDF8aVVJREx8Zg__?a=b&c=d", + "http://vaadin.com/directory?p_p_id=Directory_WAR_Directory&p_p_lifecycle=2&p_p_state=normal&p_p_mode=view&p_p_resource_id=UIDL&p_p_cacheability=cacheLevelPage&p_p_col_id=row-1&p_p_col_count=1&a=b&c=d", + + }; + + private static final String[] URIS_WITH_ABCD_PARAM_AND_FRAGMENT = new String[] { + "http://demo.vaadin.com/?a=b&c=d#fragment", + "https://demo.vaadin.com/?a=b&c=d#fragment", + "http://demo.vaadin.com/foo?a=b&c=d#fragment", + "http://demo.vaadin.com/foo?f&a=b&c=d#fragment", + "http://demo.vaadin.com/foo?f=1&a=b&c=d#fragment", + "http://demo.vaadin.com:1234/foo?a&a=b&c=d#fragment", + "", + "http://localhost:8080/jetspeed/portal/_ns:Z3RlbXBsYXRlLXRvcDJfX3BhZ2UtdGVtcGxhdGVfX2RwLTFfX1AtMTJjNTRkYjdlYjUtMTAwMDJ8YzB8ZDF8aVVJREx8Zg__?a=b&c=d#fragment", + "http://vaadin.com/directory?p_p_id=Directory_WAR_Directory&p_p_lifecycle=2&p_p_state=normal&p_p_mode=view&p_p_resource_id=UIDL&p_p_cacheability=cacheLevelPage&p_p_col_id=row-1&p_p_col_count=1&a=b&c=d#fragment", + + }; + + @Test + public void testParameterAdding() { + for (int i = 0; i < URIS.length; i++) { + // Adding nothing + assertEquals(URIS[i], + ApplicationConnection.addGetParameters(URIS[i], "")); + + // Adding a=b&c=d + assertEquals(URIS_WITH_ABCD_PARAM[i], + ApplicationConnection.addGetParameters(URIS[i], "a=b&c=d")); + + // Fragments + if (URIS_WITH_ABCD_PARAM_AND_FRAGMENT[i].length() > 0) { + assertEquals( + URIS_WITH_ABCD_PARAM_AND_FRAGMENT[i], + ApplicationConnection.addGetParameters(URIS[i] + + "#fragment", "a=b&c=d")); + + // Empty fragment + assertEquals(URIS_WITH_ABCD_PARAM_AND_FRAGMENT[i].replace( + "#fragment", "#"), + ApplicationConnection.addGetParameters(URIS[i] + "#", + "a=b&c=d")); + } + } + } +} diff --git a/client/tests/src/com/vaadin/client/TestVBrowserDetailsUserAgentParser.java b/client/tests/src/com/vaadin/client/TestVBrowserDetailsUserAgentParser.java deleted file mode 100644 index cb70fc7a39..0000000000 --- a/client/tests/src/com/vaadin/client/TestVBrowserDetailsUserAgentParser.java +++ /dev/null @@ -1,588 +0,0 @@ -package com.vaadin.client; - -import junit.framework.TestCase; - -import org.junit.Assert; - -import com.vaadin.shared.VBrowserDetails; - -public class TestVBrowserDetailsUserAgentParser extends TestCase { - - private static final String FIREFOX30_WINDOWS = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6"; - private static final String FIREFOX30_LINUX = "Mozilla/5.0 (X11; U; Linux x86_64; es-ES; rv:1.9.0.12) Gecko/2009070811 Ubuntu/9.04 (jaunty) Firefox/3.0.12"; - private static final String FIREFOX33_ANDROID = "Mozilla/5.0 (Android; Tablet; rv:33.0) Gecko/33.0 Firefox/33.0"; - private static final String FIREFOX35_WINDOWS = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.8) Gecko/20100202 Firefox/3.5.8 (.NET CLR 3.5.30729) FirePHP/0.4"; - private static final String FIREFOX36_WINDOWS = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)"; - private static final String FIREFOX36B_MAC = "UAString mozilla/5.0 (macintosh; u; intel mac os x 10.6; en-us; rv:1.9.2) gecko/20100115 firefox/3.6"; - private static final String FIREFOX_30B5_MAC = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9b5) Gecko/2008032619 Firefox/3.0b5"; - private static final String FIREFOX_40B7_WIN = "Mozilla/5.0 (Windows NT 5.1; rv:2.0b7) Gecko/20100101 Firefox/4.0b7"; - private static final String FIREFOX_40B11_WIN = "Mozilla/5.0 (Windows NT 5.1; rv:2.0b11) Gecko/20100101 Firefox/4.0b11"; - private static final String KONQUEROR_LINUX = "Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Exabot-Thumbnails)"; - - private static final String IE6_WINDOWS = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)"; - private static final String IE7_WINDOWS = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"; - - private static final String IE8_WINDOWS = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; InfoPath.2)"; - private static final String IE8_IN_IE7_MODE_WINDOWS = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; InfoPath.2)"; - - private static final String IE9_IN_IE7_MODE_WINDOWS_7 = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)"; - private static final String IE9_BETA_IN_IE8_MODE_WINDOWS_7 = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)"; - private static final String IE9_BETA_WINDOWS_7 = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"; - - private static final String IE10_WINDOWS_8 = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"; - private static final String IE11_WINDOWS_7 = "Mozilla/5.0 (Windows NT 6.1; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; rv:11.0) like Gecko"; - private static final String IE11_WINDOWS_PHONE_8_1_UPDATE = "Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 920) Like iPhone OS 7_0_3 Mac OS X AppleWebKit/537 (KHTML, like Gecko) Mobile Safari/537"; - - // "Version/" was added in 10.00 - private static final String OPERA964_WINDOWS = "Opera/9.64(Windows NT 5.1; U; en) Presto/2.1.1"; - private static final String OPERA1010_WINDOWS = "Opera/9.80 (Windows NT 5.1; U; en) Presto/2.2.15 Version/10.10"; - private static final String OPERA1050_WINDOWS = "Opera/9.80 (Windows NT 5.1; U; en) Presto/2.5.22 Version/10.50"; - - private static final String CHROME3_MAC = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; en-US) AppleWebKit/532.0 (KHTML, like Gecko) Chrome/3.0.198 Safari/532.0"; - private static final String CHROME4_WINDOWS = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.0.249.89 Safari/532.5"; - - private static final String SAFARI3_WINDOWS = "Mozilla/5.0 (Windows; U; Windows NT 5.1; cs-CZ) AppleWebKit/525.28.3 (KHTML, like Gecko) Version/3.2.3 Safari/525.29"; - private static final String SAFARI4_MAC = "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_5_8; en-us) AppleWebKit/531.22.7 (KHTML, like Gecko) Version/4.0.5 Safari/531.22.7"; - - private static final String IPHONE_IOS_5_1 = "Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B179 Safari/7534.48.3"; - private static final String IPHONE_IOS_4_0 = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7"; - private static final String IPAD_IOS_4_3_1 = "Mozilla/5.0 (iPad; U; CPU OS 4_3_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8G4 Safari/6533.18.5"; - - // application on the home screen, without Safari in user agent - private static final String IPHONE_IOS_6_1_HOMESCREEN_SIMULATOR = "Mozilla/5.0 (iPhone; CPU iPhone OS 6_1 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Mobile/10B141"; - - private static final String ANDROID_HTC_2_1 = "Mozilla/5.0 (Linux; U; Android 2.1-update1; en-us; ADR6300 Build/ERE27) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17"; - private static final String ANDROID_GOOGLE_NEXUS_2_2 = "Mozilla/5.0 (Linux; U; Android 2.2; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"; - private static final String ANDROID_MOTOROLA_3_0 = "Mozilla/5.0 (Linux; U; Android 3.0; en-us; Xoom Build/HRI39) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13"; - private static final String ANDROID_GALAXY_NEXUS_4_0_4_CHROME = "Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19"; - - public void testSafari3() { - VBrowserDetails bd = new VBrowserDetails(SAFARI3_WINDOWS); - assertWebKit(bd); - assertSafari(bd); - assertBrowserMajorVersion(bd, 3); - assertBrowserMinorVersion(bd, 2); - assertEngineVersion(bd, 525.0f); - assertWindows(bd); - } - - public void testSafari4() { - VBrowserDetails bd = new VBrowserDetails(SAFARI4_MAC); - assertWebKit(bd); - assertSafari(bd); - assertBrowserMajorVersion(bd, 4); - assertBrowserMinorVersion(bd, 0); - assertEngineVersion(bd, 531f); - assertMacOSX(bd); - } - - public void testIPhoneIOS6Homescreen() { - VBrowserDetails bd = new VBrowserDetails( - IPHONE_IOS_6_1_HOMESCREEN_SIMULATOR); - assertWebKit(bd); - // not identified as Safari, no browser version available - // assertSafari(bd); - // assertBrowserMajorVersion(bd, 6); - // assertBrowserMinorVersion(bd, 1); - assertEngineVersion(bd, 536f); - assertIOS(bd, 6, 1); - assertIPhone(bd); - } - - public void testIPhoneIOS5() { - VBrowserDetails bd = new VBrowserDetails(IPHONE_IOS_5_1); - assertWebKit(bd); - assertSafari(bd); - assertBrowserMajorVersion(bd, 5); - assertBrowserMinorVersion(bd, 1); - assertEngineVersion(bd, 534f); - assertIOS(bd, 5, 1); - assertIPhone(bd); - } - - public void testIPhoneIOS4() { - VBrowserDetails bd = new VBrowserDetails(IPHONE_IOS_4_0); - assertWebKit(bd); - assertSafari(bd); - assertBrowserMajorVersion(bd, 4); - assertBrowserMinorVersion(bd, 0); - assertEngineVersion(bd, 532f); - assertIOS(bd, 4, 0); - assertIPhone(bd); - } - - public void testIPadIOS4() { - VBrowserDetails bd = new VBrowserDetails(IPAD_IOS_4_3_1); - assertWebKit(bd); - assertSafari(bd); - assertBrowserMajorVersion(bd, 5); - assertBrowserMinorVersion(bd, 0); - assertEngineVersion(bd, 533f); - assertIOS(bd, 4, 3); - assertIPad(bd); - } - - public void testAndroid21() { - VBrowserDetails bd = new VBrowserDetails(ANDROID_HTC_2_1); - assertWebKit(bd); - assertSafari(bd); - assertBrowserMajorVersion(bd, 4); - assertBrowserMinorVersion(bd, 0); - assertEngineVersion(bd, 530f); - assertAndroid(bd, 2, 1); - - } - - public void testAndroid22() { - VBrowserDetails bd = new VBrowserDetails(ANDROID_GOOGLE_NEXUS_2_2); - assertWebKit(bd); - assertSafari(bd); - assertBrowserMajorVersion(bd, 4); - assertBrowserMinorVersion(bd, 0); - assertEngineVersion(bd, 533f); - assertAndroid(bd, 2, 2); - } - - public void testAndroid30() { - VBrowserDetails bd = new VBrowserDetails(ANDROID_MOTOROLA_3_0); - assertWebKit(bd); - assertSafari(bd); - assertBrowserMajorVersion(bd, 4); - assertBrowserMinorVersion(bd, 0); - assertEngineVersion(bd, 534f); - assertAndroid(bd, 3, 0); - } - - public void testAndroid40Chrome() { - VBrowserDetails bd = new VBrowserDetails( - ANDROID_GALAXY_NEXUS_4_0_4_CHROME); - assertWebKit(bd); - assertChrome(bd); - assertBrowserMajorVersion(bd, 18); - assertBrowserMinorVersion(bd, 0); - assertEngineVersion(bd, 535f); - assertAndroid(bd, 4, 0); - } - - private void assertOSMajorVersion(VBrowserDetails bd, int i) { - assertEquals(i, bd.getOperatingSystemMajorVersion()); - } - - private void assertOSMinorVersion(VBrowserDetails bd, int i) { - assertEquals(i, bd.getOperatingSystemMinorVersion()); - } - - public void testChrome3() { - VBrowserDetails bd = new VBrowserDetails(CHROME3_MAC); - assertWebKit(bd); - assertChrome(bd); - assertBrowserMajorVersion(bd, 3); - assertBrowserMinorVersion(bd, 0); - assertEngineVersion(bd, 532.0f); - assertMacOSX(bd); - } - - public void testChrome4() { - VBrowserDetails bd = new VBrowserDetails(CHROME4_WINDOWS); - assertWebKit(bd); - assertChrome(bd); - assertBrowserMajorVersion(bd, 4); - assertBrowserMinorVersion(bd, 0); - assertEngineVersion(bd, 532f); - assertWindows(bd); - } - - public void testFirefox3() { - VBrowserDetails bd = new VBrowserDetails(FIREFOX30_WINDOWS); - assertGecko(bd); - assertFirefox(bd); - assertBrowserMajorVersion(bd, 3); - assertBrowserMinorVersion(bd, 0); - assertEngineVersion(bd, 1.9f); - assertWindows(bd); - - bd = new VBrowserDetails(FIREFOX30_LINUX); - assertGecko(bd); - assertFirefox(bd); - assertBrowserMajorVersion(bd, 3); - assertBrowserMinorVersion(bd, 0); - assertEngineVersion(bd, 1.9f); - assertLinux(bd); - } - - public void testFirefox33Android() { - VBrowserDetails bd = new VBrowserDetails(FIREFOX33_ANDROID); - assertGecko(bd); - assertFirefox(bd); - assertBrowserMajorVersion(bd, 33); - assertBrowserMinorVersion(bd, 0); - assertAndroid(bd, -1, -1); - } - - public void testFirefox35() { - VBrowserDetails bd = new VBrowserDetails(FIREFOX35_WINDOWS); - assertGecko(bd); - assertFirefox(bd); - assertBrowserMajorVersion(bd, 3); - assertBrowserMinorVersion(bd, 5); - assertEngineVersion(bd, 1.9f); - assertWindows(bd); - } - - public void testFirefox36() { - VBrowserDetails bd = new VBrowserDetails(FIREFOX36_WINDOWS); - assertGecko(bd); - assertFirefox(bd); - assertBrowserMajorVersion(bd, 3); - assertBrowserMinorVersion(bd, 6); - assertEngineVersion(bd, 1.9f); - assertWindows(bd); - } - - public void testFirefox30b5() { - VBrowserDetails bd = new VBrowserDetails(FIREFOX_30B5_MAC); - assertGecko(bd); - assertFirefox(bd); - assertBrowserMajorVersion(bd, 3); - assertBrowserMinorVersion(bd, 0); - assertEngineVersion(bd, 1.9f); - assertMacOSX(bd); - } - - public void testFirefox40b11() { - VBrowserDetails bd = new VBrowserDetails(FIREFOX_40B11_WIN); - assertGecko(bd); - assertFirefox(bd); - assertBrowserMajorVersion(bd, 4); - assertBrowserMinorVersion(bd, 0); - assertEngineVersion(bd, 2.0f); - assertWindows(bd); - } - - public void testFirefox40b7() { - VBrowserDetails bd = new VBrowserDetails(FIREFOX_40B7_WIN); - assertGecko(bd); - assertFirefox(bd); - assertBrowserMajorVersion(bd, 4); - assertBrowserMinorVersion(bd, 0); - assertEngineVersion(bd, 2.0f); - assertWindows(bd); - } - - public void testKonquerorLinux() { - // Just ensure detection does not crash - VBrowserDetails bd = new VBrowserDetails(KONQUEROR_LINUX); - assertLinux(bd); - } - - public void testFirefox36b() { - VBrowserDetails bd = new VBrowserDetails(FIREFOX36B_MAC); - assertGecko(bd); - assertFirefox(bd); - assertBrowserMajorVersion(bd, 3); - assertBrowserMinorVersion(bd, 6); - assertEngineVersion(bd, 1.9f); - assertMacOSX(bd); - } - - public void testOpera964() { - VBrowserDetails bd = new VBrowserDetails(OPERA964_WINDOWS); - assertPresto(bd); - assertOpera(bd); - assertBrowserMajorVersion(bd, 9); - assertBrowserMinorVersion(bd, 64); - assertWindows(bd); - } - - public void testOpera1010() { - VBrowserDetails bd = new VBrowserDetails(OPERA1010_WINDOWS); - assertPresto(bd); - assertOpera(bd); - assertBrowserMajorVersion(bd, 10); - assertBrowserMinorVersion(bd, 10); - assertWindows(bd); - } - - public void testOpera1050() { - VBrowserDetails bd = new VBrowserDetails(OPERA1050_WINDOWS); - assertPresto(bd); - assertOpera(bd); - assertBrowserMajorVersion(bd, 10); - assertBrowserMinorVersion(bd, 50); - assertWindows(bd); - } - - public void testIE6() { - VBrowserDetails bd = new VBrowserDetails(IE6_WINDOWS); - assertEngineVersion(bd, -1); - assertIE(bd); - assertBrowserMajorVersion(bd, 6); - assertBrowserMinorVersion(bd, 0); - assertWindows(bd); - } - - public void testIE7() { - VBrowserDetails bd = new VBrowserDetails(IE7_WINDOWS); - assertEngineVersion(bd, -1); - assertIE(bd); - assertBrowserMajorVersion(bd, 7); - assertBrowserMinorVersion(bd, 0); - assertWindows(bd); - } - - public void testIE8() { - VBrowserDetails bd = new VBrowserDetails(IE8_WINDOWS); - assertTrident(bd); - assertEngineVersion(bd, 4); - assertIE(bd); - assertBrowserMajorVersion(bd, 8); - assertBrowserMinorVersion(bd, 0); - assertWindows(bd); - } - - public void testIE8CompatibilityMode() { - VBrowserDetails bd = new VBrowserDetails(IE8_IN_IE7_MODE_WINDOWS); - bd.setIEMode(7); - - assertTrident(bd); - assertEngineVersion(bd, 4); - assertIE(bd); - assertBrowserMajorVersion(bd, 7); - assertBrowserMinorVersion(bd, 0); - - assertWindows(bd); - } - - public void testIE9() { - VBrowserDetails bd = new VBrowserDetails(IE9_BETA_WINDOWS_7); - assertTrident(bd); - assertEngineVersion(bd, 5); - assertIE(bd); - assertBrowserMajorVersion(bd, 9); - assertBrowserMinorVersion(bd, 0); - assertWindows(bd); - } - - public void testIE9InIE7CompatibilityMode() { - VBrowserDetails bd = new VBrowserDetails(IE9_IN_IE7_MODE_WINDOWS_7); - // bd.setIE8InCompatibilityMode(); - - assertTrident(bd); - assertEngineVersion(bd, 5); - assertIE(bd); - assertBrowserMajorVersion(bd, 7); - assertBrowserMinorVersion(bd, 0); - - assertWindows(bd); - } - - public void testIE9InIE8CompatibilityMode() { - VBrowserDetails bd = new VBrowserDetails(IE9_BETA_IN_IE8_MODE_WINDOWS_7); - // bd.setIE8InCompatibilityMode(); - - /* - * Trident/4.0 in example user agent string based on beta even though it - * should be Trident/5.0 in real (non-beta) user agent strings - */ - assertTrident(bd); - assertEngineVersion(bd, 4); - assertIE(bd); - assertBrowserMajorVersion(bd, 8); - assertBrowserMinorVersion(bd, 0); - - assertWindows(bd); - } - - public void testIE10() { - VBrowserDetails bd = new VBrowserDetails(IE10_WINDOWS_8); - assertTrident(bd); - assertEngineVersion(bd, 6); - assertIE(bd); - assertBrowserMajorVersion(bd, 10); - assertBrowserMinorVersion(bd, 0); - assertWindows(bd); - } - - public void testIE11() { - VBrowserDetails bd = new VBrowserDetails(IE11_WINDOWS_7); - assertTrident(bd); - assertEngineVersion(bd, 7); - assertIE(bd); - assertBrowserMajorVersion(bd, 11); - assertBrowserMinorVersion(bd, 0); - assertWindows(bd); - } - - public void testIE11WindowsPhone81Update() { - VBrowserDetails bd = new VBrowserDetails(IE11_WINDOWS_PHONE_8_1_UPDATE); - assertTrident(bd); - assertEngineVersion(bd, 7); - assertIE(bd); - assertBrowserMajorVersion(bd, 11); - assertBrowserMinorVersion(bd, 0); - assertWindows(bd, true); - } - - /* - * Helper methods below - */ - - private void assertEngineVersion(VBrowserDetails browserDetails, - float version) { - assertEquals(version, browserDetails.getBrowserEngineVersion()); - - } - - private void assertBrowserMajorVersion(VBrowserDetails browserDetails, - int version) { - assertEquals(version, browserDetails.getBrowserMajorVersion()); - - } - - private void assertBrowserMinorVersion(VBrowserDetails browserDetails, - int version) { - assertEquals(version, browserDetails.getBrowserMinorVersion()); - - } - - private void assertGecko(VBrowserDetails browserDetails) { - // Engine - assertTrue(browserDetails.isGecko()); - assertFalse(browserDetails.isWebKit()); - assertFalse(browserDetails.isPresto()); - assertFalse(browserDetails.isTrident()); - } - - private void assertPresto(VBrowserDetails browserDetails) { - // Engine - assertFalse(browserDetails.isGecko()); - assertFalse(browserDetails.isWebKit()); - assertTrue(browserDetails.isPresto()); - assertFalse(browserDetails.isTrident()); - } - - private void assertTrident(VBrowserDetails browserDetails) { - // Engine - assertFalse(browserDetails.isGecko()); - assertFalse(browserDetails.isWebKit()); - assertFalse(browserDetails.isPresto()); - assertTrue(browserDetails.isTrident()); - } - - private void assertWebKit(VBrowserDetails browserDetails) { - // Engine - assertFalse(browserDetails.isGecko()); - assertTrue(browserDetails.isWebKit()); - assertFalse(browserDetails.isPresto()); - assertFalse(browserDetails.isTrident()); - } - - private void assertFirefox(VBrowserDetails browserDetails) { - // Browser - assertTrue(browserDetails.isFirefox()); - assertFalse(browserDetails.isChrome()); - assertFalse(browserDetails.isIE()); - assertFalse(browserDetails.isOpera()); - assertFalse(browserDetails.isSafari()); - } - - private void assertChrome(VBrowserDetails browserDetails) { - // Browser - assertFalse(browserDetails.isFirefox()); - assertTrue(browserDetails.isChrome()); - assertFalse(browserDetails.isIE()); - assertFalse(browserDetails.isOpera()); - assertFalse(browserDetails.isSafari()); - } - - private void assertIE(VBrowserDetails browserDetails) { - // Browser - assertFalse(browserDetails.isFirefox()); - assertFalse(browserDetails.isChrome()); - assertTrue(browserDetails.isIE()); - assertFalse(browserDetails.isOpera()); - assertFalse(browserDetails.isSafari()); - } - - private void assertOpera(VBrowserDetails browserDetails) { - // Browser - assertFalse(browserDetails.isFirefox()); - assertFalse(browserDetails.isChrome()); - assertFalse(browserDetails.isIE()); - assertTrue(browserDetails.isOpera()); - assertFalse(browserDetails.isSafari()); - } - - private void assertSafari(VBrowserDetails browserDetails) { - // Browser - assertFalse(browserDetails.isFirefox()); - assertFalse(browserDetails.isChrome()); - assertFalse(browserDetails.isIE()); - assertFalse(browserDetails.isOpera()); - assertTrue(browserDetails.isSafari()); - } - - private void assertMacOSX(VBrowserDetails browserDetails) { - assertFalse(browserDetails.isLinux()); - assertFalse(browserDetails.isWindows()); - assertTrue(browserDetails.isMacOSX()); - assertFalse(browserDetails.isAndroid()); - } - - private void assertAndroid(VBrowserDetails browserDetails, - int majorVersion, int minorVersion) { - assertFalse(browserDetails.isLinux()); - assertFalse(browserDetails.isWindows()); - assertFalse(browserDetails.isMacOSX()); - assertFalse(browserDetails.isIOS()); - assertTrue(browserDetails.isAndroid()); - - assertOSMajorVersion(browserDetails, majorVersion); - assertOSMinorVersion(browserDetails, minorVersion); - } - - private void assertIOS(VBrowserDetails browserDetails, int majorVersion, - int minorVersion) { - assertFalse(browserDetails.isLinux()); - assertFalse(browserDetails.isWindows()); - assertFalse(browserDetails.isMacOSX()); - assertTrue(browserDetails.isIOS()); - assertFalse(browserDetails.isAndroid()); - - assertOSMajorVersion(browserDetails, majorVersion); - assertOSMinorVersion(browserDetails, minorVersion); - } - - private void assertIPhone(VBrowserDetails browserDetails) { - assertTrue(browserDetails.isIPhone()); - assertFalse(browserDetails.isIPad()); - } - - private void assertIPad(VBrowserDetails browserDetails) { - assertFalse(browserDetails.isIPhone()); - assertTrue(browserDetails.isIPad()); - } - - private void assertWindows(VBrowserDetails browserDetails) { - assertWindows(browserDetails, false); - } - - private void assertWindows(VBrowserDetails browserDetails, - boolean isWindowsPhone) { - assertFalse(browserDetails.isLinux()); - assertTrue(browserDetails.isWindows()); - assertFalse(browserDetails.isMacOSX()); - assertFalse(browserDetails.isIOS()); - assertFalse(browserDetails.isAndroid()); - Assert.assertEquals(isWindowsPhone, browserDetails.isWindowsPhone()); - } - - private void assertLinux(VBrowserDetails browserDetails) { - assertTrue(browserDetails.isLinux()); - assertFalse(browserDetails.isWindows()); - assertFalse(browserDetails.isMacOSX()); - assertFalse(browserDetails.isIOS()); - assertFalse(browserDetails.isAndroid()); - } - -} diff --git a/client/tests/src/com/vaadin/client/VBrowserDetailsUserAgentParserTest.java b/client/tests/src/com/vaadin/client/VBrowserDetailsUserAgentParserTest.java new file mode 100644 index 0000000000..62b727e5f5 --- /dev/null +++ b/client/tests/src/com/vaadin/client/VBrowserDetailsUserAgentParserTest.java @@ -0,0 +1,588 @@ +package com.vaadin.client; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.vaadin.shared.VBrowserDetails; + +public class VBrowserDetailsUserAgentParserTest extends TestCase { + + private static final String FIREFOX30_WINDOWS = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6"; + private static final String FIREFOX30_LINUX = "Mozilla/5.0 (X11; U; Linux x86_64; es-ES; rv:1.9.0.12) Gecko/2009070811 Ubuntu/9.04 (jaunty) Firefox/3.0.12"; + private static final String FIREFOX33_ANDROID = "Mozilla/5.0 (Android; Tablet; rv:33.0) Gecko/33.0 Firefox/33.0"; + private static final String FIREFOX35_WINDOWS = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.8) Gecko/20100202 Firefox/3.5.8 (.NET CLR 3.5.30729) FirePHP/0.4"; + private static final String FIREFOX36_WINDOWS = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)"; + private static final String FIREFOX36B_MAC = "UAString mozilla/5.0 (macintosh; u; intel mac os x 10.6; en-us; rv:1.9.2) gecko/20100115 firefox/3.6"; + private static final String FIREFOX_30B5_MAC = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9b5) Gecko/2008032619 Firefox/3.0b5"; + private static final String FIREFOX_40B7_WIN = "Mozilla/5.0 (Windows NT 5.1; rv:2.0b7) Gecko/20100101 Firefox/4.0b7"; + private static final String FIREFOX_40B11_WIN = "Mozilla/5.0 (Windows NT 5.1; rv:2.0b11) Gecko/20100101 Firefox/4.0b11"; + private static final String KONQUEROR_LINUX = "Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Exabot-Thumbnails)"; + + private static final String IE6_WINDOWS = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)"; + private static final String IE7_WINDOWS = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"; + + private static final String IE8_WINDOWS = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; InfoPath.2)"; + private static final String IE8_IN_IE7_MODE_WINDOWS = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; InfoPath.2)"; + + private static final String IE9_IN_IE7_MODE_WINDOWS_7 = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)"; + private static final String IE9_BETA_IN_IE8_MODE_WINDOWS_7 = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)"; + private static final String IE9_BETA_WINDOWS_7 = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"; + + private static final String IE10_WINDOWS_8 = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"; + private static final String IE11_WINDOWS_7 = "Mozilla/5.0 (Windows NT 6.1; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; rv:11.0) like Gecko"; + private static final String IE11_WINDOWS_PHONE_8_1_UPDATE = "Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 920) Like iPhone OS 7_0_3 Mac OS X AppleWebKit/537 (KHTML, like Gecko) Mobile Safari/537"; + + // "Version/" was added in 10.00 + private static final String OPERA964_WINDOWS = "Opera/9.64(Windows NT 5.1; U; en) Presto/2.1.1"; + private static final String OPERA1010_WINDOWS = "Opera/9.80 (Windows NT 5.1; U; en) Presto/2.2.15 Version/10.10"; + private static final String OPERA1050_WINDOWS = "Opera/9.80 (Windows NT 5.1; U; en) Presto/2.5.22 Version/10.50"; + + private static final String CHROME3_MAC = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; en-US) AppleWebKit/532.0 (KHTML, like Gecko) Chrome/3.0.198 Safari/532.0"; + private static final String CHROME4_WINDOWS = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.0.249.89 Safari/532.5"; + + private static final String SAFARI3_WINDOWS = "Mozilla/5.0 (Windows; U; Windows NT 5.1; cs-CZ) AppleWebKit/525.28.3 (KHTML, like Gecko) Version/3.2.3 Safari/525.29"; + private static final String SAFARI4_MAC = "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_5_8; en-us) AppleWebKit/531.22.7 (KHTML, like Gecko) Version/4.0.5 Safari/531.22.7"; + + private static final String IPHONE_IOS_5_1 = "Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B179 Safari/7534.48.3"; + private static final String IPHONE_IOS_4_0 = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7"; + private static final String IPAD_IOS_4_3_1 = "Mozilla/5.0 (iPad; U; CPU OS 4_3_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8G4 Safari/6533.18.5"; + + // application on the home screen, without Safari in user agent + private static final String IPHONE_IOS_6_1_HOMESCREEN_SIMULATOR = "Mozilla/5.0 (iPhone; CPU iPhone OS 6_1 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Mobile/10B141"; + + private static final String ANDROID_HTC_2_1 = "Mozilla/5.0 (Linux; U; Android 2.1-update1; en-us; ADR6300 Build/ERE27) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17"; + private static final String ANDROID_GOOGLE_NEXUS_2_2 = "Mozilla/5.0 (Linux; U; Android 2.2; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"; + private static final String ANDROID_MOTOROLA_3_0 = "Mozilla/5.0 (Linux; U; Android 3.0; en-us; Xoom Build/HRI39) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13"; + private static final String ANDROID_GALAXY_NEXUS_4_0_4_CHROME = "Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19"; + + public void testSafari3() { + VBrowserDetails bd = new VBrowserDetails(SAFARI3_WINDOWS); + assertWebKit(bd); + assertSafari(bd); + assertBrowserMajorVersion(bd, 3); + assertBrowserMinorVersion(bd, 2); + assertEngineVersion(bd, 525.0f); + assertWindows(bd); + } + + public void testSafari4() { + VBrowserDetails bd = new VBrowserDetails(SAFARI4_MAC); + assertWebKit(bd); + assertSafari(bd); + assertBrowserMajorVersion(bd, 4); + assertBrowserMinorVersion(bd, 0); + assertEngineVersion(bd, 531f); + assertMacOSX(bd); + } + + public void testIPhoneIOS6Homescreen() { + VBrowserDetails bd = new VBrowserDetails( + IPHONE_IOS_6_1_HOMESCREEN_SIMULATOR); + assertWebKit(bd); + // not identified as Safari, no browser version available + // assertSafari(bd); + // assertBrowserMajorVersion(bd, 6); + // assertBrowserMinorVersion(bd, 1); + assertEngineVersion(bd, 536f); + assertIOS(bd, 6, 1); + assertIPhone(bd); + } + + public void testIPhoneIOS5() { + VBrowserDetails bd = new VBrowserDetails(IPHONE_IOS_5_1); + assertWebKit(bd); + assertSafari(bd); + assertBrowserMajorVersion(bd, 5); + assertBrowserMinorVersion(bd, 1); + assertEngineVersion(bd, 534f); + assertIOS(bd, 5, 1); + assertIPhone(bd); + } + + public void testIPhoneIOS4() { + VBrowserDetails bd = new VBrowserDetails(IPHONE_IOS_4_0); + assertWebKit(bd); + assertSafari(bd); + assertBrowserMajorVersion(bd, 4); + assertBrowserMinorVersion(bd, 0); + assertEngineVersion(bd, 532f); + assertIOS(bd, 4, 0); + assertIPhone(bd); + } + + public void testIPadIOS4() { + VBrowserDetails bd = new VBrowserDetails(IPAD_IOS_4_3_1); + assertWebKit(bd); + assertSafari(bd); + assertBrowserMajorVersion(bd, 5); + assertBrowserMinorVersion(bd, 0); + assertEngineVersion(bd, 533f); + assertIOS(bd, 4, 3); + assertIPad(bd); + } + + public void testAndroid21() { + VBrowserDetails bd = new VBrowserDetails(ANDROID_HTC_2_1); + assertWebKit(bd); + assertSafari(bd); + assertBrowserMajorVersion(bd, 4); + assertBrowserMinorVersion(bd, 0); + assertEngineVersion(bd, 530f); + assertAndroid(bd, 2, 1); + + } + + public void testAndroid22() { + VBrowserDetails bd = new VBrowserDetails(ANDROID_GOOGLE_NEXUS_2_2); + assertWebKit(bd); + assertSafari(bd); + assertBrowserMajorVersion(bd, 4); + assertBrowserMinorVersion(bd, 0); + assertEngineVersion(bd, 533f); + assertAndroid(bd, 2, 2); + } + + public void testAndroid30() { + VBrowserDetails bd = new VBrowserDetails(ANDROID_MOTOROLA_3_0); + assertWebKit(bd); + assertSafari(bd); + assertBrowserMajorVersion(bd, 4); + assertBrowserMinorVersion(bd, 0); + assertEngineVersion(bd, 534f); + assertAndroid(bd, 3, 0); + } + + public void testAndroid40Chrome() { + VBrowserDetails bd = new VBrowserDetails( + ANDROID_GALAXY_NEXUS_4_0_4_CHROME); + assertWebKit(bd); + assertChrome(bd); + assertBrowserMajorVersion(bd, 18); + assertBrowserMinorVersion(bd, 0); + assertEngineVersion(bd, 535f); + assertAndroid(bd, 4, 0); + } + + private void assertOSMajorVersion(VBrowserDetails bd, int i) { + assertEquals(i, bd.getOperatingSystemMajorVersion()); + } + + private void assertOSMinorVersion(VBrowserDetails bd, int i) { + assertEquals(i, bd.getOperatingSystemMinorVersion()); + } + + public void testChrome3() { + VBrowserDetails bd = new VBrowserDetails(CHROME3_MAC); + assertWebKit(bd); + assertChrome(bd); + assertBrowserMajorVersion(bd, 3); + assertBrowserMinorVersion(bd, 0); + assertEngineVersion(bd, 532.0f); + assertMacOSX(bd); + } + + public void testChrome4() { + VBrowserDetails bd = new VBrowserDetails(CHROME4_WINDOWS); + assertWebKit(bd); + assertChrome(bd); + assertBrowserMajorVersion(bd, 4); + assertBrowserMinorVersion(bd, 0); + assertEngineVersion(bd, 532f); + assertWindows(bd); + } + + public void testFirefox3() { + VBrowserDetails bd = new VBrowserDetails(FIREFOX30_WINDOWS); + assertGecko(bd); + assertFirefox(bd); + assertBrowserMajorVersion(bd, 3); + assertBrowserMinorVersion(bd, 0); + assertEngineVersion(bd, 1.9f); + assertWindows(bd); + + bd = new VBrowserDetails(FIREFOX30_LINUX); + assertGecko(bd); + assertFirefox(bd); + assertBrowserMajorVersion(bd, 3); + assertBrowserMinorVersion(bd, 0); + assertEngineVersion(bd, 1.9f); + assertLinux(bd); + } + + public void testFirefox33Android() { + VBrowserDetails bd = new VBrowserDetails(FIREFOX33_ANDROID); + assertGecko(bd); + assertFirefox(bd); + assertBrowserMajorVersion(bd, 33); + assertBrowserMinorVersion(bd, 0); + assertAndroid(bd, -1, -1); + } + + public void testFirefox35() { + VBrowserDetails bd = new VBrowserDetails(FIREFOX35_WINDOWS); + assertGecko(bd); + assertFirefox(bd); + assertBrowserMajorVersion(bd, 3); + assertBrowserMinorVersion(bd, 5); + assertEngineVersion(bd, 1.9f); + assertWindows(bd); + } + + public void testFirefox36() { + VBrowserDetails bd = new VBrowserDetails(FIREFOX36_WINDOWS); + assertGecko(bd); + assertFirefox(bd); + assertBrowserMajorVersion(bd, 3); + assertBrowserMinorVersion(bd, 6); + assertEngineVersion(bd, 1.9f); + assertWindows(bd); + } + + public void testFirefox30b5() { + VBrowserDetails bd = new VBrowserDetails(FIREFOX_30B5_MAC); + assertGecko(bd); + assertFirefox(bd); + assertBrowserMajorVersion(bd, 3); + assertBrowserMinorVersion(bd, 0); + assertEngineVersion(bd, 1.9f); + assertMacOSX(bd); + } + + public void testFirefox40b11() { + VBrowserDetails bd = new VBrowserDetails(FIREFOX_40B11_WIN); + assertGecko(bd); + assertFirefox(bd); + assertBrowserMajorVersion(bd, 4); + assertBrowserMinorVersion(bd, 0); + assertEngineVersion(bd, 2.0f); + assertWindows(bd); + } + + public void testFirefox40b7() { + VBrowserDetails bd = new VBrowserDetails(FIREFOX_40B7_WIN); + assertGecko(bd); + assertFirefox(bd); + assertBrowserMajorVersion(bd, 4); + assertBrowserMinorVersion(bd, 0); + assertEngineVersion(bd, 2.0f); + assertWindows(bd); + } + + public void testKonquerorLinux() { + // Just ensure detection does not crash + VBrowserDetails bd = new VBrowserDetails(KONQUEROR_LINUX); + assertLinux(bd); + } + + public void testFirefox36b() { + VBrowserDetails bd = new VBrowserDetails(FIREFOX36B_MAC); + assertGecko(bd); + assertFirefox(bd); + assertBrowserMajorVersion(bd, 3); + assertBrowserMinorVersion(bd, 6); + assertEngineVersion(bd, 1.9f); + assertMacOSX(bd); + } + + public void testOpera964() { + VBrowserDetails bd = new VBrowserDetails(OPERA964_WINDOWS); + assertPresto(bd); + assertOpera(bd); + assertBrowserMajorVersion(bd, 9); + assertBrowserMinorVersion(bd, 64); + assertWindows(bd); + } + + public void testOpera1010() { + VBrowserDetails bd = new VBrowserDetails(OPERA1010_WINDOWS); + assertPresto(bd); + assertOpera(bd); + assertBrowserMajorVersion(bd, 10); + assertBrowserMinorVersion(bd, 10); + assertWindows(bd); + } + + public void testOpera1050() { + VBrowserDetails bd = new VBrowserDetails(OPERA1050_WINDOWS); + assertPresto(bd); + assertOpera(bd); + assertBrowserMajorVersion(bd, 10); + assertBrowserMinorVersion(bd, 50); + assertWindows(bd); + } + + public void testIE6() { + VBrowserDetails bd = new VBrowserDetails(IE6_WINDOWS); + assertEngineVersion(bd, -1); + assertIE(bd); + assertBrowserMajorVersion(bd, 6); + assertBrowserMinorVersion(bd, 0); + assertWindows(bd); + } + + public void testIE7() { + VBrowserDetails bd = new VBrowserDetails(IE7_WINDOWS); + assertEngineVersion(bd, -1); + assertIE(bd); + assertBrowserMajorVersion(bd, 7); + assertBrowserMinorVersion(bd, 0); + assertWindows(bd); + } + + public void testIE8() { + VBrowserDetails bd = new VBrowserDetails(IE8_WINDOWS); + assertTrident(bd); + assertEngineVersion(bd, 4); + assertIE(bd); + assertBrowserMajorVersion(bd, 8); + assertBrowserMinorVersion(bd, 0); + assertWindows(bd); + } + + public void testIE8CompatibilityMode() { + VBrowserDetails bd = new VBrowserDetails(IE8_IN_IE7_MODE_WINDOWS); + bd.setIEMode(7); + + assertTrident(bd); + assertEngineVersion(bd, 4); + assertIE(bd); + assertBrowserMajorVersion(bd, 7); + assertBrowserMinorVersion(bd, 0); + + assertWindows(bd); + } + + public void testIE9() { + VBrowserDetails bd = new VBrowserDetails(IE9_BETA_WINDOWS_7); + assertTrident(bd); + assertEngineVersion(bd, 5); + assertIE(bd); + assertBrowserMajorVersion(bd, 9); + assertBrowserMinorVersion(bd, 0); + assertWindows(bd); + } + + public void testIE9InIE7CompatibilityMode() { + VBrowserDetails bd = new VBrowserDetails(IE9_IN_IE7_MODE_WINDOWS_7); + // bd.setIE8InCompatibilityMode(); + + assertTrident(bd); + assertEngineVersion(bd, 5); + assertIE(bd); + assertBrowserMajorVersion(bd, 7); + assertBrowserMinorVersion(bd, 0); + + assertWindows(bd); + } + + public void testIE9InIE8CompatibilityMode() { + VBrowserDetails bd = new VBrowserDetails(IE9_BETA_IN_IE8_MODE_WINDOWS_7); + // bd.setIE8InCompatibilityMode(); + + /* + * Trident/4.0 in example user agent string based on beta even though it + * should be Trident/5.0 in real (non-beta) user agent strings + */ + assertTrident(bd); + assertEngineVersion(bd, 4); + assertIE(bd); + assertBrowserMajorVersion(bd, 8); + assertBrowserMinorVersion(bd, 0); + + assertWindows(bd); + } + + public void testIE10() { + VBrowserDetails bd = new VBrowserDetails(IE10_WINDOWS_8); + assertTrident(bd); + assertEngineVersion(bd, 6); + assertIE(bd); + assertBrowserMajorVersion(bd, 10); + assertBrowserMinorVersion(bd, 0); + assertWindows(bd); + } + + public void testIE11() { + VBrowserDetails bd = new VBrowserDetails(IE11_WINDOWS_7); + assertTrident(bd); + assertEngineVersion(bd, 7); + assertIE(bd); + assertBrowserMajorVersion(bd, 11); + assertBrowserMinorVersion(bd, 0); + assertWindows(bd); + } + + public void testIE11WindowsPhone81Update() { + VBrowserDetails bd = new VBrowserDetails(IE11_WINDOWS_PHONE_8_1_UPDATE); + assertTrident(bd); + assertEngineVersion(bd, 7); + assertIE(bd); + assertBrowserMajorVersion(bd, 11); + assertBrowserMinorVersion(bd, 0); + assertWindows(bd, true); + } + + /* + * Helper methods below + */ + + private void assertEngineVersion(VBrowserDetails browserDetails, + float version) { + assertEquals(version, browserDetails.getBrowserEngineVersion()); + + } + + private void assertBrowserMajorVersion(VBrowserDetails browserDetails, + int version) { + assertEquals(version, browserDetails.getBrowserMajorVersion()); + + } + + private void assertBrowserMinorVersion(VBrowserDetails browserDetails, + int version) { + assertEquals(version, browserDetails.getBrowserMinorVersion()); + + } + + private void assertGecko(VBrowserDetails browserDetails) { + // Engine + assertTrue(browserDetails.isGecko()); + assertFalse(browserDetails.isWebKit()); + assertFalse(browserDetails.isPresto()); + assertFalse(browserDetails.isTrident()); + } + + private void assertPresto(VBrowserDetails browserDetails) { + // Engine + assertFalse(browserDetails.isGecko()); + assertFalse(browserDetails.isWebKit()); + assertTrue(browserDetails.isPresto()); + assertFalse(browserDetails.isTrident()); + } + + private void assertTrident(VBrowserDetails browserDetails) { + // Engine + assertFalse(browserDetails.isGecko()); + assertFalse(browserDetails.isWebKit()); + assertFalse(browserDetails.isPresto()); + assertTrue(browserDetails.isTrident()); + } + + private void assertWebKit(VBrowserDetails browserDetails) { + // Engine + assertFalse(browserDetails.isGecko()); + assertTrue(browserDetails.isWebKit()); + assertFalse(browserDetails.isPresto()); + assertFalse(browserDetails.isTrident()); + } + + private void assertFirefox(VBrowserDetails browserDetails) { + // Browser + assertTrue(browserDetails.isFirefox()); + assertFalse(browserDetails.isChrome()); + assertFalse(browserDetails.isIE()); + assertFalse(browserDetails.isOpera()); + assertFalse(browserDetails.isSafari()); + } + + private void assertChrome(VBrowserDetails browserDetails) { + // Browser + assertFalse(browserDetails.isFirefox()); + assertTrue(browserDetails.isChrome()); + assertFalse(browserDetails.isIE()); + assertFalse(browserDetails.isOpera()); + assertFalse(browserDetails.isSafari()); + } + + private void assertIE(VBrowserDetails browserDetails) { + // Browser + assertFalse(browserDetails.isFirefox()); + assertFalse(browserDetails.isChrome()); + assertTrue(browserDetails.isIE()); + assertFalse(browserDetails.isOpera()); + assertFalse(browserDetails.isSafari()); + } + + private void assertOpera(VBrowserDetails browserDetails) { + // Browser + assertFalse(browserDetails.isFirefox()); + assertFalse(browserDetails.isChrome()); + assertFalse(browserDetails.isIE()); + assertTrue(browserDetails.isOpera()); + assertFalse(browserDetails.isSafari()); + } + + private void assertSafari(VBrowserDetails browserDetails) { + // Browser + assertFalse(browserDetails.isFirefox()); + assertFalse(browserDetails.isChrome()); + assertFalse(browserDetails.isIE()); + assertFalse(browserDetails.isOpera()); + assertTrue(browserDetails.isSafari()); + } + + private void assertMacOSX(VBrowserDetails browserDetails) { + assertFalse(browserDetails.isLinux()); + assertFalse(browserDetails.isWindows()); + assertTrue(browserDetails.isMacOSX()); + assertFalse(browserDetails.isAndroid()); + } + + private void assertAndroid(VBrowserDetails browserDetails, + int majorVersion, int minorVersion) { + assertFalse(browserDetails.isLinux()); + assertFalse(browserDetails.isWindows()); + assertFalse(browserDetails.isMacOSX()); + assertFalse(browserDetails.isIOS()); + assertTrue(browserDetails.isAndroid()); + + assertOSMajorVersion(browserDetails, majorVersion); + assertOSMinorVersion(browserDetails, minorVersion); + } + + private void assertIOS(VBrowserDetails browserDetails, int majorVersion, + int minorVersion) { + assertFalse(browserDetails.isLinux()); + assertFalse(browserDetails.isWindows()); + assertFalse(browserDetails.isMacOSX()); + assertTrue(browserDetails.isIOS()); + assertFalse(browserDetails.isAndroid()); + + assertOSMajorVersion(browserDetails, majorVersion); + assertOSMinorVersion(browserDetails, minorVersion); + } + + private void assertIPhone(VBrowserDetails browserDetails) { + assertTrue(browserDetails.isIPhone()); + assertFalse(browserDetails.isIPad()); + } + + private void assertIPad(VBrowserDetails browserDetails) { + assertFalse(browserDetails.isIPhone()); + assertTrue(browserDetails.isIPad()); + } + + private void assertWindows(VBrowserDetails browserDetails) { + assertWindows(browserDetails, false); + } + + private void assertWindows(VBrowserDetails browserDetails, + boolean isWindowsPhone) { + assertFalse(browserDetails.isLinux()); + assertTrue(browserDetails.isWindows()); + assertFalse(browserDetails.isMacOSX()); + assertFalse(browserDetails.isIOS()); + assertFalse(browserDetails.isAndroid()); + Assert.assertEquals(isWindowsPhone, browserDetails.isWindowsPhone()); + } + + private void assertLinux(VBrowserDetails browserDetails) { + assertTrue(browserDetails.isLinux()); + assertFalse(browserDetails.isWindows()); + assertFalse(browserDetails.isMacOSX()); + assertFalse(browserDetails.isIOS()); + assertFalse(browserDetails.isAndroid()); + } + +} diff --git a/common.xml b/common.xml index edd941c5e3..80a1cbf642 100644 --- a/common.xml +++ b/common.xml @@ -353,14 +353,8 @@ - - - - - - - - + + diff --git a/server/tests/src/com/vaadin/data/fieldgroup/FieldGroupDate.java b/server/tests/src/com/vaadin/data/fieldgroup/FieldGroupDate.java deleted file mode 100644 index fd5d47b32f..0000000000 --- a/server/tests/src/com/vaadin/data/fieldgroup/FieldGroupDate.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.data.fieldgroup; - -import java.util.Date; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.vaadin.data.util.BeanItem; -import com.vaadin.ui.Field; -import com.vaadin.ui.PopupDateField; - -public class FieldGroupDate { - - private FieldGroup fieldGroup; - - public class TestBean { - private Date javaDate; - private java.sql.Date sqlDate; - - public TestBean(Date javaDate, java.sql.Date sqlDate) { - super(); - this.javaDate = javaDate; - this.sqlDate = sqlDate; - } - - public java.sql.Date getSqlDate() { - return sqlDate; - } - - public void setSqlDate(java.sql.Date sqlDate) { - this.sqlDate = sqlDate; - } - - public Date getJavaDate() { - return javaDate; - } - - public void setJavaDate(Date date) { - javaDate = date; - } - } - - @SuppressWarnings("deprecation") - @Before - public void setup() { - fieldGroup = new FieldGroup(); - fieldGroup.setItemDataSource(new BeanItem(new TestBean( - new Date(2010, 5, 7), new java.sql.Date(2011, 6, 8)))); - } - - @Test - public void testBuildAndBindDate() { - Field f = fieldGroup.buildAndBind("javaDate"); - Assert.assertNotNull(f); - Assert.assertEquals(PopupDateField.class, f.getClass()); - } - - @Test - public void testBuildAndBindSqlDate() { - Field f = fieldGroup.buildAndBind("sqlDate"); - Assert.assertNotNull(f); - Assert.assertEquals(PopupDateField.class, f.getClass()); - } - - @Test - public void clearFields() { - PopupDateField sqlDate = new PopupDateField(); - PopupDateField javaDate = new PopupDateField(); - fieldGroup.bind(sqlDate, "sqlDate"); - fieldGroup.bind(javaDate, "javaDate"); - - Assert.assertEquals(new Date(2010, 5, 7), javaDate.getValue()); - Assert.assertEquals(new Date(2011, 6, 8), sqlDate.getValue()); - - fieldGroup.clear(); - Assert.assertEquals(null, javaDate.getValue()); - Assert.assertEquals(null, sqlDate.getValue()); - - } - -} diff --git a/server/tests/src/com/vaadin/data/fieldgroup/FieldGroupDateTest.java b/server/tests/src/com/vaadin/data/fieldgroup/FieldGroupDateTest.java new file mode 100644 index 0000000000..ce76f8427b --- /dev/null +++ b/server/tests/src/com/vaadin/data/fieldgroup/FieldGroupDateTest.java @@ -0,0 +1,97 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.data.fieldgroup; + +import java.util.Date; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.vaadin.data.util.BeanItem; +import com.vaadin.ui.Field; +import com.vaadin.ui.PopupDateField; + +public class FieldGroupDateTest { + + private FieldGroup fieldGroup; + + public class TestBean { + private Date javaDate; + private java.sql.Date sqlDate; + + public TestBean(Date javaDate, java.sql.Date sqlDate) { + super(); + this.javaDate = javaDate; + this.sqlDate = sqlDate; + } + + public java.sql.Date getSqlDate() { + return sqlDate; + } + + public void setSqlDate(java.sql.Date sqlDate) { + this.sqlDate = sqlDate; + } + + public Date getJavaDate() { + return javaDate; + } + + public void setJavaDate(Date date) { + javaDate = date; + } + } + + @SuppressWarnings("deprecation") + @Before + public void setup() { + fieldGroup = new FieldGroup(); + fieldGroup.setItemDataSource(new BeanItem(new TestBean( + new Date(2010, 5, 7), new java.sql.Date(2011, 6, 8)))); + } + + @Test + public void testBuildAndBindDate() { + Field f = fieldGroup.buildAndBind("javaDate"); + Assert.assertNotNull(f); + Assert.assertEquals(PopupDateField.class, f.getClass()); + } + + @Test + public void testBuildAndBindSqlDate() { + Field f = fieldGroup.buildAndBind("sqlDate"); + Assert.assertNotNull(f); + Assert.assertEquals(PopupDateField.class, f.getClass()); + } + + @Test + public void clearFields() { + PopupDateField sqlDate = new PopupDateField(); + PopupDateField javaDate = new PopupDateField(); + fieldGroup.bind(sqlDate, "sqlDate"); + fieldGroup.bind(javaDate, "javaDate"); + + Assert.assertEquals(new Date(2010, 5, 7), javaDate.getValue()); + Assert.assertEquals(new Date(2011, 6, 8), sqlDate.getValue()); + + fieldGroup.clear(); + Assert.assertEquals(null, javaDate.getValue()); + Assert.assertEquals(null, sqlDate.getValue()); + + } + +} diff --git a/server/tests/src/com/vaadin/data/util/AbstractBeanContainerTest.java b/server/tests/src/com/vaadin/data/util/AbstractBeanContainerTest.java deleted file mode 100644 index 1e663afdd2..0000000000 --- a/server/tests/src/com/vaadin/data/util/AbstractBeanContainerTest.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.vaadin.data.util; - -/** - * Automated test for {@link AbstractBeanContainer}. - * - * Only a limited subset of the functionality is tested here, the rest in tests - * of subclasses including {@link BeanItemContainer} and {@link BeanContainer}. - */ -public abstract class AbstractBeanContainerTest extends - AbstractInMemoryContainerTest { - - public static class Person { - private String name; - - public Person(String name) { - setName(name); - } - - public void setName(String name) { - this.name = name; - } - - public String getName() { - return name; - } - } - - public static class ClassName { - // field names match constants in parent test class - private String fullyQualifiedName; - private String simpleName; - private String reverseFullyQualifiedName; - private Integer idNumber; - - public ClassName(String fullyQualifiedName, Integer idNumber) { - this.fullyQualifiedName = fullyQualifiedName; - simpleName = AbstractContainerTest - .getSimpleName(fullyQualifiedName); - reverseFullyQualifiedName = reverse(fullyQualifiedName); - this.idNumber = idNumber; - } - - public String getFullyQualifiedName() { - return fullyQualifiedName; - } - - public void setFullyQualifiedName(String fullyQualifiedName) { - this.fullyQualifiedName = fullyQualifiedName; - } - - public String getSimpleName() { - return simpleName; - } - - public void setSimpleName(String simpleName) { - this.simpleName = simpleName; - } - - public String getReverseFullyQualifiedName() { - return reverseFullyQualifiedName; - } - - public void setReverseFullyQualifiedName( - String reverseFullyQualifiedName) { - this.reverseFullyQualifiedName = reverseFullyQualifiedName; - } - - public Integer getIdNumber() { - return idNumber; - } - - public void setIdNumber(Integer idNumber) { - this.idNumber = idNumber; - } - } - -} diff --git a/server/tests/src/com/vaadin/data/util/AbstractBeanContainerTestBase.java b/server/tests/src/com/vaadin/data/util/AbstractBeanContainerTestBase.java new file mode 100644 index 0000000000..3d8f08a7ef --- /dev/null +++ b/server/tests/src/com/vaadin/data/util/AbstractBeanContainerTestBase.java @@ -0,0 +1,77 @@ +package com.vaadin.data.util; + +/** + * Automated test for {@link AbstractBeanContainer}. + * + * Only a limited subset of the functionality is tested here, the rest in tests + * of subclasses including {@link BeanItemContainer} and {@link BeanContainer}. + */ +public abstract class AbstractBeanContainerTestBase extends + AbstractInMemoryContainerTestBase { + + public static class Person { + private String name; + + public Person(String name) { + setName(name); + } + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return name; + } + } + + public static class ClassName { + // field names match constants in parent test class + private String fullyQualifiedName; + private String simpleName; + private String reverseFullyQualifiedName; + private Integer idNumber; + + public ClassName(String fullyQualifiedName, Integer idNumber) { + this.fullyQualifiedName = fullyQualifiedName; + simpleName = AbstractContainerTestBase + .getSimpleName(fullyQualifiedName); + reverseFullyQualifiedName = reverse(fullyQualifiedName); + this.idNumber = idNumber; + } + + public String getFullyQualifiedName() { + return fullyQualifiedName; + } + + public void setFullyQualifiedName(String fullyQualifiedName) { + this.fullyQualifiedName = fullyQualifiedName; + } + + public String getSimpleName() { + return simpleName; + } + + public void setSimpleName(String simpleName) { + this.simpleName = simpleName; + } + + public String getReverseFullyQualifiedName() { + return reverseFullyQualifiedName; + } + + public void setReverseFullyQualifiedName( + String reverseFullyQualifiedName) { + this.reverseFullyQualifiedName = reverseFullyQualifiedName; + } + + public Integer getIdNumber() { + return idNumber; + } + + public void setIdNumber(Integer idNumber) { + this.idNumber = idNumber; + } + } + +} diff --git a/server/tests/src/com/vaadin/data/util/AbstractContainerTest.java b/server/tests/src/com/vaadin/data/util/AbstractContainerTest.java deleted file mode 100644 index a443499a89..0000000000 --- a/server/tests/src/com/vaadin/data/util/AbstractContainerTest.java +++ /dev/null @@ -1,679 +0,0 @@ -package com.vaadin.data.util; - -import java.util.ArrayList; -import java.util.List; - -import junit.framework.TestCase; - -import org.junit.Assert; - -import com.vaadin.data.Container; -import com.vaadin.data.Container.Filterable; -import com.vaadin.data.Container.ItemSetChangeEvent; -import com.vaadin.data.Container.ItemSetChangeListener; -import com.vaadin.data.Container.Sortable; -import com.vaadin.data.Item; -import com.vaadin.data.util.filter.SimpleStringFilter; - -public abstract class AbstractContainerTest extends TestCase { - - /** - * Helper class for testing e.g. listeners expecting events to be fired. - */ - protected abstract static class AbstractEventCounter { - private int eventCount = 0; - private int lastAssertedEventCount = 0; - - /** - * Increment the event count. To be called by subclasses e.g. from a - * listener method. - */ - protected void increment() { - ++eventCount; - } - - /** - * Check that no one event has occurred since the previous assert call. - */ - public void assertNone() { - Assert.assertEquals(lastAssertedEventCount, eventCount); - } - - /** - * Check that exactly one event has occurred since the previous assert - * call. - */ - public void assertOnce() { - Assert.assertEquals(++lastAssertedEventCount, eventCount); - } - - /** - * Reset the counter and the expected count. - */ - public void reset() { - eventCount = 0; - lastAssertedEventCount = 0; - } - } - - /** - * Test class for counting item set change events and verifying they have - * been received. - */ - protected static class ItemSetChangeCounter extends AbstractEventCounter - implements ItemSetChangeListener { - - @Override - public void containerItemSetChange(ItemSetChangeEvent event) { - increment(); - } - - } - - // #6043: for items that have been filtered out, Container interface does - // not specify what to return from getItem() and getContainerProperty(), so - // need checkGetItemNull parameter for the test to be usable for most - // current containers - protected void validateContainer(Container container, - Object expectedFirstItemId, Object expectedLastItemId, - Object itemIdInSet, Object itemIdNotInSet, - boolean checkGetItemNull, int expectedSize) { - Container.Indexed indexed = null; - if (container instanceof Container.Indexed) { - indexed = (Container.Indexed) container; - } - - List itemIdList = new ArrayList(container.getItemIds()); - - // size() - assertEquals(expectedSize, container.size()); - assertEquals(expectedSize, itemIdList.size()); - - // first item, last item - Object first = itemIdList.get(0); - Object last = itemIdList.get(itemIdList.size() - 1); - - assertEquals(expectedFirstItemId, first); - assertEquals(expectedLastItemId, last); - - // containsId - assertFalse(container.containsId(itemIdNotInSet)); - assertTrue(container.containsId(itemIdInSet)); - - // getItem - if (checkGetItemNull) { - assertNull(container.getItem(itemIdNotInSet)); - } - assertNotNull(container.getItem(itemIdInSet)); - - // getContainerProperty - for (Object propId : container.getContainerPropertyIds()) { - if (checkGetItemNull) { - assertNull(container.getContainerProperty(itemIdNotInSet, - propId)); - } - assertNotNull(container.getContainerProperty(itemIdInSet, propId)); - } - - if (indexed != null) { - // firstItemId - assertEquals(first, indexed.firstItemId()); - - // lastItemId - assertEquals(last, indexed.lastItemId()); - - // nextItemId - assertEquals(itemIdList.get(1), indexed.nextItemId(first)); - - // prevItemId - assertEquals(itemIdList.get(itemIdList.size() - 2), - indexed.prevItemId(last)); - - // isFirstId - assertTrue(indexed.isFirstId(first)); - assertFalse(indexed.isFirstId(last)); - - // isLastId - assertTrue(indexed.isLastId(last)); - assertFalse(indexed.isLastId(first)); - - // indexOfId - assertEquals(0, indexed.indexOfId(first)); - assertEquals(expectedSize - 1, indexed.indexOfId(last)); - - // getIdByIndex - assertEquals(indexed.getIdByIndex(0), first); - assertEquals(indexed.getIdByIndex(expectedSize - 1), last); - - } - - } - - protected static final Object FULLY_QUALIFIED_NAME = "fullyQualifiedName"; - protected static final Object SIMPLE_NAME = "simpleName"; - protected static final Object REVERSE_FULLY_QUALIFIED_NAME = "reverseFullyQualifiedName"; - protected static final Object ID_NUMBER = "idNumber"; - - protected void testBasicContainerOperations(Container container) { - initializeContainer(container); - - // Basic container - validateContainer(container, sampleData[0], - sampleData[sampleData.length - 1], sampleData[10], "abc", true, - sampleData.length); - } - - protected void testContainerOrdered(Container.Ordered container) { - Object id = container.addItem(); - assertNotNull(id); - Item item = container.getItem(id); - assertNotNull(item); - - assertEquals(id, container.firstItemId()); - assertEquals(id, container.lastItemId()); - - // isFirstId - assertTrue(container.isFirstId(id)); - assertTrue(container.isFirstId(container.firstItemId())); - // isLastId - assertTrue(container.isLastId(id)); - assertTrue(container.isLastId(container.lastItemId())); - - // Add a new item before the first - // addItemAfter - Object newFirstId = container.addItemAfter(null); - assertNotNull(newFirstId); - assertNotNull(container.getItem(newFirstId)); - - // isFirstId - assertTrue(container.isFirstId(newFirstId)); - assertTrue(container.isFirstId(container.firstItemId())); - // isLastId - assertTrue(container.isLastId(id)); - assertTrue(container.isLastId(container.lastItemId())); - - // nextItemId - assertEquals(id, container.nextItemId(newFirstId)); - assertNull(container.nextItemId(id)); - assertNull(container.nextItemId("not-in-container")); - - // prevItemId - assertEquals(newFirstId, container.prevItemId(id)); - assertNull(container.prevItemId(newFirstId)); - assertNull(container.prevItemId("not-in-container")); - - // addItemAfter(Object) - Object newSecondItemId = container.addItemAfter(newFirstId); - // order is now: newFirstId, newSecondItemId, id - assertNotNull(newSecondItemId); - assertNotNull(container.getItem(newSecondItemId)); - assertEquals(id, container.nextItemId(newSecondItemId)); - assertEquals(newFirstId, container.prevItemId(newSecondItemId)); - - // addItemAfter(Object,Object) - String fourthId = "id of the fourth item"; - Item fourth = container.addItemAfter(newFirstId, fourthId); - // order is now: newFirstId, fourthId, newSecondItemId, id - assertNotNull(fourth); - assertEquals(fourth, container.getItem(fourthId)); - assertEquals(newSecondItemId, container.nextItemId(fourthId)); - assertEquals(newFirstId, container.prevItemId(fourthId)); - - // addItemAfter(Object,Object) - Object fifthId = new Object(); - Item fifth = container.addItemAfter(null, fifthId); - // order is now: fifthId, newFirstId, fourthId, newSecondItemId, id - assertNotNull(fifth); - assertEquals(fifth, container.getItem(fifthId)); - assertEquals(newFirstId, container.nextItemId(fifthId)); - assertNull(container.prevItemId(fifthId)); - - } - - protected void testContainerIndexed(Container.Indexed container, - Object itemId, int itemPosition, boolean testAddEmptyItemAt, - Object newItemId, boolean testAddItemAtWithId) { - initializeContainer(container); - - // indexOfId - Assert.assertEquals(itemPosition, container.indexOfId(itemId)); - - // getIdByIndex - Assert.assertEquals(itemId, container.getIdByIndex(itemPosition)); - - // addItemAt - if (testAddEmptyItemAt) { - Object addedId = container.addItemAt(itemPosition); - Assert.assertEquals(itemPosition, container.indexOfId(addedId)); - Assert.assertEquals(itemPosition + 1, container.indexOfId(itemId)); - Assert.assertEquals(addedId, container.getIdByIndex(itemPosition)); - Assert.assertEquals(itemId, - container.getIdByIndex(itemPosition + 1)); - - Object newFirstId = container.addItemAt(0); - Assert.assertEquals(0, container.indexOfId(newFirstId)); - Assert.assertEquals(itemPosition + 2, container.indexOfId(itemId)); - Assert.assertEquals(newFirstId, container.firstItemId()); - Assert.assertEquals(newFirstId, container.getIdByIndex(0)); - Assert.assertEquals(itemId, - container.getIdByIndex(itemPosition + 2)); - - Object newLastId = container.addItemAt(container.size()); - Assert.assertEquals(container.size() - 1, - container.indexOfId(newLastId)); - Assert.assertEquals(itemPosition + 2, container.indexOfId(itemId)); - Assert.assertEquals(newLastId, container.lastItemId()); - Assert.assertEquals(newLastId, - container.getIdByIndex(container.size() - 1)); - Assert.assertEquals(itemId, - container.getIdByIndex(itemPosition + 2)); - - Assert.assertTrue(container.removeItem(addedId)); - Assert.assertTrue(container.removeItem(newFirstId)); - Assert.assertTrue(container.removeItem(newLastId)); - - Assert.assertFalse( - "Removing non-existing item should indicate failure", - container.removeItem(addedId)); - } - - // addItemAt - if (testAddItemAtWithId) { - container.addItemAt(itemPosition, newItemId); - Assert.assertEquals(itemPosition, container.indexOfId(newItemId)); - Assert.assertEquals(itemPosition + 1, container.indexOfId(itemId)); - Assert.assertEquals(newItemId, container.getIdByIndex(itemPosition)); - Assert.assertEquals(itemId, - container.getIdByIndex(itemPosition + 1)); - Assert.assertTrue(container.removeItem(newItemId)); - Assert.assertFalse(container.containsId(newItemId)); - - container.addItemAt(0, newItemId); - Assert.assertEquals(0, container.indexOfId(newItemId)); - Assert.assertEquals(itemPosition + 1, container.indexOfId(itemId)); - Assert.assertEquals(newItemId, container.firstItemId()); - Assert.assertEquals(newItemId, container.getIdByIndex(0)); - Assert.assertEquals(itemId, - container.getIdByIndex(itemPosition + 1)); - Assert.assertTrue(container.removeItem(newItemId)); - Assert.assertFalse(container.containsId(newItemId)); - - container.addItemAt(container.size(), newItemId); - Assert.assertEquals(container.size() - 1, - container.indexOfId(newItemId)); - Assert.assertEquals(itemPosition, container.indexOfId(itemId)); - Assert.assertEquals(newItemId, container.lastItemId()); - Assert.assertEquals(newItemId, - container.getIdByIndex(container.size() - 1)); - Assert.assertEquals(itemId, container.getIdByIndex(itemPosition)); - Assert.assertTrue(container.removeItem(newItemId)); - Assert.assertFalse(container.containsId(newItemId)); - } - } - - protected void testContainerFiltering(Container.Filterable container) { - initializeContainer(container); - - // Filter by "contains ab" - SimpleStringFilter filter1 = new SimpleStringFilter( - FULLY_QUALIFIED_NAME, "ab", false, false); - container.addContainerFilter(filter1); - - assertTrue(container.getContainerFilters().size() == 1); - assertEquals(filter1, container.getContainerFilters().iterator().next()); - - validateContainer(container, "com.vaadin.data.BufferedValidatable", - "com.vaadin.ui.TabSheet", - "com.vaadin.terminal.gwt.client.Focusable", - "com.vaadin.data.Buffered", isFilteredOutItemNull(), 20); - - // Filter by "contains da" (reversed as ad here) - container.removeAllContainerFilters(); - - assertTrue(container.getContainerFilters().isEmpty()); - - SimpleStringFilter filter2 = new SimpleStringFilter( - REVERSE_FULLY_QUALIFIED_NAME, "ad", false, false); - container.addContainerFilter(filter2); - - assertTrue(container.getContainerFilters().size() == 1); - assertEquals(filter2, container.getContainerFilters().iterator().next()); - - validateContainer(container, "com.vaadin.data.Buffered", - "com.vaadin.server.ComponentSizeValidator", - "com.vaadin.data.util.IndexedContainer", - "com.vaadin.terminal.gwt.client.ui.VUriFragmentUtility", - isFilteredOutItemNull(), 37); - } - - /** - * Override in subclasses to return false if the container getItem() method - * returns a non-null value for an item that has been filtered out. - * - * @return - */ - protected boolean isFilteredOutItemNull() { - return true; - } - - protected void testContainerSortingAndFiltering(Container.Sortable sortable) { - Filterable filterable = (Filterable) sortable; - - initializeContainer(sortable); - - // Filter by "contains ab" - filterable.addContainerFilter(new SimpleStringFilter( - FULLY_QUALIFIED_NAME, "ab", false, false)); - - // Must be able to sort based on PROP1 for this test - assertTrue(sortable.getSortableContainerPropertyIds().contains( - FULLY_QUALIFIED_NAME)); - - sortable.sort(new Object[] { FULLY_QUALIFIED_NAME }, - new boolean[] { true }); - - validateContainer(sortable, "com.vaadin.data.BufferedValidatable", - "com.vaadin.ui.TableFieldFactory", - "com.vaadin.ui.TableFieldFactory", - "com.vaadin.data.util.BeanItem", isFilteredOutItemNull(), 20); - } - - protected void testContainerSorting(Container.Filterable container) { - Container.Sortable sortable = (Sortable) container; - - initializeContainer(container); - - // Must be able to sort based on PROP1 for this test - assertTrue(sortable.getSortableContainerPropertyIds().contains( - FULLY_QUALIFIED_NAME)); - assertTrue(sortable.getSortableContainerPropertyIds().contains( - REVERSE_FULLY_QUALIFIED_NAME)); - - sortable.sort(new Object[] { FULLY_QUALIFIED_NAME }, - new boolean[] { true }); - - validateContainer(container, "com.vaadin.Application", - "org.vaadin.test.LastClass", - "com.vaadin.server.ApplicationResource", "blah", true, - sampleData.length); - - sortable.sort(new Object[] { REVERSE_FULLY_QUALIFIED_NAME }, - new boolean[] { true }); - - validateContainer(container, "com.vaadin.server.ApplicationPortlet2", - "com.vaadin.data.util.ObjectProperty", - "com.vaadin.ui.BaseFieldFactory", "blah", true, - sampleData.length); - - } - - protected void initializeContainer(Container container) { - Assert.assertTrue(container.removeAllItems()); - Object[] propertyIds = container.getContainerPropertyIds().toArray(); - for (Object propertyId : propertyIds) { - container.removeContainerProperty(propertyId); - } - - container.addContainerProperty(FULLY_QUALIFIED_NAME, String.class, ""); - container.addContainerProperty(SIMPLE_NAME, String.class, ""); - container.addContainerProperty(REVERSE_FULLY_QUALIFIED_NAME, - String.class, null); - container.addContainerProperty(ID_NUMBER, Integer.class, null); - - for (int i = 0; i < sampleData.length; i++) { - String id = sampleData[i]; - Item item = container.addItem(id); - - item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(sampleData[i]); - item.getItemProperty(SIMPLE_NAME).setValue( - getSimpleName(sampleData[i])); - item.getItemProperty(REVERSE_FULLY_QUALIFIED_NAME).setValue( - reverse(sampleData[i])); - item.getItemProperty(ID_NUMBER).setValue(i); - } - } - - protected static String getSimpleName(String name) { - if (name.contains(".")) { - return name.substring(name.lastIndexOf('.') + 1); - } else { - return name; - } - } - - protected static String reverse(String string) { - return new StringBuilder(string).reverse().toString(); - } - - protected final String[] sampleData = { - "com.vaadin.annotations.AutoGenerated", "com.vaadin.Application", - "com.vaadin.data.Buffered", "com.vaadin.data.BufferedValidatable", - "com.vaadin.data.Container", "com.vaadin.data.Item", - "com.vaadin.data.Property", "com.vaadin.data.util.BeanItem", - "com.vaadin.data.util.BeanItemContainer", - "com.vaadin.data.util.ContainerHierarchicalWrapper", - "com.vaadin.data.util.ContainerOrderedWrapper", - "com.vaadin.data.util.DefaultItemSorter", - "com.vaadin.data.util.FilesystemContainer", - "com.vaadin.data.util.Filter", - "com.vaadin.data.util.HierarchicalContainer", - "com.vaadin.data.util.IndexedContainer", - "com.vaadin.data.util.ItemSorter", - "com.vaadin.data.util.MethodProperty", - "com.vaadin.data.util.ObjectProperty", - "com.vaadin.data.util.PropertyFormatter", - "com.vaadin.data.util.PropertysetItem", - "com.vaadin.data.util.QueryContainer", - "com.vaadin.data.util.TextFileProperty", - "com.vaadin.data.Validatable", - "com.vaadin.data.validator.AbstractStringValidator", - "com.vaadin.data.validator.AbstractValidator", - "com.vaadin.data.validator.CompositeValidator", - "com.vaadin.data.validator.DoubleValidator", - "com.vaadin.data.validator.EmailValidator", - "com.vaadin.data.validator.IntegerValidator", - "com.vaadin.data.validator.NullValidator", - "com.vaadin.data.validator.RegexpValidator", - "com.vaadin.data.validator.StringLengthValidator", - "com.vaadin.data.Validator", "com.vaadin.event.Action", - "com.vaadin.event.ComponentEventListener", - "com.vaadin.event.EventRouter", "com.vaadin.event.FieldEvents", - "com.vaadin.event.ItemClickEvent", "com.vaadin.event.LayoutEvents", - "com.vaadin.event.ListenerMethod", - "com.vaadin.event.MethodEventSource", - "com.vaadin.event.MouseEvents", "com.vaadin.event.ShortcutAction", - "com.vaadin.launcher.DemoLauncher", - "com.vaadin.launcher.DevelopmentServerLauncher", - "com.vaadin.launcher.util.BrowserLauncher", - "com.vaadin.service.ApplicationContext", - "com.vaadin.service.FileTypeResolver", - "com.vaadin.server.ApplicationResource", - "com.vaadin.server.ClassResource", - "com.vaadin.server.CompositeErrorMessage", - "com.vaadin.server.DownloadStream", - "com.vaadin.server.ErrorMessage", - "com.vaadin.server.ExternalResource", - "com.vaadin.server.FileResource", - "com.vaadin.terminal.gwt.client.ApplicationConfiguration", - "com.vaadin.terminal.gwt.client.ApplicationConnection", - "com.vaadin.terminal.gwt.client.BrowserInfo", - "com.vaadin.terminal.gwt.client.ClientExceptionHandler", - "com.vaadin.terminal.gwt.client.ComponentDetail", - "com.vaadin.terminal.gwt.client.ComponentDetailMap", - "com.vaadin.terminal.gwt.client.ComponentLocator", - "com.vaadin.terminal.gwt.client.Console", - "com.vaadin.terminal.gwt.client.Container", - "com.vaadin.terminal.gwt.client.ContainerResizedListener", - "com.vaadin.terminal.gwt.client.CSSRule", - "com.vaadin.terminal.gwt.client.DateTimeService", - "com.vaadin.terminal.gwt.client.DefaultWidgetSet", - "com.vaadin.terminal.gwt.client.Focusable", - "com.vaadin.terminal.gwt.client.HistoryImplIEVaadin", - "com.vaadin.terminal.gwt.client.LocaleNotLoadedException", - "com.vaadin.terminal.gwt.client.LocaleService", - "com.vaadin.terminal.gwt.client.MouseEventDetails", - "com.vaadin.terminal.gwt.client.NullConsole", - "com.vaadin.terminal.gwt.client.Paintable", - "com.vaadin.terminal.gwt.client.RenderInformation", - "com.vaadin.terminal.gwt.client.RenderSpace", - "com.vaadin.terminal.gwt.client.StyleConstants", - "com.vaadin.terminal.gwt.client.TooltipInfo", - "com.vaadin.terminal.gwt.client.ui.Action", - "com.vaadin.terminal.gwt.client.ui.ActionOwner", - "com.vaadin.terminal.gwt.client.ui.AlignmentInfo", - "com.vaadin.terminal.gwt.client.ui.CalendarEntry", - "com.vaadin.terminal.gwt.client.ui.ClickEventHandler", - "com.vaadin.terminal.gwt.client.ui.Field", - "com.vaadin.terminal.gwt.client.ui.Icon", - "com.vaadin.terminal.gwt.client.ui.layout.CellBasedLayout", - "com.vaadin.terminal.gwt.client.ui.layout.ChildComponentContainer", - "com.vaadin.terminal.gwt.client.ui.layout.Margins", - "com.vaadin.terminal.gwt.client.ui.LayoutClickEventHandler", - "com.vaadin.terminal.gwt.client.ui.MenuBar", - "com.vaadin.terminal.gwt.client.ui.MenuItem", - "com.vaadin.terminal.gwt.client.ui.richtextarea.VRichTextToolbar", - "com.vaadin.terminal.gwt.client.ui.ShortcutActionHandler", - "com.vaadin.terminal.gwt.client.ui.SubPartAware", - "com.vaadin.terminal.gwt.client.ui.Table", - "com.vaadin.terminal.gwt.client.ui.TreeAction", - "com.vaadin.terminal.gwt.client.ui.TreeImages", - "com.vaadin.terminal.gwt.client.ui.VAbsoluteLayout", - "com.vaadin.terminal.gwt.client.ui.VAccordion", - "com.vaadin.terminal.gwt.client.ui.VButton", - "com.vaadin.terminal.gwt.client.ui.VCalendarPanel", - "com.vaadin.terminal.gwt.client.ui.VCheckBox", - "com.vaadin.terminal.gwt.client.ui.VContextMenu", - "com.vaadin.terminal.gwt.client.ui.VCssLayout", - "com.vaadin.terminal.gwt.client.ui.VCustomComponent", - "com.vaadin.terminal.gwt.client.ui.VCustomLayout", - "com.vaadin.terminal.gwt.client.ui.VDateField", - "com.vaadin.terminal.gwt.client.ui.VDateFieldCalendar", - "com.vaadin.terminal.gwt.client.ui.VEmbedded", - "com.vaadin.terminal.gwt.client.ui.VFilterSelect", - "com.vaadin.terminal.gwt.client.ui.VForm", - "com.vaadin.terminal.gwt.client.ui.VFormLayout", - "com.vaadin.terminal.gwt.client.ui.VGridLayout", - "com.vaadin.terminal.gwt.client.ui.VHorizontalLayout", - "com.vaadin.terminal.gwt.client.ui.VLabel", - "com.vaadin.terminal.gwt.client.ui.VLink", - "com.vaadin.terminal.gwt.client.ui.VListSelect", - "com.vaadin.terminal.gwt.client.ui.VMarginInfo", - "com.vaadin.terminal.gwt.client.ui.VMenuBar", - "com.vaadin.terminal.gwt.client.ui.VNativeButton", - "com.vaadin.terminal.gwt.client.ui.VNativeSelect", - "com.vaadin.terminal.gwt.client.ui.VNotification", - "com.vaadin.terminal.gwt.client.ui.VOptionGroup", - "com.vaadin.terminal.gwt.client.ui.VOptionGroupBase", - "com.vaadin.terminal.gwt.client.ui.VOrderedLayout", - "com.vaadin.terminal.gwt.client.ui.VOverlay", - "com.vaadin.terminal.gwt.client.ui.VPanel", - "com.vaadin.terminal.gwt.client.ui.VPasswordField", - "com.vaadin.terminal.gwt.client.ui.VPopupCalendar", - "com.vaadin.terminal.gwt.client.ui.VPopupView", - "com.vaadin.terminal.gwt.client.ui.VProgressIndicator", - "com.vaadin.terminal.gwt.client.ui.VRichTextArea", - "com.vaadin.terminal.gwt.client.ui.VScrollTable", - "com.vaadin.terminal.gwt.client.ui.VSlider", - "com.vaadin.terminal.gwt.client.ui.VSplitPanel", - "com.vaadin.terminal.gwt.client.ui.VSplitPanelHorizontal", - "com.vaadin.terminal.gwt.client.ui.VSplitPanelVertical", - "com.vaadin.terminal.gwt.client.ui.VTablePaging", - "com.vaadin.terminal.gwt.client.ui.VTabsheet", - "com.vaadin.terminal.gwt.client.ui.VTabsheetBase", - "com.vaadin.terminal.gwt.client.ui.VTabsheetPanel", - "com.vaadin.terminal.gwt.client.ui.VTextArea", - "com.vaadin.terminal.gwt.client.ui.VTextField", - "com.vaadin.terminal.gwt.client.ui.VTextualDate", - "com.vaadin.terminal.gwt.client.ui.VTime", - "com.vaadin.terminal.gwt.client.ui.VTree", - "com.vaadin.terminal.gwt.client.ui.VTwinColSelect", - "com.vaadin.terminal.gwt.client.ui.VUnknownComponent", - "com.vaadin.terminal.gwt.client.ui.VUpload", - "com.vaadin.terminal.gwt.client.ui.VUriFragmentUtility", - "com.vaadin.terminal.gwt.client.ui.VVerticalLayout", - "com.vaadin.terminal.gwt.client.ui.VView", - "com.vaadin.terminal.gwt.client.ui.VWindow", - "com.vaadin.terminal.gwt.client.UIDL", - "com.vaadin.terminal.gwt.client.Util", - "com.vaadin.terminal.gwt.client.ValueMap", - "com.vaadin.terminal.gwt.client.VCaption", - "com.vaadin.terminal.gwt.client.VCaptionWrapper", - "com.vaadin.terminal.gwt.client.VDebugConsole", - "com.vaadin.terminal.gwt.client.VErrorMessage", - "com.vaadin.terminal.gwt.client.VTooltip", - "com.vaadin.terminal.gwt.client.VUIDLBrowser", - "com.vaadin.terminal.gwt.client.WidgetMap", - "com.vaadin.terminal.gwt.client.WidgetSet", - "com.vaadin.server.AbstractApplicationPortlet", - "com.vaadin.server.AbstractApplicationServlet", - "com.vaadin.server.AbstractCommunicationManager", - "com.vaadin.server.AbstractWebApplicationContext", - "com.vaadin.server.ApplicationPortlet", - "com.vaadin.server.ApplicationPortlet2", - "com.vaadin.server.ApplicationRunnerServlet", - "com.vaadin.server.ApplicationServlet", - "com.vaadin.server.ChangeVariablesErrorEvent", - "com.vaadin.server.CommunicationManager", - "com.vaadin.server.ComponentSizeValidator", - "com.vaadin.server.Constants", - "com.vaadin.server.GAEApplicationServlet", - "com.vaadin.server.HttpServletRequestListener", - "com.vaadin.server.HttpUploadStream", - "com.vaadin.server.JsonPaintTarget", - "com.vaadin.server.PortletApplicationContext", - "com.vaadin.server.PortletApplicationContext2", - "com.vaadin.server.PortletCommunicationManager", - "com.vaadin.server.PortletRequestListener", - "com.vaadin.server.RestrictedRenderResponse", - "com.vaadin.server.SessionExpiredException", - "com.vaadin.server.SystemMessageException", - "com.vaadin.server.WebApplicationContext", - "com.vaadin.server.WebBrowser", - "com.vaadin.server.widgetsetutils.ClassPathExplorer", - "com.vaadin.server.widgetsetutils.WidgetMapGenerator", - "com.vaadin.server.widgetsetutils.WidgetSetBuilder", - "com.vaadin.server.KeyMapper", "com.vaadin.server.Paintable", - "com.vaadin.server.PaintException", - "com.vaadin.server.PaintTarget", - "com.vaadin.server.ParameterHandler", "com.vaadin.server.Resource", - "com.vaadin.server.Scrollable", "com.vaadin.server.Sizeable", - "com.vaadin.server.StreamResource", - "com.vaadin.server.SystemError", "com.vaadin.server.Terminal", - "com.vaadin.server.ThemeResource", - "com.vaadin.server.UploadStream", "com.vaadin.server.URIHandler", - "com.vaadin.server.UserError", "com.vaadin.server.VariableOwner", - "com.vaadin.tools.ReflectTools", - "com.vaadin.tools.WidgetsetCompiler", - "com.vaadin.ui.AbsoluteLayout", "com.vaadin.ui.AbstractComponent", - "com.vaadin.ui.AbstractComponentContainer", - "com.vaadin.ui.AbstractField", "com.vaadin.ui.AbstractLayout", - "com.vaadin.ui.AbstractOrderedLayout", - "com.vaadin.ui.AbstractSelect", "com.vaadin.ui.Accordion", - "com.vaadin.ui.Alignment", "com.vaadin.ui.AlignmentUtils", - "com.vaadin.ui.BaseFieldFactory", "com.vaadin.ui.Button", - "com.vaadin.ui.CheckBox", "com.vaadin.ui.ClientWidget", - "com.vaadin.ui.ComboBox", "com.vaadin.ui.Component", - "com.vaadin.ui.ComponentContainer", "com.vaadin.ui.CssLayout", - "com.vaadin.ui.CustomComponent", "com.vaadin.ui.CustomLayout", - "com.vaadin.ui.DateField", "com.vaadin.ui.DefaultFieldFactory", - "com.vaadin.ui.Embedded", "com.vaadin.ui.ExpandLayout", - "com.vaadin.ui.Field", "com.vaadin.ui.FieldFactory", - "com.vaadin.ui.Form", "com.vaadin.ui.FormFieldFactory", - "com.vaadin.ui.FormLayout", "com.vaadin.ui.GridLayout", - "com.vaadin.ui.HorizontalLayout", "com.vaadin.ui.InlineDateField", - "com.vaadin.ui.Label", "com.vaadin.ui.Layout", - "com.vaadin.ui.Link", "com.vaadin.ui.ListSelect", - "com.vaadin.ui.LoginForm", "com.vaadin.ui.MenuBar", - "com.vaadin.ui.NativeButton", "com.vaadin.ui.NativeSelect", - "com.vaadin.ui.OptionGroup", "com.vaadin.ui.OrderedLayout", - "com.vaadin.ui.Panel", "com.vaadin.ui.PopupDateField", - "com.vaadin.ui.PopupView", "com.vaadin.ui.ProgressIndicator", - "com.vaadin.ui.RichTextArea", "com.vaadin.ui.Select", - "com.vaadin.ui.Slider", "com.vaadin.ui.SplitPanel", - "com.vaadin.ui.Table", "com.vaadin.ui.TableFieldFactory", - "com.vaadin.ui.TabSheet", "com.vaadin.ui.TextField", - "com.vaadin.ui.Tree", "com.vaadin.ui.TwinColSelect", - "com.vaadin.ui.Upload", "com.vaadin.ui.UriFragmentUtility", - "com.vaadin.ui.VerticalLayout", "com.vaadin.ui.Window", - "com.vaadin.util.SerializerHelper", "org.vaadin.test.LastClass" }; -} diff --git a/server/tests/src/com/vaadin/data/util/AbstractContainerTestBase.java b/server/tests/src/com/vaadin/data/util/AbstractContainerTestBase.java new file mode 100644 index 0000000000..54cbc5305d --- /dev/null +++ b/server/tests/src/com/vaadin/data/util/AbstractContainerTestBase.java @@ -0,0 +1,679 @@ +package com.vaadin.data.util; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.vaadin.data.Container; +import com.vaadin.data.Container.Filterable; +import com.vaadin.data.Container.ItemSetChangeEvent; +import com.vaadin.data.Container.ItemSetChangeListener; +import com.vaadin.data.Container.Sortable; +import com.vaadin.data.Item; +import com.vaadin.data.util.filter.SimpleStringFilter; + +public abstract class AbstractContainerTestBase extends TestCase { + + /** + * Helper class for testing e.g. listeners expecting events to be fired. + */ + protected abstract static class AbstractEventCounter { + private int eventCount = 0; + private int lastAssertedEventCount = 0; + + /** + * Increment the event count. To be called by subclasses e.g. from a + * listener method. + */ + protected void increment() { + ++eventCount; + } + + /** + * Check that no one event has occurred since the previous assert call. + */ + public void assertNone() { + Assert.assertEquals(lastAssertedEventCount, eventCount); + } + + /** + * Check that exactly one event has occurred since the previous assert + * call. + */ + public void assertOnce() { + Assert.assertEquals(++lastAssertedEventCount, eventCount); + } + + /** + * Reset the counter and the expected count. + */ + public void reset() { + eventCount = 0; + lastAssertedEventCount = 0; + } + } + + /** + * Test class for counting item set change events and verifying they have + * been received. + */ + protected static class ItemSetChangeCounter extends AbstractEventCounter + implements ItemSetChangeListener { + + @Override + public void containerItemSetChange(ItemSetChangeEvent event) { + increment(); + } + + } + + // #6043: for items that have been filtered out, Container interface does + // not specify what to return from getItem() and getContainerProperty(), so + // need checkGetItemNull parameter for the test to be usable for most + // current containers + protected void validateContainer(Container container, + Object expectedFirstItemId, Object expectedLastItemId, + Object itemIdInSet, Object itemIdNotInSet, + boolean checkGetItemNull, int expectedSize) { + Container.Indexed indexed = null; + if (container instanceof Container.Indexed) { + indexed = (Container.Indexed) container; + } + + List itemIdList = new ArrayList(container.getItemIds()); + + // size() + assertEquals(expectedSize, container.size()); + assertEquals(expectedSize, itemIdList.size()); + + // first item, last item + Object first = itemIdList.get(0); + Object last = itemIdList.get(itemIdList.size() - 1); + + assertEquals(expectedFirstItemId, first); + assertEquals(expectedLastItemId, last); + + // containsId + assertFalse(container.containsId(itemIdNotInSet)); + assertTrue(container.containsId(itemIdInSet)); + + // getItem + if (checkGetItemNull) { + assertNull(container.getItem(itemIdNotInSet)); + } + assertNotNull(container.getItem(itemIdInSet)); + + // getContainerProperty + for (Object propId : container.getContainerPropertyIds()) { + if (checkGetItemNull) { + assertNull(container.getContainerProperty(itemIdNotInSet, + propId)); + } + assertNotNull(container.getContainerProperty(itemIdInSet, propId)); + } + + if (indexed != null) { + // firstItemId + assertEquals(first, indexed.firstItemId()); + + // lastItemId + assertEquals(last, indexed.lastItemId()); + + // nextItemId + assertEquals(itemIdList.get(1), indexed.nextItemId(first)); + + // prevItemId + assertEquals(itemIdList.get(itemIdList.size() - 2), + indexed.prevItemId(last)); + + // isFirstId + assertTrue(indexed.isFirstId(first)); + assertFalse(indexed.isFirstId(last)); + + // isLastId + assertTrue(indexed.isLastId(last)); + assertFalse(indexed.isLastId(first)); + + // indexOfId + assertEquals(0, indexed.indexOfId(first)); + assertEquals(expectedSize - 1, indexed.indexOfId(last)); + + // getIdByIndex + assertEquals(indexed.getIdByIndex(0), first); + assertEquals(indexed.getIdByIndex(expectedSize - 1), last); + + } + + } + + protected static final Object FULLY_QUALIFIED_NAME = "fullyQualifiedName"; + protected static final Object SIMPLE_NAME = "simpleName"; + protected static final Object REVERSE_FULLY_QUALIFIED_NAME = "reverseFullyQualifiedName"; + protected static final Object ID_NUMBER = "idNumber"; + + protected void testBasicContainerOperations(Container container) { + initializeContainer(container); + + // Basic container + validateContainer(container, sampleData[0], + sampleData[sampleData.length - 1], sampleData[10], "abc", true, + sampleData.length); + } + + protected void testContainerOrdered(Container.Ordered container) { + Object id = container.addItem(); + assertNotNull(id); + Item item = container.getItem(id); + assertNotNull(item); + + assertEquals(id, container.firstItemId()); + assertEquals(id, container.lastItemId()); + + // isFirstId + assertTrue(container.isFirstId(id)); + assertTrue(container.isFirstId(container.firstItemId())); + // isLastId + assertTrue(container.isLastId(id)); + assertTrue(container.isLastId(container.lastItemId())); + + // Add a new item before the first + // addItemAfter + Object newFirstId = container.addItemAfter(null); + assertNotNull(newFirstId); + assertNotNull(container.getItem(newFirstId)); + + // isFirstId + assertTrue(container.isFirstId(newFirstId)); + assertTrue(container.isFirstId(container.firstItemId())); + // isLastId + assertTrue(container.isLastId(id)); + assertTrue(container.isLastId(container.lastItemId())); + + // nextItemId + assertEquals(id, container.nextItemId(newFirstId)); + assertNull(container.nextItemId(id)); + assertNull(container.nextItemId("not-in-container")); + + // prevItemId + assertEquals(newFirstId, container.prevItemId(id)); + assertNull(container.prevItemId(newFirstId)); + assertNull(container.prevItemId("not-in-container")); + + // addItemAfter(Object) + Object newSecondItemId = container.addItemAfter(newFirstId); + // order is now: newFirstId, newSecondItemId, id + assertNotNull(newSecondItemId); + assertNotNull(container.getItem(newSecondItemId)); + assertEquals(id, container.nextItemId(newSecondItemId)); + assertEquals(newFirstId, container.prevItemId(newSecondItemId)); + + // addItemAfter(Object,Object) + String fourthId = "id of the fourth item"; + Item fourth = container.addItemAfter(newFirstId, fourthId); + // order is now: newFirstId, fourthId, newSecondItemId, id + assertNotNull(fourth); + assertEquals(fourth, container.getItem(fourthId)); + assertEquals(newSecondItemId, container.nextItemId(fourthId)); + assertEquals(newFirstId, container.prevItemId(fourthId)); + + // addItemAfter(Object,Object) + Object fifthId = new Object(); + Item fifth = container.addItemAfter(null, fifthId); + // order is now: fifthId, newFirstId, fourthId, newSecondItemId, id + assertNotNull(fifth); + assertEquals(fifth, container.getItem(fifthId)); + assertEquals(newFirstId, container.nextItemId(fifthId)); + assertNull(container.prevItemId(fifthId)); + + } + + protected void testContainerIndexed(Container.Indexed container, + Object itemId, int itemPosition, boolean testAddEmptyItemAt, + Object newItemId, boolean testAddItemAtWithId) { + initializeContainer(container); + + // indexOfId + Assert.assertEquals(itemPosition, container.indexOfId(itemId)); + + // getIdByIndex + Assert.assertEquals(itemId, container.getIdByIndex(itemPosition)); + + // addItemAt + if (testAddEmptyItemAt) { + Object addedId = container.addItemAt(itemPosition); + Assert.assertEquals(itemPosition, container.indexOfId(addedId)); + Assert.assertEquals(itemPosition + 1, container.indexOfId(itemId)); + Assert.assertEquals(addedId, container.getIdByIndex(itemPosition)); + Assert.assertEquals(itemId, + container.getIdByIndex(itemPosition + 1)); + + Object newFirstId = container.addItemAt(0); + Assert.assertEquals(0, container.indexOfId(newFirstId)); + Assert.assertEquals(itemPosition + 2, container.indexOfId(itemId)); + Assert.assertEquals(newFirstId, container.firstItemId()); + Assert.assertEquals(newFirstId, container.getIdByIndex(0)); + Assert.assertEquals(itemId, + container.getIdByIndex(itemPosition + 2)); + + Object newLastId = container.addItemAt(container.size()); + Assert.assertEquals(container.size() - 1, + container.indexOfId(newLastId)); + Assert.assertEquals(itemPosition + 2, container.indexOfId(itemId)); + Assert.assertEquals(newLastId, container.lastItemId()); + Assert.assertEquals(newLastId, + container.getIdByIndex(container.size() - 1)); + Assert.assertEquals(itemId, + container.getIdByIndex(itemPosition + 2)); + + Assert.assertTrue(container.removeItem(addedId)); + Assert.assertTrue(container.removeItem(newFirstId)); + Assert.assertTrue(container.removeItem(newLastId)); + + Assert.assertFalse( + "Removing non-existing item should indicate failure", + container.removeItem(addedId)); + } + + // addItemAt + if (testAddItemAtWithId) { + container.addItemAt(itemPosition, newItemId); + Assert.assertEquals(itemPosition, container.indexOfId(newItemId)); + Assert.assertEquals(itemPosition + 1, container.indexOfId(itemId)); + Assert.assertEquals(newItemId, container.getIdByIndex(itemPosition)); + Assert.assertEquals(itemId, + container.getIdByIndex(itemPosition + 1)); + Assert.assertTrue(container.removeItem(newItemId)); + Assert.assertFalse(container.containsId(newItemId)); + + container.addItemAt(0, newItemId); + Assert.assertEquals(0, container.indexOfId(newItemId)); + Assert.assertEquals(itemPosition + 1, container.indexOfId(itemId)); + Assert.assertEquals(newItemId, container.firstItemId()); + Assert.assertEquals(newItemId, container.getIdByIndex(0)); + Assert.assertEquals(itemId, + container.getIdByIndex(itemPosition + 1)); + Assert.assertTrue(container.removeItem(newItemId)); + Assert.assertFalse(container.containsId(newItemId)); + + container.addItemAt(container.size(), newItemId); + Assert.assertEquals(container.size() - 1, + container.indexOfId(newItemId)); + Assert.assertEquals(itemPosition, container.indexOfId(itemId)); + Assert.assertEquals(newItemId, container.lastItemId()); + Assert.assertEquals(newItemId, + container.getIdByIndex(container.size() - 1)); + Assert.assertEquals(itemId, container.getIdByIndex(itemPosition)); + Assert.assertTrue(container.removeItem(newItemId)); + Assert.assertFalse(container.containsId(newItemId)); + } + } + + protected void testContainerFiltering(Container.Filterable container) { + initializeContainer(container); + + // Filter by "contains ab" + SimpleStringFilter filter1 = new SimpleStringFilter( + FULLY_QUALIFIED_NAME, "ab", false, false); + container.addContainerFilter(filter1); + + assertTrue(container.getContainerFilters().size() == 1); + assertEquals(filter1, container.getContainerFilters().iterator().next()); + + validateContainer(container, "com.vaadin.data.BufferedValidatable", + "com.vaadin.ui.TabSheet", + "com.vaadin.terminal.gwt.client.Focusable", + "com.vaadin.data.Buffered", isFilteredOutItemNull(), 20); + + // Filter by "contains da" (reversed as ad here) + container.removeAllContainerFilters(); + + assertTrue(container.getContainerFilters().isEmpty()); + + SimpleStringFilter filter2 = new SimpleStringFilter( + REVERSE_FULLY_QUALIFIED_NAME, "ad", false, false); + container.addContainerFilter(filter2); + + assertTrue(container.getContainerFilters().size() == 1); + assertEquals(filter2, container.getContainerFilters().iterator().next()); + + validateContainer(container, "com.vaadin.data.Buffered", + "com.vaadin.server.ComponentSizeValidator", + "com.vaadin.data.util.IndexedContainer", + "com.vaadin.terminal.gwt.client.ui.VUriFragmentUtility", + isFilteredOutItemNull(), 37); + } + + /** + * Override in subclasses to return false if the container getItem() method + * returns a non-null value for an item that has been filtered out. + * + * @return + */ + protected boolean isFilteredOutItemNull() { + return true; + } + + protected void testContainerSortingAndFiltering(Container.Sortable sortable) { + Filterable filterable = (Filterable) sortable; + + initializeContainer(sortable); + + // Filter by "contains ab" + filterable.addContainerFilter(new SimpleStringFilter( + FULLY_QUALIFIED_NAME, "ab", false, false)); + + // Must be able to sort based on PROP1 for this test + assertTrue(sortable.getSortableContainerPropertyIds().contains( + FULLY_QUALIFIED_NAME)); + + sortable.sort(new Object[] { FULLY_QUALIFIED_NAME }, + new boolean[] { true }); + + validateContainer(sortable, "com.vaadin.data.BufferedValidatable", + "com.vaadin.ui.TableFieldFactory", + "com.vaadin.ui.TableFieldFactory", + "com.vaadin.data.util.BeanItem", isFilteredOutItemNull(), 20); + } + + protected void testContainerSorting(Container.Filterable container) { + Container.Sortable sortable = (Sortable) container; + + initializeContainer(container); + + // Must be able to sort based on PROP1 for this test + assertTrue(sortable.getSortableContainerPropertyIds().contains( + FULLY_QUALIFIED_NAME)); + assertTrue(sortable.getSortableContainerPropertyIds().contains( + REVERSE_FULLY_QUALIFIED_NAME)); + + sortable.sort(new Object[] { FULLY_QUALIFIED_NAME }, + new boolean[] { true }); + + validateContainer(container, "com.vaadin.Application", + "org.vaadin.test.LastClass", + "com.vaadin.server.ApplicationResource", "blah", true, + sampleData.length); + + sortable.sort(new Object[] { REVERSE_FULLY_QUALIFIED_NAME }, + new boolean[] { true }); + + validateContainer(container, "com.vaadin.server.ApplicationPortlet2", + "com.vaadin.data.util.ObjectProperty", + "com.vaadin.ui.BaseFieldFactory", "blah", true, + sampleData.length); + + } + + protected void initializeContainer(Container container) { + Assert.assertTrue(container.removeAllItems()); + Object[] propertyIds = container.getContainerPropertyIds().toArray(); + for (Object propertyId : propertyIds) { + container.removeContainerProperty(propertyId); + } + + container.addContainerProperty(FULLY_QUALIFIED_NAME, String.class, ""); + container.addContainerProperty(SIMPLE_NAME, String.class, ""); + container.addContainerProperty(REVERSE_FULLY_QUALIFIED_NAME, + String.class, null); + container.addContainerProperty(ID_NUMBER, Integer.class, null); + + for (int i = 0; i < sampleData.length; i++) { + String id = sampleData[i]; + Item item = container.addItem(id); + + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(sampleData[i]); + item.getItemProperty(SIMPLE_NAME).setValue( + getSimpleName(sampleData[i])); + item.getItemProperty(REVERSE_FULLY_QUALIFIED_NAME).setValue( + reverse(sampleData[i])); + item.getItemProperty(ID_NUMBER).setValue(i); + } + } + + protected static String getSimpleName(String name) { + if (name.contains(".")) { + return name.substring(name.lastIndexOf('.') + 1); + } else { + return name; + } + } + + protected static String reverse(String string) { + return new StringBuilder(string).reverse().toString(); + } + + protected final String[] sampleData = { + "com.vaadin.annotations.AutoGenerated", "com.vaadin.Application", + "com.vaadin.data.Buffered", "com.vaadin.data.BufferedValidatable", + "com.vaadin.data.Container", "com.vaadin.data.Item", + "com.vaadin.data.Property", "com.vaadin.data.util.BeanItem", + "com.vaadin.data.util.BeanItemContainer", + "com.vaadin.data.util.ContainerHierarchicalWrapper", + "com.vaadin.data.util.ContainerOrderedWrapper", + "com.vaadin.data.util.DefaultItemSorter", + "com.vaadin.data.util.FilesystemContainer", + "com.vaadin.data.util.Filter", + "com.vaadin.data.util.HierarchicalContainer", + "com.vaadin.data.util.IndexedContainer", + "com.vaadin.data.util.ItemSorter", + "com.vaadin.data.util.MethodProperty", + "com.vaadin.data.util.ObjectProperty", + "com.vaadin.data.util.PropertyFormatter", + "com.vaadin.data.util.PropertysetItem", + "com.vaadin.data.util.QueryContainer", + "com.vaadin.data.util.TextFileProperty", + "com.vaadin.data.Validatable", + "com.vaadin.data.validator.AbstractStringValidator", + "com.vaadin.data.validator.AbstractValidator", + "com.vaadin.data.validator.CompositeValidator", + "com.vaadin.data.validator.DoubleValidator", + "com.vaadin.data.validator.EmailValidator", + "com.vaadin.data.validator.IntegerValidator", + "com.vaadin.data.validator.NullValidator", + "com.vaadin.data.validator.RegexpValidator", + "com.vaadin.data.validator.StringLengthValidator", + "com.vaadin.data.Validator", "com.vaadin.event.Action", + "com.vaadin.event.ComponentEventListener", + "com.vaadin.event.EventRouter", "com.vaadin.event.FieldEvents", + "com.vaadin.event.ItemClickEvent", "com.vaadin.event.LayoutEvents", + "com.vaadin.event.ListenerMethod", + "com.vaadin.event.MethodEventSource", + "com.vaadin.event.MouseEvents", "com.vaadin.event.ShortcutAction", + "com.vaadin.launcher.DemoLauncher", + "com.vaadin.launcher.DevelopmentServerLauncher", + "com.vaadin.launcher.util.BrowserLauncher", + "com.vaadin.service.ApplicationContext", + "com.vaadin.service.FileTypeResolver", + "com.vaadin.server.ApplicationResource", + "com.vaadin.server.ClassResource", + "com.vaadin.server.CompositeErrorMessage", + "com.vaadin.server.DownloadStream", + "com.vaadin.server.ErrorMessage", + "com.vaadin.server.ExternalResource", + "com.vaadin.server.FileResource", + "com.vaadin.terminal.gwt.client.ApplicationConfiguration", + "com.vaadin.terminal.gwt.client.ApplicationConnection", + "com.vaadin.terminal.gwt.client.BrowserInfo", + "com.vaadin.terminal.gwt.client.ClientExceptionHandler", + "com.vaadin.terminal.gwt.client.ComponentDetail", + "com.vaadin.terminal.gwt.client.ComponentDetailMap", + "com.vaadin.terminal.gwt.client.ComponentLocator", + "com.vaadin.terminal.gwt.client.Console", + "com.vaadin.terminal.gwt.client.Container", + "com.vaadin.terminal.gwt.client.ContainerResizedListener", + "com.vaadin.terminal.gwt.client.CSSRule", + "com.vaadin.terminal.gwt.client.DateTimeService", + "com.vaadin.terminal.gwt.client.DefaultWidgetSet", + "com.vaadin.terminal.gwt.client.Focusable", + "com.vaadin.terminal.gwt.client.HistoryImplIEVaadin", + "com.vaadin.terminal.gwt.client.LocaleNotLoadedException", + "com.vaadin.terminal.gwt.client.LocaleService", + "com.vaadin.terminal.gwt.client.MouseEventDetails", + "com.vaadin.terminal.gwt.client.NullConsole", + "com.vaadin.terminal.gwt.client.Paintable", + "com.vaadin.terminal.gwt.client.RenderInformation", + "com.vaadin.terminal.gwt.client.RenderSpace", + "com.vaadin.terminal.gwt.client.StyleConstants", + "com.vaadin.terminal.gwt.client.TooltipInfo", + "com.vaadin.terminal.gwt.client.ui.Action", + "com.vaadin.terminal.gwt.client.ui.ActionOwner", + "com.vaadin.terminal.gwt.client.ui.AlignmentInfo", + "com.vaadin.terminal.gwt.client.ui.CalendarEntry", + "com.vaadin.terminal.gwt.client.ui.ClickEventHandler", + "com.vaadin.terminal.gwt.client.ui.Field", + "com.vaadin.terminal.gwt.client.ui.Icon", + "com.vaadin.terminal.gwt.client.ui.layout.CellBasedLayout", + "com.vaadin.terminal.gwt.client.ui.layout.ChildComponentContainer", + "com.vaadin.terminal.gwt.client.ui.layout.Margins", + "com.vaadin.terminal.gwt.client.ui.LayoutClickEventHandler", + "com.vaadin.terminal.gwt.client.ui.MenuBar", + "com.vaadin.terminal.gwt.client.ui.MenuItem", + "com.vaadin.terminal.gwt.client.ui.richtextarea.VRichTextToolbar", + "com.vaadin.terminal.gwt.client.ui.ShortcutActionHandler", + "com.vaadin.terminal.gwt.client.ui.SubPartAware", + "com.vaadin.terminal.gwt.client.ui.Table", + "com.vaadin.terminal.gwt.client.ui.TreeAction", + "com.vaadin.terminal.gwt.client.ui.TreeImages", + "com.vaadin.terminal.gwt.client.ui.VAbsoluteLayout", + "com.vaadin.terminal.gwt.client.ui.VAccordion", + "com.vaadin.terminal.gwt.client.ui.VButton", + "com.vaadin.terminal.gwt.client.ui.VCalendarPanel", + "com.vaadin.terminal.gwt.client.ui.VCheckBox", + "com.vaadin.terminal.gwt.client.ui.VContextMenu", + "com.vaadin.terminal.gwt.client.ui.VCssLayout", + "com.vaadin.terminal.gwt.client.ui.VCustomComponent", + "com.vaadin.terminal.gwt.client.ui.VCustomLayout", + "com.vaadin.terminal.gwt.client.ui.VDateField", + "com.vaadin.terminal.gwt.client.ui.VDateFieldCalendar", + "com.vaadin.terminal.gwt.client.ui.VEmbedded", + "com.vaadin.terminal.gwt.client.ui.VFilterSelect", + "com.vaadin.terminal.gwt.client.ui.VForm", + "com.vaadin.terminal.gwt.client.ui.VFormLayout", + "com.vaadin.terminal.gwt.client.ui.VGridLayout", + "com.vaadin.terminal.gwt.client.ui.VHorizontalLayout", + "com.vaadin.terminal.gwt.client.ui.VLabel", + "com.vaadin.terminal.gwt.client.ui.VLink", + "com.vaadin.terminal.gwt.client.ui.VListSelect", + "com.vaadin.terminal.gwt.client.ui.VMarginInfo", + "com.vaadin.terminal.gwt.client.ui.VMenuBar", + "com.vaadin.terminal.gwt.client.ui.VNativeButton", + "com.vaadin.terminal.gwt.client.ui.VNativeSelect", + "com.vaadin.terminal.gwt.client.ui.VNotification", + "com.vaadin.terminal.gwt.client.ui.VOptionGroup", + "com.vaadin.terminal.gwt.client.ui.VOptionGroupBase", + "com.vaadin.terminal.gwt.client.ui.VOrderedLayout", + "com.vaadin.terminal.gwt.client.ui.VOverlay", + "com.vaadin.terminal.gwt.client.ui.VPanel", + "com.vaadin.terminal.gwt.client.ui.VPasswordField", + "com.vaadin.terminal.gwt.client.ui.VPopupCalendar", + "com.vaadin.terminal.gwt.client.ui.VPopupView", + "com.vaadin.terminal.gwt.client.ui.VProgressIndicator", + "com.vaadin.terminal.gwt.client.ui.VRichTextArea", + "com.vaadin.terminal.gwt.client.ui.VScrollTable", + "com.vaadin.terminal.gwt.client.ui.VSlider", + "com.vaadin.terminal.gwt.client.ui.VSplitPanel", + "com.vaadin.terminal.gwt.client.ui.VSplitPanelHorizontal", + "com.vaadin.terminal.gwt.client.ui.VSplitPanelVertical", + "com.vaadin.terminal.gwt.client.ui.VTablePaging", + "com.vaadin.terminal.gwt.client.ui.VTabsheet", + "com.vaadin.terminal.gwt.client.ui.VTabsheetBase", + "com.vaadin.terminal.gwt.client.ui.VTabsheetPanel", + "com.vaadin.terminal.gwt.client.ui.VTextArea", + "com.vaadin.terminal.gwt.client.ui.VTextField", + "com.vaadin.terminal.gwt.client.ui.VTextualDate", + "com.vaadin.terminal.gwt.client.ui.VTime", + "com.vaadin.terminal.gwt.client.ui.VTree", + "com.vaadin.terminal.gwt.client.ui.VTwinColSelect", + "com.vaadin.terminal.gwt.client.ui.VUnknownComponent", + "com.vaadin.terminal.gwt.client.ui.VUpload", + "com.vaadin.terminal.gwt.client.ui.VUriFragmentUtility", + "com.vaadin.terminal.gwt.client.ui.VVerticalLayout", + "com.vaadin.terminal.gwt.client.ui.VView", + "com.vaadin.terminal.gwt.client.ui.VWindow", + "com.vaadin.terminal.gwt.client.UIDL", + "com.vaadin.terminal.gwt.client.Util", + "com.vaadin.terminal.gwt.client.ValueMap", + "com.vaadin.terminal.gwt.client.VCaption", + "com.vaadin.terminal.gwt.client.VCaptionWrapper", + "com.vaadin.terminal.gwt.client.VDebugConsole", + "com.vaadin.terminal.gwt.client.VErrorMessage", + "com.vaadin.terminal.gwt.client.VTooltip", + "com.vaadin.terminal.gwt.client.VUIDLBrowser", + "com.vaadin.terminal.gwt.client.WidgetMap", + "com.vaadin.terminal.gwt.client.WidgetSet", + "com.vaadin.server.AbstractApplicationPortlet", + "com.vaadin.server.AbstractApplicationServlet", + "com.vaadin.server.AbstractCommunicationManager", + "com.vaadin.server.AbstractWebApplicationContext", + "com.vaadin.server.ApplicationPortlet", + "com.vaadin.server.ApplicationPortlet2", + "com.vaadin.server.ApplicationRunnerServlet", + "com.vaadin.server.ApplicationServlet", + "com.vaadin.server.ChangeVariablesErrorEvent", + "com.vaadin.server.CommunicationManager", + "com.vaadin.server.ComponentSizeValidator", + "com.vaadin.server.Constants", + "com.vaadin.server.GAEApplicationServlet", + "com.vaadin.server.HttpServletRequestListener", + "com.vaadin.server.HttpUploadStream", + "com.vaadin.server.JsonPaintTarget", + "com.vaadin.server.PortletApplicationContext", + "com.vaadin.server.PortletApplicationContext2", + "com.vaadin.server.PortletCommunicationManager", + "com.vaadin.server.PortletRequestListener", + "com.vaadin.server.RestrictedRenderResponse", + "com.vaadin.server.SessionExpiredException", + "com.vaadin.server.SystemMessageException", + "com.vaadin.server.WebApplicationContext", + "com.vaadin.server.WebBrowser", + "com.vaadin.server.widgetsetutils.ClassPathExplorer", + "com.vaadin.server.widgetsetutils.WidgetMapGenerator", + "com.vaadin.server.widgetsetutils.WidgetSetBuilder", + "com.vaadin.server.KeyMapper", "com.vaadin.server.Paintable", + "com.vaadin.server.PaintException", + "com.vaadin.server.PaintTarget", + "com.vaadin.server.ParameterHandler", "com.vaadin.server.Resource", + "com.vaadin.server.Scrollable", "com.vaadin.server.Sizeable", + "com.vaadin.server.StreamResource", + "com.vaadin.server.SystemError", "com.vaadin.server.Terminal", + "com.vaadin.server.ThemeResource", + "com.vaadin.server.UploadStream", "com.vaadin.server.URIHandler", + "com.vaadin.server.UserError", "com.vaadin.server.VariableOwner", + "com.vaadin.tools.ReflectTools", + "com.vaadin.tools.WidgetsetCompiler", + "com.vaadin.ui.AbsoluteLayout", "com.vaadin.ui.AbstractComponent", + "com.vaadin.ui.AbstractComponentContainer", + "com.vaadin.ui.AbstractField", "com.vaadin.ui.AbstractLayout", + "com.vaadin.ui.AbstractOrderedLayout", + "com.vaadin.ui.AbstractSelect", "com.vaadin.ui.Accordion", + "com.vaadin.ui.Alignment", "com.vaadin.ui.AlignmentUtils", + "com.vaadin.ui.BaseFieldFactory", "com.vaadin.ui.Button", + "com.vaadin.ui.CheckBox", "com.vaadin.ui.ClientWidget", + "com.vaadin.ui.ComboBox", "com.vaadin.ui.Component", + "com.vaadin.ui.ComponentContainer", "com.vaadin.ui.CssLayout", + "com.vaadin.ui.CustomComponent", "com.vaadin.ui.CustomLayout", + "com.vaadin.ui.DateField", "com.vaadin.ui.DefaultFieldFactory", + "com.vaadin.ui.Embedded", "com.vaadin.ui.ExpandLayout", + "com.vaadin.ui.Field", "com.vaadin.ui.FieldFactory", + "com.vaadin.ui.Form", "com.vaadin.ui.FormFieldFactory", + "com.vaadin.ui.FormLayout", "com.vaadin.ui.GridLayout", + "com.vaadin.ui.HorizontalLayout", "com.vaadin.ui.InlineDateField", + "com.vaadin.ui.Label", "com.vaadin.ui.Layout", + "com.vaadin.ui.Link", "com.vaadin.ui.ListSelect", + "com.vaadin.ui.LoginForm", "com.vaadin.ui.MenuBar", + "com.vaadin.ui.NativeButton", "com.vaadin.ui.NativeSelect", + "com.vaadin.ui.OptionGroup", "com.vaadin.ui.OrderedLayout", + "com.vaadin.ui.Panel", "com.vaadin.ui.PopupDateField", + "com.vaadin.ui.PopupView", "com.vaadin.ui.ProgressIndicator", + "com.vaadin.ui.RichTextArea", "com.vaadin.ui.Select", + "com.vaadin.ui.Slider", "com.vaadin.ui.SplitPanel", + "com.vaadin.ui.Table", "com.vaadin.ui.TableFieldFactory", + "com.vaadin.ui.TabSheet", "com.vaadin.ui.TextField", + "com.vaadin.ui.Tree", "com.vaadin.ui.TwinColSelect", + "com.vaadin.ui.Upload", "com.vaadin.ui.UriFragmentUtility", + "com.vaadin.ui.VerticalLayout", "com.vaadin.ui.Window", + "com.vaadin.util.SerializerHelper", "org.vaadin.test.LastClass" }; +} diff --git a/server/tests/src/com/vaadin/data/util/AbstractHierarchicalContainerTest.java b/server/tests/src/com/vaadin/data/util/AbstractHierarchicalContainerTest.java deleted file mode 100644 index 772cd250ce..0000000000 --- a/server/tests/src/com/vaadin/data/util/AbstractHierarchicalContainerTest.java +++ /dev/null @@ -1,256 +0,0 @@ -package com.vaadin.data.util; - -import java.util.Collection; - -import com.vaadin.data.Container; -import com.vaadin.data.Container.Hierarchical; -import com.vaadin.data.Container.Sortable; -import com.vaadin.data.Item; - -public abstract class AbstractHierarchicalContainerTest extends - AbstractContainerTest { - - /** - * @param container - * The container to validate - * @param expectedFirstItemId - * Expected first item id - * @param expectedLastItemId - * Expected last item id - * @param itemIdInSet - * An item id that is in the container - * @param itemIdNotInSet - * An item id that is not in the container - * @param checkGetItemNull - * true if getItem() should return null for itemIdNotInSet, false - * to skip the check (container.containsId() is checked in any - * case) - * @param expectedSize - * Expected number of items in the container. Not related to - * hierarchy. - * @param expectedTraversalSize - * Expected number of items found when traversing from the roots - * down to all available nodes. - * @param expectedRootSize - * Expected number of root items - * @param rootsHaveChildren - * true if all roots have children, false otherwise (skips some - * asserts) - */ - protected void validateHierarchicalContainer(Hierarchical container, - Object expectedFirstItemId, Object expectedLastItemId, - Object itemIdInSet, Object itemIdNotInSet, - boolean checkGetItemNull, int expectedSize, int expectedRootSize, - boolean rootsHaveChildren) { - - validateContainer(container, expectedFirstItemId, expectedLastItemId, - itemIdInSet, itemIdNotInSet, checkGetItemNull, expectedSize); - - // rootItemIds - Collection rootIds = container.rootItemIds(); - assertEquals(expectedRootSize, rootIds.size()); - - for (Object rootId : rootIds) { - // All roots must be in container - assertTrue(container.containsId(rootId)); - - // All roots must have no parent - assertNull(container.getParent(rootId)); - - // all roots must be roots - assertTrue(container.isRoot(rootId)); - - if (rootsHaveChildren) { - // all roots have children allowed in this case - assertTrue(container.areChildrenAllowed(rootId)); - - // all roots have children in this case - Collection children = container.getChildren(rootId); - assertNotNull(rootId + " should have children", children); - assertTrue(rootId + " should have children", - (children.size() > 0)); - // getParent - for (Object childId : children) { - assertEquals(container.getParent(childId), rootId); - } - - } - } - - // isRoot should return false for unknown items - assertFalse(container.isRoot(itemIdNotInSet)); - - // hasChildren should return false for unknown items - assertFalse(container.hasChildren(itemIdNotInSet)); - - // areChildrenAllowed should return false for unknown items - assertFalse(container.areChildrenAllowed(itemIdNotInSet)); - - // removeItem of unknown items should return false - assertFalse(container.removeItem(itemIdNotInSet)); - - assertEquals(expectedSize, countNodes(container)); - - validateHierarchy(container); - } - - private int countNodes(Hierarchical container) { - int totalNodes = 0; - for (Object rootId : container.rootItemIds()) { - totalNodes += countNodes(container, rootId); - } - - return totalNodes; - } - - private int countNodes(Hierarchical container, Object itemId) { - int nodes = 1; // This - Collection children = container.getChildren(itemId); - if (children != null) { - for (Object id : children) { - nodes += countNodes(container, id); - } - } - - return nodes; - } - - private void validateHierarchy(Hierarchical container) { - for (Object rootId : container.rootItemIds()) { - validateHierarchy(container, rootId, null); - } - } - - private void validateHierarchy(Hierarchical container, Object itemId, - Object parentId) { - Collection children = container.getChildren(itemId); - - // getParent - assertEquals(container.getParent(itemId), parentId); - - if (!container.areChildrenAllowed(itemId)) { - // If no children is allowed the item should have no children - assertFalse(container.hasChildren(itemId)); - assertTrue(children == null || children.size() == 0); - - return; - } - if (children != null) { - for (Object id : children) { - validateHierarchy(container, id, itemId); - } - } - } - - protected void testHierarchicalContainer(Container.Hierarchical container) { - initializeContainer(container); - - int packages = 21 + 3; - int expectedSize = sampleData.length + packages; - validateHierarchicalContainer(container, "com", - "org.vaadin.test.LastClass", - "com.vaadin.server.ApplicationResource", "blah", true, - expectedSize, 2, true); - - } - - protected void testHierarchicalSorting(Container.Hierarchical container) { - Container.Sortable sortable = (Sortable) container; - - initializeContainer(container); - - // Must be able to sort based on PROP1 and PROP2 for this test - assertTrue(sortable.getSortableContainerPropertyIds().contains( - FULLY_QUALIFIED_NAME)); - assertTrue(sortable.getSortableContainerPropertyIds().contains( - REVERSE_FULLY_QUALIFIED_NAME)); - - sortable.sort(new Object[] { FULLY_QUALIFIED_NAME }, - new boolean[] { true }); - - int packages = 21 + 3; - int expectedSize = sampleData.length + packages; - validateHierarchicalContainer(container, "com", - "org.vaadin.test.LastClass", - "com.vaadin.server.ApplicationResource", "blah", true, - expectedSize, 2, true); - - sortable.sort(new Object[] { REVERSE_FULLY_QUALIFIED_NAME }, - new boolean[] { true }); - - validateHierarchicalContainer(container, - "com.vaadin.server.ApplicationPortlet2", - "com.vaadin.data.util.ObjectProperty", - "com.vaadin.server.ApplicationResource", "blah", true, - expectedSize, 2, true); - - } - - protected void initializeContainer(Container.Hierarchical container) { - container.removeAllItems(); - Object[] propertyIds = container.getContainerPropertyIds().toArray(); - for (Object propertyId : propertyIds) { - container.removeContainerProperty(propertyId); - } - - container.addContainerProperty(FULLY_QUALIFIED_NAME, String.class, ""); - container.addContainerProperty(SIMPLE_NAME, String.class, ""); - container.addContainerProperty(REVERSE_FULLY_QUALIFIED_NAME, - String.class, null); - container.addContainerProperty(ID_NUMBER, Integer.class, null); - - for (int i = 0; i < sampleData.length; i++) { - String id = sampleData[i]; - - // Add path as parent - String paths[] = id.split("\\."); - String path = paths[0]; - // Adds "com" and other items multiple times so should return null - // for all but the first time - if (container.addItem(path) != null) { - assertTrue(container.setChildrenAllowed(path, false)); - Item item = container.getItem(path); - item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(path); - item.getItemProperty(SIMPLE_NAME).setValue(getSimpleName(path)); - item.getItemProperty(REVERSE_FULLY_QUALIFIED_NAME).setValue( - reverse(path)); - item.getItemProperty(ID_NUMBER).setValue(1); - } - for (int j = 1; j < paths.length; j++) { - String parent = path; - path = path + "." + paths[j]; - - // Adds "com" and other items multiple times so should return - // null for all but the first time - if (container.addItem(path) != null) { - assertTrue(container.setChildrenAllowed(path, false)); - - Item item = container.getItem(path); - item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(path); - item.getItemProperty(SIMPLE_NAME).setValue( - getSimpleName(path)); - item.getItemProperty(REVERSE_FULLY_QUALIFIED_NAME) - .setValue(reverse(path)); - item.getItemProperty(ID_NUMBER).setValue(1); - - } - assertTrue(container.setChildrenAllowed(parent, true)); - assertTrue( - "Failed to set " + parent + " as parent for " + path, - container.setParent(path, parent)); - } - - Item item = container.getItem(id); - assertNotNull(item); - String parent = id.substring(0, id.lastIndexOf('.')); - assertTrue(container.setParent(id, parent)); - item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(sampleData[i]); - item.getItemProperty(SIMPLE_NAME).setValue( - getSimpleName(sampleData[i])); - item.getItemProperty(REVERSE_FULLY_QUALIFIED_NAME).setValue( - reverse(sampleData[i])); - item.getItemProperty(ID_NUMBER).setValue(i % 2); - } - } - -} diff --git a/server/tests/src/com/vaadin/data/util/AbstractHierarchicalContainerTestBase.java b/server/tests/src/com/vaadin/data/util/AbstractHierarchicalContainerTestBase.java new file mode 100644 index 0000000000..3bd00cce3c --- /dev/null +++ b/server/tests/src/com/vaadin/data/util/AbstractHierarchicalContainerTestBase.java @@ -0,0 +1,256 @@ +package com.vaadin.data.util; + +import java.util.Collection; + +import com.vaadin.data.Container; +import com.vaadin.data.Container.Hierarchical; +import com.vaadin.data.Container.Sortable; +import com.vaadin.data.Item; + +public abstract class AbstractHierarchicalContainerTestBase extends + AbstractContainerTestBase { + + /** + * @param container + * The container to validate + * @param expectedFirstItemId + * Expected first item id + * @param expectedLastItemId + * Expected last item id + * @param itemIdInSet + * An item id that is in the container + * @param itemIdNotInSet + * An item id that is not in the container + * @param checkGetItemNull + * true if getItem() should return null for itemIdNotInSet, false + * to skip the check (container.containsId() is checked in any + * case) + * @param expectedSize + * Expected number of items in the container. Not related to + * hierarchy. + * @param expectedTraversalSize + * Expected number of items found when traversing from the roots + * down to all available nodes. + * @param expectedRootSize + * Expected number of root items + * @param rootsHaveChildren + * true if all roots have children, false otherwise (skips some + * asserts) + */ + protected void validateHierarchicalContainer(Hierarchical container, + Object expectedFirstItemId, Object expectedLastItemId, + Object itemIdInSet, Object itemIdNotInSet, + boolean checkGetItemNull, int expectedSize, int expectedRootSize, + boolean rootsHaveChildren) { + + validateContainer(container, expectedFirstItemId, expectedLastItemId, + itemIdInSet, itemIdNotInSet, checkGetItemNull, expectedSize); + + // rootItemIds + Collection rootIds = container.rootItemIds(); + assertEquals(expectedRootSize, rootIds.size()); + + for (Object rootId : rootIds) { + // All roots must be in container + assertTrue(container.containsId(rootId)); + + // All roots must have no parent + assertNull(container.getParent(rootId)); + + // all roots must be roots + assertTrue(container.isRoot(rootId)); + + if (rootsHaveChildren) { + // all roots have children allowed in this case + assertTrue(container.areChildrenAllowed(rootId)); + + // all roots have children in this case + Collection children = container.getChildren(rootId); + assertNotNull(rootId + " should have children", children); + assertTrue(rootId + " should have children", + (children.size() > 0)); + // getParent + for (Object childId : children) { + assertEquals(container.getParent(childId), rootId); + } + + } + } + + // isRoot should return false for unknown items + assertFalse(container.isRoot(itemIdNotInSet)); + + // hasChildren should return false for unknown items + assertFalse(container.hasChildren(itemIdNotInSet)); + + // areChildrenAllowed should return false for unknown items + assertFalse(container.areChildrenAllowed(itemIdNotInSet)); + + // removeItem of unknown items should return false + assertFalse(container.removeItem(itemIdNotInSet)); + + assertEquals(expectedSize, countNodes(container)); + + validateHierarchy(container); + } + + private int countNodes(Hierarchical container) { + int totalNodes = 0; + for (Object rootId : container.rootItemIds()) { + totalNodes += countNodes(container, rootId); + } + + return totalNodes; + } + + private int countNodes(Hierarchical container, Object itemId) { + int nodes = 1; // This + Collection children = container.getChildren(itemId); + if (children != null) { + for (Object id : children) { + nodes += countNodes(container, id); + } + } + + return nodes; + } + + private void validateHierarchy(Hierarchical container) { + for (Object rootId : container.rootItemIds()) { + validateHierarchy(container, rootId, null); + } + } + + private void validateHierarchy(Hierarchical container, Object itemId, + Object parentId) { + Collection children = container.getChildren(itemId); + + // getParent + assertEquals(container.getParent(itemId), parentId); + + if (!container.areChildrenAllowed(itemId)) { + // If no children is allowed the item should have no children + assertFalse(container.hasChildren(itemId)); + assertTrue(children == null || children.size() == 0); + + return; + } + if (children != null) { + for (Object id : children) { + validateHierarchy(container, id, itemId); + } + } + } + + protected void testHierarchicalContainer(Container.Hierarchical container) { + initializeContainer(container); + + int packages = 21 + 3; + int expectedSize = sampleData.length + packages; + validateHierarchicalContainer(container, "com", + "org.vaadin.test.LastClass", + "com.vaadin.server.ApplicationResource", "blah", true, + expectedSize, 2, true); + + } + + protected void testHierarchicalSorting(Container.Hierarchical container) { + Container.Sortable sortable = (Sortable) container; + + initializeContainer(container); + + // Must be able to sort based on PROP1 and PROP2 for this test + assertTrue(sortable.getSortableContainerPropertyIds().contains( + FULLY_QUALIFIED_NAME)); + assertTrue(sortable.getSortableContainerPropertyIds().contains( + REVERSE_FULLY_QUALIFIED_NAME)); + + sortable.sort(new Object[] { FULLY_QUALIFIED_NAME }, + new boolean[] { true }); + + int packages = 21 + 3; + int expectedSize = sampleData.length + packages; + validateHierarchicalContainer(container, "com", + "org.vaadin.test.LastClass", + "com.vaadin.server.ApplicationResource", "blah", true, + expectedSize, 2, true); + + sortable.sort(new Object[] { REVERSE_FULLY_QUALIFIED_NAME }, + new boolean[] { true }); + + validateHierarchicalContainer(container, + "com.vaadin.server.ApplicationPortlet2", + "com.vaadin.data.util.ObjectProperty", + "com.vaadin.server.ApplicationResource", "blah", true, + expectedSize, 2, true); + + } + + protected void initializeContainer(Container.Hierarchical container) { + container.removeAllItems(); + Object[] propertyIds = container.getContainerPropertyIds().toArray(); + for (Object propertyId : propertyIds) { + container.removeContainerProperty(propertyId); + } + + container.addContainerProperty(FULLY_QUALIFIED_NAME, String.class, ""); + container.addContainerProperty(SIMPLE_NAME, String.class, ""); + container.addContainerProperty(REVERSE_FULLY_QUALIFIED_NAME, + String.class, null); + container.addContainerProperty(ID_NUMBER, Integer.class, null); + + for (int i = 0; i < sampleData.length; i++) { + String id = sampleData[i]; + + // Add path as parent + String paths[] = id.split("\\."); + String path = paths[0]; + // Adds "com" and other items multiple times so should return null + // for all but the first time + if (container.addItem(path) != null) { + assertTrue(container.setChildrenAllowed(path, false)); + Item item = container.getItem(path); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(path); + item.getItemProperty(SIMPLE_NAME).setValue(getSimpleName(path)); + item.getItemProperty(REVERSE_FULLY_QUALIFIED_NAME).setValue( + reverse(path)); + item.getItemProperty(ID_NUMBER).setValue(1); + } + for (int j = 1; j < paths.length; j++) { + String parent = path; + path = path + "." + paths[j]; + + // Adds "com" and other items multiple times so should return + // null for all but the first time + if (container.addItem(path) != null) { + assertTrue(container.setChildrenAllowed(path, false)); + + Item item = container.getItem(path); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(path); + item.getItemProperty(SIMPLE_NAME).setValue( + getSimpleName(path)); + item.getItemProperty(REVERSE_FULLY_QUALIFIED_NAME) + .setValue(reverse(path)); + item.getItemProperty(ID_NUMBER).setValue(1); + + } + assertTrue(container.setChildrenAllowed(parent, true)); + assertTrue( + "Failed to set " + parent + " as parent for " + path, + container.setParent(path, parent)); + } + + Item item = container.getItem(id); + assertNotNull(item); + String parent = id.substring(0, id.lastIndexOf('.')); + assertTrue(container.setParent(id, parent)); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(sampleData[i]); + item.getItemProperty(SIMPLE_NAME).setValue( + getSimpleName(sampleData[i])); + item.getItemProperty(REVERSE_FULLY_QUALIFIED_NAME).setValue( + reverse(sampleData[i])); + item.getItemProperty(ID_NUMBER).setValue(i % 2); + } + } + +} diff --git a/server/tests/src/com/vaadin/data/util/AbstractInMemoryContainerTest.java b/server/tests/src/com/vaadin/data/util/AbstractInMemoryContainerTest.java deleted file mode 100644 index bbad33c5bc..0000000000 --- a/server/tests/src/com/vaadin/data/util/AbstractInMemoryContainerTest.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.vaadin.data.util; - -public abstract class AbstractInMemoryContainerTest extends - AbstractContainerTest { - -} diff --git a/server/tests/src/com/vaadin/data/util/AbstractInMemoryContainerTestBase.java b/server/tests/src/com/vaadin/data/util/AbstractInMemoryContainerTestBase.java new file mode 100644 index 0000000000..d2c1a17bf8 --- /dev/null +++ b/server/tests/src/com/vaadin/data/util/AbstractInMemoryContainerTestBase.java @@ -0,0 +1,6 @@ +package com.vaadin.data.util; + +public abstract class AbstractInMemoryContainerTestBase extends + AbstractContainerTestBase { + +} diff --git a/server/tests/src/com/vaadin/data/util/BeanContainerTest.java b/server/tests/src/com/vaadin/data/util/BeanContainerTest.java index f22ab8478e..3d755f4397 100644 --- a/server/tests/src/com/vaadin/data/util/BeanContainerTest.java +++ b/server/tests/src/com/vaadin/data/util/BeanContainerTest.java @@ -13,7 +13,7 @@ import com.vaadin.data.Container; import com.vaadin.data.Item; import com.vaadin.data.util.AbstractBeanContainer.BeanIdResolver; -public class BeanContainerTest extends AbstractBeanContainerTest { +public class BeanContainerTest extends AbstractBeanContainerTestBase { protected static class PersonNameResolver implements BeanIdResolver { @@ -345,7 +345,7 @@ public class BeanContainerTest extends AbstractBeanContainerTest { Person.class); // resolver that returns null as item id container - .setBeanIdResolver(new BeanIdResolver() { + .setBeanIdResolver(new BeanIdResolver() { @Override public String getIdForBean(Person bean) { diff --git a/server/tests/src/com/vaadin/data/util/BeanItemContainerGenerator.java b/server/tests/src/com/vaadin/data/util/BeanItemContainerGenerator.java index 7400f0efcf..a5bdcc7cf9 100644 --- a/server/tests/src/com/vaadin/data/util/BeanItemContainerGenerator.java +++ b/server/tests/src/com/vaadin/data/util/BeanItemContainerGenerator.java @@ -3,9 +3,6 @@ package com.vaadin.data.util; import java.util.Date; import java.util.concurrent.atomic.AtomicLong; -import org.junit.Ignore; - -@Ignore public class BeanItemContainerGenerator { public static class PortableRandom { diff --git a/server/tests/src/com/vaadin/data/util/BeanItemContainerTest.java b/server/tests/src/com/vaadin/data/util/BeanItemContainerTest.java index 514bf70416..8d2654b39b 100644 --- a/server/tests/src/com/vaadin/data/util/BeanItemContainerTest.java +++ b/server/tests/src/com/vaadin/data/util/BeanItemContainerTest.java @@ -19,7 +19,7 @@ import com.vaadin.data.util.NestedMethodPropertyTest.Address; * * Most sorting related tests are in {@link BeanItemContainerSortTest}. */ -public class BeanItemContainerTest extends AbstractBeanContainerTest { +public class BeanItemContainerTest extends AbstractBeanContainerTestBase { // basics from the common container test diff --git a/server/tests/src/com/vaadin/data/util/ContainerHierarchicalWrapperTest.java b/server/tests/src/com/vaadin/data/util/ContainerHierarchicalWrapperTest.java new file mode 100644 index 0000000000..2fd21ef118 --- /dev/null +++ b/server/tests/src/com/vaadin/data/util/ContainerHierarchicalWrapperTest.java @@ -0,0 +1,42 @@ +package com.vaadin.data.util; + +import java.util.Collection; + +public class ContainerHierarchicalWrapperTest extends + AbstractHierarchicalContainerTestBase { + + public void testBasicOperations() { + testBasicContainerOperations(new ContainerHierarchicalWrapper( + new IndexedContainer())); + } + + public void testHierarchicalContainer() { + testHierarchicalContainer(new ContainerHierarchicalWrapper( + new IndexedContainer())); + } + + public void testRemoveSubtree() { + testRemoveHierarchicalWrapperSubtree(new ContainerHierarchicalWrapper( + new IndexedContainer())); + } + + protected void testRemoveHierarchicalWrapperSubtree( + ContainerHierarchicalWrapper container) { + initializeContainer(container); + + // remove root item + container.removeItemRecursively("org"); + + int packages = 21 + 3 - 3; + int expectedSize = sampleData.length + packages - 1; + + validateContainer(container, "com", "com.vaadin.util.SerializerHelper", + "com.vaadin.server.ApplicationResource", "blah", true, + expectedSize); + + // rootItemIds + Collection rootIds = container.rootItemIds(); + assertEquals(1, rootIds.size()); + } + +} diff --git a/server/tests/src/com/vaadin/data/util/ContainerSortingTest.java b/server/tests/src/com/vaadin/data/util/ContainerSortingTest.java new file mode 100644 index 0000000000..dd713dd7b0 --- /dev/null +++ b/server/tests/src/com/vaadin/data/util/ContainerSortingTest.java @@ -0,0 +1,224 @@ +package com.vaadin.data.util; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import junit.framework.TestCase; + +import com.vaadin.data.Container; +import com.vaadin.data.Item; +import com.vaadin.tests.util.TestUtil; + +public class ContainerSortingTest extends TestCase { + + private static final String ITEM_DATA_MINUS2_NULL = "Data -2 null"; + private static final String ITEM_DATA_MINUS2 = "Data -2"; + private static final String ITEM_DATA_MINUS1 = "Data -1"; + private static final String ITEM_DATA_MINUS1_NULL = "Data -1 null"; + private static final String ITEM_ANOTHER_NULL = "Another null"; + private static final String ITEM_STRING_2 = "String 2"; + private static final String ITEM_STRING_NULL2 = "String null"; + private static final String ITEM_STRING_1 = "String 1"; + + private static final String PROPERTY_INTEGER_NULL2 = "integer-null"; + private static final String PROPERTY_INTEGER_NOT_NULL = "integer-not-null"; + private static final String PROPERTY_STRING_NULL = "string-null"; + private static final String PROPERTY_STRING_ID = "string-not-null"; + + @Override + protected void setUp() throws Exception { + super.setUp(); + } + + public void testEmptyFilteredIndexedContainer() { + IndexedContainer ic = new IndexedContainer(); + + addProperties(ic); + populate(ic); + + ic.addContainerFilter(PROPERTY_STRING_ID, "aasdfasdfasdf", true, false); + ic.sort(new Object[] { PROPERTY_STRING_ID }, new boolean[] { true }); + + } + + public void testFilteredIndexedContainer() { + IndexedContainer ic = new IndexedContainer(); + + addProperties(ic); + populate(ic); + + ic.addContainerFilter(PROPERTY_STRING_ID, "a", true, false); + ic.sort(new Object[] { PROPERTY_STRING_ID }, new boolean[] { true }); + verifyOrder(ic, + new String[] { ITEM_ANOTHER_NULL, ITEM_DATA_MINUS1, + ITEM_DATA_MINUS1_NULL, ITEM_DATA_MINUS2, + ITEM_DATA_MINUS2_NULL, }); + } + + public void testIndexedContainer() { + IndexedContainer ic = new IndexedContainer(); + + addProperties(ic); + populate(ic); + + ic.sort(new Object[] { PROPERTY_STRING_ID }, new boolean[] { true }); + verifyOrder(ic, new String[] { ITEM_ANOTHER_NULL, ITEM_DATA_MINUS1, + ITEM_DATA_MINUS1_NULL, ITEM_DATA_MINUS2, ITEM_DATA_MINUS2_NULL, + ITEM_STRING_1, ITEM_STRING_2, ITEM_STRING_NULL2 }); + + ic.sort(new Object[] { PROPERTY_INTEGER_NOT_NULL, + PROPERTY_INTEGER_NULL2, PROPERTY_STRING_ID }, new boolean[] { + true, false, true }); + verifyOrder(ic, new String[] { ITEM_DATA_MINUS2, ITEM_DATA_MINUS2_NULL, + ITEM_DATA_MINUS1, ITEM_DATA_MINUS1_NULL, ITEM_ANOTHER_NULL, + ITEM_STRING_NULL2, ITEM_STRING_1, ITEM_STRING_2 }); + + ic.sort(new Object[] { PROPERTY_INTEGER_NOT_NULL, + PROPERTY_INTEGER_NULL2, PROPERTY_STRING_ID }, new boolean[] { + true, true, true }); + verifyOrder(ic, new String[] { ITEM_DATA_MINUS2_NULL, ITEM_DATA_MINUS2, + ITEM_DATA_MINUS1_NULL, ITEM_DATA_MINUS1, ITEM_ANOTHER_NULL, + ITEM_STRING_NULL2, ITEM_STRING_1, ITEM_STRING_2 }); + + } + + public void testHierarchicalContainer() { + HierarchicalContainer hc = new HierarchicalContainer(); + populateContainer(hc); + hc.sort(new Object[] { "name" }, new boolean[] { true }); + verifyOrder(hc, new String[] { "Audi", "C++", "Call of Duty", "Cars", + "English", "Fallout", "Finnish", "Ford", "Games", "Java", + "Might and Magic", "Natural languages", "PHP", + "Programming languages", "Python", "Red Alert", "Swedish", + "Toyota", "Volvo" }); + TestUtil.assertArrays( + hc.rootItemIds().toArray(), + new Integer[] { nameToId.get("Cars"), nameToId.get("Games"), + nameToId.get("Natural languages"), + nameToId.get("Programming languages") }); + TestUtil.assertArrays( + hc.getChildren(nameToId.get("Games")).toArray(), + new Integer[] { nameToId.get("Call of Duty"), + nameToId.get("Fallout"), + nameToId.get("Might and Magic"), + nameToId.get("Red Alert") }); + } + + private static void populateContainer(HierarchicalContainer container) { + container.addContainerProperty("name", String.class, null); + + addItem(container, "Games", null); + addItem(container, "Call of Duty", "Games"); + addItem(container, "Might and Magic", "Games"); + addItem(container, "Fallout", "Games"); + addItem(container, "Red Alert", "Games"); + + addItem(container, "Cars", null); + addItem(container, "Toyota", "Cars"); + addItem(container, "Volvo", "Cars"); + addItem(container, "Audi", "Cars"); + addItem(container, "Ford", "Cars"); + + addItem(container, "Natural languages", null); + addItem(container, "Swedish", "Natural languages"); + addItem(container, "English", "Natural languages"); + addItem(container, "Finnish", "Natural languages"); + + addItem(container, "Programming languages", null); + addItem(container, "C++", "Programming languages"); + addItem(container, "PHP", "Programming languages"); + addItem(container, "Java", "Programming languages"); + addItem(container, "Python", "Programming languages"); + + } + + private static int index = 0; + private static Map nameToId = new HashMap(); + private static Map idToName = new HashMap(); + + public static void addItem(IndexedContainer container, String string, + String parent) { + nameToId.put(string, index); + idToName.put(index, string); + + Item item = container.addItem(index); + item.getItemProperty("name").setValue(string); + + if (parent != null && container instanceof HierarchicalContainer) { + ((HierarchicalContainer) container).setParent(index, + nameToId.get(parent)); + } + + index++; + } + + private void verifyOrder(Container.Sortable ic, Object[] idOrder) { + int size = ic.size(); + Object[] actual = new Object[size]; + Iterator i = ic.getItemIds().iterator(); + int index = 0; + while (i.hasNext()) { + Object o = i.next(); + if (o.getClass() == Integer.class + && idOrder[index].getClass() == String.class) { + o = idToName.get(o); + } + actual[index++] = o; + } + + TestUtil.assertArrays(actual, idOrder); + + } + + private void populate(IndexedContainer ic) { + addItem(ic, ITEM_STRING_1, ITEM_STRING_1, 1, 1); + addItem(ic, ITEM_STRING_NULL2, null, 0, null); + addItem(ic, ITEM_STRING_2, ITEM_STRING_2, 2, 2); + addItem(ic, ITEM_ANOTHER_NULL, null, 0, null); + addItem(ic, ITEM_DATA_MINUS1, ITEM_DATA_MINUS1, -1, -1); + addItem(ic, ITEM_DATA_MINUS1_NULL, null, -1, null); + addItem(ic, ITEM_DATA_MINUS2, ITEM_DATA_MINUS2, -2, -2); + addItem(ic, ITEM_DATA_MINUS2_NULL, null, -2, null); + } + + private Item addItem(Container ic, String id, String string_null, + int integer, Integer integer_null) { + Item i = ic.addItem(id); + i.getItemProperty(PROPERTY_STRING_ID).setValue(id); + i.getItemProperty(PROPERTY_STRING_NULL).setValue(string_null); + i.getItemProperty(PROPERTY_INTEGER_NOT_NULL).setValue(integer); + i.getItemProperty(PROPERTY_INTEGER_NULL2).setValue(integer_null); + + return i; + } + + private void addProperties(IndexedContainer ic) { + ic.addContainerProperty("id", String.class, null); + ic.addContainerProperty(PROPERTY_STRING_ID, String.class, ""); + ic.addContainerProperty(PROPERTY_STRING_NULL, String.class, null); + ic.addContainerProperty(PROPERTY_INTEGER_NULL2, Integer.class, null); + ic.addContainerProperty(PROPERTY_INTEGER_NOT_NULL, Integer.class, 0); + ic.addContainerProperty("comparable-null", Integer.class, 0); + } + + public class MyObject implements Comparable { + private String data; + + @Override + public int compareTo(MyObject o) { + if (o == null) { + return 1; + } + + if (o.data == null) { + return data == null ? 0 : 1; + } else if (data == null) { + return -1; + } else { + return data.compareTo(o.data); + } + } + } + +} diff --git a/server/tests/src/com/vaadin/data/util/HierarchicalContainerTest.java b/server/tests/src/com/vaadin/data/util/HierarchicalContainerTest.java new file mode 100644 index 0000000000..0b71b3dff9 --- /dev/null +++ b/server/tests/src/com/vaadin/data/util/HierarchicalContainerTest.java @@ -0,0 +1,270 @@ +package com.vaadin.data.util; + +import com.vaadin.data.Container.Filter; +import com.vaadin.data.Item; + +public class HierarchicalContainerTest extends + AbstractHierarchicalContainerTestBase { + + public void testBasicOperations() { + testBasicContainerOperations(new HierarchicalContainer()); + } + + public void testFiltering() { + testContainerFiltering(new HierarchicalContainer()); + } + + public void testSorting() { + testContainerSorting(new HierarchicalContainer()); + } + + public void testOrdered() { + testContainerOrdered(new HierarchicalContainer()); + } + + public void testHierarchicalSorting() { + testHierarchicalSorting(new HierarchicalContainer()); + } + + public void testSortingAndFiltering() { + testContainerSortingAndFiltering(new HierarchicalContainer()); + } + + public void testRemovingItemsFromFilteredContainer() { + HierarchicalContainer container = new HierarchicalContainer(); + initializeContainer(container); + container.setIncludeParentsWhenFiltering(true); + container.addContainerFilter(FULLY_QUALIFIED_NAME, "ab", false, false); + Object p1 = container.getParent("com.vaadin.ui.TabSheet"); + assertEquals("com.vaadin.ui", p1); + + container.removeItem("com.vaadin.ui.TabSheet"); + // Parent for the removed item must be null because the item is no + // longer in the container + p1 = container.getParent("com.vaadin.ui.TabSheet"); + assertNull("Parent should be null, is " + p1, p1); + + container.removeAllItems(); + p1 = container.getParent("com.vaadin.terminal.gwt.client.Focusable"); + assertNull("Parent should be null, is " + p1, p1); + + } + + public void testParentWhenRemovingFilterFromContainer() { + HierarchicalContainer container = new HierarchicalContainer(); + initializeContainer(container); + container.setIncludeParentsWhenFiltering(true); + container.addContainerFilter(FULLY_QUALIFIED_NAME, "ab", false, false); + Object p1 = container.getParent("com.vaadin.ui.TabSheet"); + assertEquals("com.vaadin.ui", p1); + p1 = container + .getParent("com.vaadin.terminal.gwt.client.ui.VPopupCalendar"); + assertNull(p1); + container.removeAllContainerFilters(); + p1 = container + .getParent("com.vaadin.terminal.gwt.client.ui.VPopupCalendar"); + assertEquals("com.vaadin.terminal.gwt.client.ui", p1); + + } + + public void testChangeParentInFilteredContainer() { + HierarchicalContainer container = new HierarchicalContainer(); + initializeContainer(container); + container.setIncludeParentsWhenFiltering(true); + container.addContainerFilter(FULLY_QUALIFIED_NAME, "Tab", false, false); + + // Change parent of filtered item + Object p1 = container.getParent("com.vaadin.ui.TabSheet"); + assertEquals("com.vaadin.ui", p1); + container.setParent("com.vaadin.ui.TabSheet", "com.vaadin"); + p1 = container.getParent("com.vaadin.ui.TabSheet"); + assertEquals("com.vaadin", p1); + container.setParent("com.vaadin.ui.TabSheet", "com"); + p1 = container.getParent("com.vaadin.ui.TabSheet"); + assertEquals("com", p1); + container.setParent("com.vaadin.ui.TabSheet", null); + p1 = container.getParent("com.vaadin.ui.TabSheet"); + assertNull(p1); + + // root -> non-root + container.setParent("com.vaadin.ui.TabSheet", "com"); + p1 = container.getParent("com.vaadin.ui.TabSheet"); + assertEquals("com", p1); + + } + + public void testHierarchicalFilteringWithParents() { + HierarchicalContainer container = new HierarchicalContainer(); + initializeContainer(container); + container.setIncludeParentsWhenFiltering(true); + + // Filter by "contains ab" + container.addContainerFilter(FULLY_QUALIFIED_NAME, "ab", false, false); + + // 20 items match the filters and the have 8 parents that should also be + // included + // only one root "com" should exist + // filtered + int expectedSize = 29; + int expectedRoots = 1; + + validateHierarchicalContainer(container, "com", + "com.vaadin.ui.TabSheet", + "com.vaadin.terminal.gwt.client.Focusable", "blah", true, + expectedSize, expectedRoots, true); + + // only include .gwt.client classes + container.removeAllContainerFilters(); + container.addContainerFilter(FULLY_QUALIFIED_NAME, ".gwt.client.", + false, false); + + int packages = 6; + int classes = 112; + + expectedSize = packages + classes; + expectedRoots = 1; + + validateHierarchicalContainer(container, "com", + "com.vaadin.terminal.gwt.client.WidgetSet", + "com.vaadin.terminal.gwt.client.ui.VSplitPanelVertical", + "blah", true, expectedSize, expectedRoots, true); + + // Additionally remove all without 'm' in the simple name. + container.addContainerFilter(SIMPLE_NAME, "m", false, false); + + expectedSize = 7 + 18; + expectedRoots = 1; + + validateHierarchicalContainer( + container, + "com", + "com.vaadin.terminal.gwt.client.ui.VUriFragmentUtility", + "com.vaadin.terminal.gwt.client.ui.layout.ChildComponentContainer", + "blah", true, expectedSize, expectedRoots, true); + + } + + public void testRemoveLastChild() { + HierarchicalContainer c = new HierarchicalContainer(); + + c.addItem("root"); + assertEquals(false, c.hasChildren("root")); + + c.addItem("child"); + c.setParent("child", "root"); + assertEquals(true, c.hasChildren("root")); + + c.removeItem("child"); + assertFalse(c.containsId("child")); + assertNull(c.getChildren("root")); + assertNull(c.getChildren("child")); + assertFalse(c.hasChildren("child")); + assertFalse(c.hasChildren("root")); + } + + public void testRemoveLastChildFromFiltered() { + HierarchicalContainer c = new HierarchicalContainer(); + + c.addItem("root"); + assertEquals(false, c.hasChildren("root")); + + c.addItem("child"); + c.setParent("child", "root"); + assertEquals(true, c.hasChildren("root")); + + // Dummy filter that does not remove any items + c.addContainerFilter(new Filter() { + + @Override + public boolean passesFilter(Object itemId, Item item) + throws UnsupportedOperationException { + return true; + } + + @Override + public boolean appliesToProperty(Object propertyId) { + return true; + } + }); + c.removeItem("child"); + + assertFalse(c.containsId("child")); + assertNull(c.getChildren("root")); + assertNull(c.getChildren("child")); + assertFalse(c.hasChildren("child")); + assertFalse(c.hasChildren("root")); + } + + public void testHierarchicalFilteringWithoutParents() { + HierarchicalContainer container = new HierarchicalContainer(); + + initializeContainer(container); + container.setIncludeParentsWhenFiltering(false); + + // Filter by "contains ab" + container.addContainerFilter(SIMPLE_NAME, "ab", false, false); + + // 20 items match the filter. + // com.vaadin.data.BufferedValidatable + // com.vaadin.data.Validatable + // com.vaadin.terminal.gwt.client.Focusable + // com.vaadin.terminal.gwt.client.Paintable + // com.vaadin.terminal.gwt.client.ui.Table + // com.vaadin.terminal.gwt.client.ui.VLabel + // com.vaadin.terminal.gwt.client.ui.VScrollTable + // com.vaadin.terminal.gwt.client.ui.VTablePaging + // com.vaadin.terminal.gwt.client.ui.VTabsheet + // com.vaadin.terminal.gwt.client.ui.VTabsheetBase + // com.vaadin.terminal.gwt.client.ui.VTabsheetPanel + // com.vaadin.server.ChangeVariablesErrorEvent + // com.vaadin.server.Paintable + // com.vaadin.server.Scrollable + // com.vaadin.server.Sizeable + // com.vaadin.server.VariableOwner + // com.vaadin.ui.Label + // com.vaadin.ui.Table + // com.vaadin.ui.TableFieldFactory + // com.vaadin.ui.TabSheet + // all become roots. + int expectedSize = 20; + int expectedRoots = 20; + + validateHierarchicalContainer(container, + "com.vaadin.data.BufferedValidatable", + "com.vaadin.ui.TabSheet", + "com.vaadin.terminal.gwt.client.ui.VTabsheetBase", "blah", + true, expectedSize, expectedRoots, false); + + // only include .gwt.client classes + container.removeAllContainerFilters(); + container.addContainerFilter(FULLY_QUALIFIED_NAME, ".gwt.client.", + false, false); + + int packages = 3; + int classes = 110; + + expectedSize = packages + classes; + expectedRoots = 35 + 1; // com.vaadin.terminal.gwt.client.ui + + // com.vaadin.terminal.gwt.client.* + + // Sorting is case insensitive + validateHierarchicalContainer(container, + "com.vaadin.terminal.gwt.client.ApplicationConfiguration", + "com.vaadin.terminal.gwt.client.WidgetSet", + "com.vaadin.terminal.gwt.client.ui.VOptionGroup", "blah", true, + expectedSize, expectedRoots, false); + + // Additionally remove all without 'P' in the simple name. + container.addContainerFilter(SIMPLE_NAME, "P", false, false); + + expectedSize = 13; + expectedRoots = expectedSize; + + validateHierarchicalContainer(container, + "com.vaadin.terminal.gwt.client.Paintable", + "com.vaadin.terminal.gwt.client.ui.VTabsheetPanel", + "com.vaadin.terminal.gwt.client.ui.VPopupCalendar", "blah", + true, expectedSize, expectedRoots, false); + + } +} diff --git a/server/tests/src/com/vaadin/data/util/IndexedContainerTest.java b/server/tests/src/com/vaadin/data/util/IndexedContainerTest.java new file mode 100644 index 0000000000..2f64e7c797 --- /dev/null +++ b/server/tests/src/com/vaadin/data/util/IndexedContainerTest.java @@ -0,0 +1,395 @@ +package com.vaadin.data.util; + +import java.util.List; + +import org.junit.Assert; + +import com.vaadin.data.Item; + +public class IndexedContainerTest extends AbstractInMemoryContainerTestBase { + + public void testBasicOperations() { + testBasicContainerOperations(new IndexedContainer()); + } + + public void testFiltering() { + testContainerFiltering(new IndexedContainer()); + } + + public void testSorting() { + testContainerSorting(new IndexedContainer()); + } + + public void testSortingAndFiltering() { + testContainerSortingAndFiltering(new IndexedContainer()); + } + + public void testContainerOrdered() { + testContainerOrdered(new IndexedContainer()); + } + + public void testContainerIndexed() { + testContainerIndexed(new IndexedContainer(), sampleData[2], 2, true, + "newItemId", true); + } + + public void testItemSetChangeListeners() { + IndexedContainer container = new IndexedContainer(); + ItemSetChangeCounter counter = new ItemSetChangeCounter(); + container.addListener(counter); + + String id1 = "id1"; + String id2 = "id2"; + String id3 = "id3"; + + initializeContainer(container); + counter.reset(); + container.addItem(); + counter.assertOnce(); + container.addItem(id1); + counter.assertOnce(); + + initializeContainer(container); + counter.reset(); + container.addItemAt(0); + counter.assertOnce(); + container.addItemAt(0, id1); + counter.assertOnce(); + container.addItemAt(0, id2); + counter.assertOnce(); + container.addItemAt(container.size(), id3); + counter.assertOnce(); + // no notification if already in container + container.addItemAt(0, id1); + counter.assertNone(); + + initializeContainer(container); + counter.reset(); + container.addItemAfter(null); + counter.assertOnce(); + container.addItemAfter(null, id1); + counter.assertOnce(); + container.addItemAfter(id1); + counter.assertOnce(); + container.addItemAfter(id1, id2); + counter.assertOnce(); + container.addItemAfter(container.firstItemId()); + counter.assertOnce(); + container.addItemAfter(container.lastItemId()); + counter.assertOnce(); + container.addItemAfter(container.lastItemId(), id3); + counter.assertOnce(); + // no notification if already in container + container.addItemAfter(0, id1); + counter.assertNone(); + + initializeContainer(container); + counter.reset(); + container.removeItem(sampleData[0]); + counter.assertOnce(); + + initializeContainer(container); + counter.reset(); + // no notification for removing a non-existing item + container.removeItem(id1); + counter.assertNone(); + + initializeContainer(container); + counter.reset(); + container.removeAllItems(); + counter.assertOnce(); + // already empty + container.removeAllItems(); + counter.assertNone(); + + } + + public void testAddRemoveContainerFilter() { + IndexedContainer container = new IndexedContainer(); + ItemSetChangeCounter counter = new ItemSetChangeCounter(); + container.addListener(counter); + + // simply adding or removing container filters should cause events + // (content changes) + + initializeContainer(container); + counter.reset(); + container.addContainerFilter(SIMPLE_NAME, "a", true, false); + counter.assertOnce(); + container.removeContainerFilters(SIMPLE_NAME); + counter.assertOnce(); + container.addContainerFilter(SIMPLE_NAME, "a", true, false); + counter.assertOnce(); + container.removeAllContainerFilters(); + counter.assertOnce(); + } + + // TODO other tests should check positions after removing filter etc, + // here concentrating on listeners + public void testItemSetChangeListenersFiltering() { + IndexedContainer container = new IndexedContainer(); + ItemSetChangeCounter counter = new ItemSetChangeCounter(); + container.addListener(counter); + + counter.reset(); + container.addContainerFilter(FULLY_QUALIFIED_NAME, "Test", true, false); + // no real change, so no notification required + counter.assertNone(); + + String id1 = "com.example.Test1"; + String id2 = "com.example.Test2"; + String id3 = "com.example.Other"; + + // perform operations while filtering container + + Item item; + + initializeContainer(container); + counter.reset(); + // passes filter + item = container.addItem(id1); + // no event if filtered out + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id1); + counter.assertOnce(); + // passes filter but already in the container + item = container.addItem(id1); + counter.assertNone(); + + initializeContainer(container); + counter.reset(); + // passes filter after change + item = container.addItemAt(0, id1); + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id1); + counter.assertOnce(); + item = container.addItemAt(container.size(), id2); + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id2); + counter.assertOnce(); + // passes filter but already in the container + item = container.addItemAt(0, id1); + counter.assertNone(); + item = container.addItemAt(container.size(), id2); + counter.assertNone(); + + initializeContainer(container); + counter.reset(); + // passes filter + item = container.addItemAfter(null, id1); + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id1); + counter.assertOnce(); + item = container.addItemAfter(container.lastItemId(), id2); + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id2); + counter.assertOnce(); + // passes filter but already in the container + item = container.addItemAfter(null, id1); + counter.assertNone(); + item = container.addItemAfter(container.lastItemId(), id2); + counter.assertNone(); + + // does not pass filter + + // TODO implement rest + + initializeContainer(container); + counter.reset(); + item = container.addItemAfter(null, id3); + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3); + counter.assertNone(); + + initializeContainer(container); + counter.reset(); + item = container.addItemAfter(container.firstItemId(), id3); + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3); + counter.assertNone(); + + initializeContainer(container); + counter.reset(); + item = container.addItemAfter(container.lastItemId(), id3); + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3); + counter.assertNone(); + + initializeContainer(container); + counter.reset(); + item = container.addItemAt(0, id3); + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3); + counter.assertNone(); + + initializeContainer(container); + counter.reset(); + item = container.addItemAt(1, id3); + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3); + counter.assertNone(); + + initializeContainer(container); + counter.reset(); + item = container.addItemAt(container.size(), id3); + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3); + counter.assertNone(); + + // passes filter + + initializeContainer(container); + counter.reset(); + item = container.addItem(id1); + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id1); + counter.assertOnce(); + container.removeItem(id1); + counter.assertOnce(); + // already removed + container.removeItem(id1); + counter.assertNone(); + + item = container.addItem(id3); + counter.assertNone(); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3); + counter.assertNone(); + // not visible + container.removeItem(id3); + counter.assertNone(); + + // remove all + + initializeContainer(container); + item = container.addItem(id1); + item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id1); + counter.reset(); + container.removeAllItems(); + counter.assertOnce(); + // no visible items + container.removeAllItems(); + counter.assertNone(); + } + + // Ticket 8028 + public void testGetItemIdsRangeIndexOutOfBounds() { + IndexedContainer ic = new IndexedContainer(); + try { + ic.getItemIds(-1, 10); + fail("Container returned items starting from index -1, something very wrong here!"); + } catch (IndexOutOfBoundsException e) { + // This is expected... + } catch (Exception e) { + // Should not happen! + fail("Container threw unspecified exception when fetching a range of items and the range started from -1"); + } + + } + + // Ticket 8028 + public void testGetItemIdsRangeIndexOutOfBounds2() { + IndexedContainer ic = new IndexedContainer(); + ic.addItem(new Object()); + try { + ic.getItemIds(2, 1); + fail("Container returned items starting from index -1, something very wrong here!"); + } catch (IndexOutOfBoundsException e) { + // This is expected... + } catch (Exception e) { + // Should not happen! + fail("Container threw unspecified exception when fetching a out of bounds range of items"); + } + + } + + // Ticket 8028 + public void testGetItemIdsRangeZeroRange() { + IndexedContainer ic = new IndexedContainer(); + ic.addItem(new Object()); + try { + List itemIds = ic.getItemIds(1, 0); + + assertTrue( + "Container returned actual values when asking for 0 items...", + itemIds.isEmpty()); + } catch (Exception e) { + // Should not happen! + fail("Container threw unspecified exception when fetching 0 items..."); + } + + } + + // Ticket 8028 + public void testGetItemIdsRangeNegativeRange() { + IndexedContainer ic = new IndexedContainer(); + ic.addItem(new Object()); + try { + List itemIds = ic.getItemIds(1, -1); + + assertTrue( + "Container returned actual values when asking for -1 items...", + itemIds.isEmpty()); + } catch (IllegalArgumentException e) { + // this is expected + + } catch (Exception e) { + // Should not happen! + fail("Container threw unspecified exception when fetching -1 items..."); + } + + } + + // Ticket 8028 + public void testGetItemIdsRangeIndexOutOfBoundsDueToSizeChange() { + IndexedContainer ic = new IndexedContainer(); + ic.addItem(new Object()); + Assert.assertEquals( + "Container returned too many items when the range was >> container size", + 1, ic.getItemIds(0, 10).size()); + } + + // Ticket 8028 + public void testGetItemIdsRangeBaseCase() { + IndexedContainer ic = new IndexedContainer(); + String object1 = new String("Obj1"); + String object2 = new String("Obj2"); + String object3 = new String("Obj3"); + String object4 = new String("Obj4"); + String object5 = new String("Obj5"); + + ic.addItem(object1); + ic.addItem(object2); + ic.addItem(object3); + ic.addItem(object4); + ic.addItem(object5); + + try { + List itemIds = ic.getItemIds(1, 2); + + assertTrue(itemIds.contains(object2)); + assertTrue(itemIds.contains(object3)); + assertEquals(2, itemIds.size()); + + } catch (Exception e) { + // Should not happen! + fail("Container threw exception when fetching a range of items "); + } + } + + // test getting non-existing property (#10445) + public void testNonExistingProperty() { + IndexedContainer ic = new IndexedContainer(); + String object1 = new String("Obj1"); + ic.addItem(object1); + assertNull(ic.getContainerProperty(object1, "xyz")); + } + + // test getting null property id (#10445) + public void testNullPropertyId() { + IndexedContainer ic = new IndexedContainer(); + String object1 = new String("Obj1"); + ic.addItem(object1); + assertNull(ic.getContainerProperty(object1, null)); + } + +} diff --git a/server/tests/src/com/vaadin/data/util/MethodPropertyMemoryConsumption.java b/server/tests/src/com/vaadin/data/util/MethodPropertyMemoryConsumption.java deleted file mode 100644 index ce0711a29e..0000000000 --- a/server/tests/src/com/vaadin/data/util/MethodPropertyMemoryConsumption.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.data.util; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.lang.reflect.Field; - -import org.junit.Assert; -import org.junit.Test; - -/** - * Test for MethodProperty: don't allocate unnecessary Object arrays. - * - * @since 7.2 - * @author Vaadin Ltd - */ -public class MethodPropertyMemoryConsumption { - - @Test - public void testSetArguments() throws NoSuchFieldException, - SecurityException, IllegalArgumentException, IllegalAccessException { - TestBean bean = new TestBean(); - TestMethodProperty property = new TestMethodProperty( - bean, "name"); - Object[] getArgs = property.getGetArgs(); - Object[] setArgs = property.getSetArgs(); - - Field getArgsField = TestMethodProperty.class - .getDeclaredField("getArgs"); - getArgsField.setAccessible(true); - - Field setArgsField = TestMethodProperty.class - .getDeclaredField("setArgs"); - setArgsField.setAccessible(true); - - Assert.assertSame("setArguments method sets non-default instance" - + " of empty Object array for getArgs", - getArgsField.get(property), getArgs); - - Assert.assertSame("setArguments method sets non-default instance" - + " of empty Object array for setArgs", - setArgsField.get(property), setArgs); - } - - @Test - public void testDefaultCtor() { - TestBean bean = new TestBean(); - TestMethodProperty property = new TestMethodProperty( - bean, "name"); - - Object[] getArgs = property.getGetArgs(); - Object[] setArgs = property.getSetArgs(); - - TestBean otherBean = new TestBean(); - TestMethodProperty otherProperty = new TestMethodProperty( - otherBean, "name"); - Assert.assertSame("setArguments method uses different instance" - + " of empty Object array for getArgs", getArgs, - otherProperty.getGetArgs()); - Assert.assertSame("setArguments method uses different instance" - + " of empty Object array for setArgs", setArgs, - otherProperty.getSetArgs()); - } - - @Test - public void testDefaultArgsSerialization() throws IOException, - ClassNotFoundException { - TestBean bean = new TestBean(); - TestMethodProperty property = new TestMethodProperty( - bean, "name"); - - ByteArrayOutputStream sourceOutStream = new ByteArrayOutputStream(); - ObjectOutputStream outStream = new ObjectOutputStream(sourceOutStream); - outStream.writeObject(property); - - ObjectInputStream inputStream = new ObjectInputStream( - new ByteArrayInputStream(sourceOutStream.toByteArray())); - Object red = inputStream.readObject(); - TestMethodProperty deserialized = (TestMethodProperty) red; - - Assert.assertNotNull("Deseriliation doesn't call setArguments method", - deserialized.getGetArgs()); - Assert.assertNotNull("Deseriliation doesn't call setArguments method", - deserialized.getSetArgs()); - - } - - public static class TestMethodProperty extends MethodProperty { - - public TestMethodProperty(Object instance, String beanPropertyName) { - super(instance, beanPropertyName); - } - - @Override - public void setArguments(Object[] getArgs, Object[] setArgs, - int setArgumentIndex) { - super.setArguments(getArgs, setArgs, setArgumentIndex); - this.getArgs = getArgs; - this.setArgs = setArgs; - } - - Object[] getGetArgs() { - return getArgs; - } - - Object[] getSetArgs() { - return setArgs; - } - - private transient Object[] getArgs; - private transient Object[] setArgs; - } - - public static class TestBean implements Serializable { - - private String name; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - } -} diff --git a/server/tests/src/com/vaadin/data/util/MethodPropertyMemoryConsumptionTest.java b/server/tests/src/com/vaadin/data/util/MethodPropertyMemoryConsumptionTest.java new file mode 100644 index 0000000000..b4621b823a --- /dev/null +++ b/server/tests/src/com/vaadin/data/util/MethodPropertyMemoryConsumptionTest.java @@ -0,0 +1,145 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.data.util; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.lang.reflect.Field; + +import org.junit.Assert; +import org.junit.Test; + +/** + * Test for MethodProperty: don't allocate unnecessary Object arrays. + * + * @since 7.2 + * @author Vaadin Ltd + */ +public class MethodPropertyMemoryConsumptionTest { + + @Test + public void testSetArguments() throws NoSuchFieldException, + SecurityException, IllegalArgumentException, IllegalAccessException { + TestBean bean = new TestBean(); + TestMethodProperty property = new TestMethodProperty( + bean, "name"); + Object[] getArgs = property.getGetArgs(); + Object[] setArgs = property.getSetArgs(); + + Field getArgsField = TestMethodProperty.class + .getDeclaredField("getArgs"); + getArgsField.setAccessible(true); + + Field setArgsField = TestMethodProperty.class + .getDeclaredField("setArgs"); + setArgsField.setAccessible(true); + + Assert.assertSame("setArguments method sets non-default instance" + + " of empty Object array for getArgs", + getArgsField.get(property), getArgs); + + Assert.assertSame("setArguments method sets non-default instance" + + " of empty Object array for setArgs", + setArgsField.get(property), setArgs); + } + + @Test + public void testDefaultCtor() { + TestBean bean = new TestBean(); + TestMethodProperty property = new TestMethodProperty( + bean, "name"); + + Object[] getArgs = property.getGetArgs(); + Object[] setArgs = property.getSetArgs(); + + TestBean otherBean = new TestBean(); + TestMethodProperty otherProperty = new TestMethodProperty( + otherBean, "name"); + Assert.assertSame("setArguments method uses different instance" + + " of empty Object array for getArgs", getArgs, + otherProperty.getGetArgs()); + Assert.assertSame("setArguments method uses different instance" + + " of empty Object array for setArgs", setArgs, + otherProperty.getSetArgs()); + } + + @Test + public void testDefaultArgsSerialization() throws IOException, + ClassNotFoundException { + TestBean bean = new TestBean(); + TestMethodProperty property = new TestMethodProperty( + bean, "name"); + + ByteArrayOutputStream sourceOutStream = new ByteArrayOutputStream(); + ObjectOutputStream outStream = new ObjectOutputStream(sourceOutStream); + outStream.writeObject(property); + + ObjectInputStream inputStream = new ObjectInputStream( + new ByteArrayInputStream(sourceOutStream.toByteArray())); + Object red = inputStream.readObject(); + TestMethodProperty deserialized = (TestMethodProperty) red; + + Assert.assertNotNull("Deseriliation doesn't call setArguments method", + deserialized.getGetArgs()); + Assert.assertNotNull("Deseriliation doesn't call setArguments method", + deserialized.getSetArgs()); + + } + + public static class TestMethodProperty extends MethodProperty { + + public TestMethodProperty(Object instance, String beanPropertyName) { + super(instance, beanPropertyName); + } + + @Override + public void setArguments(Object[] getArgs, Object[] setArgs, + int setArgumentIndex) { + super.setArguments(getArgs, setArgs, setArgumentIndex); + this.getArgs = getArgs; + this.setArgs = setArgs; + } + + Object[] getGetArgs() { + return getArgs; + } + + Object[] getSetArgs() { + return setArgs; + } + + private transient Object[] getArgs; + private transient Object[] setArgs; + } + + public static class TestBean implements Serializable { + + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } +} diff --git a/server/tests/src/com/vaadin/data/util/PerformanceTestIndexedContainer.java b/server/tests/src/com/vaadin/data/util/PerformanceTestIndexedContainer.java deleted file mode 100644 index 1c49017bf1..0000000000 --- a/server/tests/src/com/vaadin/data/util/PerformanceTestIndexedContainer.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.vaadin.data.util; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.SortedSet; -import java.util.TreeSet; - -import junit.framework.TestCase; - -import org.junit.Assert; - -public class PerformanceTestIndexedContainer extends TestCase { - - private static final int REPEATS = 10; - private final static int ITEMS = 50000; - private static final long ADD_ITEM_FAIL_THRESHOLD = 200; - // TODO should improve performance of these methods - private static final long ADD_ITEM_AT_FAIL_THRESHOLD = 5000; - private static final long ADD_ITEM_AFTER_FAIL_THRESHOLD = 5000; - private static final long ADD_ITEM_AFTER_LAST_FAIL_THRESHOLD = 5000; - private static final long ADD_ITEMS_CONSTRUCTOR_FAIL_THRESHOLD = 200; - - public void testAddItemPerformance() { - Collection times = new ArrayList(); - for (int j = 0; j < REPEATS; ++j) { - IndexedContainer c = new IndexedContainer(); - long start = System.currentTimeMillis(); - for (int i = 0; i < ITEMS; i++) { - c.addItem(); - } - times.add(System.currentTimeMillis() - start); - } - checkMedian(ITEMS, times, "IndexedContainer.addItem()", - ADD_ITEM_FAIL_THRESHOLD); - } - - public void testAddItemAtPerformance() { - Collection times = new ArrayList(); - for (int j = 0; j < REPEATS; ++j) { - IndexedContainer c = new IndexedContainer(); - long start = System.currentTimeMillis(); - for (int i = 0; i < ITEMS; i++) { - c.addItemAt(0); - } - times.add(System.currentTimeMillis() - start); - } - checkMedian(ITEMS, times, "IndexedContainer.addItemAt()", - ADD_ITEM_AT_FAIL_THRESHOLD); - } - - public void testAddItemAfterPerformance() { - Object initialId = "Item0"; - Collection times = new ArrayList(); - for (int j = 0; j < REPEATS; ++j) { - IndexedContainer c = new IndexedContainer(); - c.addItem(initialId); - long start = System.currentTimeMillis(); - for (int i = 0; i < ITEMS; i++) { - c.addItemAfter(initialId); - } - times.add(System.currentTimeMillis() - start); - } - checkMedian(ITEMS, times, "IndexedContainer.addItemAfter()", - ADD_ITEM_AFTER_FAIL_THRESHOLD); - } - - public void testAddItemAfterLastPerformance() { - // TODO running with less items because slow otherwise - Collection times = new ArrayList(); - for (int j = 0; j < REPEATS; ++j) { - IndexedContainer c = new IndexedContainer(); - c.addItem(); - long start = System.currentTimeMillis(); - for (int i = 0; i < ITEMS / 3; i++) { - c.addItemAfter(c.lastItemId()); - } - times.add(System.currentTimeMillis() - start); - } - checkMedian(ITEMS / 3, times, "IndexedContainer.addItemAfter(lastId)", - ADD_ITEM_AFTER_LAST_FAIL_THRESHOLD); - } - - public void testAddItemsConstructorPerformance() { - Collection items = new ArrayList(50000); - for (int i = 0; i < ITEMS; ++i) { - items.add(new Object()); - } - - SortedSet times = new TreeSet(); - for (int j = 0; j < REPEATS; ++j) { - long start = System.currentTimeMillis(); - new IndexedContainer(items); - times.add(System.currentTimeMillis() - start); - } - checkMedian(ITEMS, times, "IndexedContainer(Collection)", - ADD_ITEMS_CONSTRUCTOR_FAIL_THRESHOLD); - } - - private void checkMedian(int items, Collection times, - String methodName, long threshold) { - long median = median(times); - System.out.println(methodName + " timings (ms) for " + items - + " items: " + times); - Assert.assertTrue(methodName + " too slow, median time " + median - + "ms for " + items + " items", median <= threshold); - } - - private Long median(Collection times) { - ArrayList list = new ArrayList(times); - Collections.sort(list); - // not exact median in some cases, but good enough - return list.get(list.size() / 2); - } - -} diff --git a/server/tests/src/com/vaadin/data/util/PerformanceTestIndexedContainerTest.java b/server/tests/src/com/vaadin/data/util/PerformanceTestIndexedContainerTest.java new file mode 100644 index 0000000000..042f260be8 --- /dev/null +++ b/server/tests/src/com/vaadin/data/util/PerformanceTestIndexedContainerTest.java @@ -0,0 +1,116 @@ +package com.vaadin.data.util; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.SortedSet; +import java.util.TreeSet; + +import junit.framework.TestCase; + +import org.junit.Assert; + +public class PerformanceTestIndexedContainerTest extends TestCase { + + private static final int REPEATS = 10; + private final static int ITEMS = 50000; + private static final long ADD_ITEM_FAIL_THRESHOLD = 200; + // TODO should improve performance of these methods + private static final long ADD_ITEM_AT_FAIL_THRESHOLD = 5000; + private static final long ADD_ITEM_AFTER_FAIL_THRESHOLD = 5000; + private static final long ADD_ITEM_AFTER_LAST_FAIL_THRESHOLD = 5000; + private static final long ADD_ITEMS_CONSTRUCTOR_FAIL_THRESHOLD = 200; + + public void testAddItemPerformance() { + Collection times = new ArrayList(); + for (int j = 0; j < REPEATS; ++j) { + IndexedContainer c = new IndexedContainer(); + long start = System.currentTimeMillis(); + for (int i = 0; i < ITEMS; i++) { + c.addItem(); + } + times.add(System.currentTimeMillis() - start); + } + checkMedian(ITEMS, times, "IndexedContainer.addItem()", + ADD_ITEM_FAIL_THRESHOLD); + } + + public void testAddItemAtPerformance() { + Collection times = new ArrayList(); + for (int j = 0; j < REPEATS; ++j) { + IndexedContainer c = new IndexedContainer(); + long start = System.currentTimeMillis(); + for (int i = 0; i < ITEMS; i++) { + c.addItemAt(0); + } + times.add(System.currentTimeMillis() - start); + } + checkMedian(ITEMS, times, "IndexedContainer.addItemAt()", + ADD_ITEM_AT_FAIL_THRESHOLD); + } + + public void testAddItemAfterPerformance() { + Object initialId = "Item0"; + Collection times = new ArrayList(); + for (int j = 0; j < REPEATS; ++j) { + IndexedContainer c = new IndexedContainer(); + c.addItem(initialId); + long start = System.currentTimeMillis(); + for (int i = 0; i < ITEMS; i++) { + c.addItemAfter(initialId); + } + times.add(System.currentTimeMillis() - start); + } + checkMedian(ITEMS, times, "IndexedContainer.addItemAfter()", + ADD_ITEM_AFTER_FAIL_THRESHOLD); + } + + public void testAddItemAfterLastPerformance() { + // TODO running with less items because slow otherwise + Collection times = new ArrayList(); + for (int j = 0; j < REPEATS; ++j) { + IndexedContainer c = new IndexedContainer(); + c.addItem(); + long start = System.currentTimeMillis(); + for (int i = 0; i < ITEMS / 3; i++) { + c.addItemAfter(c.lastItemId()); + } + times.add(System.currentTimeMillis() - start); + } + checkMedian(ITEMS / 3, times, "IndexedContainer.addItemAfter(lastId)", + ADD_ITEM_AFTER_LAST_FAIL_THRESHOLD); + } + + public void testAddItemsConstructorPerformance() { + Collection items = new ArrayList(50000); + for (int i = 0; i < ITEMS; ++i) { + items.add(new Object()); + } + + SortedSet times = new TreeSet(); + for (int j = 0; j < REPEATS; ++j) { + long start = System.currentTimeMillis(); + new IndexedContainer(items); + times.add(System.currentTimeMillis() - start); + } + checkMedian(ITEMS, times, "IndexedContainer(Collection)", + ADD_ITEMS_CONSTRUCTOR_FAIL_THRESHOLD); + } + + private void checkMedian(int items, Collection times, + String methodName, long threshold) { + long median = median(times); + System.out.println(methodName + " timings (ms) for " + items + + " items: " + times); + Assert.assertTrue(methodName + " too slow, median time " + median + + "ms for " + items + " items", median <= threshold); + } + + private Long median(Collection times) { + ArrayList list = new ArrayList(times); + Collections.sort(list); + // not exact median in some cases, but good enough + return list.get(list.size() / 2); + } + +} diff --git a/server/tests/src/com/vaadin/data/util/ReflectToolsGetSuperField.java b/server/tests/src/com/vaadin/data/util/ReflectToolsGetSuperField.java deleted file mode 100644 index dc828689a8..0000000000 --- a/server/tests/src/com/vaadin/data/util/ReflectToolsGetSuperField.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.vaadin.data.util; - -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -import com.vaadin.data.fieldgroup.FieldGroup; -import com.vaadin.data.fieldgroup.PropertyId; -import com.vaadin.ui.TextField; - -public class ReflectToolsGetSuperField { - - @Test - public void getFieldFromSuperClass() { - class MyClass { - @PropertyId("testProperty") - TextField test = new TextField("This is a test"); - } - class MySubClass extends MyClass { - // no fields here - } - - PropertysetItem item = new PropertysetItem(); - item.addItemProperty("testProperty", new ObjectProperty( - "Value of testProperty")); - - MySubClass form = new MySubClass(); - - FieldGroup binder = new FieldGroup(item); - binder.bindMemberFields(form); - - assertTrue("Value of testProperty".equals(form.test.getValue())); - } - -} diff --git a/server/tests/src/com/vaadin/data/util/ReflectToolsGetSuperFieldTest.java b/server/tests/src/com/vaadin/data/util/ReflectToolsGetSuperFieldTest.java new file mode 100644 index 0000000000..5f31150210 --- /dev/null +++ b/server/tests/src/com/vaadin/data/util/ReflectToolsGetSuperFieldTest.java @@ -0,0 +1,35 @@ +package com.vaadin.data.util; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.vaadin.data.fieldgroup.FieldGroup; +import com.vaadin.data.fieldgroup.PropertyId; +import com.vaadin.ui.TextField; + +public class ReflectToolsGetSuperFieldTest { + + @Test + public void getFieldFromSuperClass() { + class MyClass { + @PropertyId("testProperty") + TextField test = new TextField("This is a test"); + } + class MySubClass extends MyClass { + // no fields here + } + + PropertysetItem item = new PropertysetItem(); + item.addItemProperty("testProperty", new ObjectProperty( + "Value of testProperty")); + + MySubClass form = new MySubClass(); + + FieldGroup binder = new FieldGroup(item); + binder.bindMemberFields(form); + + assertTrue("Value of testProperty".equals(form.test.getValue())); + } + +} diff --git a/server/tests/src/com/vaadin/data/util/TestContainerHierarchicalWrapper.java b/server/tests/src/com/vaadin/data/util/TestContainerHierarchicalWrapper.java deleted file mode 100644 index ff6de50651..0000000000 --- a/server/tests/src/com/vaadin/data/util/TestContainerHierarchicalWrapper.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.vaadin.data.util; - -import java.util.Collection; - -public class TestContainerHierarchicalWrapper extends - AbstractHierarchicalContainerTest { - - public void testBasicOperations() { - testBasicContainerOperations(new ContainerHierarchicalWrapper( - new IndexedContainer())); - } - - public void testHierarchicalContainer() { - testHierarchicalContainer(new ContainerHierarchicalWrapper( - new IndexedContainer())); - } - - public void testRemoveSubtree() { - testRemoveHierarchicalWrapperSubtree(new ContainerHierarchicalWrapper( - new IndexedContainer())); - } - - protected void testRemoveHierarchicalWrapperSubtree( - ContainerHierarchicalWrapper container) { - initializeContainer(container); - - // remove root item - container.removeItemRecursively("org"); - - int packages = 21 + 3 - 3; - int expectedSize = sampleData.length + packages - 1; - - validateContainer(container, "com", "com.vaadin.util.SerializerHelper", - "com.vaadin.server.ApplicationResource", "blah", true, - expectedSize); - - // rootItemIds - Collection rootIds = container.rootItemIds(); - assertEquals(1, rootIds.size()); - } - -} diff --git a/server/tests/src/com/vaadin/data/util/TestContainerSorting.java b/server/tests/src/com/vaadin/data/util/TestContainerSorting.java deleted file mode 100644 index 497699605a..0000000000 --- a/server/tests/src/com/vaadin/data/util/TestContainerSorting.java +++ /dev/null @@ -1,224 +0,0 @@ -package com.vaadin.data.util; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import junit.framework.TestCase; - -import com.vaadin.data.Container; -import com.vaadin.data.Item; -import com.vaadin.tests.util.TestUtil; - -public class TestContainerSorting extends TestCase { - - private static final String ITEM_DATA_MINUS2_NULL = "Data -2 null"; - private static final String ITEM_DATA_MINUS2 = "Data -2"; - private static final String ITEM_DATA_MINUS1 = "Data -1"; - private static final String ITEM_DATA_MINUS1_NULL = "Data -1 null"; - private static final String ITEM_ANOTHER_NULL = "Another null"; - private static final String ITEM_STRING_2 = "String 2"; - private static final String ITEM_STRING_NULL2 = "String null"; - private static final String ITEM_STRING_1 = "String 1"; - - private static final String PROPERTY_INTEGER_NULL2 = "integer-null"; - private static final String PROPERTY_INTEGER_NOT_NULL = "integer-not-null"; - private static final String PROPERTY_STRING_NULL = "string-null"; - private static final String PROPERTY_STRING_ID = "string-not-null"; - - @Override - protected void setUp() throws Exception { - super.setUp(); - } - - public void testEmptyFilteredIndexedContainer() { - IndexedContainer ic = new IndexedContainer(); - - addProperties(ic); - populate(ic); - - ic.addContainerFilter(PROPERTY_STRING_ID, "aasdfasdfasdf", true, false); - ic.sort(new Object[] { PROPERTY_STRING_ID }, new boolean[] { true }); - - } - - public void testFilteredIndexedContainer() { - IndexedContainer ic = new IndexedContainer(); - - addProperties(ic); - populate(ic); - - ic.addContainerFilter(PROPERTY_STRING_ID, "a", true, false); - ic.sort(new Object[] { PROPERTY_STRING_ID }, new boolean[] { true }); - verifyOrder(ic, - new String[] { ITEM_ANOTHER_NULL, ITEM_DATA_MINUS1, - ITEM_DATA_MINUS1_NULL, ITEM_DATA_MINUS2, - ITEM_DATA_MINUS2_NULL, }); - } - - public void testIndexedContainer() { - IndexedContainer ic = new IndexedContainer(); - - addProperties(ic); - populate(ic); - - ic.sort(new Object[] { PROPERTY_STRING_ID }, new boolean[] { true }); - verifyOrder(ic, new String[] { ITEM_ANOTHER_NULL, ITEM_DATA_MINUS1, - ITEM_DATA_MINUS1_NULL, ITEM_DATA_MINUS2, ITEM_DATA_MINUS2_NULL, - ITEM_STRING_1, ITEM_STRING_2, ITEM_STRING_NULL2 }); - - ic.sort(new Object[] { PROPERTY_INTEGER_NOT_NULL, - PROPERTY_INTEGER_NULL2, PROPERTY_STRING_ID }, new boolean[] { - true, false, true }); - verifyOrder(ic, new String[] { ITEM_DATA_MINUS2, ITEM_DATA_MINUS2_NULL, - ITEM_DATA_MINUS1, ITEM_DATA_MINUS1_NULL, ITEM_ANOTHER_NULL, - ITEM_STRING_NULL2, ITEM_STRING_1, ITEM_STRING_2 }); - - ic.sort(new Object[] { PROPERTY_INTEGER_NOT_NULL, - PROPERTY_INTEGER_NULL2, PROPERTY_STRING_ID }, new boolean[] { - true, true, true }); - verifyOrder(ic, new String[] { ITEM_DATA_MINUS2_NULL, ITEM_DATA_MINUS2, - ITEM_DATA_MINUS1_NULL, ITEM_DATA_MINUS1, ITEM_ANOTHER_NULL, - ITEM_STRING_NULL2, ITEM_STRING_1, ITEM_STRING_2 }); - - } - - public void testHierarchicalContainer() { - HierarchicalContainer hc = new HierarchicalContainer(); - populateContainer(hc); - hc.sort(new Object[] { "name" }, new boolean[] { true }); - verifyOrder(hc, new String[] { "Audi", "C++", "Call of Duty", "Cars", - "English", "Fallout", "Finnish", "Ford", "Games", "Java", - "Might and Magic", "Natural languages", "PHP", - "Programming languages", "Python", "Red Alert", "Swedish", - "Toyota", "Volvo" }); - TestUtil.assertArrays( - hc.rootItemIds().toArray(), - new Integer[] { nameToId.get("Cars"), nameToId.get("Games"), - nameToId.get("Natural languages"), - nameToId.get("Programming languages") }); - TestUtil.assertArrays( - hc.getChildren(nameToId.get("Games")).toArray(), - new Integer[] { nameToId.get("Call of Duty"), - nameToId.get("Fallout"), - nameToId.get("Might and Magic"), - nameToId.get("Red Alert") }); - } - - private static void populateContainer(HierarchicalContainer container) { - container.addContainerProperty("name", String.class, null); - - addItem(container, "Games", null); - addItem(container, "Call of Duty", "Games"); - addItem(container, "Might and Magic", "Games"); - addItem(container, "Fallout", "Games"); - addItem(container, "Red Alert", "Games"); - - addItem(container, "Cars", null); - addItem(container, "Toyota", "Cars"); - addItem(container, "Volvo", "Cars"); - addItem(container, "Audi", "Cars"); - addItem(container, "Ford", "Cars"); - - addItem(container, "Natural languages", null); - addItem(container, "Swedish", "Natural languages"); - addItem(container, "English", "Natural languages"); - addItem(container, "Finnish", "Natural languages"); - - addItem(container, "Programming languages", null); - addItem(container, "C++", "Programming languages"); - addItem(container, "PHP", "Programming languages"); - addItem(container, "Java", "Programming languages"); - addItem(container, "Python", "Programming languages"); - - } - - private static int index = 0; - private static Map nameToId = new HashMap(); - private static Map idToName = new HashMap(); - - public static void addItem(IndexedContainer container, String string, - String parent) { - nameToId.put(string, index); - idToName.put(index, string); - - Item item = container.addItem(index); - item.getItemProperty("name").setValue(string); - - if (parent != null && container instanceof HierarchicalContainer) { - ((HierarchicalContainer) container).setParent(index, - nameToId.get(parent)); - } - - index++; - } - - private void verifyOrder(Container.Sortable ic, Object[] idOrder) { - int size = ic.size(); - Object[] actual = new Object[size]; - Iterator i = ic.getItemIds().iterator(); - int index = 0; - while (i.hasNext()) { - Object o = i.next(); - if (o.getClass() == Integer.class - && idOrder[index].getClass() == String.class) { - o = idToName.get(o); - } - actual[index++] = o; - } - - TestUtil.assertArrays(actual, idOrder); - - } - - private void populate(IndexedContainer ic) { - addItem(ic, ITEM_STRING_1, ITEM_STRING_1, 1, 1); - addItem(ic, ITEM_STRING_NULL2, null, 0, null); - addItem(ic, ITEM_STRING_2, ITEM_STRING_2, 2, 2); - addItem(ic, ITEM_ANOTHER_NULL, null, 0, null); - addItem(ic, ITEM_DATA_MINUS1, ITEM_DATA_MINUS1, -1, -1); - addItem(ic, ITEM_DATA_MINUS1_NULL, null, -1, null); - addItem(ic, ITEM_DATA_MINUS2, ITEM_DATA_MINUS2, -2, -2); - addItem(ic, ITEM_DATA_MINUS2_NULL, null, -2, null); - } - - private Item addItem(Container ic, String id, String string_null, - int integer, Integer integer_null) { - Item i = ic.addItem(id); - i.getItemProperty(PROPERTY_STRING_ID).setValue(id); - i.getItemProperty(PROPERTY_STRING_NULL).setValue(string_null); - i.getItemProperty(PROPERTY_INTEGER_NOT_NULL).setValue(integer); - i.getItemProperty(PROPERTY_INTEGER_NULL2).setValue(integer_null); - - return i; - } - - private void addProperties(IndexedContainer ic) { - ic.addContainerProperty("id", String.class, null); - ic.addContainerProperty(PROPERTY_STRING_ID, String.class, ""); - ic.addContainerProperty(PROPERTY_STRING_NULL, String.class, null); - ic.addContainerProperty(PROPERTY_INTEGER_NULL2, Integer.class, null); - ic.addContainerProperty(PROPERTY_INTEGER_NOT_NULL, Integer.class, 0); - ic.addContainerProperty("comparable-null", Integer.class, 0); - } - - public class MyObject implements Comparable { - private String data; - - @Override - public int compareTo(MyObject o) { - if (o == null) { - return 1; - } - - if (o.data == null) { - return data == null ? 0 : 1; - } else if (data == null) { - return -1; - } else { - return data.compareTo(o.data); - } - } - } - -} diff --git a/server/tests/src/com/vaadin/data/util/TestHierarchicalContainer.java b/server/tests/src/com/vaadin/data/util/TestHierarchicalContainer.java deleted file mode 100644 index 2a336ffc1c..0000000000 --- a/server/tests/src/com/vaadin/data/util/TestHierarchicalContainer.java +++ /dev/null @@ -1,270 +0,0 @@ -package com.vaadin.data.util; - -import com.vaadin.data.Container.Filter; -import com.vaadin.data.Item; - -public class TestHierarchicalContainer extends - AbstractHierarchicalContainerTest { - - public void testBasicOperations() { - testBasicContainerOperations(new HierarchicalContainer()); - } - - public void testFiltering() { - testContainerFiltering(new HierarchicalContainer()); - } - - public void testSorting() { - testContainerSorting(new HierarchicalContainer()); - } - - public void testOrdered() { - testContainerOrdered(new HierarchicalContainer()); - } - - public void testHierarchicalSorting() { - testHierarchicalSorting(new HierarchicalContainer()); - } - - public void testSortingAndFiltering() { - testContainerSortingAndFiltering(new HierarchicalContainer()); - } - - public void testRemovingItemsFromFilteredContainer() { - HierarchicalContainer container = new HierarchicalContainer(); - initializeContainer(container); - container.setIncludeParentsWhenFiltering(true); - container.addContainerFilter(FULLY_QUALIFIED_NAME, "ab", false, false); - Object p1 = container.getParent("com.vaadin.ui.TabSheet"); - assertEquals("com.vaadin.ui", p1); - - container.removeItem("com.vaadin.ui.TabSheet"); - // Parent for the removed item must be null because the item is no - // longer in the container - p1 = container.getParent("com.vaadin.ui.TabSheet"); - assertNull("Parent should be null, is " + p1, p1); - - container.removeAllItems(); - p1 = container.getParent("com.vaadin.terminal.gwt.client.Focusable"); - assertNull("Parent should be null, is " + p1, p1); - - } - - public void testParentWhenRemovingFilterFromContainer() { - HierarchicalContainer container = new HierarchicalContainer(); - initializeContainer(container); - container.setIncludeParentsWhenFiltering(true); - container.addContainerFilter(FULLY_QUALIFIED_NAME, "ab", false, false); - Object p1 = container.getParent("com.vaadin.ui.TabSheet"); - assertEquals("com.vaadin.ui", p1); - p1 = container - .getParent("com.vaadin.terminal.gwt.client.ui.VPopupCalendar"); - assertNull(p1); - container.removeAllContainerFilters(); - p1 = container - .getParent("com.vaadin.terminal.gwt.client.ui.VPopupCalendar"); - assertEquals("com.vaadin.terminal.gwt.client.ui", p1); - - } - - public void testChangeParentInFilteredContainer() { - HierarchicalContainer container = new HierarchicalContainer(); - initializeContainer(container); - container.setIncludeParentsWhenFiltering(true); - container.addContainerFilter(FULLY_QUALIFIED_NAME, "Tab", false, false); - - // Change parent of filtered item - Object p1 = container.getParent("com.vaadin.ui.TabSheet"); - assertEquals("com.vaadin.ui", p1); - container.setParent("com.vaadin.ui.TabSheet", "com.vaadin"); - p1 = container.getParent("com.vaadin.ui.TabSheet"); - assertEquals("com.vaadin", p1); - container.setParent("com.vaadin.ui.TabSheet", "com"); - p1 = container.getParent("com.vaadin.ui.TabSheet"); - assertEquals("com", p1); - container.setParent("com.vaadin.ui.TabSheet", null); - p1 = container.getParent("com.vaadin.ui.TabSheet"); - assertNull(p1); - - // root -> non-root - container.setParent("com.vaadin.ui.TabSheet", "com"); - p1 = container.getParent("com.vaadin.ui.TabSheet"); - assertEquals("com", p1); - - } - - public void testHierarchicalFilteringWithParents() { - HierarchicalContainer container = new HierarchicalContainer(); - initializeContainer(container); - container.setIncludeParentsWhenFiltering(true); - - // Filter by "contains ab" - container.addContainerFilter(FULLY_QUALIFIED_NAME, "ab", false, false); - - // 20 items match the filters and the have 8 parents that should also be - // included - // only one root "com" should exist - // filtered - int expectedSize = 29; - int expectedRoots = 1; - - validateHierarchicalContainer(container, "com", - "com.vaadin.ui.TabSheet", - "com.vaadin.terminal.gwt.client.Focusable", "blah", true, - expectedSize, expectedRoots, true); - - // only include .gwt.client classes - container.removeAllContainerFilters(); - container.addContainerFilter(FULLY_QUALIFIED_NAME, ".gwt.client.", - false, false); - - int packages = 6; - int classes = 112; - - expectedSize = packages + classes; - expectedRoots = 1; - - validateHierarchicalContainer(container, "com", - "com.vaadin.terminal.gwt.client.WidgetSet", - "com.vaadin.terminal.gwt.client.ui.VSplitPanelVertical", - "blah", true, expectedSize, expectedRoots, true); - - // Additionally remove all without 'm' in the simple name. - container.addContainerFilter(SIMPLE_NAME, "m", false, false); - - expectedSize = 7 + 18; - expectedRoots = 1; - - validateHierarchicalContainer( - container, - "com", - "com.vaadin.terminal.gwt.client.ui.VUriFragmentUtility", - "com.vaadin.terminal.gwt.client.ui.layout.ChildComponentContainer", - "blah", true, expectedSize, expectedRoots, true); - - } - - public void testRemoveLastChild() { - HierarchicalContainer c = new HierarchicalContainer(); - - c.addItem("root"); - assertEquals(false, c.hasChildren("root")); - - c.addItem("child"); - c.setParent("child", "root"); - assertEquals(true, c.hasChildren("root")); - - c.removeItem("child"); - assertFalse(c.containsId("child")); - assertNull(c.getChildren("root")); - assertNull(c.getChildren("child")); - assertFalse(c.hasChildren("child")); - assertFalse(c.hasChildren("root")); - } - - public void testRemoveLastChildFromFiltered() { - HierarchicalContainer c = new HierarchicalContainer(); - - c.addItem("root"); - assertEquals(false, c.hasChildren("root")); - - c.addItem("child"); - c.setParent("child", "root"); - assertEquals(true, c.hasChildren("root")); - - // Dummy filter that does not remove any items - c.addContainerFilter(new Filter() { - - @Override - public boolean passesFilter(Object itemId, Item item) - throws UnsupportedOperationException { - return true; - } - - @Override - public boolean appliesToProperty(Object propertyId) { - return true; - } - }); - c.removeItem("child"); - - assertFalse(c.containsId("child")); - assertNull(c.getChildren("root")); - assertNull(c.getChildren("child")); - assertFalse(c.hasChildren("child")); - assertFalse(c.hasChildren("root")); - } - - public void testHierarchicalFilteringWithoutParents() { - HierarchicalContainer container = new HierarchicalContainer(); - - initializeContainer(container); - container.setIncludeParentsWhenFiltering(false); - - // Filter by "contains ab" - container.addContainerFilter(SIMPLE_NAME, "ab", false, false); - - // 20 items match the filter. - // com.vaadin.data.BufferedValidatable - // com.vaadin.data.Validatable - // com.vaadin.terminal.gwt.client.Focusable - // com.vaadin.terminal.gwt.client.Paintable - // com.vaadin.terminal.gwt.client.ui.Table - // com.vaadin.terminal.gwt.client.ui.VLabel - // com.vaadin.terminal.gwt.client.ui.VScrollTable - // com.vaadin.terminal.gwt.client.ui.VTablePaging - // com.vaadin.terminal.gwt.client.ui.VTabsheet - // com.vaadin.terminal.gwt.client.ui.VTabsheetBase - // com.vaadin.terminal.gwt.client.ui.VTabsheetPanel - // com.vaadin.server.ChangeVariablesErrorEvent - // com.vaadin.server.Paintable - // com.vaadin.server.Scrollable - // com.vaadin.server.Sizeable - // com.vaadin.server.VariableOwner - // com.vaadin.ui.Label - // com.vaadin.ui.Table - // com.vaadin.ui.TableFieldFactory - // com.vaadin.ui.TabSheet - // all become roots. - int expectedSize = 20; - int expectedRoots = 20; - - validateHierarchicalContainer(container, - "com.vaadin.data.BufferedValidatable", - "com.vaadin.ui.TabSheet", - "com.vaadin.terminal.gwt.client.ui.VTabsheetBase", "blah", - true, expectedSize, expectedRoots, false); - - // only include .gwt.client classes - container.removeAllContainerFilters(); - container.addContainerFilter(FULLY_QUALIFIED_NAME, ".gwt.client.", - false, false); - - int packages = 3; - int classes = 110; - - expectedSize = packages + classes; - expectedRoots = 35 + 1; // com.vaadin.terminal.gwt.client.ui + - // com.vaadin.terminal.gwt.client.* - - // Sorting is case insensitive - validateHierarchicalContainer(container, - "com.vaadin.terminal.gwt.client.ApplicationConfiguration", - "com.vaadin.terminal.gwt.client.WidgetSet", - "com.vaadin.terminal.gwt.client.ui.VOptionGroup", "blah", true, - expectedSize, expectedRoots, false); - - // Additionally remove all without 'P' in the simple name. - container.addContainerFilter(SIMPLE_NAME, "P", false, false); - - expectedSize = 13; - expectedRoots = expectedSize; - - validateHierarchicalContainer(container, - "com.vaadin.terminal.gwt.client.Paintable", - "com.vaadin.terminal.gwt.client.ui.VTabsheetPanel", - "com.vaadin.terminal.gwt.client.ui.VPopupCalendar", "blah", - true, expectedSize, expectedRoots, false); - - } -} diff --git a/server/tests/src/com/vaadin/data/util/TestIndexedContainer.java b/server/tests/src/com/vaadin/data/util/TestIndexedContainer.java deleted file mode 100644 index eacee7e301..0000000000 --- a/server/tests/src/com/vaadin/data/util/TestIndexedContainer.java +++ /dev/null @@ -1,395 +0,0 @@ -package com.vaadin.data.util; - -import java.util.List; - -import org.junit.Assert; - -import com.vaadin.data.Item; - -public class TestIndexedContainer extends AbstractInMemoryContainerTest { - - public void testBasicOperations() { - testBasicContainerOperations(new IndexedContainer()); - } - - public void testFiltering() { - testContainerFiltering(new IndexedContainer()); - } - - public void testSorting() { - testContainerSorting(new IndexedContainer()); - } - - public void testSortingAndFiltering() { - testContainerSortingAndFiltering(new IndexedContainer()); - } - - public void testContainerOrdered() { - testContainerOrdered(new IndexedContainer()); - } - - public void testContainerIndexed() { - testContainerIndexed(new IndexedContainer(), sampleData[2], 2, true, - "newItemId", true); - } - - public void testItemSetChangeListeners() { - IndexedContainer container = new IndexedContainer(); - ItemSetChangeCounter counter = new ItemSetChangeCounter(); - container.addListener(counter); - - String id1 = "id1"; - String id2 = "id2"; - String id3 = "id3"; - - initializeContainer(container); - counter.reset(); - container.addItem(); - counter.assertOnce(); - container.addItem(id1); - counter.assertOnce(); - - initializeContainer(container); - counter.reset(); - container.addItemAt(0); - counter.assertOnce(); - container.addItemAt(0, id1); - counter.assertOnce(); - container.addItemAt(0, id2); - counter.assertOnce(); - container.addItemAt(container.size(), id3); - counter.assertOnce(); - // no notification if already in container - container.addItemAt(0, id1); - counter.assertNone(); - - initializeContainer(container); - counter.reset(); - container.addItemAfter(null); - counter.assertOnce(); - container.addItemAfter(null, id1); - counter.assertOnce(); - container.addItemAfter(id1); - counter.assertOnce(); - container.addItemAfter(id1, id2); - counter.assertOnce(); - container.addItemAfter(container.firstItemId()); - counter.assertOnce(); - container.addItemAfter(container.lastItemId()); - counter.assertOnce(); - container.addItemAfter(container.lastItemId(), id3); - counter.assertOnce(); - // no notification if already in container - container.addItemAfter(0, id1); - counter.assertNone(); - - initializeContainer(container); - counter.reset(); - container.removeItem(sampleData[0]); - counter.assertOnce(); - - initializeContainer(container); - counter.reset(); - // no notification for removing a non-existing item - container.removeItem(id1); - counter.assertNone(); - - initializeContainer(container); - counter.reset(); - container.removeAllItems(); - counter.assertOnce(); - // already empty - container.removeAllItems(); - counter.assertNone(); - - } - - public void testAddRemoveContainerFilter() { - IndexedContainer container = new IndexedContainer(); - ItemSetChangeCounter counter = new ItemSetChangeCounter(); - container.addListener(counter); - - // simply adding or removing container filters should cause events - // (content changes) - - initializeContainer(container); - counter.reset(); - container.addContainerFilter(SIMPLE_NAME, "a", true, false); - counter.assertOnce(); - container.removeContainerFilters(SIMPLE_NAME); - counter.assertOnce(); - container.addContainerFilter(SIMPLE_NAME, "a", true, false); - counter.assertOnce(); - container.removeAllContainerFilters(); - counter.assertOnce(); - } - - // TODO other tests should check positions after removing filter etc, - // here concentrating on listeners - public void testItemSetChangeListenersFiltering() { - IndexedContainer container = new IndexedContainer(); - ItemSetChangeCounter counter = new ItemSetChangeCounter(); - container.addListener(counter); - - counter.reset(); - container.addContainerFilter(FULLY_QUALIFIED_NAME, "Test", true, false); - // no real change, so no notification required - counter.assertNone(); - - String id1 = "com.example.Test1"; - String id2 = "com.example.Test2"; - String id3 = "com.example.Other"; - - // perform operations while filtering container - - Item item; - - initializeContainer(container); - counter.reset(); - // passes filter - item = container.addItem(id1); - // no event if filtered out - counter.assertNone(); - item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id1); - counter.assertOnce(); - // passes filter but already in the container - item = container.addItem(id1); - counter.assertNone(); - - initializeContainer(container); - counter.reset(); - // passes filter after change - item = container.addItemAt(0, id1); - counter.assertNone(); - item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id1); - counter.assertOnce(); - item = container.addItemAt(container.size(), id2); - counter.assertNone(); - item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id2); - counter.assertOnce(); - // passes filter but already in the container - item = container.addItemAt(0, id1); - counter.assertNone(); - item = container.addItemAt(container.size(), id2); - counter.assertNone(); - - initializeContainer(container); - counter.reset(); - // passes filter - item = container.addItemAfter(null, id1); - counter.assertNone(); - item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id1); - counter.assertOnce(); - item = container.addItemAfter(container.lastItemId(), id2); - counter.assertNone(); - item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id2); - counter.assertOnce(); - // passes filter but already in the container - item = container.addItemAfter(null, id1); - counter.assertNone(); - item = container.addItemAfter(container.lastItemId(), id2); - counter.assertNone(); - - // does not pass filter - - // TODO implement rest - - initializeContainer(container); - counter.reset(); - item = container.addItemAfter(null, id3); - counter.assertNone(); - item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3); - counter.assertNone(); - - initializeContainer(container); - counter.reset(); - item = container.addItemAfter(container.firstItemId(), id3); - counter.assertNone(); - item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3); - counter.assertNone(); - - initializeContainer(container); - counter.reset(); - item = container.addItemAfter(container.lastItemId(), id3); - counter.assertNone(); - item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3); - counter.assertNone(); - - initializeContainer(container); - counter.reset(); - item = container.addItemAt(0, id3); - counter.assertNone(); - item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3); - counter.assertNone(); - - initializeContainer(container); - counter.reset(); - item = container.addItemAt(1, id3); - counter.assertNone(); - item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3); - counter.assertNone(); - - initializeContainer(container); - counter.reset(); - item = container.addItemAt(container.size(), id3); - counter.assertNone(); - item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3); - counter.assertNone(); - - // passes filter - - initializeContainer(container); - counter.reset(); - item = container.addItem(id1); - counter.assertNone(); - item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id1); - counter.assertOnce(); - container.removeItem(id1); - counter.assertOnce(); - // already removed - container.removeItem(id1); - counter.assertNone(); - - item = container.addItem(id3); - counter.assertNone(); - item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id3); - counter.assertNone(); - // not visible - container.removeItem(id3); - counter.assertNone(); - - // remove all - - initializeContainer(container); - item = container.addItem(id1); - item.getItemProperty(FULLY_QUALIFIED_NAME).setValue(id1); - counter.reset(); - container.removeAllItems(); - counter.assertOnce(); - // no visible items - container.removeAllItems(); - counter.assertNone(); - } - - // Ticket 8028 - public void testGetItemIdsRangeIndexOutOfBounds() { - IndexedContainer ic = new IndexedContainer(); - try { - ic.getItemIds(-1, 10); - fail("Container returned items starting from index -1, something very wrong here!"); - } catch (IndexOutOfBoundsException e) { - // This is expected... - } catch (Exception e) { - // Should not happen! - fail("Container threw unspecified exception when fetching a range of items and the range started from -1"); - } - - } - - // Ticket 8028 - public void testGetItemIdsRangeIndexOutOfBounds2() { - IndexedContainer ic = new IndexedContainer(); - ic.addItem(new Object()); - try { - ic.getItemIds(2, 1); - fail("Container returned items starting from index -1, something very wrong here!"); - } catch (IndexOutOfBoundsException e) { - // This is expected... - } catch (Exception e) { - // Should not happen! - fail("Container threw unspecified exception when fetching a out of bounds range of items"); - } - - } - - // Ticket 8028 - public void testGetItemIdsRangeZeroRange() { - IndexedContainer ic = new IndexedContainer(); - ic.addItem(new Object()); - try { - List itemIds = ic.getItemIds(1, 0); - - assertTrue( - "Container returned actual values when asking for 0 items...", - itemIds.isEmpty()); - } catch (Exception e) { - // Should not happen! - fail("Container threw unspecified exception when fetching 0 items..."); - } - - } - - // Ticket 8028 - public void testGetItemIdsRangeNegativeRange() { - IndexedContainer ic = new IndexedContainer(); - ic.addItem(new Object()); - try { - List itemIds = ic.getItemIds(1, -1); - - assertTrue( - "Container returned actual values when asking for -1 items...", - itemIds.isEmpty()); - } catch (IllegalArgumentException e) { - // this is expected - - } catch (Exception e) { - // Should not happen! - fail("Container threw unspecified exception when fetching -1 items..."); - } - - } - - // Ticket 8028 - public void testGetItemIdsRangeIndexOutOfBoundsDueToSizeChange() { - IndexedContainer ic = new IndexedContainer(); - ic.addItem(new Object()); - Assert.assertEquals( - "Container returned too many items when the range was >> container size", - 1, ic.getItemIds(0, 10).size()); - } - - // Ticket 8028 - public void testGetItemIdsRangeBaseCase() { - IndexedContainer ic = new IndexedContainer(); - String object1 = new String("Obj1"); - String object2 = new String("Obj2"); - String object3 = new String("Obj3"); - String object4 = new String("Obj4"); - String object5 = new String("Obj5"); - - ic.addItem(object1); - ic.addItem(object2); - ic.addItem(object3); - ic.addItem(object4); - ic.addItem(object5); - - try { - List itemIds = ic.getItemIds(1, 2); - - assertTrue(itemIds.contains(object2)); - assertTrue(itemIds.contains(object3)); - assertEquals(2, itemIds.size()); - - } catch (Exception e) { - // Should not happen! - fail("Container threw exception when fetching a range of items "); - } - } - - // test getting non-existing property (#10445) - public void testNonExistingProperty() { - IndexedContainer ic = new IndexedContainer(); - String object1 = new String("Obj1"); - ic.addItem(object1); - assertNull(ic.getContainerProperty(object1, "xyz")); - } - - // test getting null property id (#10445) - public void testNullPropertyId() { - IndexedContainer ic = new IndexedContainer(); - String object1 = new String("Obj1"); - ic.addItem(object1); - assertNull(ic.getContainerProperty(object1, null)); - } - -} diff --git a/server/tests/src/com/vaadin/data/util/filter/AbstractFilterTest.java b/server/tests/src/com/vaadin/data/util/filter/AbstractFilterTest.java deleted file mode 100644 index 96673ff608..0000000000 --- a/server/tests/src/com/vaadin/data/util/filter/AbstractFilterTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.vaadin.data.util.filter; - -import junit.framework.TestCase; - -import com.vaadin.data.Container.Filter; -import com.vaadin.data.Item; -import com.vaadin.data.Property; -import com.vaadin.data.util.ObjectProperty; -import com.vaadin.data.util.PropertysetItem; - -public abstract class AbstractFilterTest extends - TestCase { - - protected static final String PROPERTY1 = "property1"; - protected static final String PROPERTY2 = "property2"; - - protected static class TestItem extends PropertysetItem { - - public TestItem(T1 value1, T2 value2) { - addItemProperty(PROPERTY1, new ObjectProperty(value1)); - addItemProperty(PROPERTY2, new ObjectProperty(value2)); - } - } - - protected static class NullProperty implements Property { - - @Override - public String getValue() { - return null; - } - - @Override - public void setValue(String newValue) throws ReadOnlyException { - throw new ReadOnlyException(); - } - - @Override - public Class getType() { - return String.class; - } - - @Override - public boolean isReadOnly() { - return true; - } - - @Override - public void setReadOnly(boolean newStatus) { - // do nothing - } - - } - - public static class SameItemFilter implements Filter { - - private final Item item; - private final Object propertyId; - - public SameItemFilter(Item item) { - this(item, ""); - } - - public SameItemFilter(Item item, Object propertyId) { - this.item = item; - this.propertyId = propertyId; - } - - @Override - public boolean passesFilter(Object itemId, Item item) - throws UnsupportedOperationException { - return this.item == item; - } - - @Override - public boolean appliesToProperty(Object propertyId) { - return this.propertyId != null ? this.propertyId.equals(propertyId) - : true; - } - - @Override - public boolean equals(Object obj) { - if (obj == null || !getClass().equals(obj.getClass())) { - return false; - } - SameItemFilter other = (SameItemFilter) obj; - return item == other.item - && (propertyId == null ? other.propertyId == null - : propertyId.equals(other.propertyId)); - } - - @Override - public int hashCode() { - return item.hashCode(); - } - } - -} diff --git a/server/tests/src/com/vaadin/data/util/filter/AbstractFilterTestBase.java b/server/tests/src/com/vaadin/data/util/filter/AbstractFilterTestBase.java new file mode 100644 index 0000000000..ebd843fb53 --- /dev/null +++ b/server/tests/src/com/vaadin/data/util/filter/AbstractFilterTestBase.java @@ -0,0 +1,97 @@ +package com.vaadin.data.util.filter; + +import junit.framework.TestCase; + +import com.vaadin.data.Container.Filter; +import com.vaadin.data.Item; +import com.vaadin.data.Property; +import com.vaadin.data.util.ObjectProperty; +import com.vaadin.data.util.PropertysetItem; + +public abstract class AbstractFilterTestBase extends + TestCase { + + protected static final String PROPERTY1 = "property1"; + protected static final String PROPERTY2 = "property2"; + + protected static class TestItem extends PropertysetItem { + + public TestItem(T1 value1, T2 value2) { + addItemProperty(PROPERTY1, new ObjectProperty(value1)); + addItemProperty(PROPERTY2, new ObjectProperty(value2)); + } + } + + protected static class NullProperty implements Property { + + @Override + public String getValue() { + return null; + } + + @Override + public void setValue(String newValue) throws ReadOnlyException { + throw new ReadOnlyException(); + } + + @Override + public Class getType() { + return String.class; + } + + @Override + public boolean isReadOnly() { + return true; + } + + @Override + public void setReadOnly(boolean newStatus) { + // do nothing + } + + } + + public static class SameItemFilter implements Filter { + + private final Item item; + private final Object propertyId; + + public SameItemFilter(Item item) { + this(item, ""); + } + + public SameItemFilter(Item item, Object propertyId) { + this.item = item; + this.propertyId = propertyId; + } + + @Override + public boolean passesFilter(Object itemId, Item item) + throws UnsupportedOperationException { + return this.item == item; + } + + @Override + public boolean appliesToProperty(Object propertyId) { + return this.propertyId != null ? this.propertyId.equals(propertyId) + : true; + } + + @Override + public boolean equals(Object obj) { + if (obj == null || !getClass().equals(obj.getClass())) { + return false; + } + SameItemFilter other = (SameItemFilter) obj; + return item == other.item + && (propertyId == null ? other.propertyId == null + : propertyId.equals(other.propertyId)); + } + + @Override + public int hashCode() { + return item.hashCode(); + } + } + +} diff --git a/server/tests/src/com/vaadin/data/util/filter/AndOrFilterTest.java b/server/tests/src/com/vaadin/data/util/filter/AndOrFilterTest.java index e5bc622e39..012d0ef0bc 100644 --- a/server/tests/src/com/vaadin/data/util/filter/AndOrFilterTest.java +++ b/server/tests/src/com/vaadin/data/util/filter/AndOrFilterTest.java @@ -6,7 +6,7 @@ import com.vaadin.data.Container.Filter; import com.vaadin.data.Item; import com.vaadin.data.util.BeanItem; -public class AndOrFilterTest extends AbstractFilterTest { +public class AndOrFilterTest extends AbstractFilterTestBase { protected Item item1 = new BeanItem(1); protected Item item2 = new BeanItem(2); diff --git a/server/tests/src/com/vaadin/data/util/filter/CompareFilterTest.java b/server/tests/src/com/vaadin/data/util/filter/CompareFilterTest.java index 732a541c89..fc5ffb9b56 100644 --- a/server/tests/src/com/vaadin/data/util/filter/CompareFilterTest.java +++ b/server/tests/src/com/vaadin/data/util/filter/CompareFilterTest.java @@ -15,7 +15,7 @@ import com.vaadin.data.util.filter.Compare.GreaterOrEqual; import com.vaadin.data.util.filter.Compare.Less; import com.vaadin.data.util.filter.Compare.LessOrEqual; -public class CompareFilterTest extends AbstractFilterTest { +public class CompareFilterTest extends AbstractFilterTestBase { protected Item itemNull; protected Item itemEmpty; diff --git a/server/tests/src/com/vaadin/data/util/filter/IsNullFilterTest.java b/server/tests/src/com/vaadin/data/util/filter/IsNullFilterTest.java index d3e959e069..953bf3cd65 100644 --- a/server/tests/src/com/vaadin/data/util/filter/IsNullFilterTest.java +++ b/server/tests/src/com/vaadin/data/util/filter/IsNullFilterTest.java @@ -7,7 +7,7 @@ import com.vaadin.data.Item; import com.vaadin.data.util.ObjectProperty; import com.vaadin.data.util.PropertysetItem; -public class IsNullFilterTest extends AbstractFilterTest { +public class IsNullFilterTest extends AbstractFilterTestBase { public void testIsNull() { Item item1 = new PropertysetItem(); diff --git a/server/tests/src/com/vaadin/data/util/filter/LikeFilterTest.java b/server/tests/src/com/vaadin/data/util/filter/LikeFilterTest.java index 0fcbd26b8e..9ba5168ac9 100644 --- a/server/tests/src/com/vaadin/data/util/filter/LikeFilterTest.java +++ b/server/tests/src/com/vaadin/data/util/filter/LikeFilterTest.java @@ -22,7 +22,7 @@ import com.vaadin.data.Item; import com.vaadin.data.util.ObjectProperty; import com.vaadin.data.util.PropertysetItem; -public class LikeFilterTest extends AbstractFilterTest { +public class LikeFilterTest extends AbstractFilterTestBase { protected Item item1 = new PropertysetItem(); protected Item item2 = new PropertysetItem(); diff --git a/server/tests/src/com/vaadin/data/util/filter/NotFilterTest.java b/server/tests/src/com/vaadin/data/util/filter/NotFilterTest.java index 966ffd3a6e..310b749ce2 100644 --- a/server/tests/src/com/vaadin/data/util/filter/NotFilterTest.java +++ b/server/tests/src/com/vaadin/data/util/filter/NotFilterTest.java @@ -6,7 +6,7 @@ import com.vaadin.data.Container.Filter; import com.vaadin.data.Item; import com.vaadin.data.util.BeanItem; -public class NotFilterTest extends AbstractFilterTest { +public class NotFilterTest extends AbstractFilterTestBase { protected Item item1 = new BeanItem(1); protected Item item2 = new BeanItem(2); diff --git a/server/tests/src/com/vaadin/data/util/filter/SimpleStringFilterTest.java b/server/tests/src/com/vaadin/data/util/filter/SimpleStringFilterTest.java index eb7dff6015..fcaff6f2c3 100644 --- a/server/tests/src/com/vaadin/data/util/filter/SimpleStringFilterTest.java +++ b/server/tests/src/com/vaadin/data/util/filter/SimpleStringFilterTest.java @@ -3,7 +3,7 @@ package com.vaadin.data.util.filter; import org.junit.Assert; public class SimpleStringFilterTest extends - AbstractFilterTest { + AbstractFilterTestBase { protected static TestItem createTestItem() { return new TestItem("abcde", "TeSt"); diff --git a/server/tests/src/com/vaadin/data/util/sqlcontainer/DataGenerator.java b/server/tests/src/com/vaadin/data/util/sqlcontainer/DataGenerator.java index b76e3df10e..f6619a33b6 100644 --- a/server/tests/src/com/vaadin/data/util/sqlcontainer/DataGenerator.java +++ b/server/tests/src/com/vaadin/data/util/sqlcontainer/DataGenerator.java @@ -13,12 +13,6 @@ import com.vaadin.data.util.sqlcontainer.connection.JDBCConnectionPool; public class DataGenerator { - @Test - public void testDummy() { - // Added dummy test so JUnit will not complain about - // "No runnable methods". - } - public static void addPeopleToDatabase(JDBCConnectionPool connectionPool) throws SQLException { Connection conn = connectionPool.reserveConnection(); diff --git a/server/tests/src/com/vaadin/data/util/sqlcontainer/FreeformQueryUtil.java b/server/tests/src/com/vaadin/data/util/sqlcontainer/FreeformQueryUtil.java index e30ff8f5da..288cb65fae 100644 --- a/server/tests/src/com/vaadin/data/util/sqlcontainer/FreeformQueryUtil.java +++ b/server/tests/src/com/vaadin/data/util/sqlcontainer/FreeformQueryUtil.java @@ -11,12 +11,6 @@ import com.vaadin.data.util.sqlcontainer.query.generator.filter.QueryBuilder; public class FreeformQueryUtil { - @Test - public void testDummy() { - // Added dummy test so JUnit will not complain about - // "No runnable methods". - } - public static StatementHelper getQueryWithFilters(List filters, int offset, int limit) { StatementHelper sh = new StatementHelper(); diff --git a/server/tests/src/com/vaadin/data/util/sqlcontainer/connection/MockInitialContextFactory.java b/server/tests/src/com/vaadin/data/util/sqlcontainer/connection/MockInitialContextFactory.java index 324899e373..1c70c8dad7 100644 --- a/server/tests/src/com/vaadin/data/util/sqlcontainer/connection/MockInitialContextFactory.java +++ b/server/tests/src/com/vaadin/data/util/sqlcontainer/connection/MockInitialContextFactory.java @@ -12,12 +12,6 @@ import org.junit.Test; public class MockInitialContextFactory implements InitialContextFactory { private static Context mockCtx = null; - @Test - public void testDummy() { - // Added dummy test so JUnit will not complain about - // "No runnable methods". - } - public static void setMockContext(Context ctx) { mockCtx = ctx; } diff --git a/server/tests/src/com/vaadin/tests/data/converter/AnyEnumToStringConverterTest.java b/server/tests/src/com/vaadin/tests/data/converter/AnyEnumToStringConverterTest.java new file mode 100644 index 0000000000..83b4abad3f --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/converter/AnyEnumToStringConverterTest.java @@ -0,0 +1,127 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.data.converter; + +import java.util.Locale; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.vaadin.data.util.ObjectProperty; +import com.vaadin.data.util.converter.Converter; +import com.vaadin.data.util.converter.ReverseConverter; +import com.vaadin.tests.data.bean.AnotherTestEnum; +import com.vaadin.tests.data.bean.TestEnum; +import com.vaadin.ui.TextField; + +public class AnyEnumToStringConverterTest { + + public class AnyEnumToStringConverter implements Converter { + + public AnyEnumToStringConverter() { + } + + @Override + public String convertToModel(Enum value, + Class targetType, Locale locale) + throws com.vaadin.data.util.converter.Converter.ConversionException { + if (value == null) { + return null; + } + + return value.toString(); + } + + @Override + public Enum convertToPresentation(String value, + Class targetType, Locale locale) + throws com.vaadin.data.util.converter.Converter.ConversionException { + if (value == null) { + return null; + } + for (Enum e : targetType.getEnumConstants()) { + if (e.toString().equals(value)) { + return e; + } + } + + return null; + } + + @Override + public Class getModelType() { + return String.class; + } + + @Override + public Class getPresentationType() { + return Enum.class; + } + + } + + private AnyEnumToStringConverter converter; + + @Before + public void setup() { + converter = new AnyEnumToStringConverter(); + } + + @Test + public void nullConversion() { + Assert.assertEquals(null, converter.convertToModel(null, null, null)); + } + + @Test + public void enumToStringConversion() { + Assert.assertEquals(TestEnum.TWO.toString(), + converter.convertToModel(TestEnum.TWO, String.class, null)); + Assert.assertEquals(AnotherTestEnum.TWO.toString(), converter + .convertToModel(AnotherTestEnum.TWO, String.class, null)); + } + + @Test + public void stringToEnumConversion() { + Assert.assertEquals(TestEnum.TWO, converter.convertToPresentation( + TestEnum.TWO.toString(), TestEnum.class, null)); + Assert.assertEquals(AnotherTestEnum.TWO, converter + .convertToPresentation(AnotherTestEnum.TWO.toString(), + AnotherTestEnum.class, null)); + } + + @Test + public void stringToEnumWithField() { + TextField tf = new TextField(); + tf.setConverter(new ReverseConverter(converter)); + tf.setPropertyDataSource(new ObjectProperty(AnotherTestEnum.TWO)); + Assert.assertEquals(AnotherTestEnum.TWO.toString(), tf.getValue()); + tf.setValue(AnotherTestEnum.ONE.toString()); + Assert.assertEquals(AnotherTestEnum.ONE.toString(), tf.getValue()); + Assert.assertEquals(AnotherTestEnum.ONE, tf.getConvertedValue()); + Assert.assertEquals(AnotherTestEnum.ONE, tf.getPropertyDataSource() + .getValue()); + + tf.setPropertyDataSource(new ObjectProperty(TestEnum.TWO)); + Assert.assertEquals(TestEnum.TWO.toString(), tf.getValue()); + tf.setValue(TestEnum.ONE.toString()); + Assert.assertEquals(TestEnum.ONE.toString(), tf.getValue()); + Assert.assertEquals(TestEnum.ONE, tf.getConvertedValue()); + Assert.assertEquals(TestEnum.ONE, tf.getPropertyDataSource().getValue()); + + } +} diff --git a/server/tests/src/com/vaadin/tests/data/converter/ConverterFactory.java b/server/tests/src/com/vaadin/tests/data/converter/ConverterFactory.java deleted file mode 100644 index 32c9dc6604..0000000000 --- a/server/tests/src/com/vaadin/tests/data/converter/ConverterFactory.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.data.converter; - -import java.util.Locale; - -import junit.framework.TestCase; - -import com.vaadin.data.util.converter.Converter; -import com.vaadin.data.util.converter.DefaultConverterFactory; -import com.vaadin.server.VaadinSession; -import com.vaadin.tests.util.AlwaysLockedVaadinSession; -import com.vaadin.ui.TextField; - -public class ConverterFactory extends TestCase { - - public static class ConvertTo42 implements Converter { - - @Override - public Integer convertToModel(String value, - Class targetType, Locale locale) - throws com.vaadin.data.util.converter.Converter.ConversionException { - return 42; - } - - @Override - public String convertToPresentation(Integer value, - Class targetType, Locale locale) - throws com.vaadin.data.util.converter.Converter.ConversionException { - return "42"; - } - - @Override - public Class getModelType() { - return Integer.class; - } - - @Override - public Class getPresentationType() { - return String.class; - } - - } - - public static class ConverterFactory42 extends DefaultConverterFactory { - @Override - public Converter createConverter( - Class presentationType, Class modelType) { - if (modelType == Integer.class) { - return (Converter) new ConvertTo42(); - } - - return super.createConverter(presentationType, modelType); - } - } - - public void testApplicationConverterFactoryInBackgroundThread() { - VaadinSession.setCurrent(null); - final VaadinSession appWithCustomIntegerConverter = new AlwaysLockedVaadinSession( - null); - appWithCustomIntegerConverter - .setConverterFactory(new ConverterFactory42()); - - TextField tf = new TextField("", "123") { - @Override - public VaadinSession getSession() { - return appWithCustomIntegerConverter; - } - }; - tf.setConverter(Integer.class); - // The application converter always returns 42. Current application is - // null - assertEquals(42, tf.getConvertedValue()); - } - - public void testApplicationConverterFactoryForDetachedComponent() { - final VaadinSession appWithCustomIntegerConverter = new AlwaysLockedVaadinSession( - null); - appWithCustomIntegerConverter - .setConverterFactory(new ConverterFactory42()); - VaadinSession.setCurrent(appWithCustomIntegerConverter); - - TextField tf = new TextField("", "123"); - tf.setConverter(Integer.class); - // The application converter always returns 42. Current application is - // null - assertEquals(42, tf.getConvertedValue()); - } - - public void testApplicationConverterFactoryForDifferentThanCurrentApplication() { - final VaadinSession fieldAppWithCustomIntegerConverter = new AlwaysLockedVaadinSession( - null); - fieldAppWithCustomIntegerConverter - .setConverterFactory(new ConverterFactory42()); - VaadinSession.setCurrent(new AlwaysLockedVaadinSession(null)); - - TextField tf = new TextField("", "123") { - @Override - public VaadinSession getSession() { - return fieldAppWithCustomIntegerConverter; - } - }; - tf.setConverter(Integer.class); - - // The application converter always returns 42. Application.getCurrent() - // should not be used - assertEquals(42, tf.getConvertedValue()); - } -} diff --git a/server/tests/src/com/vaadin/tests/data/converter/ConverterFactoryTest.java b/server/tests/src/com/vaadin/tests/data/converter/ConverterFactoryTest.java new file mode 100644 index 0000000000..a61c0c9986 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/converter/ConverterFactoryTest.java @@ -0,0 +1,122 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.data.converter; + +import java.util.Locale; + +import junit.framework.TestCase; + +import com.vaadin.data.util.converter.Converter; +import com.vaadin.data.util.converter.DefaultConverterFactory; +import com.vaadin.server.VaadinSession; +import com.vaadin.tests.util.AlwaysLockedVaadinSession; +import com.vaadin.ui.TextField; + +public class ConverterFactoryTest extends TestCase { + + public static class ConvertTo42 implements Converter { + + @Override + public Integer convertToModel(String value, + Class targetType, Locale locale) + throws com.vaadin.data.util.converter.Converter.ConversionException { + return 42; + } + + @Override + public String convertToPresentation(Integer value, + Class targetType, Locale locale) + throws com.vaadin.data.util.converter.Converter.ConversionException { + return "42"; + } + + @Override + public Class getModelType() { + return Integer.class; + } + + @Override + public Class getPresentationType() { + return String.class; + } + + } + + public static class ConverterFactory42 extends DefaultConverterFactory { + @Override + public Converter createConverter( + Class presentationType, Class modelType) { + if (modelType == Integer.class) { + return (Converter) new ConvertTo42(); + } + + return super.createConverter(presentationType, modelType); + } + } + + public void testApplicationConverterFactoryInBackgroundThread() { + VaadinSession.setCurrent(null); + final VaadinSession appWithCustomIntegerConverter = new AlwaysLockedVaadinSession( + null); + appWithCustomIntegerConverter + .setConverterFactory(new ConverterFactory42()); + + TextField tf = new TextField("", "123") { + @Override + public VaadinSession getSession() { + return appWithCustomIntegerConverter; + } + }; + tf.setConverter(Integer.class); + // The application converter always returns 42. Current application is + // null + assertEquals(42, tf.getConvertedValue()); + } + + public void testApplicationConverterFactoryForDetachedComponent() { + final VaadinSession appWithCustomIntegerConverter = new AlwaysLockedVaadinSession( + null); + appWithCustomIntegerConverter + .setConverterFactory(new ConverterFactory42()); + VaadinSession.setCurrent(appWithCustomIntegerConverter); + + TextField tf = new TextField("", "123"); + tf.setConverter(Integer.class); + // The application converter always returns 42. Current application is + // null + assertEquals(42, tf.getConvertedValue()); + } + + public void testApplicationConverterFactoryForDifferentThanCurrentApplication() { + final VaadinSession fieldAppWithCustomIntegerConverter = new AlwaysLockedVaadinSession( + null); + fieldAppWithCustomIntegerConverter + .setConverterFactory(new ConverterFactory42()); + VaadinSession.setCurrent(new AlwaysLockedVaadinSession(null)); + + TextField tf = new TextField("", "123") { + @Override + public VaadinSession getSession() { + return fieldAppWithCustomIntegerConverter; + } + }; + tf.setConverter(Integer.class); + + // The application converter always returns 42. Application.getCurrent() + // should not be used + assertEquals(42, tf.getConvertedValue()); + } +} diff --git a/server/tests/src/com/vaadin/tests/data/converter/DateToLongConverterTest.java b/server/tests/src/com/vaadin/tests/data/converter/DateToLongConverterTest.java new file mode 100644 index 0000000000..d767430cc1 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/converter/DateToLongConverterTest.java @@ -0,0 +1,21 @@ +package com.vaadin.tests.data.converter; + +import java.util.Date; + +import junit.framework.TestCase; + +import com.vaadin.data.util.converter.DateToLongConverter; + +public class DateToLongConverterTest extends TestCase { + + DateToLongConverter converter = new DateToLongConverter(); + + public void testNullConversion() { + assertEquals(null, converter.convertToModel(null, Long.class, null)); + } + + public void testValueConversion() { + assertEquals(Long.valueOf(946677600000l), + converter.convertToModel(new Date(100, 0, 1), Long.class, null)); + } +} diff --git a/server/tests/src/com/vaadin/tests/data/converter/DateToSqlDateConverterTest.java b/server/tests/src/com/vaadin/tests/data/converter/DateToSqlDateConverterTest.java new file mode 100644 index 0000000000..46dca6d13e --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/converter/DateToSqlDateConverterTest.java @@ -0,0 +1,25 @@ +package com.vaadin.tests.data.converter; + +import java.util.Date; +import java.util.Locale; + +import junit.framework.TestCase; + +import com.vaadin.data.util.converter.DateToSqlDateConverter; + +public class DateToSqlDateConverterTest extends TestCase { + + DateToSqlDateConverter converter = new DateToSqlDateConverter(); + + public void testNullConversion() { + assertEquals(null, + converter.convertToModel(null, java.sql.Date.class, null)); + } + + public void testValueConversion() { + Date testDate = new Date(100, 0, 1); + long time = testDate.getTime(); + assertEquals(testDate, converter.convertToModel( + new java.sql.Date(time), java.sql.Date.class, Locale.ENGLISH)); + } +} diff --git a/server/tests/src/com/vaadin/tests/data/converter/DefaultConverterFactoryTest.java b/server/tests/src/com/vaadin/tests/data/converter/DefaultConverterFactoryTest.java new file mode 100644 index 0000000000..047ed8a79f --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/converter/DefaultConverterFactoryTest.java @@ -0,0 +1,128 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.data.converter; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Date; +import java.util.Locale; + +import org.junit.Assert; +import org.junit.Test; + +import com.vaadin.data.util.converter.DefaultConverterFactory; + +public class DefaultConverterFactoryTest { + + private DefaultConverterFactory factory = new DefaultConverterFactory(); + + @Test + public void stringToBigDecimal() { + assertConverter("14", new BigDecimal("14")); + } + + @Test + public void stringToBigInteger() { + assertConverter("14", new BigInteger("14")); + } + + @Test + public void stringToDouble() { + assertConverter("14", new Double("14")); + } + + @Test + public void stringToFloat() { + assertConverter("14", new Float("14")); + } + + @Test + public void stringToInteger() { + assertConverter("14", new Integer("14")); + } + + @Test + public void stringToLong() { + assertConverter("14", new Long("14")); + } + + @SuppressWarnings("deprecation") + @Test + public void stringToDate() { + assertConverter("Oct 12, 2014 12:00:00 AM", new Date(2014 - 1900, + 10 - 1, 12)); + } + + @Test + public void sqlDateToDate() { + long l = 1413071210000L; + assertConverter(new java.sql.Date(l), new java.util.Date(l)); + } + + @SuppressWarnings("deprecation") + @Test + public void longToDate() { + assertConverter(1413061200000L, new Date(2014 - 1900, 10 - 1, 12)); + } + + public enum Foo { + BAR, BAZ; + } + + @Test + public void stringToEnum() { + assertConverter("Bar", Foo.BAR); + } + + @Test + public void stringToShort() { + assertConverter("14", new Short("14")); + } + + @Test + public void stringToByte() { + assertConverter("14", new Byte("14")); + } + + private void assertConverter(T t, U u) { + Class tClass = (Class) t.getClass(); + Class uClass = (Class) u.getClass(); + + U tConvertedToU = factory.createConverter(tClass, uClass) + .convertToModel(t, uClass, Locale.ENGLISH); + Assert.assertEquals( + "Incorrect type of value converted from " + + tClass.getSimpleName() + " to " + + uClass.getSimpleName(), uClass, + tConvertedToU.getClass()); + Assert.assertEquals( + "Incorrect conversion of " + t + " to " + + uClass.getSimpleName(), u, tConvertedToU); + + T uConvertedToT = factory.createConverter(uClass, tClass) + .convertToModel(u, tClass, Locale.ENGLISH); + Assert.assertEquals( + "Incorrect type of value converted from " + + uClass.getSimpleName() + " to " + + tClass.getSimpleName(), tClass, + uConvertedToT.getClass()); + Assert.assertEquals( + "Incorrect conversion of " + u + " to " + + tClass.getSimpleName(), t, uConvertedToT); + + } + +} diff --git a/server/tests/src/com/vaadin/tests/data/converter/SpecificEnumToStringConverterTest.java b/server/tests/src/com/vaadin/tests/data/converter/SpecificEnumToStringConverterTest.java new file mode 100644 index 0000000000..377998db1e --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/converter/SpecificEnumToStringConverterTest.java @@ -0,0 +1,125 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.data.converter; + +import java.util.Locale; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.vaadin.data.util.ObjectProperty; +import com.vaadin.data.util.converter.Converter; +import com.vaadin.data.util.converter.ReverseConverter; +import com.vaadin.tests.data.bean.AnotherTestEnum; +import com.vaadin.tests.data.bean.TestEnum; +import com.vaadin.ui.TextField; + +public class SpecificEnumToStringConverterTest { + + public class SpecificEnumToStringConverter implements + Converter { + + private Class enumClass; + + public SpecificEnumToStringConverter(Class enumClass) { + this.enumClass = enumClass; + } + + @Override + public String convertToModel(Enum value, + Class targetType, Locale locale) + throws com.vaadin.data.util.converter.Converter.ConversionException { + if (value == null) { + return null; + } + + return value.toString(); + } + + @Override + public Enum convertToPresentation(String value, + Class targetType, Locale locale) + throws com.vaadin.data.util.converter.Converter.ConversionException { + if (value == null) { + return null; + } + + for (Enum e : enumClass.getEnumConstants()) { + if (e.toString().equals(value)) { + return e; + } + } + + return null; + } + + @Override + public Class getModelType() { + return String.class; + } + + @Override + public Class getPresentationType() { + return (Class) enumClass; + } + + } + + SpecificEnumToStringConverter testEnumConverter; + SpecificEnumToStringConverter anotherTestEnumConverter; + + @Before + public void setup() { + testEnumConverter = new SpecificEnumToStringConverter(TestEnum.class); + anotherTestEnumConverter = new SpecificEnumToStringConverter( + AnotherTestEnum.class); + } + + @Test + public void nullConversion() { + Assert.assertEquals(null, + testEnumConverter.convertToModel(null, null, null)); + } + + @Test + public void enumToStringConversion() { + Assert.assertEquals(TestEnum.TWO.toString(), testEnumConverter + .convertToModel(TestEnum.TWO, String.class, null)); + } + + @Test + public void stringToEnumConversion() { + Assert.assertEquals(TestEnum.TWO, testEnumConverter + .convertToPresentation(TestEnum.TWO.toString(), TestEnum.class, + null)); + } + + @Test + public void stringToEnumWithField() { + TextField tf = new TextField(); + tf.setConverter(new ReverseConverter(anotherTestEnumConverter)); + tf.setPropertyDataSource(new ObjectProperty(AnotherTestEnum.TWO)); + Assert.assertEquals(AnotherTestEnum.TWO.toString(), tf.getValue()); + tf.setValue(AnotherTestEnum.ONE.toString()); + Assert.assertEquals(AnotherTestEnum.ONE.toString(), tf.getValue()); + Assert.assertEquals(AnotherTestEnum.ONE, tf.getConvertedValue()); + Assert.assertEquals(AnotherTestEnum.ONE, tf.getPropertyDataSource() + .getValue()); + + } +} diff --git a/server/tests/src/com/vaadin/tests/data/converter/StringToBigDecimalConverterTest.java b/server/tests/src/com/vaadin/tests/data/converter/StringToBigDecimalConverterTest.java new file mode 100644 index 0000000000..06d407c9f4 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/converter/StringToBigDecimalConverterTest.java @@ -0,0 +1,53 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.data.converter; + +import java.math.BigDecimal; +import java.util.Locale; + +import junit.framework.TestCase; + +import com.vaadin.data.util.converter.StringToBigDecimalConverter; + +public class StringToBigDecimalConverterTest extends TestCase { + + StringToBigDecimalConverter converter = new StringToBigDecimalConverter(); + + public void testNullConversion() { + assertEquals(null, + converter.convertToModel(null, BigDecimal.class, null)); + } + + public void testEmptyStringConversion() { + assertEquals(null, converter.convertToModel("", BigDecimal.class, null)); + } + + public void testValueParsing() { + BigDecimal converted = converter.convertToModel("10", BigDecimal.class, + null); + BigDecimal expected = new BigDecimal(10); + assertEquals(expected, converted); + } + + public void testValueFormatting() { + BigDecimal bd = new BigDecimal(12.5); + String expected = "12,5"; + + String converted = converter.convertToPresentation(bd, String.class, + Locale.GERMAN); + assertEquals(expected, converted); + } +} diff --git a/server/tests/src/com/vaadin/tests/data/converter/StringToBigIntegerConverterTest.java b/server/tests/src/com/vaadin/tests/data/converter/StringToBigIntegerConverterTest.java new file mode 100644 index 0000000000..057017790d --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/converter/StringToBigIntegerConverterTest.java @@ -0,0 +1,57 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.data.converter; + +import java.math.BigInteger; +import java.util.Locale; + +import junit.framework.TestCase; + +import com.vaadin.data.util.converter.StringToBigIntegerConverter; + +public class StringToBigIntegerConverterTest extends TestCase { + + StringToBigIntegerConverter converter = new StringToBigIntegerConverter(); + + public void testNullConversion() { + assertEquals("Null value was converted incorrectly", null, + converter.convertToModel(null, BigInteger.class, null)); + } + + public void testEmptyStringConversion() { + assertEquals("Empty value was converted incorrectly", null, + converter.convertToModel("", BigInteger.class, null)); + } + + public void testValueParsing() { + String bigInt = "1180591620717411303424"; // 2^70 > 2^63 - 1 + BigInteger converted = converter.convertToModel(bigInt, + BigInteger.class, null); + BigInteger expected = new BigInteger(bigInt); + assertEquals("Value bigger than max long was converted incorrectly", + expected, converted); + } + + public void testValueFormatting() { + BigInteger bd = new BigInteger("1000"); + String expected = "1.000"; + + String converted = converter.convertToPresentation(bd, String.class, + Locale.GERMAN); + assertEquals("Value with specific locale was converted incorrectly", + expected, converted); + } +} diff --git a/server/tests/src/com/vaadin/tests/data/converter/StringToBooleanConverterTest.java b/server/tests/src/com/vaadin/tests/data/converter/StringToBooleanConverterTest.java new file mode 100644 index 0000000000..f734d76633 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/converter/StringToBooleanConverterTest.java @@ -0,0 +1,23 @@ +package com.vaadin.tests.data.converter; + +import junit.framework.TestCase; + +import com.vaadin.data.util.converter.StringToBooleanConverter; + +public class StringToBooleanConverterTest extends TestCase { + + StringToBooleanConverter converter = new StringToBooleanConverter(); + + public void testNullConversion() { + assertEquals(null, converter.convertToModel(null, Boolean.class, null)); + } + + public void testEmptyStringConversion() { + assertEquals(null, converter.convertToModel("", Boolean.class, null)); + } + + public void testValueConversion() { + assertTrue(converter.convertToModel("true", Boolean.class, null)); + assertFalse(converter.convertToModel("false", Boolean.class, null)); + } +} diff --git a/server/tests/src/com/vaadin/tests/data/converter/StringToByteConverterTest.java b/server/tests/src/com/vaadin/tests/data/converter/StringToByteConverterTest.java new file mode 100644 index 0000000000..3859d03cc3 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/converter/StringToByteConverterTest.java @@ -0,0 +1,69 @@ +package com.vaadin.tests.data.converter; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.vaadin.data.util.converter.Converter; +import com.vaadin.data.util.converter.Converter.ConversionException; +import com.vaadin.data.util.converter.ReverseConverter; +import com.vaadin.data.util.converter.StringToByteConverter; + +public class StringToByteConverterTest extends TestCase { + + StringToByteConverter converter = new StringToByteConverter(); + Converter reverseConverter = new ReverseConverter( + converter); + + public void testNullConversion() { + assertEquals("Null value was converted incorrectly", null, + converter.convertToModel(null, Byte.class, null)); + } + + public void testReverseNullConversion() { + assertEquals("Null value reversely was converted incorrectly", null, + reverseConverter.convertToModel(null, String.class, null)); + } + + public void testEmptyStringConversion() { + assertEquals("Empty value was converted incorrectly", null, + converter.convertToModel("", Byte.class, null)); + } + + public void testValueConversion() { + assertEquals("Byte value was converted incorrectly", + Byte.valueOf((byte) 10), + converter.convertToModel("10", Byte.class, null)); + } + + public void testReverseValueConversion() { + assertEquals("Byte value reversely was converted incorrectly", + reverseConverter.convertToModel((byte) 10, String.class, null), + "10"); + } + + public void testExtremeByteValueConversion() { + byte b = converter.convertToModel("127", Byte.class, null); + Assert.assertEquals(Byte.MAX_VALUE, b); + b = converter.convertToModel("-128", Byte.class, null); + assertEquals("Min byte value was converted incorrectly", + Byte.MIN_VALUE, b); + } + + public void testValueOutOfRange() { + Double[] values = new Double[] { Byte.MAX_VALUE * 2.0, + Byte.MIN_VALUE * 2.0, Long.MAX_VALUE * 2.0, + Long.MIN_VALUE * 2.0 }; + + boolean accepted = false; + for (Number value : values) { + try { + converter.convertToModel(String.format("%.0f", value), + Byte.class, null); + accepted = true; + } catch (ConversionException expected) { + } + } + assertFalse("Accepted value outside range of int", accepted); + } +} diff --git a/server/tests/src/com/vaadin/tests/data/converter/StringToDateConverterTest.java b/server/tests/src/com/vaadin/tests/data/converter/StringToDateConverterTest.java new file mode 100644 index 0000000000..16008d89c2 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/converter/StringToDateConverterTest.java @@ -0,0 +1,26 @@ +package com.vaadin.tests.data.converter; + +import java.util.Date; +import java.util.Locale; + +import junit.framework.TestCase; + +import com.vaadin.data.util.converter.StringToDateConverter; + +public class StringToDateConverterTest extends TestCase { + + StringToDateConverter converter = new StringToDateConverter(); + + public void testNullConversion() { + assertEquals(null, converter.convertToModel(null, Date.class, null)); + } + + public void testEmptyStringConversion() { + assertEquals(null, converter.convertToModel("", Date.class, null)); + } + + public void testValueConversion() { + assertEquals(new Date(100, 0, 1), converter.convertToModel( + "Jan 1, 2000 12:00:00 AM", Date.class, Locale.ENGLISH)); + } +} diff --git a/server/tests/src/com/vaadin/tests/data/converter/StringToDoubleConverterTest.java b/server/tests/src/com/vaadin/tests/data/converter/StringToDoubleConverterTest.java new file mode 100644 index 0000000000..7054587009 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/converter/StringToDoubleConverterTest.java @@ -0,0 +1,22 @@ +package com.vaadin.tests.data.converter; + +import junit.framework.TestCase; + +import com.vaadin.data.util.converter.StringToDoubleConverter; + +public class StringToDoubleConverterTest extends TestCase { + + StringToDoubleConverter converter = new StringToDoubleConverter(); + + public void testNullConversion() { + assertEquals(null, converter.convertToModel(null, Double.class, null)); + } + + public void testEmptyStringConversion() { + assertEquals(null, converter.convertToModel("", Double.class, null)); + } + + public void testValueConversion() { + assertEquals(10.0, converter.convertToModel("10", Double.class, null)); + } +} diff --git a/server/tests/src/com/vaadin/tests/data/converter/StringToEnumConverterTest.java b/server/tests/src/com/vaadin/tests/data/converter/StringToEnumConverterTest.java new file mode 100644 index 0000000000..a4c3732e1f --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/converter/StringToEnumConverterTest.java @@ -0,0 +1,73 @@ +package com.vaadin.tests.data.converter; + +import junit.framework.TestCase; + +import com.vaadin.data.util.converter.Converter; +import com.vaadin.data.util.converter.Converter.ConversionException; +import com.vaadin.data.util.converter.ReverseConverter; +import com.vaadin.data.util.converter.StringToEnumConverter; + +public class StringToEnumConverterTest extends TestCase { + + public static enum FooEnum { + VALUE1, SOME_VALUE, FOO_BAR_BAZ, Bar, nonStandardCase, _HUGH; + } + + StringToEnumConverter converter = new StringToEnumConverter(); + Converter reverseConverter = new ReverseConverter( + converter); + + public void testEmptyStringConversion() { + assertEquals(null, converter.convertToModel("", Enum.class, null)); + } + + public void testInvalidEnumClassConversion() { + try { + converter.convertToModel("Foo", Enum.class, null); + fail("No exception thrown"); + } catch (ConversionException e) { + // OK + } + } + + public void testNullConversion() { + assertEquals(null, converter.convertToModel(null, Enum.class, null)); + } + + public void testReverseNullConversion() { + assertEquals(null, + reverseConverter.convertToModel(null, String.class, null)); + } + + public void testValueConversion() { + assertEquals(FooEnum.VALUE1, + converter.convertToModel("Value1", FooEnum.class, null)); + assertEquals(FooEnum.SOME_VALUE, + converter.convertToModel("Some value", FooEnum.class, null)); + assertEquals(FooEnum.FOO_BAR_BAZ, + converter.convertToModel("Foo bar baz", FooEnum.class, null)); + assertEquals(FooEnum.Bar, + converter.convertToModel("Bar", FooEnum.class, null)); + assertEquals(FooEnum.nonStandardCase, converter.convertToModel( + "Nonstandardcase", FooEnum.class, null)); + assertEquals(FooEnum._HUGH, + converter.convertToModel("_hugh", FooEnum.class, null)); + } + + public void testReverseValueConversion() { + assertEquals("Value1", reverseConverter.convertToModel(FooEnum.VALUE1, + String.class, null)); + assertEquals("Some value", reverseConverter.convertToModel( + FooEnum.SOME_VALUE, String.class, null)); + assertEquals("Foo bar baz", reverseConverter.convertToModel( + FooEnum.FOO_BAR_BAZ, String.class, null)); + assertEquals("Bar", reverseConverter.convertToModel(FooEnum.Bar, + String.class, null)); + assertEquals("Nonstandardcase", reverseConverter.convertToModel( + FooEnum.nonStandardCase, String.class, null)); + assertEquals("_hugh", reverseConverter.convertToModel(FooEnum._HUGH, + String.class, null)); + + } + +} diff --git a/server/tests/src/com/vaadin/tests/data/converter/StringToFloatConverterTest.java b/server/tests/src/com/vaadin/tests/data/converter/StringToFloatConverterTest.java new file mode 100644 index 0000000000..86319e641c --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/converter/StringToFloatConverterTest.java @@ -0,0 +1,23 @@ +package com.vaadin.tests.data.converter; + +import junit.framework.TestCase; + +import com.vaadin.data.util.converter.StringToFloatConverter; + +public class StringToFloatConverterTest extends TestCase { + + StringToFloatConverter converter = new StringToFloatConverter(); + + public void testNullConversion() { + assertEquals(null, converter.convertToModel(null, Float.class, null)); + } + + public void testEmptyStringConversion() { + assertEquals(null, converter.convertToModel("", Float.class, null)); + } + + public void testValueConversion() { + assertEquals(Float.valueOf(10), + converter.convertToModel("10", Float.class, null)); + } +} diff --git a/server/tests/src/com/vaadin/tests/data/converter/StringToIntegerConverterTest.java b/server/tests/src/com/vaadin/tests/data/converter/StringToIntegerConverterTest.java new file mode 100644 index 0000000000..0076f2c9d1 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/converter/StringToIntegerConverterTest.java @@ -0,0 +1,41 @@ +package com.vaadin.tests.data.converter; + +import junit.framework.TestCase; + +import com.vaadin.data.util.converter.Converter.ConversionException; +import com.vaadin.data.util.converter.StringToIntegerConverter; + +public class StringToIntegerConverterTest extends TestCase { + + StringToIntegerConverter converter = new StringToIntegerConverter(); + + public void testNullConversion() { + assertEquals(null, converter.convertToModel(null, Integer.class, null)); + } + + public void testEmptyStringConversion() { + assertEquals(null, converter.convertToModel("", Integer.class, null)); + } + + public void testValueOutOfRange() { + Double[] values = new Double[] { Integer.MAX_VALUE * 2.0, + Integer.MIN_VALUE * 2.0, Long.MAX_VALUE * 2.0, + Long.MIN_VALUE * 2.0 }; + + boolean accepted = false; + for (Number value : values) { + try { + converter.convertToModel(String.format("%.0f", value), + Integer.class, null); + accepted = true; + } catch (ConversionException expected) { + } + } + assertFalse("Accepted value outside range of int", accepted); + } + + public void testValueConversion() { + assertEquals(Integer.valueOf(10), + converter.convertToModel("10", Integer.class, null)); + } +} diff --git a/server/tests/src/com/vaadin/tests/data/converter/StringToLongConverterTest.java b/server/tests/src/com/vaadin/tests/data/converter/StringToLongConverterTest.java new file mode 100644 index 0000000000..989dbcbbf5 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/converter/StringToLongConverterTest.java @@ -0,0 +1,69 @@ +package com.vaadin.tests.data.converter; + +import java.util.Locale; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.vaadin.data.util.converter.Converter; +import com.vaadin.data.util.converter.ReverseConverter; +import com.vaadin.data.util.converter.StringToLongConverter; + +public class StringToLongConverterTest extends TestCase { + + StringToLongConverter converter = new StringToLongConverter(); + Converter reverseConverter = new ReverseConverter( + converter); + + public void testNullConversion() { + assertEquals(null, converter.convertToModel(null, Long.class, null)); + } + + public void testReverseNullConversion() { + assertEquals(null, + reverseConverter.convertToModel(null, String.class, null)); + } + + public void testEmptyStringConversion() { + assertEquals(null, converter.convertToModel("", Long.class, null)); + } + + public void testValueConversion() { + assertEquals(Long.valueOf(10), + converter.convertToModel("10", Long.class, null)); + } + + public void testReverseValueConversion() { + assertEquals(reverseConverter.convertToModel(10L, String.class, null), + "10"); + } + + public void testExtremeLongValueConversion() { + long l = converter.convertToModel("9223372036854775807", Long.class, + null); + Assert.assertEquals(Long.MAX_VALUE, l); + l = converter.convertToModel("-9223372036854775808", Long.class, null); + assertEquals(Long.MIN_VALUE, l); + } + + public void testExtremeReverseLongValueConversion() { + String str = reverseConverter.convertToModel(Long.MAX_VALUE, + String.class, Locale.ENGLISH); + Assert.assertEquals("9,223,372,036,854,775,807", str); + str = reverseConverter.convertToModel(Long.MIN_VALUE, String.class, + Locale.ENGLISH); + Assert.assertEquals("-9,223,372,036,854,775,808", str); + } + + public void testOutOfBoundsValueConversion() { + // Long.MAX_VALUE+1 is converted to Long.MAX_VALUE + long l = converter.convertToModel("9223372036854775808", Long.class, + null); + Assert.assertEquals(Long.MAX_VALUE, l); + // Long.MIN_VALUE-1 is converted to Long.MIN_VALUE + l = converter.convertToModel("-9223372036854775809", Long.class, null); + assertEquals(Long.MIN_VALUE, l); + + } +} diff --git a/server/tests/src/com/vaadin/tests/data/converter/StringToShortConverterTest.java b/server/tests/src/com/vaadin/tests/data/converter/StringToShortConverterTest.java new file mode 100644 index 0000000000..ab255bce80 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/converter/StringToShortConverterTest.java @@ -0,0 +1,70 @@ +package com.vaadin.tests.data.converter; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.vaadin.data.util.converter.Converter; +import com.vaadin.data.util.converter.Converter.ConversionException; +import com.vaadin.data.util.converter.ReverseConverter; +import com.vaadin.data.util.converter.StringToShortConverter; + +public class StringToShortConverterTest extends TestCase { + + StringToShortConverter converter = new StringToShortConverter(); + Converter reverseConverter = new ReverseConverter( + converter); + + public void testNullConversion() { + assertEquals("Null value was converted incorrectly", null, + converter.convertToModel(null, Short.class, null)); + } + + public void testReverseNullConversion() { + assertEquals("Null value reversely was converted incorrectly", null, + reverseConverter.convertToModel(null, String.class, null)); + } + + public void testEmptyStringConversion() { + assertEquals("Empty value was converted incorrectly", null, + converter.convertToModel("", Short.class, null)); + } + + public void testValueConversion() { + assertEquals("Short value was converted incorrectly", + Short.valueOf((short) 10), + converter.convertToModel("10", Short.class, null)); + } + + public void testReverseValueConversion() { + assertEquals( + "Short value reversely was converted incorrectly", + reverseConverter.convertToModel((short) 10, String.class, null), + "10"); + } + + public void testExtremeShortValueConversion() { + short b = converter.convertToModel("32767", Short.class, null); + Assert.assertEquals(Short.MAX_VALUE, b); + b = converter.convertToModel("-32768", Short.class, null); + assertEquals("Min short value was converted incorrectly", + Short.MIN_VALUE, b); + } + + public void testValueOutOfRange() { + Double[] values = new Double[] { Integer.MAX_VALUE * 2.0, + Integer.MIN_VALUE * 2.0, Long.MAX_VALUE * 2.0, + Long.MIN_VALUE * 2.0 }; + + boolean accepted = false; + for (Number value : values) { + try { + converter.convertToModel(String.format("%.0f", value), + Short.class, null); + accepted = true; + } catch (ConversionException expected) { + } + } + assertFalse("Accepted value outside range of int", accepted); + } +} diff --git a/server/tests/src/com/vaadin/tests/data/converter/TestAnyEnumToStringConverter.java b/server/tests/src/com/vaadin/tests/data/converter/TestAnyEnumToStringConverter.java deleted file mode 100644 index 64b06f651e..0000000000 --- a/server/tests/src/com/vaadin/tests/data/converter/TestAnyEnumToStringConverter.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.data.converter; - -import java.util.Locale; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.vaadin.data.util.ObjectProperty; -import com.vaadin.data.util.converter.Converter; -import com.vaadin.data.util.converter.ReverseConverter; -import com.vaadin.tests.data.bean.AnotherTestEnum; -import com.vaadin.tests.data.bean.TestEnum; -import com.vaadin.ui.TextField; - -public class TestAnyEnumToStringConverter { - - public class AnyEnumToStringConverter implements Converter { - - public AnyEnumToStringConverter() { - } - - @Override - public String convertToModel(Enum value, - Class targetType, Locale locale) - throws com.vaadin.data.util.converter.Converter.ConversionException { - if (value == null) { - return null; - } - - return value.toString(); - } - - @Override - public Enum convertToPresentation(String value, - Class targetType, Locale locale) - throws com.vaadin.data.util.converter.Converter.ConversionException { - if (value == null) { - return null; - } - for (Enum e : targetType.getEnumConstants()) { - if (e.toString().equals(value)) { - return e; - } - } - - return null; - } - - @Override - public Class getModelType() { - return String.class; - } - - @Override - public Class getPresentationType() { - return Enum.class; - } - - } - - private AnyEnumToStringConverter converter; - - @Before - public void setup() { - converter = new AnyEnumToStringConverter(); - } - - @Test - public void nullConversion() { - Assert.assertEquals(null, converter.convertToModel(null, null, null)); - } - - @Test - public void enumToStringConversion() { - Assert.assertEquals(TestEnum.TWO.toString(), - converter.convertToModel(TestEnum.TWO, String.class, null)); - Assert.assertEquals(AnotherTestEnum.TWO.toString(), converter - .convertToModel(AnotherTestEnum.TWO, String.class, null)); - } - - @Test - public void stringToEnumConversion() { - Assert.assertEquals(TestEnum.TWO, converter.convertToPresentation( - TestEnum.TWO.toString(), TestEnum.class, null)); - Assert.assertEquals(AnotherTestEnum.TWO, converter - .convertToPresentation(AnotherTestEnum.TWO.toString(), - AnotherTestEnum.class, null)); - } - - @Test - public void stringToEnumWithField() { - TextField tf = new TextField(); - tf.setConverter(new ReverseConverter(converter)); - tf.setPropertyDataSource(new ObjectProperty(AnotherTestEnum.TWO)); - Assert.assertEquals(AnotherTestEnum.TWO.toString(), tf.getValue()); - tf.setValue(AnotherTestEnum.ONE.toString()); - Assert.assertEquals(AnotherTestEnum.ONE.toString(), tf.getValue()); - Assert.assertEquals(AnotherTestEnum.ONE, tf.getConvertedValue()); - Assert.assertEquals(AnotherTestEnum.ONE, tf.getPropertyDataSource() - .getValue()); - - tf.setPropertyDataSource(new ObjectProperty(TestEnum.TWO)); - Assert.assertEquals(TestEnum.TWO.toString(), tf.getValue()); - tf.setValue(TestEnum.ONE.toString()); - Assert.assertEquals(TestEnum.ONE.toString(), tf.getValue()); - Assert.assertEquals(TestEnum.ONE, tf.getConvertedValue()); - Assert.assertEquals(TestEnum.ONE, tf.getPropertyDataSource().getValue()); - - } -} diff --git a/server/tests/src/com/vaadin/tests/data/converter/TestDateToLongConverter.java b/server/tests/src/com/vaadin/tests/data/converter/TestDateToLongConverter.java deleted file mode 100644 index 6b9fa93e27..0000000000 --- a/server/tests/src/com/vaadin/tests/data/converter/TestDateToLongConverter.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.vaadin.tests.data.converter; - -import java.util.Date; - -import junit.framework.TestCase; - -import com.vaadin.data.util.converter.DateToLongConverter; - -public class TestDateToLongConverter extends TestCase { - - DateToLongConverter converter = new DateToLongConverter(); - - public void testNullConversion() { - assertEquals(null, converter.convertToModel(null, Long.class, null)); - } - - public void testValueConversion() { - assertEquals(Long.valueOf(946677600000l), - converter.convertToModel(new Date(100, 0, 1), Long.class, null)); - } -} diff --git a/server/tests/src/com/vaadin/tests/data/converter/TestDateToSqlDateConverter.java b/server/tests/src/com/vaadin/tests/data/converter/TestDateToSqlDateConverter.java deleted file mode 100644 index d591d10e18..0000000000 --- a/server/tests/src/com/vaadin/tests/data/converter/TestDateToSqlDateConverter.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.vaadin.tests.data.converter; - -import java.util.Date; -import java.util.Locale; - -import junit.framework.TestCase; - -import com.vaadin.data.util.converter.DateToSqlDateConverter; - -public class TestDateToSqlDateConverter extends TestCase { - - DateToSqlDateConverter converter = new DateToSqlDateConverter(); - - public void testNullConversion() { - assertEquals(null, - converter.convertToModel(null, java.sql.Date.class, null)); - } - - public void testValueConversion() { - Date testDate = new Date(100, 0, 1); - long time = testDate.getTime(); - assertEquals(testDate, converter.convertToModel( - new java.sql.Date(time), java.sql.Date.class, Locale.ENGLISH)); - } -} diff --git a/server/tests/src/com/vaadin/tests/data/converter/TestDefaultConverterFactory.java b/server/tests/src/com/vaadin/tests/data/converter/TestDefaultConverterFactory.java deleted file mode 100644 index e1becf43e1..0000000000 --- a/server/tests/src/com/vaadin/tests/data/converter/TestDefaultConverterFactory.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.data.converter; - -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.Date; -import java.util.Locale; - -import org.junit.Assert; -import org.junit.Test; - -import com.vaadin.data.util.converter.DefaultConverterFactory; - -public class TestDefaultConverterFactory { - - private DefaultConverterFactory factory = new DefaultConverterFactory(); - - @Test - public void stringToBigDecimal() { - assertConverter("14", new BigDecimal("14")); - } - - @Test - public void stringToBigInteger() { - assertConverter("14", new BigInteger("14")); - } - - @Test - public void stringToDouble() { - assertConverter("14", new Double("14")); - } - - @Test - public void stringToFloat() { - assertConverter("14", new Float("14")); - } - - @Test - public void stringToInteger() { - assertConverter("14", new Integer("14")); - } - - @Test - public void stringToLong() { - assertConverter("14", new Long("14")); - } - - @SuppressWarnings("deprecation") - @Test - public void stringToDate() { - assertConverter("Oct 12, 2014 12:00:00 AM", new Date(2014 - 1900, - 10 - 1, 12)); - } - - @Test - public void sqlDateToDate() { - long l = 1413071210000L; - assertConverter(new java.sql.Date(l), new java.util.Date(l)); - } - - @SuppressWarnings("deprecation") - @Test - public void longToDate() { - assertConverter(1413061200000L, new Date(2014 - 1900, 10 - 1, 12)); - } - - public enum Foo { - BAR, BAZ; - } - - @Test - public void stringToEnum() { - assertConverter("Bar", Foo.BAR); - } - - @Test - public void stringToShort() { - assertConverter("14", new Short("14")); - } - - @Test - public void stringToByte() { - assertConverter("14", new Byte("14")); - } - - private void assertConverter(T t, U u) { - Class tClass = (Class) t.getClass(); - Class uClass = (Class) u.getClass(); - - U tConvertedToU = factory.createConverter(tClass, uClass) - .convertToModel(t, uClass, Locale.ENGLISH); - Assert.assertEquals( - "Incorrect type of value converted from " - + tClass.getSimpleName() + " to " - + uClass.getSimpleName(), uClass, - tConvertedToU.getClass()); - Assert.assertEquals( - "Incorrect conversion of " + t + " to " - + uClass.getSimpleName(), u, tConvertedToU); - - T uConvertedToT = factory.createConverter(uClass, tClass) - .convertToModel(u, tClass, Locale.ENGLISH); - Assert.assertEquals( - "Incorrect type of value converted from " - + uClass.getSimpleName() + " to " - + tClass.getSimpleName(), tClass, - uConvertedToT.getClass()); - Assert.assertEquals( - "Incorrect conversion of " + u + " to " - + tClass.getSimpleName(), t, uConvertedToT); - - } - -} diff --git a/server/tests/src/com/vaadin/tests/data/converter/TestSpecificEnumToStringConverter.java b/server/tests/src/com/vaadin/tests/data/converter/TestSpecificEnumToStringConverter.java deleted file mode 100644 index 75c742775f..0000000000 --- a/server/tests/src/com/vaadin/tests/data/converter/TestSpecificEnumToStringConverter.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.data.converter; - -import java.util.Locale; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.vaadin.data.util.ObjectProperty; -import com.vaadin.data.util.converter.Converter; -import com.vaadin.data.util.converter.ReverseConverter; -import com.vaadin.tests.data.bean.AnotherTestEnum; -import com.vaadin.tests.data.bean.TestEnum; -import com.vaadin.ui.TextField; - -public class TestSpecificEnumToStringConverter { - - public class SpecificEnumToStringConverter implements - Converter { - - private Class enumClass; - - public SpecificEnumToStringConverter(Class enumClass) { - this.enumClass = enumClass; - } - - @Override - public String convertToModel(Enum value, - Class targetType, Locale locale) - throws com.vaadin.data.util.converter.Converter.ConversionException { - if (value == null) { - return null; - } - - return value.toString(); - } - - @Override - public Enum convertToPresentation(String value, - Class targetType, Locale locale) - throws com.vaadin.data.util.converter.Converter.ConversionException { - if (value == null) { - return null; - } - - for (Enum e : enumClass.getEnumConstants()) { - if (e.toString().equals(value)) { - return e; - } - } - - return null; - } - - @Override - public Class getModelType() { - return String.class; - } - - @Override - public Class getPresentationType() { - return (Class) enumClass; - } - - } - - SpecificEnumToStringConverter testEnumConverter; - SpecificEnumToStringConverter anotherTestEnumConverter; - - @Before - public void setup() { - testEnumConverter = new SpecificEnumToStringConverter(TestEnum.class); - anotherTestEnumConverter = new SpecificEnumToStringConverter( - AnotherTestEnum.class); - } - - @Test - public void nullConversion() { - Assert.assertEquals(null, - testEnumConverter.convertToModel(null, null, null)); - } - - @Test - public void enumToStringConversion() { - Assert.assertEquals(TestEnum.TWO.toString(), testEnumConverter - .convertToModel(TestEnum.TWO, String.class, null)); - } - - @Test - public void stringToEnumConversion() { - Assert.assertEquals(TestEnum.TWO, testEnumConverter - .convertToPresentation(TestEnum.TWO.toString(), TestEnum.class, - null)); - } - - @Test - public void stringToEnumWithField() { - TextField tf = new TextField(); - tf.setConverter(new ReverseConverter(anotherTestEnumConverter)); - tf.setPropertyDataSource(new ObjectProperty(AnotherTestEnum.TWO)); - Assert.assertEquals(AnotherTestEnum.TWO.toString(), tf.getValue()); - tf.setValue(AnotherTestEnum.ONE.toString()); - Assert.assertEquals(AnotherTestEnum.ONE.toString(), tf.getValue()); - Assert.assertEquals(AnotherTestEnum.ONE, tf.getConvertedValue()); - Assert.assertEquals(AnotherTestEnum.ONE, tf.getPropertyDataSource() - .getValue()); - - } -} diff --git a/server/tests/src/com/vaadin/tests/data/converter/TestStringToBigDecimalConverter.java b/server/tests/src/com/vaadin/tests/data/converter/TestStringToBigDecimalConverter.java deleted file mode 100644 index b8e74c7572..0000000000 --- a/server/tests/src/com/vaadin/tests/data/converter/TestStringToBigDecimalConverter.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.data.converter; - -import java.math.BigDecimal; -import java.util.Locale; - -import junit.framework.TestCase; - -import com.vaadin.data.util.converter.StringToBigDecimalConverter; - -public class TestStringToBigDecimalConverter extends TestCase { - - StringToBigDecimalConverter converter = new StringToBigDecimalConverter(); - - public void testNullConversion() { - assertEquals(null, - converter.convertToModel(null, BigDecimal.class, null)); - } - - public void testEmptyStringConversion() { - assertEquals(null, converter.convertToModel("", BigDecimal.class, null)); - } - - public void testValueParsing() { - BigDecimal converted = converter.convertToModel("10", BigDecimal.class, - null); - BigDecimal expected = new BigDecimal(10); - assertEquals(expected, converted); - } - - public void testValueFormatting() { - BigDecimal bd = new BigDecimal(12.5); - String expected = "12,5"; - - String converted = converter.convertToPresentation(bd, String.class, - Locale.GERMAN); - assertEquals(expected, converted); - } -} diff --git a/server/tests/src/com/vaadin/tests/data/converter/TestStringToBigIntegerConverter.java b/server/tests/src/com/vaadin/tests/data/converter/TestStringToBigIntegerConverter.java deleted file mode 100644 index 8d493609fe..0000000000 --- a/server/tests/src/com/vaadin/tests/data/converter/TestStringToBigIntegerConverter.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.data.converter; - -import java.math.BigInteger; -import java.util.Locale; - -import junit.framework.TestCase; - -import com.vaadin.data.util.converter.StringToBigIntegerConverter; - -public class TestStringToBigIntegerConverter extends TestCase { - - StringToBigIntegerConverter converter = new StringToBigIntegerConverter(); - - public void testNullConversion() { - assertEquals("Null value was converted incorrectly", null, - converter.convertToModel(null, BigInteger.class, null)); - } - - public void testEmptyStringConversion() { - assertEquals("Empty value was converted incorrectly", null, - converter.convertToModel("", BigInteger.class, null)); - } - - public void testValueParsing() { - String bigInt = "1180591620717411303424"; // 2^70 > 2^63 - 1 - BigInteger converted = converter.convertToModel(bigInt, - BigInteger.class, null); - BigInteger expected = new BigInteger(bigInt); - assertEquals("Value bigger than max long was converted incorrectly", - expected, converted); - } - - public void testValueFormatting() { - BigInteger bd = new BigInteger("1000"); - String expected = "1.000"; - - String converted = converter.convertToPresentation(bd, String.class, - Locale.GERMAN); - assertEquals("Value with specific locale was converted incorrectly", - expected, converted); - } -} diff --git a/server/tests/src/com/vaadin/tests/data/converter/TestStringToBooleanConverter.java b/server/tests/src/com/vaadin/tests/data/converter/TestStringToBooleanConverter.java deleted file mode 100644 index 7be922a63a..0000000000 --- a/server/tests/src/com/vaadin/tests/data/converter/TestStringToBooleanConverter.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.vaadin.tests.data.converter; - -import junit.framework.TestCase; - -import com.vaadin.data.util.converter.StringToBooleanConverter; - -public class TestStringToBooleanConverter extends TestCase { - - StringToBooleanConverter converter = new StringToBooleanConverter(); - - public void testNullConversion() { - assertEquals(null, converter.convertToModel(null, Boolean.class, null)); - } - - public void testEmptyStringConversion() { - assertEquals(null, converter.convertToModel("", Boolean.class, null)); - } - - public void testValueConversion() { - assertTrue(converter.convertToModel("true", Boolean.class, null)); - assertFalse(converter.convertToModel("false", Boolean.class, null)); - } -} diff --git a/server/tests/src/com/vaadin/tests/data/converter/TestStringToByteConverter.java b/server/tests/src/com/vaadin/tests/data/converter/TestStringToByteConverter.java deleted file mode 100644 index 19a68fbfdb..0000000000 --- a/server/tests/src/com/vaadin/tests/data/converter/TestStringToByteConverter.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.vaadin.tests.data.converter; - -import junit.framework.TestCase; - -import org.junit.Assert; - -import com.vaadin.data.util.converter.Converter; -import com.vaadin.data.util.converter.Converter.ConversionException; -import com.vaadin.data.util.converter.ReverseConverter; -import com.vaadin.data.util.converter.StringToByteConverter; - -public class TestStringToByteConverter extends TestCase { - - StringToByteConverter converter = new StringToByteConverter(); - Converter reverseConverter = new ReverseConverter( - converter); - - public void testNullConversion() { - assertEquals("Null value was converted incorrectly", null, - converter.convertToModel(null, Byte.class, null)); - } - - public void testReverseNullConversion() { - assertEquals("Null value reversely was converted incorrectly", null, - reverseConverter.convertToModel(null, String.class, null)); - } - - public void testEmptyStringConversion() { - assertEquals("Empty value was converted incorrectly", null, - converter.convertToModel("", Byte.class, null)); - } - - public void testValueConversion() { - assertEquals("Byte value was converted incorrectly", - Byte.valueOf((byte) 10), - converter.convertToModel("10", Byte.class, null)); - } - - public void testReverseValueConversion() { - assertEquals("Byte value reversely was converted incorrectly", - reverseConverter.convertToModel((byte) 10, String.class, null), - "10"); - } - - public void testExtremeByteValueConversion() { - byte b = converter.convertToModel("127", Byte.class, null); - Assert.assertEquals(Byte.MAX_VALUE, b); - b = converter.convertToModel("-128", Byte.class, null); - assertEquals("Min byte value was converted incorrectly", - Byte.MIN_VALUE, b); - } - - public void testValueOutOfRange() { - Double[] values = new Double[] { Byte.MAX_VALUE * 2.0, - Byte.MIN_VALUE * 2.0, Long.MAX_VALUE * 2.0, - Long.MIN_VALUE * 2.0 }; - - boolean accepted = false; - for (Number value : values) { - try { - converter.convertToModel(String.format("%.0f", value), - Byte.class, null); - accepted = true; - } catch (ConversionException expected) { - } - } - assertFalse("Accepted value outside range of int", accepted); - } -} diff --git a/server/tests/src/com/vaadin/tests/data/converter/TestStringToDateConverter.java b/server/tests/src/com/vaadin/tests/data/converter/TestStringToDateConverter.java deleted file mode 100644 index eb0e1461b2..0000000000 --- a/server/tests/src/com/vaadin/tests/data/converter/TestStringToDateConverter.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.vaadin.tests.data.converter; - -import java.util.Date; -import java.util.Locale; - -import junit.framework.TestCase; - -import com.vaadin.data.util.converter.StringToDateConverter; - -public class TestStringToDateConverter extends TestCase { - - StringToDateConverter converter = new StringToDateConverter(); - - public void testNullConversion() { - assertEquals(null, converter.convertToModel(null, Date.class, null)); - } - - public void testEmptyStringConversion() { - assertEquals(null, converter.convertToModel("", Date.class, null)); - } - - public void testValueConversion() { - assertEquals(new Date(100, 0, 1), converter.convertToModel( - "Jan 1, 2000 12:00:00 AM", Date.class, Locale.ENGLISH)); - } -} diff --git a/server/tests/src/com/vaadin/tests/data/converter/TestStringToDoubleConverter.java b/server/tests/src/com/vaadin/tests/data/converter/TestStringToDoubleConverter.java deleted file mode 100644 index 14691bd922..0000000000 --- a/server/tests/src/com/vaadin/tests/data/converter/TestStringToDoubleConverter.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.vaadin.tests.data.converter; - -import junit.framework.TestCase; - -import com.vaadin.data.util.converter.StringToDoubleConverter; - -public class TestStringToDoubleConverter extends TestCase { - - StringToDoubleConverter converter = new StringToDoubleConverter(); - - public void testNullConversion() { - assertEquals(null, converter.convertToModel(null, Double.class, null)); - } - - public void testEmptyStringConversion() { - assertEquals(null, converter.convertToModel("", Double.class, null)); - } - - public void testValueConversion() { - assertEquals(10.0, converter.convertToModel("10", Double.class, null)); - } -} diff --git a/server/tests/src/com/vaadin/tests/data/converter/TestStringToEnumConverter.java b/server/tests/src/com/vaadin/tests/data/converter/TestStringToEnumConverter.java deleted file mode 100644 index 5dc24ca43a..0000000000 --- a/server/tests/src/com/vaadin/tests/data/converter/TestStringToEnumConverter.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.vaadin.tests.data.converter; - -import junit.framework.TestCase; - -import com.vaadin.data.util.converter.Converter; -import com.vaadin.data.util.converter.Converter.ConversionException; -import com.vaadin.data.util.converter.ReverseConverter; -import com.vaadin.data.util.converter.StringToEnumConverter; - -public class TestStringToEnumConverter extends TestCase { - - public static enum FooEnum { - VALUE1, SOME_VALUE, FOO_BAR_BAZ, Bar, nonStandardCase, _HUGH; - } - - StringToEnumConverter converter = new StringToEnumConverter(); - Converter reverseConverter = new ReverseConverter( - converter); - - public void testEmptyStringConversion() { - assertEquals(null, converter.convertToModel("", Enum.class, null)); - } - - public void testInvalidEnumClassConversion() { - try { - converter.convertToModel("Foo", Enum.class, null); - fail("No exception thrown"); - } catch (ConversionException e) { - // OK - } - } - - public void testNullConversion() { - assertEquals(null, converter.convertToModel(null, Enum.class, null)); - } - - public void testReverseNullConversion() { - assertEquals(null, - reverseConverter.convertToModel(null, String.class, null)); - } - - public void testValueConversion() { - assertEquals(FooEnum.VALUE1, - converter.convertToModel("Value1", FooEnum.class, null)); - assertEquals(FooEnum.SOME_VALUE, - converter.convertToModel("Some value", FooEnum.class, null)); - assertEquals(FooEnum.FOO_BAR_BAZ, - converter.convertToModel("Foo bar baz", FooEnum.class, null)); - assertEquals(FooEnum.Bar, - converter.convertToModel("Bar", FooEnum.class, null)); - assertEquals(FooEnum.nonStandardCase, converter.convertToModel( - "Nonstandardcase", FooEnum.class, null)); - assertEquals(FooEnum._HUGH, - converter.convertToModel("_hugh", FooEnum.class, null)); - } - - public void testReverseValueConversion() { - assertEquals("Value1", reverseConverter.convertToModel(FooEnum.VALUE1, - String.class, null)); - assertEquals("Some value", reverseConverter.convertToModel( - FooEnum.SOME_VALUE, String.class, null)); - assertEquals("Foo bar baz", reverseConverter.convertToModel( - FooEnum.FOO_BAR_BAZ, String.class, null)); - assertEquals("Bar", reverseConverter.convertToModel(FooEnum.Bar, - String.class, null)); - assertEquals("Nonstandardcase", reverseConverter.convertToModel( - FooEnum.nonStandardCase, String.class, null)); - assertEquals("_hugh", reverseConverter.convertToModel(FooEnum._HUGH, - String.class, null)); - - } - -} diff --git a/server/tests/src/com/vaadin/tests/data/converter/TestStringToFloatConverter.java b/server/tests/src/com/vaadin/tests/data/converter/TestStringToFloatConverter.java deleted file mode 100644 index 6721a92b1a..0000000000 --- a/server/tests/src/com/vaadin/tests/data/converter/TestStringToFloatConverter.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.vaadin.tests.data.converter; - -import junit.framework.TestCase; - -import com.vaadin.data.util.converter.StringToFloatConverter; - -public class TestStringToFloatConverter extends TestCase { - - StringToFloatConverter converter = new StringToFloatConverter(); - - public void testNullConversion() { - assertEquals(null, converter.convertToModel(null, Float.class, null)); - } - - public void testEmptyStringConversion() { - assertEquals(null, converter.convertToModel("", Float.class, null)); - } - - public void testValueConversion() { - assertEquals(Float.valueOf(10), - converter.convertToModel("10", Float.class, null)); - } -} diff --git a/server/tests/src/com/vaadin/tests/data/converter/TestStringToIntegerConverter.java b/server/tests/src/com/vaadin/tests/data/converter/TestStringToIntegerConverter.java deleted file mode 100644 index e810106631..0000000000 --- a/server/tests/src/com/vaadin/tests/data/converter/TestStringToIntegerConverter.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.vaadin.tests.data.converter; - -import junit.framework.TestCase; - -import com.vaadin.data.util.converter.Converter.ConversionException; -import com.vaadin.data.util.converter.StringToIntegerConverter; - -public class TestStringToIntegerConverter extends TestCase { - - StringToIntegerConverter converter = new StringToIntegerConverter(); - - public void testNullConversion() { - assertEquals(null, converter.convertToModel(null, Integer.class, null)); - } - - public void testEmptyStringConversion() { - assertEquals(null, converter.convertToModel("", Integer.class, null)); - } - - public void testValueOutOfRange() { - Double[] values = new Double[] { Integer.MAX_VALUE * 2.0, - Integer.MIN_VALUE * 2.0, Long.MAX_VALUE * 2.0, - Long.MIN_VALUE * 2.0 }; - - boolean accepted = false; - for (Number value : values) { - try { - converter.convertToModel(String.format("%.0f", value), - Integer.class, null); - accepted = true; - } catch (ConversionException expected) { - } - } - assertFalse("Accepted value outside range of int", accepted); - } - - public void testValueConversion() { - assertEquals(Integer.valueOf(10), - converter.convertToModel("10", Integer.class, null)); - } -} diff --git a/server/tests/src/com/vaadin/tests/data/converter/TestStringToLongConverter.java b/server/tests/src/com/vaadin/tests/data/converter/TestStringToLongConverter.java deleted file mode 100644 index 0e95975c17..0000000000 --- a/server/tests/src/com/vaadin/tests/data/converter/TestStringToLongConverter.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.vaadin.tests.data.converter; - -import java.util.Locale; - -import junit.framework.TestCase; - -import org.junit.Assert; - -import com.vaadin.data.util.converter.Converter; -import com.vaadin.data.util.converter.ReverseConverter; -import com.vaadin.data.util.converter.StringToLongConverter; - -public class TestStringToLongConverter extends TestCase { - - StringToLongConverter converter = new StringToLongConverter(); - Converter reverseConverter = new ReverseConverter( - converter); - - public void testNullConversion() { - assertEquals(null, converter.convertToModel(null, Long.class, null)); - } - - public void testReverseNullConversion() { - assertEquals(null, - reverseConverter.convertToModel(null, String.class, null)); - } - - public void testEmptyStringConversion() { - assertEquals(null, converter.convertToModel("", Long.class, null)); - } - - public void testValueConversion() { - assertEquals(Long.valueOf(10), - converter.convertToModel("10", Long.class, null)); - } - - public void testReverseValueConversion() { - assertEquals(reverseConverter.convertToModel(10L, String.class, null), - "10"); - } - - public void testExtremeLongValueConversion() { - long l = converter.convertToModel("9223372036854775807", Long.class, - null); - Assert.assertEquals(Long.MAX_VALUE, l); - l = converter.convertToModel("-9223372036854775808", Long.class, null); - assertEquals(Long.MIN_VALUE, l); - } - - public void testExtremeReverseLongValueConversion() { - String str = reverseConverter.convertToModel(Long.MAX_VALUE, - String.class, Locale.ENGLISH); - Assert.assertEquals("9,223,372,036,854,775,807", str); - str = reverseConverter.convertToModel(Long.MIN_VALUE, String.class, - Locale.ENGLISH); - Assert.assertEquals("-9,223,372,036,854,775,808", str); - } - - public void testOutOfBoundsValueConversion() { - // Long.MAX_VALUE+1 is converted to Long.MAX_VALUE - long l = converter.convertToModel("9223372036854775808", Long.class, - null); - Assert.assertEquals(Long.MAX_VALUE, l); - // Long.MIN_VALUE-1 is converted to Long.MIN_VALUE - l = converter.convertToModel("-9223372036854775809", Long.class, null); - assertEquals(Long.MIN_VALUE, l); - - } -} diff --git a/server/tests/src/com/vaadin/tests/data/converter/TestStringToShortConverter.java b/server/tests/src/com/vaadin/tests/data/converter/TestStringToShortConverter.java deleted file mode 100644 index 542c580025..0000000000 --- a/server/tests/src/com/vaadin/tests/data/converter/TestStringToShortConverter.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.vaadin.tests.data.converter; - -import junit.framework.TestCase; - -import org.junit.Assert; - -import com.vaadin.data.util.converter.Converter; -import com.vaadin.data.util.converter.Converter.ConversionException; -import com.vaadin.data.util.converter.ReverseConverter; -import com.vaadin.data.util.converter.StringToShortConverter; - -public class TestStringToShortConverter extends TestCase { - - StringToShortConverter converter = new StringToShortConverter(); - Converter reverseConverter = new ReverseConverter( - converter); - - public void testNullConversion() { - assertEquals("Null value was converted incorrectly", null, - converter.convertToModel(null, Short.class, null)); - } - - public void testReverseNullConversion() { - assertEquals("Null value reversely was converted incorrectly", null, - reverseConverter.convertToModel(null, String.class, null)); - } - - public void testEmptyStringConversion() { - assertEquals("Empty value was converted incorrectly", null, - converter.convertToModel("", Short.class, null)); - } - - public void testValueConversion() { - assertEquals("Short value was converted incorrectly", - Short.valueOf((short) 10), - converter.convertToModel("10", Short.class, null)); - } - - public void testReverseValueConversion() { - assertEquals( - "Short value reversely was converted incorrectly", - reverseConverter.convertToModel((short) 10, String.class, null), - "10"); - } - - public void testExtremeShortValueConversion() { - short b = converter.convertToModel("32767", Short.class, null); - Assert.assertEquals(Short.MAX_VALUE, b); - b = converter.convertToModel("-32768", Short.class, null); - assertEquals("Min short value was converted incorrectly", - Short.MIN_VALUE, b); - } - - public void testValueOutOfRange() { - Double[] values = new Double[] { Integer.MAX_VALUE * 2.0, - Integer.MIN_VALUE * 2.0, Long.MAX_VALUE * 2.0, - Long.MIN_VALUE * 2.0 }; - - boolean accepted = false; - for (Number value : values) { - try { - converter.convertToModel(String.format("%.0f", value), - Short.class, null); - accepted = true; - } catch (ConversionException expected) { - } - } - assertFalse("Accepted value outside range of int", accepted); - } -} diff --git a/server/tests/src/com/vaadin/tests/data/validator/BigDecimalRangeValidatorTest.java b/server/tests/src/com/vaadin/tests/data/validator/BigDecimalRangeValidatorTest.java new file mode 100644 index 0000000000..36f120151b --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/validator/BigDecimalRangeValidatorTest.java @@ -0,0 +1,55 @@ +package com.vaadin.tests.data.validator; + +import java.math.BigDecimal; + +import junit.framework.TestCase; + +import com.vaadin.data.validator.BigDecimalRangeValidator; + +public class BigDecimalRangeValidatorTest extends TestCase { + + private BigDecimalRangeValidator cleanValidator = new BigDecimalRangeValidator( + "no values", null, null); + private BigDecimalRangeValidator minValidator = new BigDecimalRangeValidator( + "no values", new BigDecimal(10.1), null); + private BigDecimalRangeValidator maxValidator = new BigDecimalRangeValidator( + "no values", null, new BigDecimal(100.1)); + private BigDecimalRangeValidator minMaxValidator = new BigDecimalRangeValidator( + "no values", new BigDecimal(10.5), new BigDecimal(100.5)); + + public void testNullValue() { + assertTrue("Didn't accept null", cleanValidator.isValid(null)); + assertTrue("Didn't accept null", minValidator.isValid(null)); + assertTrue("Didn't accept null", maxValidator.isValid(null)); + assertTrue("Didn't accept null", minMaxValidator.isValid(null)); + } + + public void testMinValue() { + assertTrue("Validator without ranges didn't accept value", + cleanValidator.isValid(new BigDecimal(-15.0))); + assertTrue("Didn't accept valid value", + minValidator.isValid(new BigDecimal(10.1))); + assertFalse("Accepted too small value", + minValidator.isValid(new BigDecimal(10.0))); + } + + public void testMaxValue() { + assertTrue("Validator without ranges didn't accept value", + cleanValidator.isValid(new BigDecimal(1120.0))); + assertTrue("Didn't accept valid value", + maxValidator.isValid(new BigDecimal(15.0))); + assertFalse("Accepted too large value", + maxValidator.isValid(new BigDecimal(100.6))); + } + + public void testMinMaxValue() { + assertTrue("Didn't accept valid value", + minMaxValidator.isValid(new BigDecimal(10.5))); + assertTrue("Didn't accept valid value", + minMaxValidator.isValid(new BigDecimal(100.5))); + assertFalse("Accepted too small value", + minMaxValidator.isValid(new BigDecimal(10.4))); + assertFalse("Accepted too large value", + minMaxValidator.isValid(new BigDecimal(100.6))); + } +} diff --git a/server/tests/src/com/vaadin/tests/data/validator/BigIntegerRangeValidatorTest.java b/server/tests/src/com/vaadin/tests/data/validator/BigIntegerRangeValidatorTest.java new file mode 100644 index 0000000000..92fabbb02a --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/validator/BigIntegerRangeValidatorTest.java @@ -0,0 +1,55 @@ +package com.vaadin.tests.data.validator; + +import java.math.BigInteger; + +import junit.framework.TestCase; + +import com.vaadin.data.validator.BigIntegerRangeValidator; + +public class BigIntegerRangeValidatorTest extends TestCase { + + private BigIntegerRangeValidator cleanValidator = new BigIntegerRangeValidator( + "no values", null, null); + private BigIntegerRangeValidator minValidator = new BigIntegerRangeValidator( + "no values", BigInteger.valueOf(10), null); + private BigIntegerRangeValidator maxValidator = new BigIntegerRangeValidator( + "no values", null, BigInteger.valueOf(100)); + private BigIntegerRangeValidator minMaxValidator = new BigIntegerRangeValidator( + "no values", BigInteger.valueOf(10), BigInteger.valueOf(100)); + + public void testNullValue() { + assertTrue("Didn't accept null", cleanValidator.isValid(null)); + assertTrue("Didn't accept null", minValidator.isValid(null)); + assertTrue("Didn't accept null", maxValidator.isValid(null)); + assertTrue("Didn't accept null", minMaxValidator.isValid(null)); + } + + public void testMinValue() { + assertTrue("Validator without ranges didn't accept value", + cleanValidator.isValid(BigInteger.valueOf(-15))); + assertTrue("Didn't accept valid value", + minValidator.isValid(BigInteger.valueOf(15))); + assertFalse("Accepted too small value", + minValidator.isValid(BigInteger.valueOf(9))); + } + + public void testMaxValue() { + assertTrue("Validator without ranges didn't accept value", + cleanValidator.isValid(BigInteger.valueOf(1120))); + assertTrue("Didn't accept valid value", + maxValidator.isValid(BigInteger.valueOf(15))); + assertFalse("Accepted too large value", + maxValidator.isValid(BigInteger.valueOf(120))); + } + + public void testMinMaxValue() { + assertTrue("Didn't accept valid value", + minMaxValidator.isValid(BigInteger.valueOf(15))); + assertTrue("Didn't accept valid value", + minMaxValidator.isValid(BigInteger.valueOf(99))); + assertFalse("Accepted too small value", + minMaxValidator.isValid(BigInteger.valueOf(9))); + assertFalse("Accepted too large value", + minMaxValidator.isValid(BigInteger.valueOf(110))); + } +} diff --git a/server/tests/src/com/vaadin/tests/data/validator/ByteRangeValidatorTest.java b/server/tests/src/com/vaadin/tests/data/validator/ByteRangeValidatorTest.java new file mode 100644 index 0000000000..03f35fe1bb --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/validator/ByteRangeValidatorTest.java @@ -0,0 +1,50 @@ +package com.vaadin.tests.data.validator; + +import junit.framework.TestCase; + +import com.vaadin.data.validator.ByteRangeValidator; + +public class ByteRangeValidatorTest extends TestCase { + + private ByteRangeValidator cleanValidator = new ByteRangeValidator( + "no values", null, null); + private ByteRangeValidator minValidator = new ByteRangeValidator( + "no values", (byte) 10, null); + private ByteRangeValidator maxValidator = new ByteRangeValidator( + "no values", null, (byte) 100); + private ByteRangeValidator minMaxValidator = new ByteRangeValidator( + "no values", (byte) 10, (byte) 100); + + public void testNullValue() { + assertTrue("Didn't accept null", cleanValidator.isValid(null)); + assertTrue("Didn't accept null", minValidator.isValid(null)); + assertTrue("Didn't accept null", maxValidator.isValid(null)); + assertTrue("Didn't accept null", minMaxValidator.isValid(null)); + } + + public void testMinValue() { + assertTrue("Validator without ranges didn't accept value", + cleanValidator.isValid((byte) -15)); + assertTrue("Didn't accept valid value", minValidator.isValid((byte) 15)); + assertFalse("Accepted too small value", minValidator.isValid((byte) 9)); + } + + public void testMaxValue() { + assertTrue("Validator without ranges didn't accept value", + cleanValidator.isValid((byte) 112)); + assertTrue("Didn't accept valid value", maxValidator.isValid((byte) 15)); + assertFalse("Accepted too large value", + maxValidator.isValid((byte) 120)); + } + + public void testMinMaxValue() { + assertTrue("Didn't accept valid value", + minMaxValidator.isValid((byte) 15)); + assertTrue("Didn't accept valid value", + minMaxValidator.isValid((byte) 99)); + assertFalse("Accepted too small value", + minMaxValidator.isValid((byte) 9)); + assertFalse("Accepted too large value", + minMaxValidator.isValid((byte) 110)); + } +} diff --git a/server/tests/src/com/vaadin/tests/data/validator/CompositeValidatorTest.java b/server/tests/src/com/vaadin/tests/data/validator/CompositeValidatorTest.java new file mode 100644 index 0000000000..8199419b67 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/validator/CompositeValidatorTest.java @@ -0,0 +1,116 @@ +package com.vaadin.tests.data.validator; + +import junit.framework.TestCase; + +import com.vaadin.data.Validator; +import com.vaadin.data.validator.CompositeValidator; +import com.vaadin.data.validator.CompositeValidator.CombinationMode; +import com.vaadin.data.validator.EmailValidator; +import com.vaadin.data.validator.RegexpValidator; + +public class CompositeValidatorTest extends TestCase { + + CompositeValidator and = new CompositeValidator(CombinationMode.AND, + "One validator not valid"); + CompositeValidator or = new CompositeValidator(CombinationMode.OR, + "No validators are valid"); + EmailValidator email = new EmailValidator("Faulty email"); + RegexpValidator regex = new RegexpValidator("@mail.com", false, + "Partial match validator error"); + + @Override + protected void setUp() throws Exception { + super.setUp(); + + and.addValidator(email); + and.addValidator(regex); + + or.addValidator(email); + or.addValidator(regex); + } + + public void testCorrectValue() { + String testString = "user@mail.com"; + assertTrue(email.isValid(testString)); + assertTrue(regex.isValid(testString)); + try { + // notNull.validate(null); + // fail("expected null to fail with an exception"); + and.validate(testString); + } catch (Validator.InvalidValueException ex) { + // assertEquals("Null not accepted", ex.getMessage()); + fail("And validator should be valid"); + } + try { + or.validate(testString); + } catch (Validator.InvalidValueException ex) { + // assertEquals("Null not accepted", ex.getMessage()); + fail("And validator should be valid"); + } + } + + public void testCorrectRegex() { + + String testString = "@mail.com"; + assertFalse(testString + " should not validate", + email.isValid(testString)); + assertTrue(testString + "should validate", regex.isValid(testString)); + try { + // notNull.validate(null); + and.validate(testString); + fail("expected and to fail with an exception"); + } catch (Validator.InvalidValueException ex) { + assertEquals("Faulty email", ex.getMessage()); + // fail("And validator should be valid"); + } + try { + or.validate(testString); + } catch (Validator.InvalidValueException ex) { + // assertEquals("Null not accepted", ex.getMessage()); + fail("Or validator should be valid"); + } + } + + public void testCorrectEmail() { + + String testString = "user@gmail.com"; + + assertTrue(testString + " should validate", email.isValid(testString)); + assertFalse(testString + " should not validate", + regex.isValid(testString)); + try { + and.validate(testString); + fail("expected and to fail with an exception"); + } catch (Validator.InvalidValueException ex) { + assertEquals("Partial match validator error", ex.getMessage()); + } + try { + or.validate(testString); + } catch (Validator.InvalidValueException ex) { + fail("Or validator should be valid"); + } + } + + public void testBothFaulty() { + + String testString = "gmail.com"; + + assertFalse(testString + " should not validate", + email.isValid(testString)); + assertFalse(testString + " should not validate", + regex.isValid(testString)); + try { + and.validate(testString); + fail("expected and to fail with an exception"); + } catch (Validator.InvalidValueException ex) { + assertEquals("Faulty email", ex.getMessage()); + } + try { + or.validate(testString); + fail("expected or to fail with an exception"); + } catch (Validator.InvalidValueException ex) { + assertEquals("No validators are valid", ex.getMessage()); + } + } + +} diff --git a/server/tests/src/com/vaadin/tests/data/validator/DateRangeValidatorTest.java b/server/tests/src/com/vaadin/tests/data/validator/DateRangeValidatorTest.java new file mode 100644 index 0000000000..7bb3e20160 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/validator/DateRangeValidatorTest.java @@ -0,0 +1,97 @@ +package com.vaadin.tests.data.validator; + +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.Locale; +import java.util.TimeZone; + +import junit.framework.TestCase; + +import com.vaadin.data.validator.DateRangeValidator; +import com.vaadin.shared.ui.datefield.Resolution; + +public class DateRangeValidatorTest extends TestCase { + Calendar startDate = new GregorianCalendar(TimeZone.getTimeZone("GMT"), + Locale.ENGLISH); + Calendar endDate = new GregorianCalendar(TimeZone.getTimeZone("GMT"), + Locale.ENGLISH); + + private DateRangeValidator cleanValidator; + private DateRangeValidator minValidator; + private DateRangeValidator maxValidator; + private DateRangeValidator minMaxValidator; + + @Override + protected void setUp() throws Exception { + super.setUp(); + startDate.set(2000, Calendar.JANUARY, 1, 12, 0, 0); + endDate.set(2000, Calendar.FEBRUARY, 20, 12, 0, 0); + + cleanValidator = new DateRangeValidator("Given date outside range", + null, null, Resolution.DAY); + minValidator = new DateRangeValidator("Given date before startDate", + startDate.getTime(), null, Resolution.DAY); + maxValidator = new DateRangeValidator("Given date after endDate", null, + endDate.getTime(), Resolution.DAY); + minMaxValidator = new DateRangeValidator("Given date outside range", + startDate.getTime(), endDate.getTime(), Resolution.DAY); + } + + public void testNullValue() { + assertTrue("Didn't accept null", cleanValidator.isValid(null)); + assertTrue("Didn't accept null", minValidator.isValid(null)); + assertTrue("Didn't accept null", maxValidator.isValid(null)); + assertTrue("Didn't accept null", minMaxValidator.isValid(null)); + } + + public void testMinValue() { + Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"), + Locale.ENGLISH); + cal.setTime(startDate.getTime()); + cal.add(Calendar.SECOND, 1); + + assertTrue("Validator without ranges didn't accept value", + cleanValidator.isValid(cal.getTime())); + assertTrue("Didn't accept valid value", + minValidator.isValid(cal.getTime())); + + cal.add(Calendar.SECOND, -3); + + assertFalse("Accepted too small value", + minValidator.isValid(cal.getTime())); + } + + public void testMaxValue() { + Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"), + Locale.ENGLISH); + cal.setTime(endDate.getTime()); + cal.add(Calendar.SECOND, -1); + + assertTrue("Validator without ranges didn't accept value", + cleanValidator.isValid(cal.getTime())); + assertTrue("Didn't accept valid value", + maxValidator.isValid(cal.getTime())); + + cal.add(Calendar.SECOND, 2); + assertFalse("Accepted too large value", + maxValidator.isValid(cal.getTime())); + } + + public void testMinMaxValue() { + Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"), + Locale.ENGLISH); + cal.setTime(endDate.getTime()); + + assertTrue("Didn't accept valid value", + minMaxValidator.isValid(cal.getTime())); + cal.add(Calendar.SECOND, 1); + assertFalse("Accepted too large value", + minMaxValidator.isValid(cal.getTime())); + cal.setTime(startDate.getTime()); + assertTrue("Didn't accept valid value", + minMaxValidator.isValid(cal.getTime())); + cal.add(Calendar.SECOND, -1); + assertFalse("Accepted too small value", + minMaxValidator.isValid(cal.getTime())); + } +} diff --git a/server/tests/src/com/vaadin/tests/data/validator/DoubleRangeValidatorTest.java b/server/tests/src/com/vaadin/tests/data/validator/DoubleRangeValidatorTest.java new file mode 100644 index 0000000000..b096937bd2 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/validator/DoubleRangeValidatorTest.java @@ -0,0 +1,45 @@ +package com.vaadin.tests.data.validator; + +import junit.framework.TestCase; + +import com.vaadin.data.validator.DoubleRangeValidator; + +public class DoubleRangeValidatorTest extends TestCase { + + private DoubleRangeValidator cleanValidator = new DoubleRangeValidator( + "no values", null, null); + private DoubleRangeValidator minValidator = new DoubleRangeValidator( + "no values", 10.1, null); + private DoubleRangeValidator maxValidator = new DoubleRangeValidator( + "no values", null, 100.1); + private DoubleRangeValidator minMaxValidator = new DoubleRangeValidator( + "no values", 10.5, 100.5); + + public void testNullValue() { + assertTrue("Didn't accept null", cleanValidator.isValid(null)); + assertTrue("Didn't accept null", minValidator.isValid(null)); + assertTrue("Didn't accept null", maxValidator.isValid(null)); + assertTrue("Didn't accept null", minMaxValidator.isValid(null)); + } + + public void testMinValue() { + assertTrue("Validator without ranges didn't accept value", + cleanValidator.isValid(-15.0)); + assertTrue("Didn't accept valid value", minValidator.isValid(10.1)); + assertFalse("Accepted too small value", minValidator.isValid(10.0)); + } + + public void testMaxValue() { + assertTrue("Validator without ranges didn't accept value", + cleanValidator.isValid(1120.0)); + assertTrue("Didn't accept valid value", maxValidator.isValid(15.0)); + assertFalse("Accepted too large value", maxValidator.isValid(100.6)); + } + + public void testMinMaxValue() { + assertTrue("Didn't accept valid value", minMaxValidator.isValid(10.5)); + assertTrue("Didn't accept valid value", minMaxValidator.isValid(100.5)); + assertFalse("Accepted too small value", minMaxValidator.isValid(10.4)); + assertFalse("Accepted too large value", minMaxValidator.isValid(100.6)); + } +} diff --git a/server/tests/src/com/vaadin/tests/data/validator/EmailValidatorTest.java b/server/tests/src/com/vaadin/tests/data/validator/EmailValidatorTest.java new file mode 100644 index 0000000000..19fe9e6580 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/validator/EmailValidatorTest.java @@ -0,0 +1,26 @@ +package com.vaadin.tests.data.validator; + +import junit.framework.TestCase; + +import com.vaadin.data.validator.EmailValidator; + +public class EmailValidatorTest extends TestCase { + + private EmailValidator validator = new EmailValidator("Error"); + + public void testEmailValidatorWithNull() { + assertTrue(validator.isValid(null)); + } + + public void testEmailValidatorWithEmptyString() { + assertTrue(validator.isValid("")); + } + + public void testEmailValidatorWithFaultyString() { + assertFalse(validator.isValid("not.an.email")); + } + + public void testEmailValidatorWithOkEmail() { + assertTrue(validator.isValid("my.name@email.com")); + } +} diff --git a/server/tests/src/com/vaadin/tests/data/validator/FloatRangeValidatorTest.java b/server/tests/src/com/vaadin/tests/data/validator/FloatRangeValidatorTest.java new file mode 100644 index 0000000000..c5a07be43f --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/validator/FloatRangeValidatorTest.java @@ -0,0 +1,45 @@ +package com.vaadin.tests.data.validator; + +import junit.framework.TestCase; + +import com.vaadin.data.validator.FloatRangeValidator; + +public class FloatRangeValidatorTest extends TestCase { + + private FloatRangeValidator cleanValidator = new FloatRangeValidator( + "no values", null, null); + private FloatRangeValidator minValidator = new FloatRangeValidator( + "no values", 10.1f, null); + private FloatRangeValidator maxValidator = new FloatRangeValidator( + "no values", null, 100.1f); + private FloatRangeValidator minMaxValidator = new FloatRangeValidator( + "no values", 10.5f, 100.5f); + + public void testNullValue() { + assertTrue("Didn't accept null", cleanValidator.isValid(null)); + assertTrue("Didn't accept null", minValidator.isValid(null)); + assertTrue("Didn't accept null", maxValidator.isValid(null)); + assertTrue("Didn't accept null", minMaxValidator.isValid(null)); + } + + public void testMinValue() { + assertTrue("Validator without ranges didn't accept value", + cleanValidator.isValid(-15.0f)); + assertTrue("Didn't accept valid value", minValidator.isValid(10.1f)); + assertFalse("Accepted too small value", minValidator.isValid(10.0f)); + } + + public void testMaxValue() { + assertTrue("Validator without ranges didn't accept value", + cleanValidator.isValid(1120.0f)); + assertTrue("Didn't accept valid value", maxValidator.isValid(15.0f)); + assertFalse("Accepted too large value", maxValidator.isValid(100.6f)); + } + + public void testMinMaxValue() { + assertTrue("Didn't accept valid value", minMaxValidator.isValid(10.5f)); + assertTrue("Didn't accept valid value", minMaxValidator.isValid(100.5f)); + assertFalse("Accepted too small value", minMaxValidator.isValid(10.4f)); + assertFalse("Accepted too large value", minMaxValidator.isValid(100.6f)); + } +} diff --git a/server/tests/src/com/vaadin/tests/data/validator/IntegerRangeValidatorTest.java b/server/tests/src/com/vaadin/tests/data/validator/IntegerRangeValidatorTest.java new file mode 100644 index 0000000000..5e64d0107e --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/validator/IntegerRangeValidatorTest.java @@ -0,0 +1,45 @@ +package com.vaadin.tests.data.validator; + +import junit.framework.TestCase; + +import com.vaadin.data.validator.IntegerRangeValidator; + +public class IntegerRangeValidatorTest extends TestCase { + + private IntegerRangeValidator cleanValidator = new IntegerRangeValidator( + "no values", null, null); + private IntegerRangeValidator minValidator = new IntegerRangeValidator( + "no values", 10, null); + private IntegerRangeValidator maxValidator = new IntegerRangeValidator( + "no values", null, 100); + private IntegerRangeValidator minMaxValidator = new IntegerRangeValidator( + "no values", 10, 100); + + public void testNullValue() { + assertTrue("Didn't accept null", cleanValidator.isValid(null)); + assertTrue("Didn't accept null", minValidator.isValid(null)); + assertTrue("Didn't accept null", maxValidator.isValid(null)); + assertTrue("Didn't accept null", minMaxValidator.isValid(null)); + } + + public void testMinValue() { + assertTrue("Validator without ranges didn't accept value", + cleanValidator.isValid(-15)); + assertTrue("Didn't accept valid value", minValidator.isValid(15)); + assertFalse("Accepted too small value", minValidator.isValid(9)); + } + + public void testMaxValue() { + assertTrue("Validator without ranges didn't accept value", + cleanValidator.isValid(1120)); + assertTrue("Didn't accept valid value", maxValidator.isValid(15)); + assertFalse("Accepted too large value", maxValidator.isValid(120)); + } + + public void testMinMaxValue() { + assertTrue("Didn't accept valid value", minMaxValidator.isValid(15)); + assertTrue("Didn't accept valid value", minMaxValidator.isValid(99)); + assertFalse("Accepted too small value", minMaxValidator.isValid(9)); + assertFalse("Accepted too large value", minMaxValidator.isValid(110)); + } +} diff --git a/server/tests/src/com/vaadin/tests/data/validator/LongRangeValidatorTest.java b/server/tests/src/com/vaadin/tests/data/validator/LongRangeValidatorTest.java new file mode 100644 index 0000000000..440e9c3fd2 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/validator/LongRangeValidatorTest.java @@ -0,0 +1,45 @@ +package com.vaadin.tests.data.validator; + +import junit.framework.TestCase; + +import com.vaadin.data.validator.LongRangeValidator; + +public class LongRangeValidatorTest extends TestCase { + + private LongRangeValidator cleanValidator = new LongRangeValidator( + "no values", null, null); + private LongRangeValidator minValidator = new LongRangeValidator( + "no values", 10l, null); + private LongRangeValidator maxValidator = new LongRangeValidator( + "no values", null, 100l); + private LongRangeValidator minMaxValidator = new LongRangeValidator( + "no values", 10l, 100l); + + public void testNullValue() { + assertTrue("Didn't accept null", cleanValidator.isValid(null)); + assertTrue("Didn't accept null", minValidator.isValid(null)); + assertTrue("Didn't accept null", maxValidator.isValid(null)); + assertTrue("Didn't accept null", minMaxValidator.isValid(null)); + } + + public void testMinValue() { + assertTrue("Validator without ranges didn't accept value", + cleanValidator.isValid(-15l)); + assertTrue("Didn't accept valid value", minValidator.isValid(15l)); + assertFalse("Accepted too small value", minValidator.isValid(9l)); + } + + public void testMaxValue() { + assertTrue("Validator without ranges didn't accept value", + cleanValidator.isValid(1120l)); + assertTrue("Didn't accept valid value", maxValidator.isValid(15l)); + assertFalse("Accepted too large value", maxValidator.isValid(120l)); + } + + public void testMinMaxValue() { + assertTrue("Didn't accept valid value", minMaxValidator.isValid(15l)); + assertTrue("Didn't accept valid value", minMaxValidator.isValid(99l)); + assertFalse("Accepted too small value", minMaxValidator.isValid(9l)); + assertFalse("Accepted too large value", minMaxValidator.isValid(110l)); + } +} diff --git a/server/tests/src/com/vaadin/tests/data/validator/NullValidatorTest.java b/server/tests/src/com/vaadin/tests/data/validator/NullValidatorTest.java new file mode 100644 index 0000000000..1e08ea7e2c --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/validator/NullValidatorTest.java @@ -0,0 +1,40 @@ +package com.vaadin.tests.data.validator; + +import junit.framework.TestCase; + +import com.vaadin.data.Validator; +import com.vaadin.data.validator.NullValidator; + +public class NullValidatorTest extends TestCase { + + NullValidator notNull = new NullValidator("Null not accepted", false); + NullValidator onlyNull = new NullValidator("Only null accepted", true); + + public void testNullValue() { + try { + notNull.validate(null); + fail("expected null to fail with an exception"); + } catch (Validator.InvalidValueException ex) { + assertEquals("Null not accepted", ex.getMessage()); + } + try { + onlyNull.validate(null); + } catch (Validator.InvalidValueException ex) { + fail("onlyNull should not throw exception for null"); + } + } + + public void testNonNullValue() { + try { + onlyNull.validate("Not a null value"); + fail("expected onlyNull validator to fail with an exception"); + } catch (Validator.InvalidValueException ex) { + assertEquals("Only null accepted", ex.getMessage()); + } + try { + notNull.validate("Not a null value"); + } catch (Validator.InvalidValueException ex) { + fail("notNull should not throw exception for \"Not a null value\""); + } + } +} diff --git a/server/tests/src/com/vaadin/tests/data/validator/RegexpValidatorTest.java b/server/tests/src/com/vaadin/tests/data/validator/RegexpValidatorTest.java new file mode 100644 index 0000000000..2a62d23059 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/validator/RegexpValidatorTest.java @@ -0,0 +1,44 @@ +package com.vaadin.tests.data.validator; + +import junit.framework.TestCase; + +import com.vaadin.data.validator.RegexpValidator; + +public class RegexpValidatorTest extends TestCase { + + private RegexpValidator completeValidator = new RegexpValidator("pattern", + true, "Complete match validator error"); + private RegexpValidator partialValidator = new RegexpValidator("pattern", + false, "Partial match validator error"); + + public void testRegexpValidatorWithNull() { + assertTrue(completeValidator.isValid(null)); + assertTrue(partialValidator.isValid(null)); + } + + public void testRegexpValidatorWithEmptyString() { + assertTrue(completeValidator.isValid("")); + assertTrue(partialValidator.isValid("")); + } + + public void testCompleteRegexpValidatorWithFaultyString() { + assertFalse(completeValidator.isValid("mismatch")); + assertFalse(completeValidator.isValid("pattern2")); + assertFalse(completeValidator.isValid("1pattern")); + } + + public void testCompleteRegexpValidatorWithOkString() { + assertTrue(completeValidator.isValid("pattern")); + } + + public void testPartialRegexpValidatorWithFaultyString() { + assertFalse(partialValidator.isValid("mismatch")); + } + + public void testPartialRegexpValidatorWithOkString() { + assertTrue(partialValidator.isValid("pattern")); + assertTrue(partialValidator.isValid("1pattern")); + assertTrue(partialValidator.isValid("pattern2")); + assertTrue(partialValidator.isValid("1pattern2")); + } +} diff --git a/server/tests/src/com/vaadin/tests/data/validator/ShortRangeValidatorTest.java b/server/tests/src/com/vaadin/tests/data/validator/ShortRangeValidatorTest.java new file mode 100644 index 0000000000..69d22eb91e --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/validator/ShortRangeValidatorTest.java @@ -0,0 +1,52 @@ +package com.vaadin.tests.data.validator; + +import junit.framework.TestCase; + +import com.vaadin.data.validator.ShortRangeValidator; + +public class ShortRangeValidatorTest extends TestCase { + + private ShortRangeValidator cleanValidator = new ShortRangeValidator( + "no values", null, null); + private ShortRangeValidator minValidator = new ShortRangeValidator( + "no values", (short) 10, null); + private ShortRangeValidator maxValidator = new ShortRangeValidator( + "no values", null, (short) 100); + private ShortRangeValidator minMaxValidator = new ShortRangeValidator( + "no values", (short) 10, (short) 100); + + public void testNullValue() { + assertTrue("Didn't accept null", cleanValidator.isValid(null)); + assertTrue("Didn't accept null", minValidator.isValid(null)); + assertTrue("Didn't accept null", maxValidator.isValid(null)); + assertTrue("Didn't accept null", minMaxValidator.isValid(null)); + } + + public void testMinValue() { + assertTrue("Validator without ranges didn't accept value", + cleanValidator.isValid((short) -15)); + assertTrue("Didn't accept valid value", + minValidator.isValid((short) 15)); + assertFalse("Accepted too small value", minValidator.isValid((short) 9)); + } + + public void testMaxValue() { + assertTrue("Validator without ranges didn't accept value", + cleanValidator.isValid((short) 1120)); + assertTrue("Didn't accept valid value", + maxValidator.isValid((short) 15)); + assertFalse("Accepted too large value", + maxValidator.isValid((short) 120)); + } + + public void testMinMaxValue() { + assertTrue("Didn't accept valid value", + minMaxValidator.isValid((short) 15)); + assertTrue("Didn't accept valid value", + minMaxValidator.isValid((short) 99)); + assertFalse("Accepted too small value", + minMaxValidator.isValid((short) 9)); + assertFalse("Accepted too large value", + minMaxValidator.isValid((short) 110)); + } +} diff --git a/server/tests/src/com/vaadin/tests/data/validator/StringLengthValidatorTest.java b/server/tests/src/com/vaadin/tests/data/validator/StringLengthValidatorTest.java new file mode 100644 index 0000000000..5f12367f09 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/data/validator/StringLengthValidatorTest.java @@ -0,0 +1,65 @@ +package com.vaadin.tests.data.validator; + +import junit.framework.TestCase; + +import com.vaadin.data.validator.StringLengthValidator; + +public class StringLengthValidatorTest extends TestCase { + + private StringLengthValidator validator = new StringLengthValidator("Error"); + private StringLengthValidator validatorNoNull = new StringLengthValidator( + "Error", 1, 5, false); + private StringLengthValidator validatorMinValue = new StringLengthValidator( + "Error", 5, null, true); + private StringLengthValidator validatorMaxValue = new StringLengthValidator( + "Error", null, 15, true); + + public void testValidatorWithNull() { + assertTrue("Didn't accept null", validator.isValid(null)); + assertTrue("Didn't accept null", validatorMinValue.isValid(null)); + } + + public void testValidatorNotAcceptingNull() { + assertFalse("Accepted null", validatorNoNull.isValid(null)); + } + + public void testEmptyString() { + assertTrue("Didn't accept empty String", validator.isValid("")); + assertTrue("Didn't accept empty String", validatorMaxValue.isValid("")); + assertFalse("Accepted empty string even though has lower bound of 1", + validatorNoNull.isValid("")); + assertFalse("Accepted empty string even though has lower bound of 5", + validatorMinValue.isValid("")); + } + + public void testTooLongString() { + assertFalse("Too long string was accepted", + validatorNoNull.isValid("This string is too long")); + assertFalse("Too long string was accepted", + validatorMaxValue.isValid("This string is too long")); + } + + public void testNoUpperBound() { + assertTrue( + "String not accepted even though no upper bound", + validatorMinValue + .isValid("This is a really long string to test that no upper bound exists")); + } + + public void testNoLowerBound() { + assertTrue("Didn't accept short string", validatorMaxValue.isValid("")); + assertTrue("Didn't accept short string", validatorMaxValue.isValid("1")); + } + + public void testStringLengthValidatorWithOkStringLength() { + assertTrue("Didn't accept string of correct length", + validatorNoNull.isValid("OK!")); + assertTrue("Didn't accept string of correct length", + validatorMaxValue.isValid("OK!")); + } + + public void testTooShortStringLength() { + assertFalse("Accepted a string that was too short.", + validatorMinValue.isValid("shot")); + } +} diff --git a/server/tests/src/com/vaadin/tests/data/validator/TestBigDecimalRangeValidator.java b/server/tests/src/com/vaadin/tests/data/validator/TestBigDecimalRangeValidator.java deleted file mode 100644 index 2ce576fb77..0000000000 --- a/server/tests/src/com/vaadin/tests/data/validator/TestBigDecimalRangeValidator.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.vaadin.tests.data.validator; - -import java.math.BigDecimal; - -import junit.framework.TestCase; - -import com.vaadin.data.validator.BigDecimalRangeValidator; - -public class TestBigDecimalRangeValidator extends TestCase { - - private BigDecimalRangeValidator cleanValidator = new BigDecimalRangeValidator( - "no values", null, null); - private BigDecimalRangeValidator minValidator = new BigDecimalRangeValidator( - "no values", new BigDecimal(10.1), null); - private BigDecimalRangeValidator maxValidator = new BigDecimalRangeValidator( - "no values", null, new BigDecimal(100.1)); - private BigDecimalRangeValidator minMaxValidator = new BigDecimalRangeValidator( - "no values", new BigDecimal(10.5), new BigDecimal(100.5)); - - public void testNullValue() { - assertTrue("Didn't accept null", cleanValidator.isValid(null)); - assertTrue("Didn't accept null", minValidator.isValid(null)); - assertTrue("Didn't accept null", maxValidator.isValid(null)); - assertTrue("Didn't accept null", minMaxValidator.isValid(null)); - } - - public void testMinValue() { - assertTrue("Validator without ranges didn't accept value", - cleanValidator.isValid(new BigDecimal(-15.0))); - assertTrue("Didn't accept valid value", - minValidator.isValid(new BigDecimal(10.1))); - assertFalse("Accepted too small value", - minValidator.isValid(new BigDecimal(10.0))); - } - - public void testMaxValue() { - assertTrue("Validator without ranges didn't accept value", - cleanValidator.isValid(new BigDecimal(1120.0))); - assertTrue("Didn't accept valid value", - maxValidator.isValid(new BigDecimal(15.0))); - assertFalse("Accepted too large value", - maxValidator.isValid(new BigDecimal(100.6))); - } - - public void testMinMaxValue() { - assertTrue("Didn't accept valid value", - minMaxValidator.isValid(new BigDecimal(10.5))); - assertTrue("Didn't accept valid value", - minMaxValidator.isValid(new BigDecimal(100.5))); - assertFalse("Accepted too small value", - minMaxValidator.isValid(new BigDecimal(10.4))); - assertFalse("Accepted too large value", - minMaxValidator.isValid(new BigDecimal(100.6))); - } -} diff --git a/server/tests/src/com/vaadin/tests/data/validator/TestBigIntegerRangeValidator.java b/server/tests/src/com/vaadin/tests/data/validator/TestBigIntegerRangeValidator.java deleted file mode 100644 index d3263df6d2..0000000000 --- a/server/tests/src/com/vaadin/tests/data/validator/TestBigIntegerRangeValidator.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.vaadin.tests.data.validator; - -import java.math.BigInteger; - -import junit.framework.TestCase; - -import com.vaadin.data.validator.BigIntegerRangeValidator; - -public class TestBigIntegerRangeValidator extends TestCase { - - private BigIntegerRangeValidator cleanValidator = new BigIntegerRangeValidator( - "no values", null, null); - private BigIntegerRangeValidator minValidator = new BigIntegerRangeValidator( - "no values", BigInteger.valueOf(10), null); - private BigIntegerRangeValidator maxValidator = new BigIntegerRangeValidator( - "no values", null, BigInteger.valueOf(100)); - private BigIntegerRangeValidator minMaxValidator = new BigIntegerRangeValidator( - "no values", BigInteger.valueOf(10), BigInteger.valueOf(100)); - - public void testNullValue() { - assertTrue("Didn't accept null", cleanValidator.isValid(null)); - assertTrue("Didn't accept null", minValidator.isValid(null)); - assertTrue("Didn't accept null", maxValidator.isValid(null)); - assertTrue("Didn't accept null", minMaxValidator.isValid(null)); - } - - public void testMinValue() { - assertTrue("Validator without ranges didn't accept value", - cleanValidator.isValid(BigInteger.valueOf(-15))); - assertTrue("Didn't accept valid value", - minValidator.isValid(BigInteger.valueOf(15))); - assertFalse("Accepted too small value", - minValidator.isValid(BigInteger.valueOf(9))); - } - - public void testMaxValue() { - assertTrue("Validator without ranges didn't accept value", - cleanValidator.isValid(BigInteger.valueOf(1120))); - assertTrue("Didn't accept valid value", - maxValidator.isValid(BigInteger.valueOf(15))); - assertFalse("Accepted too large value", - maxValidator.isValid(BigInteger.valueOf(120))); - } - - public void testMinMaxValue() { - assertTrue("Didn't accept valid value", - minMaxValidator.isValid(BigInteger.valueOf(15))); - assertTrue("Didn't accept valid value", - minMaxValidator.isValid(BigInteger.valueOf(99))); - assertFalse("Accepted too small value", - minMaxValidator.isValid(BigInteger.valueOf(9))); - assertFalse("Accepted too large value", - minMaxValidator.isValid(BigInteger.valueOf(110))); - } -} diff --git a/server/tests/src/com/vaadin/tests/data/validator/TestByteRangeValidator.java b/server/tests/src/com/vaadin/tests/data/validator/TestByteRangeValidator.java deleted file mode 100644 index 6fac06c31b..0000000000 --- a/server/tests/src/com/vaadin/tests/data/validator/TestByteRangeValidator.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.vaadin.tests.data.validator; - -import junit.framework.TestCase; - -import com.vaadin.data.validator.ByteRangeValidator; - -public class TestByteRangeValidator extends TestCase { - - private ByteRangeValidator cleanValidator = new ByteRangeValidator( - "no values", null, null); - private ByteRangeValidator minValidator = new ByteRangeValidator( - "no values", (byte) 10, null); - private ByteRangeValidator maxValidator = new ByteRangeValidator( - "no values", null, (byte) 100); - private ByteRangeValidator minMaxValidator = new ByteRangeValidator( - "no values", (byte) 10, (byte) 100); - - public void testNullValue() { - assertTrue("Didn't accept null", cleanValidator.isValid(null)); - assertTrue("Didn't accept null", minValidator.isValid(null)); - assertTrue("Didn't accept null", maxValidator.isValid(null)); - assertTrue("Didn't accept null", minMaxValidator.isValid(null)); - } - - public void testMinValue() { - assertTrue("Validator without ranges didn't accept value", - cleanValidator.isValid((byte) -15)); - assertTrue("Didn't accept valid value", minValidator.isValid((byte) 15)); - assertFalse("Accepted too small value", minValidator.isValid((byte) 9)); - } - - public void testMaxValue() { - assertTrue("Validator without ranges didn't accept value", - cleanValidator.isValid((byte) 112)); - assertTrue("Didn't accept valid value", maxValidator.isValid((byte) 15)); - assertFalse("Accepted too large value", - maxValidator.isValid((byte) 120)); - } - - public void testMinMaxValue() { - assertTrue("Didn't accept valid value", - minMaxValidator.isValid((byte) 15)); - assertTrue("Didn't accept valid value", - minMaxValidator.isValid((byte) 99)); - assertFalse("Accepted too small value", - minMaxValidator.isValid((byte) 9)); - assertFalse("Accepted too large value", - minMaxValidator.isValid((byte) 110)); - } -} diff --git a/server/tests/src/com/vaadin/tests/data/validator/TestCompositeValidator.java b/server/tests/src/com/vaadin/tests/data/validator/TestCompositeValidator.java deleted file mode 100644 index 1d69c77a3d..0000000000 --- a/server/tests/src/com/vaadin/tests/data/validator/TestCompositeValidator.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.vaadin.tests.data.validator; - -import junit.framework.TestCase; - -import com.vaadin.data.Validator; -import com.vaadin.data.validator.CompositeValidator; -import com.vaadin.data.validator.CompositeValidator.CombinationMode; -import com.vaadin.data.validator.EmailValidator; -import com.vaadin.data.validator.RegexpValidator; - -public class TestCompositeValidator extends TestCase { - - CompositeValidator and = new CompositeValidator(CombinationMode.AND, - "One validator not valid"); - CompositeValidator or = new CompositeValidator(CombinationMode.OR, - "No validators are valid"); - EmailValidator email = new EmailValidator("Faulty email"); - RegexpValidator regex = new RegexpValidator("@mail.com", false, - "Partial match validator error"); - - @Override - protected void setUp() throws Exception { - super.setUp(); - - and.addValidator(email); - and.addValidator(regex); - - or.addValidator(email); - or.addValidator(regex); - } - - public void testCorrectValue() { - String testString = "user@mail.com"; - assertTrue(email.isValid(testString)); - assertTrue(regex.isValid(testString)); - try { - // notNull.validate(null); - // fail("expected null to fail with an exception"); - and.validate(testString); - } catch (Validator.InvalidValueException ex) { - // assertEquals("Null not accepted", ex.getMessage()); - fail("And validator should be valid"); - } - try { - or.validate(testString); - } catch (Validator.InvalidValueException ex) { - // assertEquals("Null not accepted", ex.getMessage()); - fail("And validator should be valid"); - } - } - - public void testCorrectRegex() { - - String testString = "@mail.com"; - assertFalse(testString + " should not validate", - email.isValid(testString)); - assertTrue(testString + "should validate", regex.isValid(testString)); - try { - // notNull.validate(null); - and.validate(testString); - fail("expected and to fail with an exception"); - } catch (Validator.InvalidValueException ex) { - assertEquals("Faulty email", ex.getMessage()); - // fail("And validator should be valid"); - } - try { - or.validate(testString); - } catch (Validator.InvalidValueException ex) { - // assertEquals("Null not accepted", ex.getMessage()); - fail("Or validator should be valid"); - } - } - - public void testCorrectEmail() { - - String testString = "user@gmail.com"; - - assertTrue(testString + " should validate", email.isValid(testString)); - assertFalse(testString + " should not validate", - regex.isValid(testString)); - try { - and.validate(testString); - fail("expected and to fail with an exception"); - } catch (Validator.InvalidValueException ex) { - assertEquals("Partial match validator error", ex.getMessage()); - } - try { - or.validate(testString); - } catch (Validator.InvalidValueException ex) { - fail("Or validator should be valid"); - } - } - - public void testBothFaulty() { - - String testString = "gmail.com"; - - assertFalse(testString + " should not validate", - email.isValid(testString)); - assertFalse(testString + " should not validate", - regex.isValid(testString)); - try { - and.validate(testString); - fail("expected and to fail with an exception"); - } catch (Validator.InvalidValueException ex) { - assertEquals("Faulty email", ex.getMessage()); - } - try { - or.validate(testString); - fail("expected or to fail with an exception"); - } catch (Validator.InvalidValueException ex) { - assertEquals("No validators are valid", ex.getMessage()); - } - } - -} diff --git a/server/tests/src/com/vaadin/tests/data/validator/TestDateRangeValidator.java b/server/tests/src/com/vaadin/tests/data/validator/TestDateRangeValidator.java deleted file mode 100644 index cdb1e12545..0000000000 --- a/server/tests/src/com/vaadin/tests/data/validator/TestDateRangeValidator.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.vaadin.tests.data.validator; - -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.Locale; -import java.util.TimeZone; - -import junit.framework.TestCase; - -import com.vaadin.data.validator.DateRangeValidator; -import com.vaadin.shared.ui.datefield.Resolution; - -public class TestDateRangeValidator extends TestCase { - Calendar startDate = new GregorianCalendar(TimeZone.getTimeZone("GMT"), - Locale.ENGLISH); - Calendar endDate = new GregorianCalendar(TimeZone.getTimeZone("GMT"), - Locale.ENGLISH); - - private DateRangeValidator cleanValidator; - private DateRangeValidator minValidator; - private DateRangeValidator maxValidator; - private DateRangeValidator minMaxValidator; - - @Override - protected void setUp() throws Exception { - super.setUp(); - startDate.set(2000, Calendar.JANUARY, 1, 12, 0, 0); - endDate.set(2000, Calendar.FEBRUARY, 20, 12, 0, 0); - - cleanValidator = new DateRangeValidator("Given date outside range", - null, null, Resolution.DAY); - minValidator = new DateRangeValidator("Given date before startDate", - startDate.getTime(), null, Resolution.DAY); - maxValidator = new DateRangeValidator("Given date after endDate", null, - endDate.getTime(), Resolution.DAY); - minMaxValidator = new DateRangeValidator("Given date outside range", - startDate.getTime(), endDate.getTime(), Resolution.DAY); - } - - public void testNullValue() { - assertTrue("Didn't accept null", cleanValidator.isValid(null)); - assertTrue("Didn't accept null", minValidator.isValid(null)); - assertTrue("Didn't accept null", maxValidator.isValid(null)); - assertTrue("Didn't accept null", minMaxValidator.isValid(null)); - } - - public void testMinValue() { - Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"), - Locale.ENGLISH); - cal.setTime(startDate.getTime()); - cal.add(Calendar.SECOND, 1); - - assertTrue("Validator without ranges didn't accept value", - cleanValidator.isValid(cal.getTime())); - assertTrue("Didn't accept valid value", - minValidator.isValid(cal.getTime())); - - cal.add(Calendar.SECOND, -3); - - assertFalse("Accepted too small value", - minValidator.isValid(cal.getTime())); - } - - public void testMaxValue() { - Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"), - Locale.ENGLISH); - cal.setTime(endDate.getTime()); - cal.add(Calendar.SECOND, -1); - - assertTrue("Validator without ranges didn't accept value", - cleanValidator.isValid(cal.getTime())); - assertTrue("Didn't accept valid value", - maxValidator.isValid(cal.getTime())); - - cal.add(Calendar.SECOND, 2); - assertFalse("Accepted too large value", - maxValidator.isValid(cal.getTime())); - } - - public void testMinMaxValue() { - Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"), - Locale.ENGLISH); - cal.setTime(endDate.getTime()); - - assertTrue("Didn't accept valid value", - minMaxValidator.isValid(cal.getTime())); - cal.add(Calendar.SECOND, 1); - assertFalse("Accepted too large value", - minMaxValidator.isValid(cal.getTime())); - cal.setTime(startDate.getTime()); - assertTrue("Didn't accept valid value", - minMaxValidator.isValid(cal.getTime())); - cal.add(Calendar.SECOND, -1); - assertFalse("Accepted too small value", - minMaxValidator.isValid(cal.getTime())); - } -} diff --git a/server/tests/src/com/vaadin/tests/data/validator/TestDoubleRangeValidator.java b/server/tests/src/com/vaadin/tests/data/validator/TestDoubleRangeValidator.java deleted file mode 100644 index 3fe61e13f4..0000000000 --- a/server/tests/src/com/vaadin/tests/data/validator/TestDoubleRangeValidator.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.vaadin.tests.data.validator; - -import junit.framework.TestCase; - -import com.vaadin.data.validator.DoubleRangeValidator; - -public class TestDoubleRangeValidator extends TestCase { - - private DoubleRangeValidator cleanValidator = new DoubleRangeValidator( - "no values", null, null); - private DoubleRangeValidator minValidator = new DoubleRangeValidator( - "no values", 10.1, null); - private DoubleRangeValidator maxValidator = new DoubleRangeValidator( - "no values", null, 100.1); - private DoubleRangeValidator minMaxValidator = new DoubleRangeValidator( - "no values", 10.5, 100.5); - - public void testNullValue() { - assertTrue("Didn't accept null", cleanValidator.isValid(null)); - assertTrue("Didn't accept null", minValidator.isValid(null)); - assertTrue("Didn't accept null", maxValidator.isValid(null)); - assertTrue("Didn't accept null", minMaxValidator.isValid(null)); - } - - public void testMinValue() { - assertTrue("Validator without ranges didn't accept value", - cleanValidator.isValid(-15.0)); - assertTrue("Didn't accept valid value", minValidator.isValid(10.1)); - assertFalse("Accepted too small value", minValidator.isValid(10.0)); - } - - public void testMaxValue() { - assertTrue("Validator without ranges didn't accept value", - cleanValidator.isValid(1120.0)); - assertTrue("Didn't accept valid value", maxValidator.isValid(15.0)); - assertFalse("Accepted too large value", maxValidator.isValid(100.6)); - } - - public void testMinMaxValue() { - assertTrue("Didn't accept valid value", minMaxValidator.isValid(10.5)); - assertTrue("Didn't accept valid value", minMaxValidator.isValid(100.5)); - assertFalse("Accepted too small value", minMaxValidator.isValid(10.4)); - assertFalse("Accepted too large value", minMaxValidator.isValid(100.6)); - } -} diff --git a/server/tests/src/com/vaadin/tests/data/validator/TestEmailValidator.java b/server/tests/src/com/vaadin/tests/data/validator/TestEmailValidator.java deleted file mode 100644 index 7644b4738c..0000000000 --- a/server/tests/src/com/vaadin/tests/data/validator/TestEmailValidator.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.vaadin.tests.data.validator; - -import junit.framework.TestCase; - -import com.vaadin.data.validator.EmailValidator; - -public class TestEmailValidator extends TestCase { - - private EmailValidator validator = new EmailValidator("Error"); - - public void testEmailValidatorWithNull() { - assertTrue(validator.isValid(null)); - } - - public void testEmailValidatorWithEmptyString() { - assertTrue(validator.isValid("")); - } - - public void testEmailValidatorWithFaultyString() { - assertFalse(validator.isValid("not.an.email")); - } - - public void testEmailValidatorWithOkEmail() { - assertTrue(validator.isValid("my.name@email.com")); - } -} diff --git a/server/tests/src/com/vaadin/tests/data/validator/TestFloatRangeValidator.java b/server/tests/src/com/vaadin/tests/data/validator/TestFloatRangeValidator.java deleted file mode 100644 index 8de363e3d7..0000000000 --- a/server/tests/src/com/vaadin/tests/data/validator/TestFloatRangeValidator.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.vaadin.tests.data.validator; - -import junit.framework.TestCase; - -import com.vaadin.data.validator.FloatRangeValidator; - -public class TestFloatRangeValidator extends TestCase { - - private FloatRangeValidator cleanValidator = new FloatRangeValidator( - "no values", null, null); - private FloatRangeValidator minValidator = new FloatRangeValidator( - "no values", 10.1f, null); - private FloatRangeValidator maxValidator = new FloatRangeValidator( - "no values", null, 100.1f); - private FloatRangeValidator minMaxValidator = new FloatRangeValidator( - "no values", 10.5f, 100.5f); - - public void testNullValue() { - assertTrue("Didn't accept null", cleanValidator.isValid(null)); - assertTrue("Didn't accept null", minValidator.isValid(null)); - assertTrue("Didn't accept null", maxValidator.isValid(null)); - assertTrue("Didn't accept null", minMaxValidator.isValid(null)); - } - - public void testMinValue() { - assertTrue("Validator without ranges didn't accept value", - cleanValidator.isValid(-15.0f)); - assertTrue("Didn't accept valid value", minValidator.isValid(10.1f)); - assertFalse("Accepted too small value", minValidator.isValid(10.0f)); - } - - public void testMaxValue() { - assertTrue("Validator without ranges didn't accept value", - cleanValidator.isValid(1120.0f)); - assertTrue("Didn't accept valid value", maxValidator.isValid(15.0f)); - assertFalse("Accepted too large value", maxValidator.isValid(100.6f)); - } - - public void testMinMaxValue() { - assertTrue("Didn't accept valid value", minMaxValidator.isValid(10.5f)); - assertTrue("Didn't accept valid value", minMaxValidator.isValid(100.5f)); - assertFalse("Accepted too small value", minMaxValidator.isValid(10.4f)); - assertFalse("Accepted too large value", minMaxValidator.isValid(100.6f)); - } -} diff --git a/server/tests/src/com/vaadin/tests/data/validator/TestIntegerRangeValidator.java b/server/tests/src/com/vaadin/tests/data/validator/TestIntegerRangeValidator.java deleted file mode 100644 index 864fc61ab6..0000000000 --- a/server/tests/src/com/vaadin/tests/data/validator/TestIntegerRangeValidator.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.vaadin.tests.data.validator; - -import junit.framework.TestCase; - -import com.vaadin.data.validator.IntegerRangeValidator; - -public class TestIntegerRangeValidator extends TestCase { - - private IntegerRangeValidator cleanValidator = new IntegerRangeValidator( - "no values", null, null); - private IntegerRangeValidator minValidator = new IntegerRangeValidator( - "no values", 10, null); - private IntegerRangeValidator maxValidator = new IntegerRangeValidator( - "no values", null, 100); - private IntegerRangeValidator minMaxValidator = new IntegerRangeValidator( - "no values", 10, 100); - - public void testNullValue() { - assertTrue("Didn't accept null", cleanValidator.isValid(null)); - assertTrue("Didn't accept null", minValidator.isValid(null)); - assertTrue("Didn't accept null", maxValidator.isValid(null)); - assertTrue("Didn't accept null", minMaxValidator.isValid(null)); - } - - public void testMinValue() { - assertTrue("Validator without ranges didn't accept value", - cleanValidator.isValid(-15)); - assertTrue("Didn't accept valid value", minValidator.isValid(15)); - assertFalse("Accepted too small value", minValidator.isValid(9)); - } - - public void testMaxValue() { - assertTrue("Validator without ranges didn't accept value", - cleanValidator.isValid(1120)); - assertTrue("Didn't accept valid value", maxValidator.isValid(15)); - assertFalse("Accepted too large value", maxValidator.isValid(120)); - } - - public void testMinMaxValue() { - assertTrue("Didn't accept valid value", minMaxValidator.isValid(15)); - assertTrue("Didn't accept valid value", minMaxValidator.isValid(99)); - assertFalse("Accepted too small value", minMaxValidator.isValid(9)); - assertFalse("Accepted too large value", minMaxValidator.isValid(110)); - } -} diff --git a/server/tests/src/com/vaadin/tests/data/validator/TestLongRangeValidator.java b/server/tests/src/com/vaadin/tests/data/validator/TestLongRangeValidator.java deleted file mode 100644 index a9aeb6b67b..0000000000 --- a/server/tests/src/com/vaadin/tests/data/validator/TestLongRangeValidator.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.vaadin.tests.data.validator; - -import junit.framework.TestCase; - -import com.vaadin.data.validator.LongRangeValidator; - -public class TestLongRangeValidator extends TestCase { - - private LongRangeValidator cleanValidator = new LongRangeValidator( - "no values", null, null); - private LongRangeValidator minValidator = new LongRangeValidator( - "no values", 10l, null); - private LongRangeValidator maxValidator = new LongRangeValidator( - "no values", null, 100l); - private LongRangeValidator minMaxValidator = new LongRangeValidator( - "no values", 10l, 100l); - - public void testNullValue() { - assertTrue("Didn't accept null", cleanValidator.isValid(null)); - assertTrue("Didn't accept null", minValidator.isValid(null)); - assertTrue("Didn't accept null", maxValidator.isValid(null)); - assertTrue("Didn't accept null", minMaxValidator.isValid(null)); - } - - public void testMinValue() { - assertTrue("Validator without ranges didn't accept value", - cleanValidator.isValid(-15l)); - assertTrue("Didn't accept valid value", minValidator.isValid(15l)); - assertFalse("Accepted too small value", minValidator.isValid(9l)); - } - - public void testMaxValue() { - assertTrue("Validator without ranges didn't accept value", - cleanValidator.isValid(1120l)); - assertTrue("Didn't accept valid value", maxValidator.isValid(15l)); - assertFalse("Accepted too large value", maxValidator.isValid(120l)); - } - - public void testMinMaxValue() { - assertTrue("Didn't accept valid value", minMaxValidator.isValid(15l)); - assertTrue("Didn't accept valid value", minMaxValidator.isValid(99l)); - assertFalse("Accepted too small value", minMaxValidator.isValid(9l)); - assertFalse("Accepted too large value", minMaxValidator.isValid(110l)); - } -} diff --git a/server/tests/src/com/vaadin/tests/data/validator/TestNullValidator.java b/server/tests/src/com/vaadin/tests/data/validator/TestNullValidator.java deleted file mode 100644 index 0a0634ec8f..0000000000 --- a/server/tests/src/com/vaadin/tests/data/validator/TestNullValidator.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.vaadin.tests.data.validator; - -import junit.framework.TestCase; - -import com.vaadin.data.Validator; -import com.vaadin.data.validator.NullValidator; - -public class TestNullValidator extends TestCase { - - NullValidator notNull = new NullValidator("Null not accepted", false); - NullValidator onlyNull = new NullValidator("Only null accepted", true); - - public void testNullValue() { - try { - notNull.validate(null); - fail("expected null to fail with an exception"); - } catch (Validator.InvalidValueException ex) { - assertEquals("Null not accepted", ex.getMessage()); - } - try { - onlyNull.validate(null); - } catch (Validator.InvalidValueException ex) { - fail("onlyNull should not throw exception for null"); - } - } - - public void testNonNullValue() { - try { - onlyNull.validate("Not a null value"); - fail("expected onlyNull validator to fail with an exception"); - } catch (Validator.InvalidValueException ex) { - assertEquals("Only null accepted", ex.getMessage()); - } - try { - notNull.validate("Not a null value"); - } catch (Validator.InvalidValueException ex) { - fail("notNull should not throw exception for \"Not a null value\""); - } - } -} diff --git a/server/tests/src/com/vaadin/tests/data/validator/TestRegexpValidator.java b/server/tests/src/com/vaadin/tests/data/validator/TestRegexpValidator.java deleted file mode 100644 index bcff224451..0000000000 --- a/server/tests/src/com/vaadin/tests/data/validator/TestRegexpValidator.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.vaadin.tests.data.validator; - -import junit.framework.TestCase; - -import com.vaadin.data.validator.RegexpValidator; - -public class TestRegexpValidator extends TestCase { - - private RegexpValidator completeValidator = new RegexpValidator("pattern", - true, "Complete match validator error"); - private RegexpValidator partialValidator = new RegexpValidator("pattern", - false, "Partial match validator error"); - - public void testRegexpValidatorWithNull() { - assertTrue(completeValidator.isValid(null)); - assertTrue(partialValidator.isValid(null)); - } - - public void testRegexpValidatorWithEmptyString() { - assertTrue(completeValidator.isValid("")); - assertTrue(partialValidator.isValid("")); - } - - public void testCompleteRegexpValidatorWithFaultyString() { - assertFalse(completeValidator.isValid("mismatch")); - assertFalse(completeValidator.isValid("pattern2")); - assertFalse(completeValidator.isValid("1pattern")); - } - - public void testCompleteRegexpValidatorWithOkString() { - assertTrue(completeValidator.isValid("pattern")); - } - - public void testPartialRegexpValidatorWithFaultyString() { - assertFalse(partialValidator.isValid("mismatch")); - } - - public void testPartialRegexpValidatorWithOkString() { - assertTrue(partialValidator.isValid("pattern")); - assertTrue(partialValidator.isValid("1pattern")); - assertTrue(partialValidator.isValid("pattern2")); - assertTrue(partialValidator.isValid("1pattern2")); - } -} diff --git a/server/tests/src/com/vaadin/tests/data/validator/TestShortRangeValidator.java b/server/tests/src/com/vaadin/tests/data/validator/TestShortRangeValidator.java deleted file mode 100644 index b522abb179..0000000000 --- a/server/tests/src/com/vaadin/tests/data/validator/TestShortRangeValidator.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.vaadin.tests.data.validator; - -import junit.framework.TestCase; - -import com.vaadin.data.validator.ShortRangeValidator; - -public class TestShortRangeValidator extends TestCase { - - private ShortRangeValidator cleanValidator = new ShortRangeValidator( - "no values", null, null); - private ShortRangeValidator minValidator = new ShortRangeValidator( - "no values", (short) 10, null); - private ShortRangeValidator maxValidator = new ShortRangeValidator( - "no values", null, (short) 100); - private ShortRangeValidator minMaxValidator = new ShortRangeValidator( - "no values", (short) 10, (short) 100); - - public void testNullValue() { - assertTrue("Didn't accept null", cleanValidator.isValid(null)); - assertTrue("Didn't accept null", minValidator.isValid(null)); - assertTrue("Didn't accept null", maxValidator.isValid(null)); - assertTrue("Didn't accept null", minMaxValidator.isValid(null)); - } - - public void testMinValue() { - assertTrue("Validator without ranges didn't accept value", - cleanValidator.isValid((short) -15)); - assertTrue("Didn't accept valid value", - minValidator.isValid((short) 15)); - assertFalse("Accepted too small value", minValidator.isValid((short) 9)); - } - - public void testMaxValue() { - assertTrue("Validator without ranges didn't accept value", - cleanValidator.isValid((short) 1120)); - assertTrue("Didn't accept valid value", - maxValidator.isValid((short) 15)); - assertFalse("Accepted too large value", - maxValidator.isValid((short) 120)); - } - - public void testMinMaxValue() { - assertTrue("Didn't accept valid value", - minMaxValidator.isValid((short) 15)); - assertTrue("Didn't accept valid value", - minMaxValidator.isValid((short) 99)); - assertFalse("Accepted too small value", - minMaxValidator.isValid((short) 9)); - assertFalse("Accepted too large value", - minMaxValidator.isValid((short) 110)); - } -} diff --git a/server/tests/src/com/vaadin/tests/data/validator/TestStringLengthValidator.java b/server/tests/src/com/vaadin/tests/data/validator/TestStringLengthValidator.java deleted file mode 100644 index 6b4b2b0d51..0000000000 --- a/server/tests/src/com/vaadin/tests/data/validator/TestStringLengthValidator.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.vaadin.tests.data.validator; - -import junit.framework.TestCase; - -import com.vaadin.data.validator.StringLengthValidator; - -public class TestStringLengthValidator extends TestCase { - - private StringLengthValidator validator = new StringLengthValidator("Error"); - private StringLengthValidator validatorNoNull = new StringLengthValidator( - "Error", 1, 5, false); - private StringLengthValidator validatorMinValue = new StringLengthValidator( - "Error", 5, null, true); - private StringLengthValidator validatorMaxValue = new StringLengthValidator( - "Error", null, 15, true); - - public void testValidatorWithNull() { - assertTrue("Didn't accept null", validator.isValid(null)); - assertTrue("Didn't accept null", validatorMinValue.isValid(null)); - } - - public void testValidatorNotAcceptingNull() { - assertFalse("Accepted null", validatorNoNull.isValid(null)); - } - - public void testEmptyString() { - assertTrue("Didn't accept empty String", validator.isValid("")); - assertTrue("Didn't accept empty String", validatorMaxValue.isValid("")); - assertFalse("Accepted empty string even though has lower bound of 1", - validatorNoNull.isValid("")); - assertFalse("Accepted empty string even though has lower bound of 5", - validatorMinValue.isValid("")); - } - - public void testTooLongString() { - assertFalse("Too long string was accepted", - validatorNoNull.isValid("This string is too long")); - assertFalse("Too long string was accepted", - validatorMaxValue.isValid("This string is too long")); - } - - public void testNoUpperBound() { - assertTrue( - "String not accepted even though no upper bound", - validatorMinValue - .isValid("This is a really long string to test that no upper bound exists")); - } - - public void testNoLowerBound() { - assertTrue("Didn't accept short string", validatorMaxValue.isValid("")); - assertTrue("Didn't accept short string", validatorMaxValue.isValid("1")); - } - - public void testStringLengthValidatorWithOkStringLength() { - assertTrue("Didn't accept string of correct length", - validatorNoNull.isValid("OK!")); - assertTrue("Didn't accept string of correct length", - validatorMaxValue.isValid("OK!")); - } - - public void testTooShortStringLength() { - assertFalse("Accepted a string that was too short.", - validatorMinValue.isValid("shot")); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/AbstractBeanContainerListenersTest.java b/server/tests/src/com/vaadin/tests/server/AbstractBeanContainerListenersTest.java new file mode 100644 index 0000000000..b9b4f8025d --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/AbstractBeanContainerListenersTest.java @@ -0,0 +1,16 @@ +package com.vaadin.tests.server; + +import com.vaadin.data.Container.PropertySetChangeEvent; +import com.vaadin.data.Container.PropertySetChangeListener; +import com.vaadin.data.util.BeanItemContainer; +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; + +public class AbstractBeanContainerListenersTest extends + AbstractListenerMethodsTestBase { + public void testPropertySetChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(BeanItemContainer.class, + PropertySetChangeEvent.class, PropertySetChangeListener.class, + new BeanItemContainer( + PropertySetChangeListener.class)); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/AbstractContainerListenersTest.java b/server/tests/src/com/vaadin/tests/server/AbstractContainerListenersTest.java new file mode 100644 index 0000000000..a5c7dc3ab2 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/AbstractContainerListenersTest.java @@ -0,0 +1,21 @@ +package com.vaadin.tests.server; + +import com.vaadin.data.Container.ItemSetChangeEvent; +import com.vaadin.data.Container.ItemSetChangeListener; +import com.vaadin.data.Container.PropertySetChangeEvent; +import com.vaadin.data.Container.PropertySetChangeListener; +import com.vaadin.data.util.IndexedContainer; +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; + +public class AbstractContainerListenersTest extends AbstractListenerMethodsTestBase { + + public void testItemSetChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(IndexedContainer.class, + ItemSetChangeEvent.class, ItemSetChangeListener.class); + } + + public void testPropertySetChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(IndexedContainer.class, + PropertySetChangeEvent.class, PropertySetChangeListener.class); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/AbstractInMemoryContainerListenersTest.java b/server/tests/src/com/vaadin/tests/server/AbstractInMemoryContainerListenersTest.java new file mode 100644 index 0000000000..072998b8e1 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/AbstractInMemoryContainerListenersTest.java @@ -0,0 +1,14 @@ +package com.vaadin.tests.server; + +import com.vaadin.data.Container.ItemSetChangeEvent; +import com.vaadin.data.Container.ItemSetChangeListener; +import com.vaadin.data.util.IndexedContainer; +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; + +public class AbstractInMemoryContainerListenersTest extends + AbstractListenerMethodsTestBase { + public void testItemSetChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(IndexedContainer.class, + ItemSetChangeEvent.class, ItemSetChangeListener.class); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/AbstractPropertyListenersTest.java b/server/tests/src/com/vaadin/tests/server/AbstractPropertyListenersTest.java new file mode 100644 index 0000000000..28e6f7e0a5 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/AbstractPropertyListenersTest.java @@ -0,0 +1,24 @@ +package com.vaadin.tests.server; + +import com.vaadin.data.Property.ReadOnlyStatusChangeEvent; +import com.vaadin.data.Property.ReadOnlyStatusChangeListener; +import com.vaadin.data.Property.ValueChangeEvent; +import com.vaadin.data.Property.ValueChangeListener; +import com.vaadin.data.util.AbstractProperty; +import com.vaadin.data.util.ObjectProperty; +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; + +public class AbstractPropertyListenersTest extends AbstractListenerMethodsTestBase { + public void testValueChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(AbstractProperty.class, + ValueChangeEvent.class, ValueChangeListener.class, + new ObjectProperty("")); + } + + public void testReadOnlyStatusChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(AbstractProperty.class, + ReadOnlyStatusChangeEvent.class, + ReadOnlyStatusChangeListener.class, new ObjectProperty( + "")); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/AssertionsEnabledTest.java b/server/tests/src/com/vaadin/tests/server/AssertionsEnabledTest.java new file mode 100644 index 0000000000..087a7fb0f5 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/AssertionsEnabledTest.java @@ -0,0 +1,33 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server; + +import junit.framework.TestCase; + +public class AssertionsEnabledTest extends TestCase { + public void testAssertionsEnabled() { + boolean assertFailed = false; + try { + assert false; + } catch (AssertionError e) { + assertFailed = true; + } finally { + assertTrue("Unit tests should be run with assertions enabled", + assertFailed); + } + } +} diff --git a/server/tests/src/com/vaadin/tests/server/AtmosphereVersionTest.java b/server/tests/src/com/vaadin/tests/server/AtmosphereVersionTest.java new file mode 100644 index 0000000000..90a0283cda --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/AtmosphereVersionTest.java @@ -0,0 +1,18 @@ +package com.vaadin.tests.server; + +import junit.framework.TestCase; + +import org.atmosphere.util.Version; + +import com.vaadin.server.Constants; + +public class AtmosphereVersionTest extends TestCase { + /** + * Test that the atmosphere version constant matches the version on our + * classpath + */ + public void testAtmosphereVersion() { + assertEquals(Constants.REQUIRED_ATMOSPHERE_RUNTIME_VERSION, + Version.getRawVersion()); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/ClassesSerializableTest.java b/server/tests/src/com/vaadin/tests/server/ClassesSerializableTest.java new file mode 100644 index 0000000000..6e7b778f78 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/ClassesSerializableTest.java @@ -0,0 +1,323 @@ +package com.vaadin.tests.server; + +import java.io.File; +import java.io.IOException; +import java.io.Serializable; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.Enumeration; +import java.util.Iterator; +import java.util.List; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +import junit.framework.TestCase; + +import org.junit.Ignore; +import org.junit.Test; + +public class ClassesSerializableTest extends TestCase { + + /** + * JARs that will be scanned for classes to test, in addition to classpath + * directories. + */ + private static String JAR_PATTERN = ".*vaadin.*\\.jar"; + + private static String[] BASE_PACKAGES = { "com.vaadin" }; + + private static String[] EXCLUDED_PATTERNS = { + "com\\.vaadin\\.demo\\..*", // + "com\\.vaadin\\.external\\.org\\.apache\\.commons\\.fileupload\\..*", // + "com\\.vaadin\\.launcher\\..*", // + "com\\.vaadin\\.client\\..*", // + "com\\.vaadin\\.server\\.widgetsetutils\\..*", // + "com\\.vaadin\\.server\\.themeutils\\..*", // + "com\\.vaadin\\.tests\\..*", // exclude automated tests + "com\\.vaadin\\.tools\\..*", // + "com\\.vaadin\\.ui\\.themes\\..*", // + // exact class level filtering + "com\\.vaadin\\.event\\.FieldEvents", // + "com\\.vaadin\\.event\\.LayoutEvents", // + "com\\.vaadin\\.event\\.MouseEvents", // + "com\\.vaadin\\.event\\.UIEvents", // + "com\\.vaadin\\.server\\.VaadinPortlet", // + "com\\.vaadin\\.server\\.MockServletConfig", // + "com\\.vaadin\\.server\\.MockServletContext", // + "com\\.vaadin\\.server\\.Constants", // + "com\\.vaadin\\.server\\.VaadinServiceClassLoaderUtil", // + "com\\.vaadin\\.server\\.VaadinServiceClassLoaderUtil\\$GetClassLoaderPrivilegedAction", // + "com\\.vaadin\\.server\\.communication\\.FileUploadHandler\\$SimpleMultiPartInputStream", // + "com\\.vaadin\\.server\\.communication\\.PushRequestHandler.*", + "com\\.vaadin\\.server\\.communication\\.PushHandler.*", // PushHandler + "com\\.vaadin\\.server\\.communication\\.DateSerializer", // + "com\\.vaadin\\.server\\.communication\\.JSONSerializer", // + // and its inner classes do not need to be serializable + "com\\.vaadin\\.util\\.SerializerHelper", // fully static + // class level filtering, also affecting nested classes and + // interfaces + "com\\.vaadin\\.server\\.LegacyCommunicationManager.*", // + "com\\.vaadin\\.buildhelpers.*", // + "com\\.vaadin\\.util\\.ReflectTools.*", // + "com\\.vaadin\\.data\\.util\\.ReflectTools.*", // + "com\\.vaadin\\.data\\.util.BeanItemContainerGenerator.*", + "com\\.vaadin\\.data\\.util\\.sqlcontainer\\.connection\\.MockInitialContextFactory", + "com\\.vaadin\\.data\\.util\\.sqlcontainer\\.DataGenerator", + "com\\.vaadin\\.data\\.util\\.sqlcontainer\\.FreeformQueryUtil", + "com\\.vaadin\\.sass.*", // + "com\\.vaadin\\.testbench.*", // + "com\\.vaadin\\.util\\.CurrentInstance\\$1", // + "com\\.vaadin\\.server\\.AbstractClientConnector\\$1", // + "com\\.vaadin\\.server\\.AbstractClientConnector\\$1\\$1", // + "com\\.vaadin\\.server\\.JsonCodec\\$1", // + "com\\.vaadin\\.server\\.communication\\.PushConnection", // + "com\\.vaadin\\.server\\.communication\\.AtmospherePushConnection", // + "com\\.vaadin\\.util\\.ConnectorHelper", // + "com\\.vaadin\\.server\\.VaadinSession\\$FutureAccess", // + "com\\.vaadin\\.external\\..*", // + "com\\.vaadin\\.util\\.WeakValueMap.*", // + }; + + /** + * Tests that all the relevant classes and interfaces under + * {@link #BASE_PACKAGES} implement Serializable. + * + * @throws Exception + */ + public void testClassesSerializable() throws Exception { + List rawClasspathEntries = getRawClasspathEntries(); + + List classes = new ArrayList(); + for (String location : rawClasspathEntries) { + classes.addAll(findServerClasses(location)); + } + + ArrayList> nonSerializableClasses = new ArrayList>(); + for (String className : classes) { + Class cls = Class.forName(className); + // skip annotations and synthetic classes + if (cls.isAnnotation() || cls.isSynthetic()) { + continue; + } + // Don't add classes that have a @Ignore annotation on the class + if (isTestClass(cls)) { + continue; + } + + // report non-serializable classes and interfaces + if (!Serializable.class.isAssignableFrom(cls)) { + if (cls.getSuperclass() == Object.class + && cls.getInterfaces().length == 1) { + // Single interface implementors + Class iface = cls.getInterfaces()[0]; + + if (iface == Runnable.class) { + // Ignore Runnables used with access() + continue; + } else if (iface == Comparator.class) { + // Ignore inline comparators + continue; + } + } + nonSerializableClasses.add(cls); + // TODO easier to read when testing + // System.err.println(cls); + } + } + + // useful failure message including all non-serializable classes and + // interfaces + if (!nonSerializableClasses.isEmpty()) { + String nonSerializableString = ""; + Iterator> it = nonSerializableClasses.iterator(); + while (it.hasNext()) { + Class c = it.next(); + nonSerializableString += ", " + c.getName(); + if (c.isAnonymousClass()) { + nonSerializableString += "(super: "; + nonSerializableString += c.getSuperclass().getName(); + nonSerializableString += ", interfaces: "; + for (Class i : c.getInterfaces()) { + nonSerializableString += i.getName(); + nonSerializableString += ","; + } + nonSerializableString += ")"; + } + } + fail("Serializable not implemented by the following classes and interfaces: " + + nonSerializableString); + } + } + + private boolean isTestClass(Class cls) { + if (cls.getEnclosingClass() != null + && isTestClass(cls.getEnclosingClass())) { + return true; + } + + // Test classes with a @Test annotation on some method + for (Method method : cls.getMethods()) { + if (method.isAnnotationPresent(Test.class)) { + return true; + } + } + + return false; + } + + /** + * Lists all class path entries by splitting the class path string. + * + * Adapted from ClassPathExplorer.getRawClasspathEntries(), but without + * filtering. + * + * @return List of class path segment strings + */ + // + private final static List getRawClasspathEntries() { + // try to keep the order of the classpath + List locations = new ArrayList(); + + String pathSep = System.getProperty("path.separator"); + String classpath = System.getProperty("java.class.path"); + + if (classpath.startsWith("\"")) { + classpath = classpath.substring(1); + } + if (classpath.endsWith("\"")) { + classpath = classpath.substring(0, classpath.length() - 1); + } + + String[] split = classpath.split(pathSep); + for (int i = 0; i < split.length; i++) { + String classpathEntry = split[i]; + locations.add(classpathEntry); + } + + return locations; + } + + /** + * Finds the server side classes/interfaces under a class path entry - + * either a directory or a JAR that matches {@link #JAR_PATTERN}. + * + * Only classes under {@link #BASE_PACKAGES} are considered, and those + * matching {@link #EXCLUDED_PATTERNS} are filtered out. + * + * @param classpathEntry + * @return + * @throws IOException + */ + private List findServerClasses(String classpathEntry) + throws IOException { + Collection classes = new ArrayList(); + + File file = new File(classpathEntry); + if (file.isDirectory()) { + classes = findClassesInDirectory(null, file); + } else if (file.getName().matches(JAR_PATTERN)) { + classes = findClassesInJar(file); + } else { + System.out.println("Ignoring " + classpathEntry); + return Collections.emptyList(); + } + + List filteredClasses = new ArrayList(); + for (String className : classes) { + boolean ok = false; + for (String basePackage : BASE_PACKAGES) { + if (className.startsWith(basePackage + ".")) { + ok = true; + break; + } + } + for (String excludedPrefix : EXCLUDED_PATTERNS) { + if (className.matches(excludedPrefix)) { + ok = false; + break; + } + } + + // Don't add test classes + if (className.contains("Test")) { + ok = false; + } + + if (ok) { + filteredClasses.add(className); + } + } + + return filteredClasses; + } + + /** + * Lists class names (based on .class files) in a JAR file. + * + * @param file + * a valid JAR file + * @return collection of fully qualified class names in the JAR + * @throws IOException + */ + private Collection findClassesInJar(File file) throws IOException { + Collection classes = new ArrayList(); + + JarFile jar = new JarFile(file); + Enumeration e = jar.entries(); + while (e.hasMoreElements()) { + JarEntry entry = e.nextElement(); + if (entry.getName().endsWith(".class")) { + String nameWithoutExtension = entry.getName().replaceAll( + "\\.class", ""); + String className = nameWithoutExtension.replace('/', '.'); + classes.add(className); + } + } + return classes; + } + + /** + * Lists class names (based on .class files) in a directory (a package path + * root). + * + * @param parentPackage + * parent package name or null at root of hierarchy, used by + * recursion + * @param parent + * File representing the directory to scan + * @return collection of fully qualified class names in the directory + */ + private final static Collection findClassesInDirectory( + String parentPackage, File parent) { + if (parent.isHidden() + || parent.getPath().contains(File.separator + ".")) { + return Collections.emptyList(); + } + + if (parentPackage == null) { + parentPackage = ""; + } else { + parentPackage += "."; + } + + Collection classNames = new ArrayList(); + + // add all directories recursively + File[] files = parent.listFiles(); + for (File child : files) { + if (child.isDirectory()) { + classNames.addAll(findClassesInDirectory( + parentPackage + child.getName(), child)); + } else if (child.getName().endsWith(".class")) { + classNames.add(parentPackage.replace(File.separatorChar, '.') + + child.getName().replaceAll("\\.class", "")); + } + } + + return classNames; + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/ClientMethodSerializationTest.java b/server/tests/src/com/vaadin/tests/server/ClientMethodSerializationTest.java new file mode 100644 index 0000000000..da6bc76a0f --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/ClientMethodSerializationTest.java @@ -0,0 +1,115 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.lang.reflect.Method; + +import junit.framework.TestCase; + +import com.vaadin.server.ClientMethodInvocation; +import com.vaadin.server.JavaScriptCallbackHelper; +import com.vaadin.ui.JavaScript.JavaScriptCallbackRpc; +import com.vaadin.util.ReflectTools; + +import elemental.json.Json; +import elemental.json.JsonArray; +import elemental.json.impl.JsonUtil; + +public class ClientMethodSerializationTest extends TestCase { + + private static final Method JAVASCRIPT_CALLBACK_METHOD = ReflectTools + .findMethod(JavaScriptCallbackRpc.class, "call", String.class, + JsonArray.class); + + private static final Method BASIC_PARAMS_CALL_METHOD = ReflectTools + .findMethod(ClientMethodSerializationTest.class, + "basicParamsMethodForTesting", String.class, Integer.class); + + private static final Method NO_PARAMS_CALL_METHOD = ReflectTools + .findMethod(ClientMethodSerializationTest.class, + "noParamsMethodForTesting"); + + public void basicParamsMethodForTesting(String stringParam, + Integer integerParam) { + } + + public void noParamsMethodForTesting() { + } + + /** + * Tests the {@link ClientMethodInvocation} serialization when using + * {@link JavaScriptCallbackHelper#invokeCallback(String, Object...)}. + * #12532 + */ + public void testClientMethodSerialization_WithJSONArray_ContentStaysSame() + throws Exception { + JsonArray originalArray = Json.createArray(); + originalArray.set(0, "callbackParameter1"); + originalArray.set(1, "callBackParameter2"); + originalArray.set(2, "12345"); + ClientMethodInvocation original = new ClientMethodInvocation(null, + "interfaceName", JAVASCRIPT_CALLBACK_METHOD, new Object[] { + "callBackMethodName", originalArray }); + + ClientMethodInvocation copy = (ClientMethodInvocation) serializeAndDeserialize(original); + JsonArray copyArray = (JsonArray) copy.getParameters()[1]; + assertEquals(JsonUtil.stringify(originalArray), + JsonUtil.stringify(copyArray)); + } + + public void testClientMethodSerialization_WithBasicParams_NoChanges() + throws Exception { + String stringParam = "a string 123"; + Integer integerParam = 1234567890; + ClientMethodInvocation original = new ClientMethodInvocation(null, + "interfaceName", BASIC_PARAMS_CALL_METHOD, new Serializable[] { + stringParam, integerParam }); + ClientMethodInvocation copy = (ClientMethodInvocation) serializeAndDeserialize(original); + String copyString = (String) copy.getParameters()[0]; + Integer copyInteger = (Integer) copy.getParameters()[1]; + assertEquals(copyString, stringParam); + assertEquals(copyInteger, integerParam); + } + + public void testClientMethodSerialization_NoParams_NoExceptions() { + ClientMethodInvocation original = new ClientMethodInvocation(null, + "interfaceName", NO_PARAMS_CALL_METHOD, null); + ClientMethodInvocation copy = (ClientMethodInvocation) serializeAndDeserialize(original); + } + + private static Serializable serializeAndDeserialize(Serializable input) { + Serializable output = null; + try { + ByteArrayOutputStream bs = new ByteArrayOutputStream(); + ObjectOutputStream out = new ObjectOutputStream(bs); + out.writeObject(input); + byte[] data = bs.toByteArray(); + ObjectInputStream in = new ObjectInputStream( + new ByteArrayInputStream(data)); + output = (Serializable) in.readObject(); + } catch (Exception e) { + fail("Exception during serialization/deserialization: " + + e.getMessage()); + } + return output; + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/CsrfTokenMissingTest.java b/server/tests/src/com/vaadin/tests/server/CsrfTokenMissingTest.java new file mode 100644 index 0000000000..18fbf70a2a --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/CsrfTokenMissingTest.java @@ -0,0 +1,253 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server; + +import java.util.UUID; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; + +import org.easymock.EasyMock; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.vaadin.server.MockServletConfig; +import com.vaadin.server.ServiceException; +import com.vaadin.server.VaadinService; +import com.vaadin.server.VaadinServlet; +import com.vaadin.server.VaadinServletRequest; +import com.vaadin.server.VaadinServletService; +import com.vaadin.server.VaadinSession; +import com.vaadin.server.communication.ServerRpcHandler.RpcRequest; +import com.vaadin.shared.ApplicationConstants; +import com.vaadin.tests.util.AlwaysLockedVaadinSession; +import com.vaadin.tests.util.MockDeploymentConfiguration; + +import elemental.json.JsonException; + +/** + * Test the actual csrf token validation by the server. + * + * @since + * @author Vaadin Ltd + */ +public class CsrfTokenMissingTest { + + // Dummy fields just to run the test. + private VaadinServlet mockServlet; + + // The mock deployment configuration. + private MockDeploymentConfiguration mockDeploymentConfiguration; + + private VaadinServletService mockService; + + // The mock UI session. + private VaadinSession mockSession; + + // The mock vaadin request. + private VaadinServletRequest vaadinRequest; + + /** + * Initialize the mock servlet and other stuff for our tests. + * + */ + @Before + public void initMockStuff() throws ServiceException, ServletException { + mockServlet = new VaadinServlet(); + mockServlet.init(new MockServletConfig()); + mockDeploymentConfiguration = new MockDeploymentConfiguration(); + + mockService = new VaadinServletService(mockServlet, + mockDeploymentConfiguration); + + mockSession = new AlwaysLockedVaadinSession(mockService); + + vaadinRequest = new VaadinServletRequest( + EasyMock.createMock(HttpServletRequest.class), mockService); + + } + + private enum TokenType { + MISSING, INVALID, VALID + } + + private TokenType tokenType; + + private String invalidToken; + + public String getInvalidToken() { + if (invalidToken == null) { + // Just making sure this will never be in the same format as a valid + // token. + invalidToken = UUID.randomUUID().toString().substring(1); + } + return invalidToken; + } + + private String getValidToken() { + return mockSession.getCsrfToken(); + } + + /* + * Gets the payload with the default token. + */ + private String getPayload() { + switch (tokenType) { + case MISSING: + return getPayload(null); + + case INVALID: + return getPayload(getInvalidToken()); + + case VALID: + return getPayload(getValidToken()); + } + + return null; + } + + /* + * Gets the payload with the specified token. + */ + private String getPayload(String token) { + return "{" + + (token != null ? "\"csrfToken\":" + "\"" + token + "\", " + : "") + + "\"rpc\":[[\"0\",\"com.vaadin.shared.ui.ui.UIServerRpc\",\"resize\",[\"449\",\"1155\",\"1155\",\"449\"]],[\"4\",\"com.vaadin.shared.ui.button.ButtonServerRpc\",\"click\",[{\"clientY\":\"53\", \"clientX\":\"79\", \"shiftKey\":false, \"button\":\"LEFT\", \"ctrlKey\":false, \"type\":\"1\", \"metaKey\":false, \"altKey\":false, \"relativeY\":\"17\", \"relativeX\":\"61\"}]]], \"syncId\":1}"; + } + + /* + * Init the test parameters. + */ + private void initTest(boolean enableSecurity, TokenType tokenType) { + mockDeploymentConfiguration.setXsrfProtectionEnabled(enableSecurity); + this.tokenType = tokenType; + } + + /* + * Create the requets. + */ + private RpcRequest createRequest() { + try { + return new RpcRequest(getPayload(), vaadinRequest); + } catch (JsonException e) { + LOGGER.log(Level.SEVERE, "", e); + + Assert.assertTrue(false); + return null; + } + } + + /* + * Gets whether the token from the request is the default one. + */ + private boolean isDefaultToken(RpcRequest rpcRequest) { + return ApplicationConstants.CSRF_TOKEN_DEFAULT_VALUE.equals(rpcRequest + .getCsrfToken()); + } + + /* + * Gets whether the token from the request is the invalid one. + */ + private boolean isInvalidToken(RpcRequest rpcRequest) { + return getInvalidToken().equals(rpcRequest.getCsrfToken()); + } + + /* + * Gets whether the token from the request is the valid one. + */ + private boolean isValidToken(RpcRequest rpcRequest) { + return getValidToken().equals(rpcRequest.getCsrfToken()); + } + + /* + * Gets whether the token from the request is valid. + */ + private boolean isRequestValid(RpcRequest rpcRequest) { + return VaadinService.isCsrfTokenValid(mockSession, + rpcRequest.getCsrfToken()); + } + + private static Logger LOGGER = Logger + .getLogger(CsrfTokenMissingTest.class.getName()); + static { + LOGGER.setLevel(Level.ALL); + } + + @Test + public void securityOnAndNoToken() { + initTest(true, TokenType.MISSING); + + RpcRequest rpcRequest = createRequest(); + + Assert.assertTrue(isDefaultToken(rpcRequest)); + Assert.assertFalse(isRequestValid(rpcRequest)); + } + + @Test + public void securityOffAndNoToken() { + initTest(false, TokenType.MISSING); + + RpcRequest rpcRequest = createRequest(); + + Assert.assertTrue(isDefaultToken(rpcRequest)); + Assert.assertTrue(isRequestValid(rpcRequest)); + } + + @Test + public void securityOnAndInvalidToken() { + initTest(true, TokenType.INVALID); + + RpcRequest rpcRequest = createRequest(); + + Assert.assertTrue(isInvalidToken(rpcRequest)); + Assert.assertFalse(isRequestValid(rpcRequest)); + } + + @Test + public void securityOffAndInvalidToken() { + initTest(false, TokenType.INVALID); + + RpcRequest rpcRequest = createRequest(); + + Assert.assertTrue(isInvalidToken(rpcRequest)); + Assert.assertTrue(isRequestValid(rpcRequest)); + } + + @Test + public void securityOnAndValidToken() { + initTest(true, TokenType.VALID); + + RpcRequest rpcRequest = createRequest(); + + Assert.assertTrue(isValidToken(rpcRequest)); + Assert.assertTrue(isRequestValid(rpcRequest)); + } + + @Test + public void securityOffAndValidToken() { + initTest(false, TokenType.VALID); + + RpcRequest rpcRequest = createRequest(); + + Assert.assertTrue(isValidToken(rpcRequest)); + Assert.assertTrue(isRequestValid(rpcRequest)); + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/CsrfTokenMissingTestServer.java b/server/tests/src/com/vaadin/tests/server/CsrfTokenMissingTestServer.java deleted file mode 100644 index b127ffe7e5..0000000000 --- a/server/tests/src/com/vaadin/tests/server/CsrfTokenMissingTestServer.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server; - -import java.util.UUID; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; - -import org.easymock.EasyMock; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.vaadin.server.MockServletConfig; -import com.vaadin.server.ServiceException; -import com.vaadin.server.VaadinService; -import com.vaadin.server.VaadinServlet; -import com.vaadin.server.VaadinServletRequest; -import com.vaadin.server.VaadinServletService; -import com.vaadin.server.VaadinSession; -import com.vaadin.server.communication.ServerRpcHandler.RpcRequest; -import com.vaadin.shared.ApplicationConstants; -import com.vaadin.tests.util.AlwaysLockedVaadinSession; -import com.vaadin.tests.util.MockDeploymentConfiguration; - -import elemental.json.JsonException; - -/** - * Test the actual csrf token validation by the server. - * - * @since - * @author Vaadin Ltd - */ -public class CsrfTokenMissingTestServer { - - // Dummy fields just to run the test. - private VaadinServlet mockServlet; - - // The mock deployment configuration. - private MockDeploymentConfiguration mockDeploymentConfiguration; - - private VaadinServletService mockService; - - // The mock UI session. - private VaadinSession mockSession; - - // The mock vaadin request. - private VaadinServletRequest vaadinRequest; - - /** - * Initialize the mock servlet and other stuff for our tests. - * - */ - @Before - public void initMockStuff() throws ServiceException, ServletException { - mockServlet = new VaadinServlet(); - mockServlet.init(new MockServletConfig()); - mockDeploymentConfiguration = new MockDeploymentConfiguration(); - - mockService = new VaadinServletService(mockServlet, - mockDeploymentConfiguration); - - mockSession = new AlwaysLockedVaadinSession(mockService); - - vaadinRequest = new VaadinServletRequest( - EasyMock.createMock(HttpServletRequest.class), mockService); - - } - - private enum TokenType { - MISSING, INVALID, VALID - } - - private TokenType tokenType; - - private String invalidToken; - - public String getInvalidToken() { - if (invalidToken == null) { - // Just making sure this will never be in the same format as a valid - // token. - invalidToken = UUID.randomUUID().toString().substring(1); - } - return invalidToken; - } - - private String getValidToken() { - return mockSession.getCsrfToken(); - } - - /* - * Gets the payload with the default token. - */ - private String getPayload() { - switch (tokenType) { - case MISSING: - return getPayload(null); - - case INVALID: - return getPayload(getInvalidToken()); - - case VALID: - return getPayload(getValidToken()); - } - - return null; - } - - /* - * Gets the payload with the specified token. - */ - private String getPayload(String token) { - return "{" - + (token != null ? "\"csrfToken\":" + "\"" + token + "\", " - : "") - + "\"rpc\":[[\"0\",\"com.vaadin.shared.ui.ui.UIServerRpc\",\"resize\",[\"449\",\"1155\",\"1155\",\"449\"]],[\"4\",\"com.vaadin.shared.ui.button.ButtonServerRpc\",\"click\",[{\"clientY\":\"53\", \"clientX\":\"79\", \"shiftKey\":false, \"button\":\"LEFT\", \"ctrlKey\":false, \"type\":\"1\", \"metaKey\":false, \"altKey\":false, \"relativeY\":\"17\", \"relativeX\":\"61\"}]]], \"syncId\":1}"; - } - - /* - * Init the test parameters. - */ - private void initTest(boolean enableSecurity, TokenType tokenType) { - mockDeploymentConfiguration.setXsrfProtectionEnabled(enableSecurity); - this.tokenType = tokenType; - } - - /* - * Create the requets. - */ - private RpcRequest createRequest() { - try { - return new RpcRequest(getPayload(), vaadinRequest); - } catch (JsonException e) { - LOGGER.log(Level.SEVERE, "", e); - - Assert.assertTrue(false); - return null; - } - } - - /* - * Gets whether the token from the request is the default one. - */ - private boolean isDefaultToken(RpcRequest rpcRequest) { - return ApplicationConstants.CSRF_TOKEN_DEFAULT_VALUE.equals(rpcRequest - .getCsrfToken()); - } - - /* - * Gets whether the token from the request is the invalid one. - */ - private boolean isInvalidToken(RpcRequest rpcRequest) { - return getInvalidToken().equals(rpcRequest.getCsrfToken()); - } - - /* - * Gets whether the token from the request is the valid one. - */ - private boolean isValidToken(RpcRequest rpcRequest) { - return getValidToken().equals(rpcRequest.getCsrfToken()); - } - - /* - * Gets whether the token from the request is valid. - */ - private boolean isRequestValid(RpcRequest rpcRequest) { - return VaadinService.isCsrfTokenValid(mockSession, - rpcRequest.getCsrfToken()); - } - - private static Logger LOGGER = Logger - .getLogger(CsrfTokenMissingTestServer.class.getName()); - static { - LOGGER.setLevel(Level.ALL); - } - - @Test - public void securityOnAndNoToken() { - initTest(true, TokenType.MISSING); - - RpcRequest rpcRequest = createRequest(); - - Assert.assertTrue(isDefaultToken(rpcRequest)); - Assert.assertFalse(isRequestValid(rpcRequest)); - } - - @Test - public void securityOffAndNoToken() { - initTest(false, TokenType.MISSING); - - RpcRequest rpcRequest = createRequest(); - - Assert.assertTrue(isDefaultToken(rpcRequest)); - Assert.assertTrue(isRequestValid(rpcRequest)); - } - - @Test - public void securityOnAndInvalidToken() { - initTest(true, TokenType.INVALID); - - RpcRequest rpcRequest = createRequest(); - - Assert.assertTrue(isInvalidToken(rpcRequest)); - Assert.assertFalse(isRequestValid(rpcRequest)); - } - - @Test - public void securityOffAndInvalidToken() { - initTest(false, TokenType.INVALID); - - RpcRequest rpcRequest = createRequest(); - - Assert.assertTrue(isInvalidToken(rpcRequest)); - Assert.assertTrue(isRequestValid(rpcRequest)); - } - - @Test - public void securityOnAndValidToken() { - initTest(true, TokenType.VALID); - - RpcRequest rpcRequest = createRequest(); - - Assert.assertTrue(isValidToken(rpcRequest)); - Assert.assertTrue(isRequestValid(rpcRequest)); - } - - @Test - public void securityOffAndValidToken() { - initTest(false, TokenType.VALID); - - RpcRequest rpcRequest = createRequest(); - - Assert.assertTrue(isValidToken(rpcRequest)); - Assert.assertTrue(isRequestValid(rpcRequest)); - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/EventRouterTest.java b/server/tests/src/com/vaadin/tests/server/EventRouterTest.java new file mode 100644 index 0000000000..67f39d301d --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/EventRouterTest.java @@ -0,0 +1,39 @@ +package com.vaadin.tests.server; + +import junit.framework.TestCase; + +import com.vaadin.data.Property.ValueChangeEvent; +import com.vaadin.data.Property.ValueChangeListener; +import com.vaadin.ui.TextField; + +public class EventRouterTest extends TestCase { + + int innerListenerCalls = 0; + + public void testAddInEventListener() { + final TextField tf = new TextField(); + + final ValueChangeListener outer = new ValueChangeListener() { + + @Override + public void valueChange(ValueChangeEvent event) { + ValueChangeListener inner = new ValueChangeListener() { + + @Override + public void valueChange(ValueChangeEvent event) { + innerListenerCalls++; + System.out.println("The inner listener was called"); + } + }; + + tf.addListener(inner); + } + }; + + tf.addListener(outer); + tf.setValue("abc"); // No inner listener calls, adds one inner + tf.setValue("def"); // One inner listener call, adds one inner + tf.setValue("ghi"); // Two inner listener calls, adds one inner + assert (innerListenerCalls == 3); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/FileTypeResolverTest.java b/server/tests/src/com/vaadin/tests/server/FileTypeResolverTest.java new file mode 100644 index 0000000000..3c68e86afa --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/FileTypeResolverTest.java @@ -0,0 +1,79 @@ +package com.vaadin.tests.server; + +import java.io.File; + +import junit.framework.TestCase; + +import com.vaadin.util.FileTypeResolver; + +public class FileTypeResolverTest extends TestCase { + + private static final String FLASH_MIME_TYPE = "application/x-shockwave-flash"; + private static final String TEXT_MIME_TYPE = "text/plain"; + private static final String HTML_MIME_TYPE = "text/html"; + + public void testMimeTypes() { + File plainFlash = new File("MyFlash.swf"); + File plainText = new File("/a/b/MyFlash.txt"); + File plainHtml = new File("c:\\MyFlash.html"); + + // Flash + assertEquals( + FileTypeResolver.getMIMEType(plainFlash.getAbsolutePath()), + FLASH_MIME_TYPE); + assertEquals( + FileTypeResolver.getMIMEType(plainFlash.getAbsolutePath() + + "?param1=value1"), FLASH_MIME_TYPE); + assertEquals( + FileTypeResolver.getMIMEType(plainFlash.getAbsolutePath() + + "?param1=value1¶m2=value2"), FLASH_MIME_TYPE); + + // Plain text + assertEquals(FileTypeResolver.getMIMEType(plainText.getAbsolutePath()), + TEXT_MIME_TYPE); + assertEquals( + FileTypeResolver.getMIMEType(plainText.getAbsolutePath() + + "?param1=value1"), TEXT_MIME_TYPE); + assertEquals( + FileTypeResolver.getMIMEType(plainText.getAbsolutePath() + + "?param1=value1¶m2=value2"), TEXT_MIME_TYPE); + + // Plain text + assertEquals(FileTypeResolver.getMIMEType(plainHtml.getAbsolutePath()), + HTML_MIME_TYPE); + assertEquals( + FileTypeResolver.getMIMEType(plainHtml.getAbsolutePath() + + "?param1=value1"), HTML_MIME_TYPE); + assertEquals( + FileTypeResolver.getMIMEType(plainHtml.getAbsolutePath() + + "?param1=value1¶m2=value2"), HTML_MIME_TYPE); + + // Filename missing + assertEquals(FileTypeResolver.DEFAULT_MIME_TYPE, + FileTypeResolver.getMIMEType("")); + assertEquals(FileTypeResolver.DEFAULT_MIME_TYPE, + FileTypeResolver.getMIMEType("?param1")); + + } + + public void testExtensionCase() { + assertEquals("image/jpeg", FileTypeResolver.getMIMEType("abc.jpg")); + assertEquals("image/jpeg", FileTypeResolver.getMIMEType("abc.jPg")); + assertEquals("image/jpeg", FileTypeResolver.getMIMEType("abc.JPG")); + assertEquals("image/jpeg", FileTypeResolver.getMIMEType("abc.JPEG")); + assertEquals("image/jpeg", FileTypeResolver.getMIMEType("abc.Jpeg")); + assertEquals("image/jpeg", FileTypeResolver.getMIMEType("abc.JPE")); + } + + public void testCustomMimeType() { + assertEquals(FileTypeResolver.DEFAULT_MIME_TYPE, + FileTypeResolver.getMIMEType("vaadin.foo")); + + FileTypeResolver.addExtension("foo", "Vaadin Foo/Bar"); + FileTypeResolver.addExtension("FOO2", "Vaadin Foo/Bar2"); + assertEquals("Vaadin Foo/Bar", + FileTypeResolver.getMIMEType("vaadin.foo")); + assertEquals("Vaadin Foo/Bar2", + FileTypeResolver.getMIMEType("vaadin.Foo2")); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/IndexedContainerListeners.java b/server/tests/src/com/vaadin/tests/server/IndexedContainerListeners.java deleted file mode 100644 index 8334c7f183..0000000000 --- a/server/tests/src/com/vaadin/tests/server/IndexedContainerListeners.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.vaadin.tests.server; - -import com.vaadin.data.Container.PropertySetChangeEvent; -import com.vaadin.data.Container.PropertySetChangeListener; -import com.vaadin.data.Property.ValueChangeEvent; -import com.vaadin.data.Property.ValueChangeListener; -import com.vaadin.data.util.IndexedContainer; -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; - -public class IndexedContainerListeners extends AbstractListenerMethodsTest { - public void testValueChangeListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(IndexedContainer.class, - ValueChangeEvent.class, ValueChangeListener.class); - } - - public void testPropertySetChangeListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(IndexedContainer.class, - PropertySetChangeEvent.class, PropertySetChangeListener.class); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/IndexedContainerListenersTest.java b/server/tests/src/com/vaadin/tests/server/IndexedContainerListenersTest.java new file mode 100644 index 0000000000..2e1fa83540 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/IndexedContainerListenersTest.java @@ -0,0 +1,20 @@ +package com.vaadin.tests.server; + +import com.vaadin.data.Container.PropertySetChangeEvent; +import com.vaadin.data.Container.PropertySetChangeListener; +import com.vaadin.data.Property.ValueChangeEvent; +import com.vaadin.data.Property.ValueChangeListener; +import com.vaadin.data.util.IndexedContainer; +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; + +public class IndexedContainerListenersTest extends AbstractListenerMethodsTestBase { + public void testValueChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(IndexedContainer.class, + ValueChangeEvent.class, ValueChangeListener.class); + } + + public void testPropertySetChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(IndexedContainer.class, + PropertySetChangeEvent.class, PropertySetChangeListener.class); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/KeyMapperTest.java b/server/tests/src/com/vaadin/tests/server/KeyMapperTest.java new file mode 100644 index 0000000000..d632e65c9f --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/KeyMapperTest.java @@ -0,0 +1,102 @@ +package com.vaadin.tests.server; + +import java.lang.reflect.Field; +import java.util.HashMap; + +import junit.framework.TestCase; + +import com.vaadin.server.KeyMapper; + +public class KeyMapperTest extends TestCase { + + public void testAdd() { + KeyMapper mapper = new KeyMapper(); + Object o1 = new Object(); + Object o2 = new Object(); + Object o3 = new Object(); + + // Create new ids + String key1 = mapper.key(o1); + String key2 = mapper.key(o2); + String key3 = mapper.key(o3); + + assertEquals(mapper.get(key1), o1); + assertEquals(mapper.get(key2), o2); + assertEquals(mapper.get(key3), o3); + assertNotSame(key1, key2); + assertNotSame(key1, key3); + assertNotSame(key2, key3); + + assertSize(mapper, 3); + + // Key should not add if there already is a mapping + assertEquals(mapper.key(o3), key3); + assertSize(mapper, 3); + + // Remove -> add should return a new key + mapper.remove(o1); + String newkey1 = mapper.key(o1); + assertNotSame(key1, newkey1); + + } + + public void testRemoveAll() { + KeyMapper mapper = new KeyMapper(); + Object o1 = new Object(); + Object o2 = new Object(); + Object o3 = new Object(); + + // Create new ids + mapper.key(o1); + mapper.key(o2); + mapper.key(o3); + + assertSize(mapper, 3); + mapper.removeAll(); + assertSize(mapper, 0); + + } + + public void testRemove() { + KeyMapper mapper = new KeyMapper(); + Object o1 = new Object(); + Object o2 = new Object(); + Object o3 = new Object(); + + // Create new ids + mapper.key(o1); + mapper.key(o2); + mapper.key(o3); + + assertSize(mapper, 3); + mapper.remove(o1); + assertSize(mapper, 2); + mapper.key(o1); + assertSize(mapper, 3); + mapper.remove(o1); + assertSize(mapper, 2); + + mapper.remove(o2); + mapper.remove(o3); + assertSize(mapper, 0); + + } + + private void assertSize(KeyMapper mapper, int i) { + try { + Field f1 = KeyMapper.class.getDeclaredField("objectKeyMap"); + Field f2 = KeyMapper.class.getDeclaredField("keyObjectMap"); + f1.setAccessible(true); + f2.setAccessible(true); + + HashMap h1 = (HashMap) f1.get(mapper); + HashMap h2 = (HashMap) f2.get(mapper); + + assertEquals(i, h1.size()); + assertEquals(i, h2.size()); + } catch (Throwable t) { + t.printStackTrace(); + fail(); + } + } +} diff --git a/server/tests/src/com/vaadin/tests/server/MimeTypesTest.java b/server/tests/src/com/vaadin/tests/server/MimeTypesTest.java new file mode 100644 index 0000000000..36007fae17 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/MimeTypesTest.java @@ -0,0 +1,17 @@ +package com.vaadin.tests.server; + +import junit.framework.TestCase; + +import com.vaadin.server.ClassResource; +import com.vaadin.ui.Embedded; + +public class MimeTypesTest extends TestCase { + + public void testEmbeddedPDF() { + Embedded e = new Embedded("A pdf", new ClassResource("file.pddf")); + assertEquals("Invalid mimetype", "application/octet-stream", + e.getMimeType()); + e = new Embedded("A pdf", new ClassResource("file.pdf")); + assertEquals("Invalid mimetype", "application/pdf", e.getMimeType()); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/PropertyFormatterTest.java b/server/tests/src/com/vaadin/tests/server/PropertyFormatterTest.java new file mode 100644 index 0000000000..6563556a4e --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/PropertyFormatterTest.java @@ -0,0 +1,75 @@ +package com.vaadin.tests.server; + +import java.util.Date; + +import junit.framework.TestCase; + +import org.junit.Test; + +import com.vaadin.data.util.ObjectProperty; +import com.vaadin.data.util.PropertyFormatter; + +@SuppressWarnings("unchecked") +public class PropertyFormatterTest extends TestCase { + + class TestFormatter extends PropertyFormatter { + + @Override + public String format(Object value) { + boolean isCorrectType = getExpectedClass().isAssignableFrom( + value.getClass()); + assertTrue(isCorrectType); + return "FOO"; + } + + @Override + public Object parse(String formattedValue) throws Exception { + return getExpectedClass().newInstance(); + } + } + + @SuppressWarnings("rawtypes") + private Class expectedClass; + + @SuppressWarnings("rawtypes") + private Class getExpectedClass() { + return expectedClass; + } + + /** + * The object passed to format should be same as property's type. + * + * @throws IllegalAccessException + * @throws InstantiationException + */ + @Test + @SuppressWarnings({ "rawtypes" }) + public void testCorrectTypeForFormat() throws InstantiationException, + IllegalAccessException { + Class[] testedTypes = new Class[] { Integer.class, Boolean.class, + Double.class, String.class, Date.class }; + Object[] testValues = new Object[] { new Integer(3), Boolean.FALSE, + new Double(3.3), "bar", new Date() }; + + int i = 0; + for (Class class1 : testedTypes) { + expectedClass = class1; + + TestFormatter formatter = new TestFormatter(); + + // Should just return null, without formatting + Object value = formatter.getValue(); + + // test with property which value is null + formatter.setPropertyDataSource(new ObjectProperty(null, + expectedClass)); + formatter.getValue(); // calls format + + // test with a value + formatter.setPropertyDataSource(new ObjectProperty(testValues[i++], + expectedClass)); + formatter.getValue(); // calls format + } + + } +} diff --git a/server/tests/src/com/vaadin/tests/server/PropertysetItemListeners.java b/server/tests/src/com/vaadin/tests/server/PropertysetItemListeners.java deleted file mode 100644 index d493f22779..0000000000 --- a/server/tests/src/com/vaadin/tests/server/PropertysetItemListeners.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.vaadin.tests.server; - -import com.vaadin.data.Item.PropertySetChangeEvent; -import com.vaadin.data.Item.PropertySetChangeListener; -import com.vaadin.data.util.PropertysetItem; -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; - -public class PropertysetItemListeners extends AbstractListenerMethodsTest { - public void testPropertySetChangeListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(PropertysetItem.class, - PropertySetChangeEvent.class, PropertySetChangeListener.class); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/PropertysetItemListenersTest.java b/server/tests/src/com/vaadin/tests/server/PropertysetItemListenersTest.java new file mode 100644 index 0000000000..7edaa2826a --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/PropertysetItemListenersTest.java @@ -0,0 +1,13 @@ +package com.vaadin.tests.server; + +import com.vaadin.data.Item.PropertySetChangeEvent; +import com.vaadin.data.Item.PropertySetChangeListener; +import com.vaadin.data.util.PropertysetItem; +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; + +public class PropertysetItemListenersTest extends AbstractListenerMethodsTestBase { + public void testPropertySetChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(PropertysetItem.class, + PropertySetChangeEvent.class, PropertySetChangeListener.class); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/SerializationTest.java b/server/tests/src/com/vaadin/tests/server/SerializationTest.java new file mode 100644 index 0000000000..4de30e579e --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/SerializationTest.java @@ -0,0 +1,139 @@ +package com.vaadin.tests.server; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; + +import junit.framework.TestCase; + +import com.vaadin.data.Item; +import com.vaadin.data.Property; +import com.vaadin.data.util.IndexedContainer; +import com.vaadin.data.util.MethodProperty; +import com.vaadin.data.validator.RegexpValidator; +import com.vaadin.server.VaadinSession; +import com.vaadin.ui.Form; + +public class SerializationTest extends TestCase { + + public void testValidators() throws Exception { + RegexpValidator validator = new RegexpValidator(".*", "Error"); + validator.validate("aaa"); + RegexpValidator validator2 = serializeAndDeserialize(validator); + validator2.validate("aaa"); + } + + public void testForm() throws Exception { + Form f = new Form(); + String propertyId = "My property"; + f.addItemProperty(propertyId, new MethodProperty(new Data(), + "dummyGetterAndSetter")); + f.replaceWithSelect(propertyId, new Object[] { "a", "b", null }, + new String[] { "Item a", "ITem b", "Null item" }); + + serializeAndDeserialize(f); + + } + + public void testIndedexContainerItemIds() throws Exception { + IndexedContainer ic = new IndexedContainer(); + ic.addContainerProperty("prop1", String.class, null); + Object id = ic.addItem(); + ic.getItem(id).getItemProperty("prop1").setValue("1"); + + Item item2 = ic.addItem("item2"); + item2.getItemProperty("prop1").setValue("2"); + + serializeAndDeserialize(ic); + } + + public void testMethodPropertyGetter() throws Exception { + MethodProperty mp = new MethodProperty(new Data(), + "dummyGetter"); + serializeAndDeserialize(mp); + } + + public void testMethodPropertyGetterAndSetter() throws Exception { + MethodProperty mp = new MethodProperty(new Data(), + "dummyGetterAndSetter"); + serializeAndDeserialize(mp); + } + + public void testMethodPropertyInt() throws Exception { + MethodProperty mp = new MethodProperty(new Data(), + "dummyInt"); + serializeAndDeserialize(mp); + } + + public void testVaadinSession() throws Exception { + VaadinSession session = new VaadinSession(null); + + session = serializeAndDeserialize(session); + + assertNotNull( + "Pending access queue was not recreated after deserialization", + session.getPendingAccessQueue()); + } + + private static S serializeAndDeserialize(S s) + throws IOException, ClassNotFoundException { + // Serialize and deserialize + + ByteArrayOutputStream bs = new ByteArrayOutputStream(); + ObjectOutputStream out = new ObjectOutputStream(bs); + out.writeObject(s); + byte[] data = bs.toByteArray(); + ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream( + data)); + @SuppressWarnings("unchecked") + S s2 = (S) in.readObject(); + + // using special toString(Object) method to avoid calling + // Property.toString(), which will be temporarily disabled + // TODO This is hilariously broken (#12723) + if (s.equals(s2)) { + System.out.println(toString(s) + " equals " + toString(s2)); + } else { + System.out.println(toString(s) + " does NOT equal " + toString(s2)); + } + + return s2; + } + + private static String toString(Object o) { + if (o instanceof Property) { + return String.valueOf(((Property) o).getValue()); + } else { + return String.valueOf(o); + } + } + + public static class Data implements Serializable { + private String dummyGetter; + private String dummyGetterAndSetter; + private int dummyInt; + + public String getDummyGetterAndSetter() { + return dummyGetterAndSetter; + } + + public void setDummyGetterAndSetter(String dummyGetterAndSetter) { + this.dummyGetterAndSetter = dummyGetterAndSetter; + } + + public int getDummyInt() { + return dummyInt; + } + + public void setDummyInt(int dummyInt) { + this.dummyInt = dummyInt; + } + + public String getDummyGetter() { + return dummyGetter; + } + } +} diff --git a/server/tests/src/com/vaadin/tests/server/SimpleMultiPartInputStreamTest.java b/server/tests/src/com/vaadin/tests/server/SimpleMultiPartInputStreamTest.java new file mode 100644 index 0000000000..04e621d5d2 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/SimpleMultiPartInputStreamTest.java @@ -0,0 +1,138 @@ +package com.vaadin.tests.server; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Arrays; + +import junit.framework.TestCase; + +import com.vaadin.server.communication.FileUploadHandler.SimpleMultiPartInputStream; + +public class SimpleMultiPartInputStreamTest extends TestCase { + + /** + * Check that the output for a given stream until boundary is as expected. + * + * @param input + * @param boundary + * @param expected + * @throws Exception + */ + protected void checkBoundaryDetection(byte[] input, String boundary, + byte[] expected) throws Exception { + ByteArrayInputStream bais = new ByteArrayInputStream(input); + SimpleMultiPartInputStream smpis = new SimpleMultiPartInputStream(bais, + boundary); + ByteArrayOutputStream resultStream = new ByteArrayOutputStream(); + int outbyte; + try { + while ((outbyte = smpis.read()) != -1) { + resultStream.write(outbyte); + } + } catch (IOException e) { + throw new IOException(e.getMessage() + "; expected " + + new String(expected) + " but got " + + resultStream.toString()); + } + if (!Arrays.equals(expected, resultStream.toByteArray())) { + throw new Exception("Mismatch: expected " + new String(expected) + + " but got " + resultStream.toString()); + } + } + + protected void checkBoundaryDetection(String input, String boundary, + String expected) throws Exception { + checkBoundaryDetection(input.getBytes(), boundary, expected.getBytes()); + } + + public void testSingleByteBoundaryAtEnd() throws Exception { + checkBoundaryDetection("xyz123" + getFullBoundary("a"), "a", "xyz123"); + } + + public void testSingleByteBoundaryInMiddle() throws Exception { + checkBoundaryDetection("xyz" + getFullBoundary("a") + "123", "a", "xyz"); + } + + public void testCorrectBoundaryAtEnd() throws Exception { + checkBoundaryDetection("xyz123" + getFullBoundary("abc"), "abc", + "xyz123"); + } + + public void testCorrectBoundaryNearEnd() throws Exception { + checkBoundaryDetection("xyz123" + getFullBoundary("abc") + "de", "abc", + "xyz123"); + } + + public void testCorrectBoundaryAtBeginning() throws Exception { + checkBoundaryDetection(getFullBoundary("abc") + "xyz123", "abc", ""); + } + + public void testRepeatingCharacterBoundary() throws Exception { + checkBoundaryDetection(getFullBoundary("aa") + "xyz123", "aa", ""); + checkBoundaryDetection("axyz" + getFullBoundary("aa") + "123", "aa", + "axyz"); + checkBoundaryDetection("xyz123" + getFullBoundary("aa"), "aa", "xyz123"); + } + + /** + * Note, the boundary in this test is invalid. Boundary strings don't + * contain CR/LF. + * + */ + // public void testRepeatingNewlineBoundary() throws Exception { + // checkBoundaryDetection("1234567890" + getFullBoundary("\n\n") + // + "1234567890", "\n\n", ""); + // } + + public void testRepeatingStringBoundary() throws Exception { + checkBoundaryDetection(getFullBoundary("abab") + "xyz123", "abab", ""); + checkBoundaryDetection("abaxyz" + getFullBoundary("abab") + "123", + "abab", "abaxyz"); + checkBoundaryDetection("xyz123" + getFullBoundary("abab"), "abab", + "xyz123"); + } + + public void testOverlappingBoundary() throws Exception { + checkBoundaryDetection("abc" + getFullBoundary("abcabd") + "xyz123", + "abcabd", "abc"); + checkBoundaryDetection("xyzabc" + getFullBoundary("abcabd") + "123", + "abcabd", "xyzabc"); + checkBoundaryDetection("xyz123abc" + getFullBoundary("abcabd"), + "abcabd", "xyz123abc"); + } + + /* + * TODO fix these tests, they don't do what their method name says. + */ + + // public void testNoBoundaryInInput() throws Exception { + // try { + // checkBoundaryDetection("xyz123", "abc", "xyz123"); + // fail(); + // } catch (IOException e) { + // } + // } + // + // public void testPartialBoundaryAtInputEnd() throws Exception { + // try { + // // This should lead to IOException (stream end), not AIOOBE + // checkBoundaryDetection("xyz123ab", "abc", "xyz123ab"); + // fail(); + // } catch (IOException e) { + // } + // } + // + // public void testPartialBoundaryAtInputBeginning() throws Exception { + // try { + // checkBoundaryDetection("abxyz123", "abc", "abxyz123"); + // fail(); + // } catch (IOException e) { + // } + // } + + public static String getFullBoundary(String str) { + return "\r\n--" + str + "--"; + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/StreamResourceTest.java b/server/tests/src/com/vaadin/tests/server/StreamResourceTest.java new file mode 100644 index 0000000000..4971f556db --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/StreamResourceTest.java @@ -0,0 +1,55 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server; + +import org.easymock.EasyMock; +import org.junit.Assert; +import org.junit.Test; + +import com.vaadin.server.StreamResource; +import com.vaadin.server.StreamResource.StreamSource; + +/** + * + * @author Vaadin Ltd + */ +public class StreamResourceTest { + + @Test + public void testEqualsWithNullFields() { + StreamResource resource1 = new StreamResource(null, null); + StreamResource resource2 = new StreamResource(null, null); + + Assert.assertEquals(resource1, resource2); + } + + @Test + public void testNotEqualsWithNullFields() { + StreamResource resource1 = new StreamResource(null, null); + StreamResource resource2 = new StreamResource( + EasyMock.createMock(StreamSource.class), ""); + + Assert.assertNotEquals(resource1, resource2); + } + + @Test + public void testHashCodeForNullFields() { + StreamResource resource = new StreamResource(null, null); + // No NPE + resource.hashCode(); + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/StreamVariableMappingTest.java b/server/tests/src/com/vaadin/tests/server/StreamVariableMappingTest.java new file mode 100644 index 0000000000..e15e722199 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/StreamVariableMappingTest.java @@ -0,0 +1,90 @@ +package com.vaadin.tests.server; + +import junit.framework.TestCase; + +import org.easymock.EasyMock; + +import com.vaadin.server.LegacyCommunicationManager; +import com.vaadin.server.MockServletConfig; +import com.vaadin.server.StreamVariable; +import com.vaadin.server.VaadinRequest; +import com.vaadin.server.VaadinServlet; +import com.vaadin.server.VaadinServletService; +import com.vaadin.server.VaadinSession; +import com.vaadin.tests.util.AlwaysLockedVaadinSession; +import com.vaadin.tests.util.MockDeploymentConfiguration; +import com.vaadin.ui.ConnectorTracker; +import com.vaadin.ui.UI; +import com.vaadin.ui.Upload; + +public class StreamVariableMappingTest extends TestCase { + private static final String variableName = "myName"; + + private Upload owner; + private StreamVariable streamVariable; + + private LegacyCommunicationManager cm; + + @Override + protected void setUp() throws Exception { + final VaadinSession application = new AlwaysLockedVaadinSession(null); + final UI uI = new UI() { + @Override + protected void init(VaadinRequest request) { + // TODO Auto-generated method stub + + } + + @Override + public VaadinSession getSession() { + return application; + } + }; + owner = new Upload() { + @Override + public UI getUI() { + return uI; + } + }; + streamVariable = EasyMock.createMock(StreamVariable.class); + cm = createCommunicationManager(); + + super.setUp(); + } + + public void testAddStreamVariable() { + owner.getUI().getConnectorTracker().registerConnector(owner); + String targetUrl = cm.getStreamVariableTargetUrl(owner, variableName, + streamVariable); + assertTrue(targetUrl.startsWith("app://APP/UPLOAD/-1/" + + owner.getConnectorId() + "/myName/")); + + ConnectorTracker tracker = owner.getUI().getConnectorTracker(); + StreamVariable streamVariable2 = tracker.getStreamVariable( + owner.getConnectorId(), variableName); + assertSame(streamVariable, streamVariable2); + } + + public void testRemoveVariable() { + ConnectorTracker tracker = owner.getUI().getConnectorTracker(); + tracker.registerConnector(owner); + cm.getStreamVariableTargetUrl(owner, variableName, streamVariable); + assertNotNull(tracker.getStreamVariable(owner.getConnectorId(), + variableName)); + + tracker.cleanStreamVariable(owner.getConnectorId(), variableName); + assertNull(tracker.getStreamVariable(owner.getConnectorId(), + variableName)); + } + + private LegacyCommunicationManager createCommunicationManager() + throws Exception { + VaadinServlet servlet = new VaadinServlet(); + servlet.init(new MockServletConfig()); + VaadinServletService vss = new VaadinServletService(servlet, + new MockDeploymentConfiguration()); + servlet.init(new MockServletConfig()); + return new LegacyCommunicationManager( + new AlwaysLockedVaadinSession(vss)); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/TestAbstractBeanContainerListeners.java b/server/tests/src/com/vaadin/tests/server/TestAbstractBeanContainerListeners.java deleted file mode 100644 index 0d8433d1c6..0000000000 --- a/server/tests/src/com/vaadin/tests/server/TestAbstractBeanContainerListeners.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.vaadin.tests.server; - -import com.vaadin.data.Container.PropertySetChangeEvent; -import com.vaadin.data.Container.PropertySetChangeListener; -import com.vaadin.data.util.BeanItemContainer; -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; - -public class TestAbstractBeanContainerListeners extends - AbstractListenerMethodsTest { - public void testPropertySetChangeListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(BeanItemContainer.class, - PropertySetChangeEvent.class, PropertySetChangeListener.class, - new BeanItemContainer( - PropertySetChangeListener.class)); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/TestAbstractContainerListeners.java b/server/tests/src/com/vaadin/tests/server/TestAbstractContainerListeners.java deleted file mode 100644 index b63e4f809a..0000000000 --- a/server/tests/src/com/vaadin/tests/server/TestAbstractContainerListeners.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.vaadin.tests.server; - -import com.vaadin.data.Container.ItemSetChangeEvent; -import com.vaadin.data.Container.ItemSetChangeListener; -import com.vaadin.data.Container.PropertySetChangeEvent; -import com.vaadin.data.Container.PropertySetChangeListener; -import com.vaadin.data.util.IndexedContainer; -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; - -public class TestAbstractContainerListeners extends AbstractListenerMethodsTest { - - public void testItemSetChangeListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(IndexedContainer.class, - ItemSetChangeEvent.class, ItemSetChangeListener.class); - } - - public void testPropertySetChangeListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(IndexedContainer.class, - PropertySetChangeEvent.class, PropertySetChangeListener.class); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/TestAbstractInMemoryContainerListeners.java b/server/tests/src/com/vaadin/tests/server/TestAbstractInMemoryContainerListeners.java deleted file mode 100644 index a8e2a4aa2a..0000000000 --- a/server/tests/src/com/vaadin/tests/server/TestAbstractInMemoryContainerListeners.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.vaadin.tests.server; - -import com.vaadin.data.Container.ItemSetChangeEvent; -import com.vaadin.data.Container.ItemSetChangeListener; -import com.vaadin.data.util.IndexedContainer; -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; - -public class TestAbstractInMemoryContainerListeners extends - AbstractListenerMethodsTest { - public void testItemSetChangeListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(IndexedContainer.class, - ItemSetChangeEvent.class, ItemSetChangeListener.class); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/TestAbstractPropertyListeners.java b/server/tests/src/com/vaadin/tests/server/TestAbstractPropertyListeners.java deleted file mode 100644 index a1d01d1930..0000000000 --- a/server/tests/src/com/vaadin/tests/server/TestAbstractPropertyListeners.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.vaadin.tests.server; - -import com.vaadin.data.Property.ReadOnlyStatusChangeEvent; -import com.vaadin.data.Property.ReadOnlyStatusChangeListener; -import com.vaadin.data.Property.ValueChangeEvent; -import com.vaadin.data.Property.ValueChangeListener; -import com.vaadin.data.util.AbstractProperty; -import com.vaadin.data.util.ObjectProperty; -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; - -public class TestAbstractPropertyListeners extends AbstractListenerMethodsTest { - public void testValueChangeListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(AbstractProperty.class, - ValueChangeEvent.class, ValueChangeListener.class, - new ObjectProperty("")); - } - - public void testReadOnlyStatusChangeListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(AbstractProperty.class, - ReadOnlyStatusChangeEvent.class, - ReadOnlyStatusChangeListener.class, new ObjectProperty( - "")); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/TestAssertionsEnabled.java b/server/tests/src/com/vaadin/tests/server/TestAssertionsEnabled.java deleted file mode 100644 index 7e120cb9dd..0000000000 --- a/server/tests/src/com/vaadin/tests/server/TestAssertionsEnabled.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server; - -import junit.framework.TestCase; - -public class TestAssertionsEnabled extends TestCase { - public void testAssertionsEnabled() { - boolean assertFailed = false; - try { - assert false; - } catch (AssertionError e) { - assertFailed = true; - } finally { - assertTrue("Unit tests should be run with assertions enabled", - assertFailed); - } - } -} diff --git a/server/tests/src/com/vaadin/tests/server/TestAtmosphereVersion.java b/server/tests/src/com/vaadin/tests/server/TestAtmosphereVersion.java deleted file mode 100644 index 3d37022b81..0000000000 --- a/server/tests/src/com/vaadin/tests/server/TestAtmosphereVersion.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.vaadin.tests.server; - -import junit.framework.TestCase; - -import org.atmosphere.util.Version; - -import com.vaadin.server.Constants; - -public class TestAtmosphereVersion extends TestCase { - /** - * Test that the atmosphere version constant matches the version on our - * classpath - */ - public void testAtmosphereVersion() { - assertEquals(Constants.REQUIRED_ATMOSPHERE_RUNTIME_VERSION, - Version.getRawVersion()); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/TestClassesSerializable.java b/server/tests/src/com/vaadin/tests/server/TestClassesSerializable.java deleted file mode 100644 index 83269ede28..0000000000 --- a/server/tests/src/com/vaadin/tests/server/TestClassesSerializable.java +++ /dev/null @@ -1,324 +0,0 @@ -package com.vaadin.tests.server; - -import java.io.File; -import java.io.IOException; -import java.io.Serializable; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; - -import junit.framework.TestCase; - -import org.junit.Ignore; -import org.junit.Test; - -public class TestClassesSerializable extends TestCase { - - /** - * JARs that will be scanned for classes to test, in addition to classpath - * directories. - */ - private static String JAR_PATTERN = ".*vaadin.*\\.jar"; - - private static String[] BASE_PACKAGES = { "com.vaadin" }; - - private static String[] EXCLUDED_PATTERNS = { - "com\\.vaadin\\.demo\\..*", // - "com\\.vaadin\\.external\\.org\\.apache\\.commons\\.fileupload\\..*", // - "com\\.vaadin\\.launcher\\..*", // - "com\\.vaadin\\.client\\..*", // - "com\\.vaadin\\.server\\.widgetsetutils\\..*", // - "com\\.vaadin\\.server\\.themeutils\\..*", // - "com\\.vaadin\\.tests\\..*", // exclude automated tests - "com\\.vaadin\\.tools\\..*", // - "com\\.vaadin\\.ui\\.themes\\..*", // - // exact class level filtering - "com\\.vaadin\\.event\\.FieldEvents", // - "com\\.vaadin\\.event\\.LayoutEvents", // - "com\\.vaadin\\.event\\.MouseEvents", // - "com\\.vaadin\\.event\\.UIEvents", // - "com\\.vaadin\\.server\\.VaadinPortlet", // - "com\\.vaadin\\.server\\.MockServletConfig", // - "com\\.vaadin\\.server\\.MockServletContext", // - "com\\.vaadin\\.server\\.Constants", // - "com\\.vaadin\\.server\\.VaadinServiceClassLoaderUtil", // - "com\\.vaadin\\.server\\.VaadinServiceClassLoaderUtil\\$GetClassLoaderPrivilegedAction", // - "com\\.vaadin\\.server\\.communication\\.FileUploadHandler\\$SimpleMultiPartInputStream", // - "com\\.vaadin\\.server\\.communication\\.PushRequestHandler.*", - "com\\.vaadin\\.server\\.communication\\.PushHandler.*", // PushHandler - "com\\.vaadin\\.server\\.communication\\.DateSerializer", // - "com\\.vaadin\\.server\\.communication\\.JSONSerializer", // - // and its inner classes do not need to be serializable - "com\\.vaadin\\.util\\.SerializerHelper", // fully static - // class level filtering, also affecting nested classes and - // interfaces - "com\\.vaadin\\.server\\.LegacyCommunicationManager.*", // - "com\\.vaadin\\.buildhelpers.*", // - "com\\.vaadin\\.util\\.ReflectTools.*", // - "com\\.vaadin\\.data\\.util\\.ReflectTools.*", // - "com\\.vaadin\\.sass.*", // - "com\\.vaadin\\.testbench.*", // - "com\\.vaadin\\.util\\.CurrentInstance\\$1", // - "com\\.vaadin\\.server\\.AbstractClientConnector\\$1", // - "com\\.vaadin\\.server\\.AbstractClientConnector\\$1\\$1", // - "com\\.vaadin\\.server\\.JsonCodec\\$1", // - "com\\.vaadin\\.server\\.communication\\.PushConnection", // - "com\\.vaadin\\.server\\.communication\\.AtmospherePushConnection", // - "com\\.vaadin\\.util\\.ConnectorHelper", // - "com\\.vaadin\\.server\\.VaadinSession\\$FutureAccess", // - "com\\.vaadin\\.external\\..*", // - "com\\.vaadin\\.util\\.WeakValueMap.*", // - }; - - /** - * Tests that all the relevant classes and interfaces under - * {@link #BASE_PACKAGES} implement Serializable. - * - * @throws Exception - */ - public void testClassesSerializable() throws Exception { - List rawClasspathEntries = getRawClasspathEntries(); - - List classes = new ArrayList(); - for (String location : rawClasspathEntries) { - classes.addAll(findServerClasses(location)); - } - - ArrayList> nonSerializableClasses = new ArrayList>(); - for (String className : classes) { - Class cls = Class.forName(className); - // skip annotations and synthetic classes - if (cls.isAnnotation() || cls.isSynthetic()) { - continue; - } - // Don't add classes that have a @Ignore annotation on the class - if (isTestClass(cls)) { - continue; - } - - // report non-serializable classes and interfaces - if (!Serializable.class.isAssignableFrom(cls)) { - if (cls.getSuperclass() == Object.class - && cls.getInterfaces().length == 1) { - // Single interface implementors - Class iface = cls.getInterfaces()[0]; - - if (iface == Runnable.class) { - // Ignore Runnables used with access() - continue; - } else if (iface == Comparator.class) { - // Ignore inline comparators - continue; - } - } - nonSerializableClasses.add(cls); - // TODO easier to read when testing - // System.err.println(cls); - } - } - - // useful failure message including all non-serializable classes and - // interfaces - if (!nonSerializableClasses.isEmpty()) { - String nonSerializableString = ""; - Iterator> it = nonSerializableClasses.iterator(); - while (it.hasNext()) { - Class c = it.next(); - nonSerializableString += ", " + c.getName(); - if (c.isAnonymousClass()) { - nonSerializableString += "(super: "; - nonSerializableString += c.getSuperclass().getName(); - nonSerializableString += ", interfaces: "; - for (Class i : c.getInterfaces()) { - nonSerializableString += i.getName(); - nonSerializableString += ","; - } - nonSerializableString += ")"; - } - } - fail("Serializable not implemented by the following classes and interfaces: " - + nonSerializableString); - } - } - - private boolean isTestClass(Class cls) { - // @Ignore is used on test util classes - if (cls.isAnnotationPresent(Ignore.class)) { - return true; - } - - if (cls.getEnclosingClass() != null - && isTestClass(cls.getEnclosingClass())) { - return true; - } - - // Test classes with a @Test annotation on some method - for (Method method : cls.getMethods()) { - if (method.isAnnotationPresent(Test.class)) { - return true; - } - } - - return false; - } - - /** - * Lists all class path entries by splitting the class path string. - * - * Adapted from ClassPathExplorer.getRawClasspathEntries(), but without - * filtering. - * - * @return List of class path segment strings - */ - // - private final static List getRawClasspathEntries() { - // try to keep the order of the classpath - List locations = new ArrayList(); - - String pathSep = System.getProperty("path.separator"); - String classpath = System.getProperty("java.class.path"); - - if (classpath.startsWith("\"")) { - classpath = classpath.substring(1); - } - if (classpath.endsWith("\"")) { - classpath = classpath.substring(0, classpath.length() - 1); - } - - String[] split = classpath.split(pathSep); - for (int i = 0; i < split.length; i++) { - String classpathEntry = split[i]; - locations.add(classpathEntry); - } - - return locations; - } - - /** - * Finds the server side classes/interfaces under a class path entry - - * either a directory or a JAR that matches {@link #JAR_PATTERN}. - * - * Only classes under {@link #BASE_PACKAGES} are considered, and those - * matching {@link #EXCLUDED_PATTERNS} are filtered out. - * - * @param classpathEntry - * @return - * @throws IOException - */ - private List findServerClasses(String classpathEntry) - throws IOException { - Collection classes = new ArrayList(); - - File file = new File(classpathEntry); - if (file.isDirectory()) { - classes = findClassesInDirectory(null, file); - } else if (file.getName().matches(JAR_PATTERN)) { - classes = findClassesInJar(file); - } else { - System.out.println("Ignoring " + classpathEntry); - return Collections.emptyList(); - } - - List filteredClasses = new ArrayList(); - for (String className : classes) { - boolean ok = false; - for (String basePackage : BASE_PACKAGES) { - if (className.startsWith(basePackage + ".")) { - ok = true; - break; - } - } - for (String excludedPrefix : EXCLUDED_PATTERNS) { - if (className.matches(excludedPrefix)) { - ok = false; - break; - } - } - - // Don't add test classes - if (className.contains("Test")) { - ok = false; - } - - if (ok) { - filteredClasses.add(className); - } - } - - return filteredClasses; - } - - /** - * Lists class names (based on .class files) in a JAR file. - * - * @param file - * a valid JAR file - * @return collection of fully qualified class names in the JAR - * @throws IOException - */ - private Collection findClassesInJar(File file) throws IOException { - Collection classes = new ArrayList(); - - JarFile jar = new JarFile(file); - Enumeration e = jar.entries(); - while (e.hasMoreElements()) { - JarEntry entry = e.nextElement(); - if (entry.getName().endsWith(".class")) { - String nameWithoutExtension = entry.getName().replaceAll( - "\\.class", ""); - String className = nameWithoutExtension.replace('/', '.'); - classes.add(className); - } - } - return classes; - } - - /** - * Lists class names (based on .class files) in a directory (a package path - * root). - * - * @param parentPackage - * parent package name or null at root of hierarchy, used by - * recursion - * @param parent - * File representing the directory to scan - * @return collection of fully qualified class names in the directory - */ - private final static Collection findClassesInDirectory( - String parentPackage, File parent) { - if (parent.isHidden() - || parent.getPath().contains(File.separator + ".")) { - return Collections.emptyList(); - } - - if (parentPackage == null) { - parentPackage = ""; - } else { - parentPackage += "."; - } - - Collection classNames = new ArrayList(); - - // add all directories recursively - File[] files = parent.listFiles(); - for (File child : files) { - if (child.isDirectory()) { - classNames.addAll(findClassesInDirectory( - parentPackage + child.getName(), child)); - } else if (child.getName().endsWith(".class")) { - classNames.add(parentPackage.replace(File.separatorChar, '.') - + child.getName().replaceAll("\\.class", "")); - } - } - - return classNames; - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/TestClientMethodSerialization.java b/server/tests/src/com/vaadin/tests/server/TestClientMethodSerialization.java deleted file mode 100644 index d6a71028db..0000000000 --- a/server/tests/src/com/vaadin/tests/server/TestClientMethodSerialization.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.lang.reflect.Method; - -import junit.framework.TestCase; - -import com.vaadin.server.ClientMethodInvocation; -import com.vaadin.server.JavaScriptCallbackHelper; -import com.vaadin.ui.JavaScript.JavaScriptCallbackRpc; -import com.vaadin.util.ReflectTools; - -import elemental.json.Json; -import elemental.json.JsonArray; -import elemental.json.impl.JsonUtil; - -public class TestClientMethodSerialization extends TestCase { - - private static final Method JAVASCRIPT_CALLBACK_METHOD = ReflectTools - .findMethod(JavaScriptCallbackRpc.class, "call", String.class, - JsonArray.class); - - private static final Method BASIC_PARAMS_CALL_METHOD = ReflectTools - .findMethod(TestClientMethodSerialization.class, - "basicParamsMethodForTesting", String.class, Integer.class); - - private static final Method NO_PARAMS_CALL_METHOD = ReflectTools - .findMethod(TestClientMethodSerialization.class, - "noParamsMethodForTesting"); - - public void basicParamsMethodForTesting(String stringParam, - Integer integerParam) { - } - - public void noParamsMethodForTesting() { - } - - /** - * Tests the {@link ClientMethodInvocation} serialization when using - * {@link JavaScriptCallbackHelper#invokeCallback(String, Object...)}. - * #12532 - */ - public void testClientMethodSerialization_WithJSONArray_ContentStaysSame() - throws Exception { - JsonArray originalArray = Json.createArray(); - originalArray.set(0, "callbackParameter1"); - originalArray.set(1, "callBackParameter2"); - originalArray.set(2, "12345"); - ClientMethodInvocation original = new ClientMethodInvocation(null, - "interfaceName", JAVASCRIPT_CALLBACK_METHOD, new Object[] { - "callBackMethodName", originalArray }); - - ClientMethodInvocation copy = (ClientMethodInvocation) serializeAndDeserialize(original); - JsonArray copyArray = (JsonArray) copy.getParameters()[1]; - assertEquals(JsonUtil.stringify(originalArray), - JsonUtil.stringify(copyArray)); - } - - public void testClientMethodSerialization_WithBasicParams_NoChanges() - throws Exception { - String stringParam = "a string 123"; - Integer integerParam = 1234567890; - ClientMethodInvocation original = new ClientMethodInvocation(null, - "interfaceName", BASIC_PARAMS_CALL_METHOD, new Serializable[] { - stringParam, integerParam }); - ClientMethodInvocation copy = (ClientMethodInvocation) serializeAndDeserialize(original); - String copyString = (String) copy.getParameters()[0]; - Integer copyInteger = (Integer) copy.getParameters()[1]; - assertEquals(copyString, stringParam); - assertEquals(copyInteger, integerParam); - } - - public void testClientMethodSerialization_NoParams_NoExceptions() { - ClientMethodInvocation original = new ClientMethodInvocation(null, - "interfaceName", NO_PARAMS_CALL_METHOD, null); - ClientMethodInvocation copy = (ClientMethodInvocation) serializeAndDeserialize(original); - } - - private static Serializable serializeAndDeserialize(Serializable input) { - Serializable output = null; - try { - ByteArrayOutputStream bs = new ByteArrayOutputStream(); - ObjectOutputStream out = new ObjectOutputStream(bs); - out.writeObject(input); - byte[] data = bs.toByteArray(); - ObjectInputStream in = new ObjectInputStream( - new ByteArrayInputStream(data)); - output = (Serializable) in.readObject(); - } catch (Exception e) { - fail("Exception during serialization/deserialization: " - + e.getMessage()); - } - return output; - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/TestEventRouter.java b/server/tests/src/com/vaadin/tests/server/TestEventRouter.java deleted file mode 100644 index a8f5039042..0000000000 --- a/server/tests/src/com/vaadin/tests/server/TestEventRouter.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.vaadin.tests.server; - -import junit.framework.TestCase; - -import com.vaadin.data.Property.ValueChangeEvent; -import com.vaadin.data.Property.ValueChangeListener; -import com.vaadin.ui.TextField; - -public class TestEventRouter extends TestCase { - - int innerListenerCalls = 0; - - public void testAddInEventListener() { - final TextField tf = new TextField(); - - final ValueChangeListener outer = new ValueChangeListener() { - - @Override - public void valueChange(ValueChangeEvent event) { - ValueChangeListener inner = new ValueChangeListener() { - - @Override - public void valueChange(ValueChangeEvent event) { - innerListenerCalls++; - System.out.println("The inner listener was called"); - } - }; - - tf.addListener(inner); - } - }; - - tf.addListener(outer); - tf.setValue("abc"); // No inner listener calls, adds one inner - tf.setValue("def"); // One inner listener call, adds one inner - tf.setValue("ghi"); // Two inner listener calls, adds one inner - assert (innerListenerCalls == 3); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/TestFileTypeResolver.java b/server/tests/src/com/vaadin/tests/server/TestFileTypeResolver.java deleted file mode 100644 index 413926c89a..0000000000 --- a/server/tests/src/com/vaadin/tests/server/TestFileTypeResolver.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.vaadin.tests.server; - -import java.io.File; - -import junit.framework.TestCase; - -import com.vaadin.util.FileTypeResolver; - -public class TestFileTypeResolver extends TestCase { - - private static final String FLASH_MIME_TYPE = "application/x-shockwave-flash"; - private static final String TEXT_MIME_TYPE = "text/plain"; - private static final String HTML_MIME_TYPE = "text/html"; - - public void testMimeTypes() { - File plainFlash = new File("MyFlash.swf"); - File plainText = new File("/a/b/MyFlash.txt"); - File plainHtml = new File("c:\\MyFlash.html"); - - // Flash - assertEquals( - FileTypeResolver.getMIMEType(plainFlash.getAbsolutePath()), - FLASH_MIME_TYPE); - assertEquals( - FileTypeResolver.getMIMEType(plainFlash.getAbsolutePath() - + "?param1=value1"), FLASH_MIME_TYPE); - assertEquals( - FileTypeResolver.getMIMEType(plainFlash.getAbsolutePath() - + "?param1=value1¶m2=value2"), FLASH_MIME_TYPE); - - // Plain text - assertEquals(FileTypeResolver.getMIMEType(plainText.getAbsolutePath()), - TEXT_MIME_TYPE); - assertEquals( - FileTypeResolver.getMIMEType(plainText.getAbsolutePath() - + "?param1=value1"), TEXT_MIME_TYPE); - assertEquals( - FileTypeResolver.getMIMEType(plainText.getAbsolutePath() - + "?param1=value1¶m2=value2"), TEXT_MIME_TYPE); - - // Plain text - assertEquals(FileTypeResolver.getMIMEType(plainHtml.getAbsolutePath()), - HTML_MIME_TYPE); - assertEquals( - FileTypeResolver.getMIMEType(plainHtml.getAbsolutePath() - + "?param1=value1"), HTML_MIME_TYPE); - assertEquals( - FileTypeResolver.getMIMEType(plainHtml.getAbsolutePath() - + "?param1=value1¶m2=value2"), HTML_MIME_TYPE); - - // Filename missing - assertEquals(FileTypeResolver.DEFAULT_MIME_TYPE, - FileTypeResolver.getMIMEType("")); - assertEquals(FileTypeResolver.DEFAULT_MIME_TYPE, - FileTypeResolver.getMIMEType("?param1")); - - } - - public void testExtensionCase() { - assertEquals("image/jpeg", FileTypeResolver.getMIMEType("abc.jpg")); - assertEquals("image/jpeg", FileTypeResolver.getMIMEType("abc.jPg")); - assertEquals("image/jpeg", FileTypeResolver.getMIMEType("abc.JPG")); - assertEquals("image/jpeg", FileTypeResolver.getMIMEType("abc.JPEG")); - assertEquals("image/jpeg", FileTypeResolver.getMIMEType("abc.Jpeg")); - assertEquals("image/jpeg", FileTypeResolver.getMIMEType("abc.JPE")); - } - - public void testCustomMimeType() { - assertEquals(FileTypeResolver.DEFAULT_MIME_TYPE, - FileTypeResolver.getMIMEType("vaadin.foo")); - - FileTypeResolver.addExtension("foo", "Vaadin Foo/Bar"); - FileTypeResolver.addExtension("FOO2", "Vaadin Foo/Bar2"); - assertEquals("Vaadin Foo/Bar", - FileTypeResolver.getMIMEType("vaadin.foo")); - assertEquals("Vaadin Foo/Bar2", - FileTypeResolver.getMIMEType("vaadin.Foo2")); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/TestKeyMapper.java b/server/tests/src/com/vaadin/tests/server/TestKeyMapper.java deleted file mode 100644 index 1c1f9624c8..0000000000 --- a/server/tests/src/com/vaadin/tests/server/TestKeyMapper.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.vaadin.tests.server; - -import java.lang.reflect.Field; -import java.util.HashMap; - -import junit.framework.TestCase; - -import com.vaadin.server.KeyMapper; - -public class TestKeyMapper extends TestCase { - - public void testAdd() { - KeyMapper mapper = new KeyMapper(); - Object o1 = new Object(); - Object o2 = new Object(); - Object o3 = new Object(); - - // Create new ids - String key1 = mapper.key(o1); - String key2 = mapper.key(o2); - String key3 = mapper.key(o3); - - assertEquals(mapper.get(key1), o1); - assertEquals(mapper.get(key2), o2); - assertEquals(mapper.get(key3), o3); - assertNotSame(key1, key2); - assertNotSame(key1, key3); - assertNotSame(key2, key3); - - assertSize(mapper, 3); - - // Key should not add if there already is a mapping - assertEquals(mapper.key(o3), key3); - assertSize(mapper, 3); - - // Remove -> add should return a new key - mapper.remove(o1); - String newkey1 = mapper.key(o1); - assertNotSame(key1, newkey1); - - } - - public void testRemoveAll() { - KeyMapper mapper = new KeyMapper(); - Object o1 = new Object(); - Object o2 = new Object(); - Object o3 = new Object(); - - // Create new ids - mapper.key(o1); - mapper.key(o2); - mapper.key(o3); - - assertSize(mapper, 3); - mapper.removeAll(); - assertSize(mapper, 0); - - } - - public void testRemove() { - KeyMapper mapper = new KeyMapper(); - Object o1 = new Object(); - Object o2 = new Object(); - Object o3 = new Object(); - - // Create new ids - mapper.key(o1); - mapper.key(o2); - mapper.key(o3); - - assertSize(mapper, 3); - mapper.remove(o1); - assertSize(mapper, 2); - mapper.key(o1); - assertSize(mapper, 3); - mapper.remove(o1); - assertSize(mapper, 2); - - mapper.remove(o2); - mapper.remove(o3); - assertSize(mapper, 0); - - } - - private void assertSize(KeyMapper mapper, int i) { - try { - Field f1 = KeyMapper.class.getDeclaredField("objectKeyMap"); - Field f2 = KeyMapper.class.getDeclaredField("keyObjectMap"); - f1.setAccessible(true); - f2.setAccessible(true); - - HashMap h1 = (HashMap) f1.get(mapper); - HashMap h2 = (HashMap) f2.get(mapper); - - assertEquals(i, h1.size()); - assertEquals(i, h2.size()); - } catch (Throwable t) { - t.printStackTrace(); - fail(); - } - } -} diff --git a/server/tests/src/com/vaadin/tests/server/TestMimeTypes.java b/server/tests/src/com/vaadin/tests/server/TestMimeTypes.java deleted file mode 100644 index 12e5b09632..0000000000 --- a/server/tests/src/com/vaadin/tests/server/TestMimeTypes.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.vaadin.tests.server; - -import junit.framework.TestCase; - -import com.vaadin.server.ClassResource; -import com.vaadin.ui.Embedded; - -public class TestMimeTypes extends TestCase { - - public void testEmbeddedPDF() { - Embedded e = new Embedded("A pdf", new ClassResource("file.pddf")); - assertEquals("Invalid mimetype", "application/octet-stream", - e.getMimeType()); - e = new Embedded("A pdf", new ClassResource("file.pdf")); - assertEquals("Invalid mimetype", "application/pdf", e.getMimeType()); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/TestPropertyFormatter.java b/server/tests/src/com/vaadin/tests/server/TestPropertyFormatter.java deleted file mode 100644 index b47a2953ce..0000000000 --- a/server/tests/src/com/vaadin/tests/server/TestPropertyFormatter.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.vaadin.tests.server; - -import java.util.Date; - -import junit.framework.TestCase; - -import org.junit.Test; - -import com.vaadin.data.util.ObjectProperty; -import com.vaadin.data.util.PropertyFormatter; - -@SuppressWarnings("unchecked") -public class TestPropertyFormatter extends TestCase { - - class TestFormatter extends PropertyFormatter { - - @Override - public String format(Object value) { - boolean isCorrectType = getExpectedClass().isAssignableFrom( - value.getClass()); - assertTrue(isCorrectType); - return "FOO"; - } - - @Override - public Object parse(String formattedValue) throws Exception { - return getExpectedClass().newInstance(); - } - } - - @SuppressWarnings("rawtypes") - private Class expectedClass; - - @SuppressWarnings("rawtypes") - private Class getExpectedClass() { - return expectedClass; - } - - /** - * The object passed to format should be same as property's type. - * - * @throws IllegalAccessException - * @throws InstantiationException - */ - @Test - @SuppressWarnings({ "rawtypes" }) - public void testCorrectTypeForFormat() throws InstantiationException, - IllegalAccessException { - Class[] testedTypes = new Class[] { Integer.class, Boolean.class, - Double.class, String.class, Date.class }; - Object[] testValues = new Object[] { new Integer(3), Boolean.FALSE, - new Double(3.3), "bar", new Date() }; - - int i = 0; - for (Class class1 : testedTypes) { - expectedClass = class1; - - TestFormatter formatter = new TestFormatter(); - - // Should just return null, without formatting - Object value = formatter.getValue(); - - // test with property which value is null - formatter.setPropertyDataSource(new ObjectProperty(null, - expectedClass)); - formatter.getValue(); // calls format - - // test with a value - formatter.setPropertyDataSource(new ObjectProperty(testValues[i++], - expectedClass)); - formatter.getValue(); // calls format - } - - } -} diff --git a/server/tests/src/com/vaadin/tests/server/TestSerialization.java b/server/tests/src/com/vaadin/tests/server/TestSerialization.java deleted file mode 100644 index 3c18035dab..0000000000 --- a/server/tests/src/com/vaadin/tests/server/TestSerialization.java +++ /dev/null @@ -1,139 +0,0 @@ -package com.vaadin.tests.server; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; - -import junit.framework.TestCase; - -import com.vaadin.data.Item; -import com.vaadin.data.Property; -import com.vaadin.data.util.IndexedContainer; -import com.vaadin.data.util.MethodProperty; -import com.vaadin.data.validator.RegexpValidator; -import com.vaadin.server.VaadinSession; -import com.vaadin.ui.Form; - -public class TestSerialization extends TestCase { - - public void testValidators() throws Exception { - RegexpValidator validator = new RegexpValidator(".*", "Error"); - validator.validate("aaa"); - RegexpValidator validator2 = serializeAndDeserialize(validator); - validator2.validate("aaa"); - } - - public void testForm() throws Exception { - Form f = new Form(); - String propertyId = "My property"; - f.addItemProperty(propertyId, new MethodProperty(new Data(), - "dummyGetterAndSetter")); - f.replaceWithSelect(propertyId, new Object[] { "a", "b", null }, - new String[] { "Item a", "ITem b", "Null item" }); - - serializeAndDeserialize(f); - - } - - public void testIndedexContainerItemIds() throws Exception { - IndexedContainer ic = new IndexedContainer(); - ic.addContainerProperty("prop1", String.class, null); - Object id = ic.addItem(); - ic.getItem(id).getItemProperty("prop1").setValue("1"); - - Item item2 = ic.addItem("item2"); - item2.getItemProperty("prop1").setValue("2"); - - serializeAndDeserialize(ic); - } - - public void testMethodPropertyGetter() throws Exception { - MethodProperty mp = new MethodProperty(new Data(), - "dummyGetter"); - serializeAndDeserialize(mp); - } - - public void testMethodPropertyGetterAndSetter() throws Exception { - MethodProperty mp = new MethodProperty(new Data(), - "dummyGetterAndSetter"); - serializeAndDeserialize(mp); - } - - public void testMethodPropertyInt() throws Exception { - MethodProperty mp = new MethodProperty(new Data(), - "dummyInt"); - serializeAndDeserialize(mp); - } - - public void testVaadinSession() throws Exception { - VaadinSession session = new VaadinSession(null); - - session = serializeAndDeserialize(session); - - assertNotNull( - "Pending access queue was not recreated after deserialization", - session.getPendingAccessQueue()); - } - - private static S serializeAndDeserialize(S s) - throws IOException, ClassNotFoundException { - // Serialize and deserialize - - ByteArrayOutputStream bs = new ByteArrayOutputStream(); - ObjectOutputStream out = new ObjectOutputStream(bs); - out.writeObject(s); - byte[] data = bs.toByteArray(); - ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream( - data)); - @SuppressWarnings("unchecked") - S s2 = (S) in.readObject(); - - // using special toString(Object) method to avoid calling - // Property.toString(), which will be temporarily disabled - // TODO This is hilariously broken (#12723) - if (s.equals(s2)) { - System.out.println(toString(s) + " equals " + toString(s2)); - } else { - System.out.println(toString(s) + " does NOT equal " + toString(s2)); - } - - return s2; - } - - private static String toString(Object o) { - if (o instanceof Property) { - return String.valueOf(((Property) o).getValue()); - } else { - return String.valueOf(o); - } - } - - public static class Data implements Serializable { - private String dummyGetter; - private String dummyGetterAndSetter; - private int dummyInt; - - public String getDummyGetterAndSetter() { - return dummyGetterAndSetter; - } - - public void setDummyGetterAndSetter(String dummyGetterAndSetter) { - this.dummyGetterAndSetter = dummyGetterAndSetter; - } - - public int getDummyInt() { - return dummyInt; - } - - public void setDummyInt(int dummyInt) { - this.dummyInt = dummyInt; - } - - public String getDummyGetter() { - return dummyGetter; - } - } -} diff --git a/server/tests/src/com/vaadin/tests/server/TestSimpleMultiPartInputStream.java b/server/tests/src/com/vaadin/tests/server/TestSimpleMultiPartInputStream.java deleted file mode 100644 index 6907594b5e..0000000000 --- a/server/tests/src/com/vaadin/tests/server/TestSimpleMultiPartInputStream.java +++ /dev/null @@ -1,138 +0,0 @@ -package com.vaadin.tests.server; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Arrays; - -import junit.framework.TestCase; - -import com.vaadin.server.communication.FileUploadHandler.SimpleMultiPartInputStream; - -public class TestSimpleMultiPartInputStream extends TestCase { - - /** - * Check that the output for a given stream until boundary is as expected. - * - * @param input - * @param boundary - * @param expected - * @throws Exception - */ - protected void checkBoundaryDetection(byte[] input, String boundary, - byte[] expected) throws Exception { - ByteArrayInputStream bais = new ByteArrayInputStream(input); - SimpleMultiPartInputStream smpis = new SimpleMultiPartInputStream(bais, - boundary); - ByteArrayOutputStream resultStream = new ByteArrayOutputStream(); - int outbyte; - try { - while ((outbyte = smpis.read()) != -1) { - resultStream.write(outbyte); - } - } catch (IOException e) { - throw new IOException(e.getMessage() + "; expected " - + new String(expected) + " but got " - + resultStream.toString()); - } - if (!Arrays.equals(expected, resultStream.toByteArray())) { - throw new Exception("Mismatch: expected " + new String(expected) - + " but got " + resultStream.toString()); - } - } - - protected void checkBoundaryDetection(String input, String boundary, - String expected) throws Exception { - checkBoundaryDetection(input.getBytes(), boundary, expected.getBytes()); - } - - public void testSingleByteBoundaryAtEnd() throws Exception { - checkBoundaryDetection("xyz123" + getFullBoundary("a"), "a", "xyz123"); - } - - public void testSingleByteBoundaryInMiddle() throws Exception { - checkBoundaryDetection("xyz" + getFullBoundary("a") + "123", "a", "xyz"); - } - - public void testCorrectBoundaryAtEnd() throws Exception { - checkBoundaryDetection("xyz123" + getFullBoundary("abc"), "abc", - "xyz123"); - } - - public void testCorrectBoundaryNearEnd() throws Exception { - checkBoundaryDetection("xyz123" + getFullBoundary("abc") + "de", "abc", - "xyz123"); - } - - public void testCorrectBoundaryAtBeginning() throws Exception { - checkBoundaryDetection(getFullBoundary("abc") + "xyz123", "abc", ""); - } - - public void testRepeatingCharacterBoundary() throws Exception { - checkBoundaryDetection(getFullBoundary("aa") + "xyz123", "aa", ""); - checkBoundaryDetection("axyz" + getFullBoundary("aa") + "123", "aa", - "axyz"); - checkBoundaryDetection("xyz123" + getFullBoundary("aa"), "aa", "xyz123"); - } - - /** - * Note, the boundary in this test is invalid. Boundary strings don't - * contain CR/LF. - * - */ - // public void testRepeatingNewlineBoundary() throws Exception { - // checkBoundaryDetection("1234567890" + getFullBoundary("\n\n") - // + "1234567890", "\n\n", ""); - // } - - public void testRepeatingStringBoundary() throws Exception { - checkBoundaryDetection(getFullBoundary("abab") + "xyz123", "abab", ""); - checkBoundaryDetection("abaxyz" + getFullBoundary("abab") + "123", - "abab", "abaxyz"); - checkBoundaryDetection("xyz123" + getFullBoundary("abab"), "abab", - "xyz123"); - } - - public void testOverlappingBoundary() throws Exception { - checkBoundaryDetection("abc" + getFullBoundary("abcabd") + "xyz123", - "abcabd", "abc"); - checkBoundaryDetection("xyzabc" + getFullBoundary("abcabd") + "123", - "abcabd", "xyzabc"); - checkBoundaryDetection("xyz123abc" + getFullBoundary("abcabd"), - "abcabd", "xyz123abc"); - } - - /* - * TODO fix these tests, they don't do what their method name says. - */ - - // public void testNoBoundaryInInput() throws Exception { - // try { - // checkBoundaryDetection("xyz123", "abc", "xyz123"); - // fail(); - // } catch (IOException e) { - // } - // } - // - // public void testPartialBoundaryAtInputEnd() throws Exception { - // try { - // // This should lead to IOException (stream end), not AIOOBE - // checkBoundaryDetection("xyz123ab", "abc", "xyz123ab"); - // fail(); - // } catch (IOException e) { - // } - // } - // - // public void testPartialBoundaryAtInputBeginning() throws Exception { - // try { - // checkBoundaryDetection("abxyz123", "abc", "abxyz123"); - // fail(); - // } catch (IOException e) { - // } - // } - - public static String getFullBoundary(String str) { - return "\r\n--" + str + "--"; - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/TestStreamResource.java b/server/tests/src/com/vaadin/tests/server/TestStreamResource.java deleted file mode 100644 index 0fdcc9e39c..0000000000 --- a/server/tests/src/com/vaadin/tests/server/TestStreamResource.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server; - -import org.easymock.EasyMock; -import org.junit.Assert; -import org.junit.Test; - -import com.vaadin.server.StreamResource; -import com.vaadin.server.StreamResource.StreamSource; - -/** - * - * @author Vaadin Ltd - */ -public class TestStreamResource { - - @Test - public void testEqualsWithNullFields() { - StreamResource resource1 = new StreamResource(null, null); - StreamResource resource2 = new StreamResource(null, null); - - Assert.assertEquals(resource1, resource2); - } - - @Test - public void testNotEqualsWithNullFields() { - StreamResource resource1 = new StreamResource(null, null); - StreamResource resource2 = new StreamResource( - EasyMock.createMock(StreamSource.class), ""); - - Assert.assertNotEquals(resource1, resource2); - } - - @Test - public void testHashCodeForNullFields() { - StreamResource resource = new StreamResource(null, null); - // No NPE - resource.hashCode(); - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/TestStreamVariableMapping.java b/server/tests/src/com/vaadin/tests/server/TestStreamVariableMapping.java deleted file mode 100644 index b2faca1ed6..0000000000 --- a/server/tests/src/com/vaadin/tests/server/TestStreamVariableMapping.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.vaadin.tests.server; - -import junit.framework.TestCase; - -import org.easymock.EasyMock; - -import com.vaadin.server.LegacyCommunicationManager; -import com.vaadin.server.MockServletConfig; -import com.vaadin.server.StreamVariable; -import com.vaadin.server.VaadinRequest; -import com.vaadin.server.VaadinServlet; -import com.vaadin.server.VaadinServletService; -import com.vaadin.server.VaadinSession; -import com.vaadin.tests.util.AlwaysLockedVaadinSession; -import com.vaadin.tests.util.MockDeploymentConfiguration; -import com.vaadin.ui.ConnectorTracker; -import com.vaadin.ui.UI; -import com.vaadin.ui.Upload; - -public class TestStreamVariableMapping extends TestCase { - private static final String variableName = "myName"; - - private Upload owner; - private StreamVariable streamVariable; - - private LegacyCommunicationManager cm; - - @Override - protected void setUp() throws Exception { - final VaadinSession application = new AlwaysLockedVaadinSession(null); - final UI uI = new UI() { - @Override - protected void init(VaadinRequest request) { - // TODO Auto-generated method stub - - } - - @Override - public VaadinSession getSession() { - return application; - } - }; - owner = new Upload() { - @Override - public UI getUI() { - return uI; - } - }; - streamVariable = EasyMock.createMock(StreamVariable.class); - cm = createCommunicationManager(); - - super.setUp(); - } - - public void testAddStreamVariable() { - owner.getUI().getConnectorTracker().registerConnector(owner); - String targetUrl = cm.getStreamVariableTargetUrl(owner, variableName, - streamVariable); - assertTrue(targetUrl.startsWith("app://APP/UPLOAD/-1/" - + owner.getConnectorId() + "/myName/")); - - ConnectorTracker tracker = owner.getUI().getConnectorTracker(); - StreamVariable streamVariable2 = tracker.getStreamVariable( - owner.getConnectorId(), variableName); - assertSame(streamVariable, streamVariable2); - } - - public void testRemoveVariable() { - ConnectorTracker tracker = owner.getUI().getConnectorTracker(); - tracker.registerConnector(owner); - cm.getStreamVariableTargetUrl(owner, variableName, streamVariable); - assertNotNull(tracker.getStreamVariable(owner.getConnectorId(), - variableName)); - - tracker.cleanStreamVariable(owner.getConnectorId(), variableName); - assertNull(tracker.getStreamVariable(owner.getConnectorId(), - variableName)); - } - - private LegacyCommunicationManager createCommunicationManager() - throws Exception { - VaadinServlet servlet = new VaadinServlet(); - servlet.init(new MockServletConfig()); - VaadinServletService vss = new VaadinServletService(servlet, - new MockDeploymentConfiguration()); - servlet.init(new MockServletConfig()); - return new LegacyCommunicationManager( - new AlwaysLockedVaadinSession(vss)); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/clientconnector/AttachDetachListeners.java b/server/tests/src/com/vaadin/tests/server/clientconnector/AttachDetachListeners.java deleted file mode 100644 index bd7053af40..0000000000 --- a/server/tests/src/com/vaadin/tests/server/clientconnector/AttachDetachListeners.java +++ /dev/null @@ -1,182 +0,0 @@ -/* -@VaadinApache2LicenseForJavaFiles@ - */ - -package com.vaadin.tests.server.clientconnector; - -import org.easymock.EasyMock; -import org.easymock.IArgumentMatcher; -import org.easymock.IMocksControl; -import org.junit.Before; -import org.junit.Test; - -import com.vaadin.event.ConnectorEvent; -import com.vaadin.server.ClientConnector.AttachEvent; -import com.vaadin.server.ClientConnector.AttachListener; -import com.vaadin.server.ClientConnector.DetachEvent; -import com.vaadin.server.ClientConnector.DetachListener; -import com.vaadin.server.VaadinRequest; -import com.vaadin.server.VaadinService; -import com.vaadin.server.VaadinSession; -import com.vaadin.tests.util.AlwaysLockedVaadinSession; -import com.vaadin.ui.Component; -import com.vaadin.ui.CssLayout; -import com.vaadin.ui.Label; -import com.vaadin.ui.Layout; -import com.vaadin.ui.UI; - -public class AttachDetachListeners { - - private IMocksControl control; - - private VaadinSession session; - private UI ui; - private Layout content; - private Component component; - - AttachListener attachListener; - DetachListener detachListener; - - @Before - public void setUp() { - control = EasyMock.createStrictControl(); - - session = new AlwaysLockedVaadinSession( - control.createMock(VaadinService.class)); - - ui = new UI() { - @Override - protected void init(VaadinRequest request) { - } - }; - content = new CssLayout(); - component = new Label(); - - attachListener = control.createMock(AttachListener.class); - detachListener = control.createMock(DetachListener.class); - } - - @Test - public void attachListeners_setSessionLast() { - setupAttachListeners(); - - ui.setContent(content); - content.addComponent(component); - ui.setSession(session); - - control.verify(); - } - - @Test - public void attachListeners_setSessionFirst() { - setupAttachListeners(); - - ui.setSession(session); - ui.setContent(content); - content.addComponent(component); - - control.verify(); - } - - @Test - public void attachListeners_setSessionBetween() { - setupAttachListeners(); - - ui.setContent(content); - ui.setSession(session); - content.addComponent(component); - - control.verify(); - } - - @Test - public void detachListeners_setSessionNull() { - setupDetachListeners(); - - ui.setContent(content); - content.addComponent(component); - ui.setSession(null); - - control.verify(); - } - - @Test - public void detachListeners_removeComponent() { - setupDetachListeners(); - - ui.setContent(content); - content.addComponent(component); - content.removeAllComponents(); - ui.setSession(null); - - control.verify(); - } - - @Test - public void detachListeners_setContentNull() { - setupDetachListeners(); - - ui.setContent(content); - content.addComponent(component); - ui.setContent(null); - ui.setSession(null); - - control.verify(); - } - - public static class EventEquals implements - IArgumentMatcher { - - private E expected; - - public EventEquals(E expected) { - this.expected = expected; - } - - @Override - public void appendTo(StringBuffer buffer) { - buffer.append("EventEquals("); - buffer.append("expected " + expected.getClass().getSimpleName() - + " with connector " + expected.getConnector()); - buffer.append(")"); - } - - @Override - public boolean matches(Object argument) { - return expected.getClass().isInstance(argument) - && ((ConnectorEvent) argument).getConnector() == expected - .getConnector(); - } - } - - public static E eventEquals(E expected) { - EasyMock.reportMatcher(new EventEquals(expected)); - return null; - } - - private void setupDetachListeners() { - detachListener.detach(eventEquals(new DetachEvent(component))); - detachListener.detach(eventEquals(new DetachEvent(content))); - detachListener.detach(eventEquals(new DetachEvent(ui))); - - control.replay(); - - ui.addDetachListener(detachListener); - content.addDetachListener(detachListener); - component.addDetachListener(detachListener); - - ui.setSession(session); - } - - private void setupAttachListeners() { - attachListener.attach(eventEquals(new AttachEvent(ui))); - attachListener.attach(eventEquals(new AttachEvent(content))); - attachListener.attach(eventEquals(new AttachEvent(component))); - - control.replay(); - - ui.addAttachListener(attachListener); - content.addAttachListener(attachListener); - component.addAttachListener(attachListener); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/clientconnector/AttachDetachListenersTest.java b/server/tests/src/com/vaadin/tests/server/clientconnector/AttachDetachListenersTest.java new file mode 100644 index 0000000000..68964dbfd1 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/clientconnector/AttachDetachListenersTest.java @@ -0,0 +1,182 @@ +/* +@VaadinApache2LicenseForJavaFiles@ + */ + +package com.vaadin.tests.server.clientconnector; + +import org.easymock.EasyMock; +import org.easymock.IArgumentMatcher; +import org.easymock.IMocksControl; +import org.junit.Before; +import org.junit.Test; + +import com.vaadin.event.ConnectorEvent; +import com.vaadin.server.ClientConnector.AttachEvent; +import com.vaadin.server.ClientConnector.AttachListener; +import com.vaadin.server.ClientConnector.DetachEvent; +import com.vaadin.server.ClientConnector.DetachListener; +import com.vaadin.server.VaadinRequest; +import com.vaadin.server.VaadinService; +import com.vaadin.server.VaadinSession; +import com.vaadin.tests.util.AlwaysLockedVaadinSession; +import com.vaadin.ui.Component; +import com.vaadin.ui.CssLayout; +import com.vaadin.ui.Label; +import com.vaadin.ui.Layout; +import com.vaadin.ui.UI; + +public class AttachDetachListenersTest { + + private IMocksControl control; + + private VaadinSession session; + private UI ui; + private Layout content; + private Component component; + + AttachListener attachListener; + DetachListener detachListener; + + @Before + public void setUp() { + control = EasyMock.createStrictControl(); + + session = new AlwaysLockedVaadinSession( + control.createMock(VaadinService.class)); + + ui = new UI() { + @Override + protected void init(VaadinRequest request) { + } + }; + content = new CssLayout(); + component = new Label(); + + attachListener = control.createMock(AttachListener.class); + detachListener = control.createMock(DetachListener.class); + } + + @Test + public void attachListeners_setSessionLast() { + setupAttachListeners(); + + ui.setContent(content); + content.addComponent(component); + ui.setSession(session); + + control.verify(); + } + + @Test + public void attachListeners_setSessionFirst() { + setupAttachListeners(); + + ui.setSession(session); + ui.setContent(content); + content.addComponent(component); + + control.verify(); + } + + @Test + public void attachListeners_setSessionBetween() { + setupAttachListeners(); + + ui.setContent(content); + ui.setSession(session); + content.addComponent(component); + + control.verify(); + } + + @Test + public void detachListeners_setSessionNull() { + setupDetachListeners(); + + ui.setContent(content); + content.addComponent(component); + ui.setSession(null); + + control.verify(); + } + + @Test + public void detachListeners_removeComponent() { + setupDetachListeners(); + + ui.setContent(content); + content.addComponent(component); + content.removeAllComponents(); + ui.setSession(null); + + control.verify(); + } + + @Test + public void detachListeners_setContentNull() { + setupDetachListeners(); + + ui.setContent(content); + content.addComponent(component); + ui.setContent(null); + ui.setSession(null); + + control.verify(); + } + + public static class EventEquals implements + IArgumentMatcher { + + private E expected; + + public EventEquals(E expected) { + this.expected = expected; + } + + @Override + public void appendTo(StringBuffer buffer) { + buffer.append("EventEquals("); + buffer.append("expected " + expected.getClass().getSimpleName() + + " with connector " + expected.getConnector()); + buffer.append(")"); + } + + @Override + public boolean matches(Object argument) { + return expected.getClass().isInstance(argument) + && ((ConnectorEvent) argument).getConnector() == expected + .getConnector(); + } + } + + public static E eventEquals(E expected) { + EasyMock.reportMatcher(new EventEquals(expected)); + return null; + } + + private void setupDetachListeners() { + detachListener.detach(eventEquals(new DetachEvent(component))); + detachListener.detach(eventEquals(new DetachEvent(content))); + detachListener.detach(eventEquals(new DetachEvent(ui))); + + control.replay(); + + ui.addDetachListener(detachListener); + content.addDetachListener(detachListener); + component.addDetachListener(detachListener); + + ui.setSession(session); + } + + private void setupAttachListeners() { + attachListener.attach(eventEquals(new AttachEvent(ui))); + attachListener.attach(eventEquals(new AttachEvent(content))); + attachListener.attach(eventEquals(new AttachEvent(component))); + + control.replay(); + + ui.addAttachListener(attachListener); + content.addAttachListener(attachListener); + component.addAttachListener(attachListener); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/AbstractListenerMethodsTest.java b/server/tests/src/com/vaadin/tests/server/component/AbstractListenerMethodsTest.java deleted file mode 100644 index e189ffc77d..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/AbstractListenerMethodsTest.java +++ /dev/null @@ -1,173 +0,0 @@ -package com.vaadin.tests.server.component; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - -import junit.framework.TestCase; - -import org.easymock.EasyMock; -import org.junit.Assert; - -import com.vaadin.tests.VaadinClasses; -import com.vaadin.ui.Component; - -public abstract class AbstractListenerMethodsTest extends TestCase { - - public static void main(String[] args) { - findAllListenerMethods(); - } - - private static void findAllListenerMethods() { - Set> classes = new HashSet>(); - for (Class c : VaadinClasses.getAllServerSideClasses()) { - while (c != null && c.getName().startsWith("com.vaadin.")) { - classes.add(c); - c = c.getSuperclass(); - } - } - - for (Class c : classes) { - boolean found = false; - for (Method m : c.getDeclaredMethods()) { - if (m.getName().equals("addListener")) { - if (m.getParameterTypes().length != 1) { - continue; - } - String packageName = "com.vaadin.tests.server"; - if (Component.class.isAssignableFrom(c)) { - packageName += ".component." - + c.getSimpleName().toLowerCase(); - continue; - } - - if (!found) { - found = true; - System.out.println("package " + packageName + ";"); - - System.out.println("import " - + AbstractListenerMethodsTest.class.getName() - + ";"); - System.out.println("import " + c.getName() + ";"); - System.out.println("public class " - + c.getSimpleName() - + "Listeners extends " - + AbstractListenerMethodsTest.class - .getSimpleName() + " {"); - } - - String listenerClassName = m.getParameterTypes()[0] - .getSimpleName(); - String eventClassName = listenerClassName.replaceFirst( - "Listener$", "Event"); - System.out.println("public void test" + listenerClassName - + "() throws Exception {"); - System.out.println(" testListener(" + c.getSimpleName() - + ".class, " + eventClassName + ".class, " - + listenerClassName + ".class);"); - System.out.println("}"); - } - } - if (found) { - System.out.println("}"); - System.out.println(); - } - } - } - - protected void testListenerAddGetRemove(Class testClass, - Class eventClass, Class listenerClass) throws Exception { - // Create a component for testing - Object c = testClass.newInstance(); - testListenerAddGetRemove(testClass, eventClass, listenerClass, c); - - } - - protected void testListenerAddGetRemove(Class cls, Class eventClass, - Class listenerClass, Object c) throws Exception { - - Object mockListener1 = EasyMock.createMock(listenerClass); - Object mockListener2 = EasyMock.createMock(listenerClass); - - // Verify we start from no listeners - verifyListeners(c, eventClass); - - // Add one listener and verify - addListener(c, mockListener1, listenerClass); - verifyListeners(c, eventClass, mockListener1); - - // Add another listener and verify - addListener(c, mockListener2, listenerClass); - verifyListeners(c, eventClass, mockListener1, mockListener2); - - // Ensure we can fetch using parent class also - if (eventClass.getSuperclass() != null) { - verifyListeners(c, eventClass.getSuperclass(), mockListener1, - mockListener2); - } - - // Remove the first and verify - removeListener(c, mockListener1, listenerClass); - verifyListeners(c, eventClass, mockListener2); - - // Remove the remaining and verify - removeListener(c, mockListener2, listenerClass); - verifyListeners(c, eventClass); - - } - - private void removeListener(Object c, Object listener, - Class listenerClass) throws IllegalArgumentException, - IllegalAccessException, InvocationTargetException, - SecurityException, NoSuchMethodException { - Method method = getRemoveListenerMethod(c.getClass(), listenerClass); - method.invoke(c, listener); - - } - - private void addListener(Object c, Object listener1, Class listenerClass) - throws IllegalArgumentException, IllegalAccessException, - InvocationTargetException, SecurityException, NoSuchMethodException { - Method method = getAddListenerMethod(c.getClass(), listenerClass); - method.invoke(c, listener1); - } - - private Collection getListeners(Object c, Class eventType) - throws IllegalArgumentException, IllegalAccessException, - InvocationTargetException, SecurityException, NoSuchMethodException { - Method method = getGetListenersMethod(c.getClass()); - return (Collection) method.invoke(c, eventType); - } - - private Method getGetListenersMethod(Class cls) - throws SecurityException, NoSuchMethodException { - return cls.getMethod("getListeners", Class.class); - } - - private Method getAddListenerMethod(Class cls, Class listenerClass) - throws SecurityException, NoSuchMethodException { - return cls.getMethod("addListener", listenerClass); - - } - - private Method getRemoveListenerMethod(Class cls, Class listenerClass) - throws SecurityException, NoSuchMethodException { - return cls.getMethod("removeListener", listenerClass); - - } - - private void verifyListeners(Object c, Class eventClass, - Object... expectedListeners) throws IllegalArgumentException, - SecurityException, IllegalAccessException, - InvocationTargetException, NoSuchMethodException { - Collection registeredListeners = getListeners(c, eventClass); - assertEquals("Number of listeners", expectedListeners.length, - registeredListeners.size()); - - Assert.assertArrayEquals(expectedListeners, - registeredListeners.toArray()); - - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/AbstractListenerMethodsTestBase.java b/server/tests/src/com/vaadin/tests/server/component/AbstractListenerMethodsTestBase.java new file mode 100644 index 0000000000..ec3754d037 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/AbstractListenerMethodsTestBase.java @@ -0,0 +1,173 @@ +package com.vaadin.tests.server.component; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +import junit.framework.TestCase; + +import org.easymock.EasyMock; +import org.junit.Assert; + +import com.vaadin.tests.VaadinClasses; +import com.vaadin.ui.Component; + +public abstract class AbstractListenerMethodsTestBase extends TestCase { + + public static void main(String[] args) { + findAllListenerMethods(); + } + + private static void findAllListenerMethods() { + Set> classes = new HashSet>(); + for (Class c : VaadinClasses.getAllServerSideClasses()) { + while (c != null && c.getName().startsWith("com.vaadin.")) { + classes.add(c); + c = c.getSuperclass(); + } + } + + for (Class c : classes) { + boolean found = false; + for (Method m : c.getDeclaredMethods()) { + if (m.getName().equals("addListener")) { + if (m.getParameterTypes().length != 1) { + continue; + } + String packageName = "com.vaadin.tests.server"; + if (Component.class.isAssignableFrom(c)) { + packageName += ".component." + + c.getSimpleName().toLowerCase(); + continue; + } + + if (!found) { + found = true; + System.out.println("package " + packageName + ";"); + + System.out.println("import " + + AbstractListenerMethodsTestBase.class.getName() + + ";"); + System.out.println("import " + c.getName() + ";"); + System.out.println("public class " + + c.getSimpleName() + + "Listeners extends " + + AbstractListenerMethodsTestBase.class + .getSimpleName() + " {"); + } + + String listenerClassName = m.getParameterTypes()[0] + .getSimpleName(); + String eventClassName = listenerClassName.replaceFirst( + "Listener$", "Event"); + System.out.println("public void test" + listenerClassName + + "() throws Exception {"); + System.out.println(" testListener(" + c.getSimpleName() + + ".class, " + eventClassName + ".class, " + + listenerClassName + ".class);"); + System.out.println("}"); + } + } + if (found) { + System.out.println("}"); + System.out.println(); + } + } + } + + protected void testListenerAddGetRemove(Class testClass, + Class eventClass, Class listenerClass) throws Exception { + // Create a component for testing + Object c = testClass.newInstance(); + testListenerAddGetRemove(testClass, eventClass, listenerClass, c); + + } + + protected void testListenerAddGetRemove(Class cls, Class eventClass, + Class listenerClass, Object c) throws Exception { + + Object mockListener1 = EasyMock.createMock(listenerClass); + Object mockListener2 = EasyMock.createMock(listenerClass); + + // Verify we start from no listeners + verifyListeners(c, eventClass); + + // Add one listener and verify + addListener(c, mockListener1, listenerClass); + verifyListeners(c, eventClass, mockListener1); + + // Add another listener and verify + addListener(c, mockListener2, listenerClass); + verifyListeners(c, eventClass, mockListener1, mockListener2); + + // Ensure we can fetch using parent class also + if (eventClass.getSuperclass() != null) { + verifyListeners(c, eventClass.getSuperclass(), mockListener1, + mockListener2); + } + + // Remove the first and verify + removeListener(c, mockListener1, listenerClass); + verifyListeners(c, eventClass, mockListener2); + + // Remove the remaining and verify + removeListener(c, mockListener2, listenerClass); + verifyListeners(c, eventClass); + + } + + private void removeListener(Object c, Object listener, + Class listenerClass) throws IllegalArgumentException, + IllegalAccessException, InvocationTargetException, + SecurityException, NoSuchMethodException { + Method method = getRemoveListenerMethod(c.getClass(), listenerClass); + method.invoke(c, listener); + + } + + private void addListener(Object c, Object listener1, Class listenerClass) + throws IllegalArgumentException, IllegalAccessException, + InvocationTargetException, SecurityException, NoSuchMethodException { + Method method = getAddListenerMethod(c.getClass(), listenerClass); + method.invoke(c, listener1); + } + + private Collection getListeners(Object c, Class eventType) + throws IllegalArgumentException, IllegalAccessException, + InvocationTargetException, SecurityException, NoSuchMethodException { + Method method = getGetListenersMethod(c.getClass()); + return (Collection) method.invoke(c, eventType); + } + + private Method getGetListenersMethod(Class cls) + throws SecurityException, NoSuchMethodException { + return cls.getMethod("getListeners", Class.class); + } + + private Method getAddListenerMethod(Class cls, Class listenerClass) + throws SecurityException, NoSuchMethodException { + return cls.getMethod("addListener", listenerClass); + + } + + private Method getRemoveListenerMethod(Class cls, Class listenerClass) + throws SecurityException, NoSuchMethodException { + return cls.getMethod("removeListener", listenerClass); + + } + + private void verifyListeners(Object c, Class eventClass, + Object... expectedListeners) throws IllegalArgumentException, + SecurityException, IllegalAccessException, + InvocationTargetException, NoSuchMethodException { + Collection registeredListeners = getListeners(c, eventClass); + assertEquals("Number of listeners", expectedListeners.length, + registeredListeners.size()); + + Assert.assertArrayEquals(expectedListeners, + registeredListeners.toArray()); + + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/ReadEmptyDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/ReadEmptyDesignTest.java new file mode 100644 index 0000000000..5cf3b9700e --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/ReadEmptyDesignTest.java @@ -0,0 +1,78 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Document; +import org.jsoup.nodes.DocumentType; +import org.jsoup.nodes.Element; + +import com.vaadin.ui.Component; +import com.vaadin.ui.VerticalLayout; +import com.vaadin.ui.declarative.Design; +import com.vaadin.ui.declarative.DesignContext; +import com.vaadin.ui.declarative.DesignException; + +/** + * Test cases for checking that reading a design with no elements in the html + * body produces null as the root component. + */ +public class ReadEmptyDesignTest extends TestCase { + InputStream is; + + @Override + protected void setUp() throws Exception { + super.setUp(); + String html = createDesign().toString(); + is = new ByteArrayInputStream(html.getBytes()); + } + + public void testReadComponent() { + Component root = Design.read(is); + assertNull("The root component should be null.", root); + } + + public void testReadContext() { + DesignContext ctx = Design.read(is, null); + assertNotNull("The design context should not be null.", ctx); + assertNull("The root component should be null.", ctx.getRootComponent()); + } + + public void testReadContextWithRootParameter() { + try { + Component rootComponent = new VerticalLayout(); + DesignContext ctx = Design.read(is, rootComponent); + fail("Reading a design with no elements should fail when a non-null root Component is specified."); + } catch (DesignException e) { + // This is the expected outcome, nothing to do. + } + } + + private Document createDesign() { + Document doc = new Document(""); + DocumentType docType = new DocumentType("html", "", "", ""); + doc.appendChild(docType); + Element html = doc.createElement("html"); + doc.appendChild(html); + html.appendChild(doc.createElement("head")); + html.appendChild(doc.createElement("body")); + return doc; + } +} \ No newline at end of file diff --git a/server/tests/src/com/vaadin/tests/server/component/StateGetDoesNotMarkDirty.java b/server/tests/src/com/vaadin/tests/server/component/StateGetDoesNotMarkDirty.java deleted file mode 100644 index 280d638707..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/StateGetDoesNotMarkDirty.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.vaadin.tests.server.component; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Locale; -import java.util.Set; - -import junit.framework.TestCase; - -import org.mockito.Mockito; - -import com.vaadin.tests.VaadinClasses; -import com.vaadin.ui.Component; -import com.vaadin.ui.ConnectorTracker; -import com.vaadin.ui.Label; -import com.vaadin.ui.UI; - -public class StateGetDoesNotMarkDirty extends TestCase { - - private Set excludedMethods = new HashSet(); - - @Override - protected void setUp() throws Exception { - excludedMethods.add(Label.class.getName() + "getDataSourceValue"); - excludedMethods.add("getConnectorId"); - } - - public void testGetDoesntMarkStateDirty() throws Exception { - for (Class c : VaadinClasses.getComponents()) { - Component newInstance = construct(c); - prepareMockUI(newInstance); - - Set methods = new HashSet(); - methods.addAll(Arrays.asList(c.getMethods())); - methods.addAll(Arrays.asList(c.getDeclaredMethods())); - for (Method method : methods) { - try { - if (method.getName().startsWith("is") - || method.getName().startsWith("get")) { - if (method.getName().startsWith("getState")) { - continue; - } - if (method.getParameterTypes().length > 0) { - // usually getters do not have params, if they have - // we still wouldnt know what to put into - continue; - } - if (excludedMethods.contains(c.getName() - + method.getName())) { - // blacklisted method for specific classes - continue; - } - if (excludedMethods.contains(method.getName())) { - // blacklisted method for all classes - continue; - } - // just to make sure we can invoke it - method.setAccessible(true); - method.invoke(newInstance); - } - } catch (Exception e) { - System.err.println("problem with method " + c.getName() - + "# " + method.getName()); - e.printStackTrace(); - throw e; - } - } - } - - } - - private void prepareMockUI(Component newInstance) { - UI ui = Mockito.mock(UI.class); - Mockito.when(ui.getLocale()).thenReturn(Locale.ENGLISH); - ConnectorTracker connectorTracker = Mockito - .mock(ConnectorTracker.class); - Mockito.when(ui.getConnectorTracker()).thenReturn(connectorTracker); - Mockito.doThrow(new RuntimeException("getState(true) called in getter")) - .when(connectorTracker).markDirty(newInstance); - - newInstance.setParent(ui); - } - - private Component construct(Class c) { - try { - try { - Constructor declaredConstructor = c - .getDeclaredConstructor(); - declaredConstructor.setAccessible(true); - return declaredConstructor.newInstance(); - } catch (NoSuchMethodException e) { - return c.newInstance(); - } - } catch (Exception e) { - throw new RuntimeException(e); - } - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/StateGetDoesNotMarkDirtyTest.java b/server/tests/src/com/vaadin/tests/server/component/StateGetDoesNotMarkDirtyTest.java new file mode 100644 index 0000000000..da4d8a92d4 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/StateGetDoesNotMarkDirtyTest.java @@ -0,0 +1,100 @@ +package com.vaadin.tests.server.component; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Locale; +import java.util.Set; + +import junit.framework.TestCase; + +import org.mockito.Mockito; + +import com.vaadin.tests.VaadinClasses; +import com.vaadin.ui.Component; +import com.vaadin.ui.ConnectorTracker; +import com.vaadin.ui.Label; +import com.vaadin.ui.UI; + +public class StateGetDoesNotMarkDirtyTest extends TestCase { + + private Set excludedMethods = new HashSet(); + + @Override + protected void setUp() throws Exception { + excludedMethods.add(Label.class.getName() + "getDataSourceValue"); + excludedMethods.add("getConnectorId"); + } + + public void testGetDoesntMarkStateDirty() throws Exception { + for (Class c : VaadinClasses.getComponents()) { + Component newInstance = construct(c); + prepareMockUI(newInstance); + + Set methods = new HashSet(); + methods.addAll(Arrays.asList(c.getMethods())); + methods.addAll(Arrays.asList(c.getDeclaredMethods())); + for (Method method : methods) { + try { + if (method.getName().startsWith("is") + || method.getName().startsWith("get")) { + if (method.getName().startsWith("getState")) { + continue; + } + if (method.getParameterTypes().length > 0) { + // usually getters do not have params, if they have + // we still wouldnt know what to put into + continue; + } + if (excludedMethods.contains(c.getName() + + method.getName())) { + // blacklisted method for specific classes + continue; + } + if (excludedMethods.contains(method.getName())) { + // blacklisted method for all classes + continue; + } + // just to make sure we can invoke it + method.setAccessible(true); + method.invoke(newInstance); + } + } catch (Exception e) { + System.err.println("problem with method " + c.getName() + + "# " + method.getName()); + e.printStackTrace(); + throw e; + } + } + } + + } + + private void prepareMockUI(Component newInstance) { + UI ui = Mockito.mock(UI.class); + Mockito.when(ui.getLocale()).thenReturn(Locale.ENGLISH); + ConnectorTracker connectorTracker = Mockito + .mock(ConnectorTracker.class); + Mockito.when(ui.getConnectorTracker()).thenReturn(connectorTracker); + Mockito.doThrow(new RuntimeException("getState(true) called in getter")) + .when(connectorTracker).markDirty(newInstance); + + newInstance.setParent(ui); + } + + private Component construct(Class c) { + try { + try { + Constructor declaredConstructor = c + .getDeclaredConstructor(); + declaredConstructor.setAccessible(true); + return declaredConstructor.newInstance(); + } catch (NoSuchMethodException e) { + return c.newInstance(); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/TestReadEmptyDesign.java b/server/tests/src/com/vaadin/tests/server/component/TestReadEmptyDesign.java deleted file mode 100644 index ecd303b678..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/TestReadEmptyDesign.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Document; -import org.jsoup.nodes.DocumentType; -import org.jsoup.nodes.Element; - -import com.vaadin.ui.Component; -import com.vaadin.ui.VerticalLayout; -import com.vaadin.ui.declarative.Design; -import com.vaadin.ui.declarative.DesignContext; -import com.vaadin.ui.declarative.DesignException; - -/** - * Test cases for checking that reading a design with no elements in the html - * body produces null as the root component. - */ -public class TestReadEmptyDesign extends TestCase { - InputStream is; - - @Override - protected void setUp() throws Exception { - super.setUp(); - String html = createDesign().toString(); - is = new ByteArrayInputStream(html.getBytes()); - } - - public void testReadComponent() { - Component root = Design.read(is); - assertNull("The root component should be null.", root); - } - - public void testReadContext() { - DesignContext ctx = Design.read(is, null); - assertNotNull("The design context should not be null.", ctx); - assertNull("The root component should be null.", ctx.getRootComponent()); - } - - public void testReadContextWithRootParameter() { - try { - Component rootComponent = new VerticalLayout(); - DesignContext ctx = Design.read(is, rootComponent); - fail("Reading a design with no elements should fail when a non-null root Component is specified."); - } catch (DesignException e) { - // This is the expected outcome, nothing to do. - } - } - - private Document createDesign() { - Document doc = new Document(""); - DocumentType docType = new DocumentType("html", "", "", ""); - doc.appendChild(docType); - Element html = doc.createElement("html"); - doc.appendChild(html); - html.appendChild(doc.createElement("head")); - html.appendChild(doc.createElement("body")); - return doc; - } -} \ No newline at end of file diff --git a/server/tests/src/com/vaadin/tests/server/component/TestWriteEmptyDesign.java b/server/tests/src/com/vaadin/tests/server/component/TestWriteEmptyDesign.java deleted file mode 100644 index b50915f1fd..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/TestWriteEmptyDesign.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -import junit.framework.TestCase; - -import org.jsoup.Jsoup; -import org.jsoup.nodes.Document; -import org.jsoup.nodes.Element; - -import com.vaadin.ui.Component; -import com.vaadin.ui.declarative.Design; -import com.vaadin.ui.declarative.DesignContext; - -/** - * Test cases for checking that writing a component hierarchy with null root - * produces an html document that has no elements in the html body. - */ -public class TestWriteEmptyDesign extends TestCase { - - public void testWriteComponent() throws IOException { - OutputStream os = new ByteArrayOutputStream(); - Design.write((Component) null, os); - checkHtml(os.toString()); - } - - public void testWriteContext() throws IOException { - OutputStream os = new ByteArrayOutputStream(); - DesignContext ctx = new DesignContext(); - ctx.setRootComponent(null); - Design.write(ctx, os); - checkHtml(os.toString()); - } - - private void checkHtml(String html) { - Document doc = Jsoup.parse(html); - Element body = doc.body(); - assertEquals("There should be no elements in the html body.", "", - body.html()); - } -} \ No newline at end of file diff --git a/server/tests/src/com/vaadin/tests/server/component/WriteEmptyDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/WriteEmptyDesignTest.java new file mode 100644 index 0000000000..a535de2b24 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/WriteEmptyDesignTest.java @@ -0,0 +1,58 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; + +import junit.framework.TestCase; + +import org.jsoup.Jsoup; +import org.jsoup.nodes.Document; +import org.jsoup.nodes.Element; + +import com.vaadin.ui.Component; +import com.vaadin.ui.declarative.Design; +import com.vaadin.ui.declarative.DesignContext; + +/** + * Test cases for checking that writing a component hierarchy with null root + * produces an html document that has no elements in the html body. + */ +public class WriteEmptyDesignTest extends TestCase { + + public void testWriteComponent() throws IOException { + OutputStream os = new ByteArrayOutputStream(); + Design.write((Component) null, os); + checkHtml(os.toString()); + } + + public void testWriteContext() throws IOException { + OutputStream os = new ByteArrayOutputStream(); + DesignContext ctx = new DesignContext(); + ctx.setRootComponent(null); + Design.write(ctx, os); + checkHtml(os.toString()); + } + + private void checkHtml(String html) { + Document doc = Jsoup.parse(html); + Element body = doc.body(); + assertEquals("There should be no elements in the html body.", "", + body.html()); + } +} \ No newline at end of file diff --git a/server/tests/src/com/vaadin/tests/server/component/absolutelayout/AbsoluteLayoutListeners.java b/server/tests/src/com/vaadin/tests/server/component/absolutelayout/AbsoluteLayoutListeners.java deleted file mode 100644 index 7d6db42d1a..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/absolutelayout/AbsoluteLayoutListeners.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.vaadin.tests.server.component.absolutelayout; - -import com.vaadin.event.LayoutEvents.LayoutClickEvent; -import com.vaadin.event.LayoutEvents.LayoutClickListener; -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; -import com.vaadin.ui.AbsoluteLayout; - -public class AbsoluteLayoutListeners extends AbstractListenerMethodsTest { - public void testLayoutClickListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(AbsoluteLayout.class, LayoutClickEvent.class, - LayoutClickListener.class); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/absolutelayout/AbsoluteLayoutListenersTest.java b/server/tests/src/com/vaadin/tests/server/component/absolutelayout/AbsoluteLayoutListenersTest.java new file mode 100644 index 0000000000..062a89ad62 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/absolutelayout/AbsoluteLayoutListenersTest.java @@ -0,0 +1,13 @@ +package com.vaadin.tests.server.component.absolutelayout; + +import com.vaadin.event.LayoutEvents.LayoutClickEvent; +import com.vaadin.event.LayoutEvents.LayoutClickListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; +import com.vaadin.ui.AbsoluteLayout; + +public class AbsoluteLayoutListenersTest extends AbstractListenerMethodsTestBase { + public void testLayoutClickListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(AbsoluteLayout.class, LayoutClickEvent.class, + LayoutClickListener.class); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/absolutelayout/ComponentPosition.java b/server/tests/src/com/vaadin/tests/server/component/absolutelayout/ComponentPosition.java deleted file mode 100644 index d76dcffa2f..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/absolutelayout/ComponentPosition.java +++ /dev/null @@ -1,204 +0,0 @@ -package com.vaadin.tests.server.component.absolutelayout; - -import junit.framework.TestCase; - -import com.vaadin.server.Sizeable; -import com.vaadin.server.Sizeable.Unit; -import com.vaadin.ui.AbsoluteLayout; -import com.vaadin.ui.Button; - -public class ComponentPosition extends TestCase { - - private static final String CSS = "top:7.0px;right:7.0%;bottom:7.0pc;left:7.0em;z-index:7;"; - private static final String PARTIAL_CSS = "top:7.0px;left:7.0em;"; - private static final Float CSS_VALUE = Float.valueOf(7); - - private static final Unit UNIT_UNSET = Sizeable.Unit.PIXELS; - - /** - * Add component w/o giving positions, assert that everything is unset - */ - public void testNoPosition() { - AbsoluteLayout layout = new AbsoluteLayout(); - Button b = new Button(); - layout.addComponent(b); - - assertNull(layout.getPosition(b).getTopValue()); - assertNull(layout.getPosition(b).getBottomValue()); - assertNull(layout.getPosition(b).getLeftValue()); - assertNull(layout.getPosition(b).getRightValue()); - - assertEquals(UNIT_UNSET, layout.getPosition(b).getTopUnits()); - assertEquals(UNIT_UNSET, layout.getPosition(b).getBottomUnits()); - assertEquals(UNIT_UNSET, layout.getPosition(b).getLeftUnits()); - assertEquals(UNIT_UNSET, layout.getPosition(b).getRightUnits()); - - assertEquals(-1, layout.getPosition(b).getZIndex()); - - assertEquals("", layout.getPosition(b).getCSSString()); - - } - - /** - * Add component, setting all attributes using CSS, assert getter agree - */ - public void testFullCss() { - AbsoluteLayout layout = new AbsoluteLayout(); - Button b = new Button(); - layout.addComponent(b, CSS); - - assertEquals(CSS_VALUE, layout.getPosition(b).getTopValue()); - assertEquals(CSS_VALUE, layout.getPosition(b).getBottomValue()); - assertEquals(CSS_VALUE, layout.getPosition(b).getLeftValue()); - assertEquals(CSS_VALUE, layout.getPosition(b).getRightValue()); - - assertEquals(Sizeable.Unit.PIXELS, layout.getPosition(b).getTopUnits()); - assertEquals(Sizeable.Unit.PICAS, layout.getPosition(b) - .getBottomUnits()); - assertEquals(Sizeable.Unit.EM, layout.getPosition(b).getLeftUnits()); - assertEquals(Sizeable.Unit.PERCENTAGE, layout.getPosition(b) - .getRightUnits()); - - assertEquals(7, layout.getPosition(b).getZIndex()); - - assertEquals(CSS, layout.getPosition(b).getCSSString()); - - } - - /** - * Add component, setting some attributes using CSS, assert getters agree - */ - public void testPartialCss() { - AbsoluteLayout layout = new AbsoluteLayout(); - Button b = new Button(); - layout.addComponent(b, PARTIAL_CSS); - - assertEquals(CSS_VALUE, layout.getPosition(b).getTopValue()); - assertNull(layout.getPosition(b).getBottomValue()); - assertEquals(CSS_VALUE, layout.getPosition(b).getLeftValue()); - assertNull(layout.getPosition(b).getRightValue()); - - assertEquals(Sizeable.Unit.PIXELS, layout.getPosition(b).getTopUnits()); - assertEquals(UNIT_UNSET, layout.getPosition(b).getBottomUnits()); - assertEquals(Sizeable.Unit.EM, layout.getPosition(b).getLeftUnits()); - assertEquals(UNIT_UNSET, layout.getPosition(b).getRightUnits()); - - assertEquals(-1, layout.getPosition(b).getZIndex()); - - assertEquals(PARTIAL_CSS, layout.getPosition(b).getCSSString()); - - } - - /** - * Add component setting all attributes using CSS, then reset using partial - * CSS; assert getters agree and the appropriate attributes are unset. - */ - public void testPartialCssReset() { - AbsoluteLayout layout = new AbsoluteLayout(); - Button b = new Button(); - layout.addComponent(b, CSS); - - layout.getPosition(b).setCSSString(PARTIAL_CSS); - - assertEquals(CSS_VALUE, layout.getPosition(b).getTopValue()); - assertNull(layout.getPosition(b).getBottomValue()); - assertEquals(CSS_VALUE, layout.getPosition(b).getLeftValue()); - assertNull(layout.getPosition(b).getRightValue()); - - assertEquals(Sizeable.Unit.PIXELS, layout.getPosition(b).getTopUnits()); - assertEquals(UNIT_UNSET, layout.getPosition(b).getBottomUnits()); - assertEquals(Sizeable.Unit.EM, layout.getPosition(b).getLeftUnits()); - assertEquals(UNIT_UNSET, layout.getPosition(b).getRightUnits()); - - assertEquals(-1, layout.getPosition(b).getZIndex()); - - assertEquals(PARTIAL_CSS, layout.getPosition(b).getCSSString()); - - } - - /** - * Add component, then set all position attributes with individual setters - * for value and units; assert getters agree. - */ - public void testSetPosition() { - final Float SIZE = Float.valueOf(12); - - AbsoluteLayout layout = new AbsoluteLayout(); - Button b = new Button(); - layout.addComponent(b); - - layout.getPosition(b).setTopValue(SIZE); - layout.getPosition(b).setRightValue(SIZE); - layout.getPosition(b).setBottomValue(SIZE); - layout.getPosition(b).setLeftValue(SIZE); - - layout.getPosition(b).setTopUnits(Sizeable.Unit.CM); - layout.getPosition(b).setRightUnits(Sizeable.Unit.EX); - layout.getPosition(b).setBottomUnits(Sizeable.Unit.INCH); - layout.getPosition(b).setLeftUnits(Sizeable.Unit.MM); - - assertEquals(SIZE, layout.getPosition(b).getTopValue()); - assertEquals(SIZE, layout.getPosition(b).getRightValue()); - assertEquals(SIZE, layout.getPosition(b).getBottomValue()); - assertEquals(SIZE, layout.getPosition(b).getLeftValue()); - - assertEquals(Sizeable.Unit.CM, layout.getPosition(b).getTopUnits()); - assertEquals(Sizeable.Unit.EX, layout.getPosition(b).getRightUnits()); - assertEquals(Sizeable.Unit.INCH, layout.getPosition(b).getBottomUnits()); - assertEquals(Sizeable.Unit.MM, layout.getPosition(b).getLeftUnits()); - - } - - /** - * Add component, then set all position attributes with combined setters for - * value and units; assert getters agree. - */ - public void testSetPosition2() { - final Float SIZE = Float.valueOf(12); - AbsoluteLayout layout = new AbsoluteLayout(); - Button b = new Button(); - layout.addComponent(b); - - layout.getPosition(b).setTop(SIZE, Sizeable.Unit.CM); - layout.getPosition(b).setRight(SIZE, Sizeable.Unit.EX); - layout.getPosition(b).setBottom(SIZE, Sizeable.Unit.INCH); - layout.getPosition(b).setLeft(SIZE, Sizeable.Unit.MM); - - assertEquals(SIZE, layout.getPosition(b).getTopValue()); - assertEquals(SIZE, layout.getPosition(b).getRightValue()); - assertEquals(SIZE, layout.getPosition(b).getBottomValue()); - assertEquals(SIZE, layout.getPosition(b).getLeftValue()); - - assertEquals(Sizeable.Unit.CM, layout.getPosition(b).getTopUnits()); - assertEquals(Sizeable.Unit.EX, layout.getPosition(b).getRightUnits()); - assertEquals(Sizeable.Unit.INCH, layout.getPosition(b).getBottomUnits()); - assertEquals(Sizeable.Unit.MM, layout.getPosition(b).getLeftUnits()); - - } - - /** - * Add component, set all attributes using CSS, unset some using method - * calls, assert getters agree. - */ - public void testUnsetPosition() { - AbsoluteLayout layout = new AbsoluteLayout(); - Button b = new Button(); - layout.addComponent(b, CSS); - - layout.getPosition(b).setTopValue(null); - layout.getPosition(b).setRightValue(null); - layout.getPosition(b).setBottomValue(null); - layout.getPosition(b).setLeftValue(null); - - layout.getPosition(b).setZIndex(-1); - - assertNull(layout.getPosition(b).getTopValue()); - assertNull(layout.getPosition(b).getBottomValue()); - assertNull(layout.getPosition(b).getLeftValue()); - assertNull(layout.getPosition(b).getRightValue()); - - assertEquals("", layout.getPosition(b).getCSSString()); - - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/component/absolutelayout/ComponentPositionTest.java b/server/tests/src/com/vaadin/tests/server/component/absolutelayout/ComponentPositionTest.java new file mode 100644 index 0000000000..eac7ff4d8a --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/absolutelayout/ComponentPositionTest.java @@ -0,0 +1,204 @@ +package com.vaadin.tests.server.component.absolutelayout; + +import junit.framework.TestCase; + +import com.vaadin.server.Sizeable; +import com.vaadin.server.Sizeable.Unit; +import com.vaadin.ui.AbsoluteLayout; +import com.vaadin.ui.Button; + +public class ComponentPositionTest extends TestCase { + + private static final String CSS = "top:7.0px;right:7.0%;bottom:7.0pc;left:7.0em;z-index:7;"; + private static final String PARTIAL_CSS = "top:7.0px;left:7.0em;"; + private static final Float CSS_VALUE = Float.valueOf(7); + + private static final Unit UNIT_UNSET = Sizeable.Unit.PIXELS; + + /** + * Add component w/o giving positions, assert that everything is unset + */ + public void testNoPosition() { + AbsoluteLayout layout = new AbsoluteLayout(); + Button b = new Button(); + layout.addComponent(b); + + assertNull(layout.getPosition(b).getTopValue()); + assertNull(layout.getPosition(b).getBottomValue()); + assertNull(layout.getPosition(b).getLeftValue()); + assertNull(layout.getPosition(b).getRightValue()); + + assertEquals(UNIT_UNSET, layout.getPosition(b).getTopUnits()); + assertEquals(UNIT_UNSET, layout.getPosition(b).getBottomUnits()); + assertEquals(UNIT_UNSET, layout.getPosition(b).getLeftUnits()); + assertEquals(UNIT_UNSET, layout.getPosition(b).getRightUnits()); + + assertEquals(-1, layout.getPosition(b).getZIndex()); + + assertEquals("", layout.getPosition(b).getCSSString()); + + } + + /** + * Add component, setting all attributes using CSS, assert getter agree + */ + public void testFullCss() { + AbsoluteLayout layout = new AbsoluteLayout(); + Button b = new Button(); + layout.addComponent(b, CSS); + + assertEquals(CSS_VALUE, layout.getPosition(b).getTopValue()); + assertEquals(CSS_VALUE, layout.getPosition(b).getBottomValue()); + assertEquals(CSS_VALUE, layout.getPosition(b).getLeftValue()); + assertEquals(CSS_VALUE, layout.getPosition(b).getRightValue()); + + assertEquals(Sizeable.Unit.PIXELS, layout.getPosition(b).getTopUnits()); + assertEquals(Sizeable.Unit.PICAS, layout.getPosition(b) + .getBottomUnits()); + assertEquals(Sizeable.Unit.EM, layout.getPosition(b).getLeftUnits()); + assertEquals(Sizeable.Unit.PERCENTAGE, layout.getPosition(b) + .getRightUnits()); + + assertEquals(7, layout.getPosition(b).getZIndex()); + + assertEquals(CSS, layout.getPosition(b).getCSSString()); + + } + + /** + * Add component, setting some attributes using CSS, assert getters agree + */ + public void testPartialCss() { + AbsoluteLayout layout = new AbsoluteLayout(); + Button b = new Button(); + layout.addComponent(b, PARTIAL_CSS); + + assertEquals(CSS_VALUE, layout.getPosition(b).getTopValue()); + assertNull(layout.getPosition(b).getBottomValue()); + assertEquals(CSS_VALUE, layout.getPosition(b).getLeftValue()); + assertNull(layout.getPosition(b).getRightValue()); + + assertEquals(Sizeable.Unit.PIXELS, layout.getPosition(b).getTopUnits()); + assertEquals(UNIT_UNSET, layout.getPosition(b).getBottomUnits()); + assertEquals(Sizeable.Unit.EM, layout.getPosition(b).getLeftUnits()); + assertEquals(UNIT_UNSET, layout.getPosition(b).getRightUnits()); + + assertEquals(-1, layout.getPosition(b).getZIndex()); + + assertEquals(PARTIAL_CSS, layout.getPosition(b).getCSSString()); + + } + + /** + * Add component setting all attributes using CSS, then reset using partial + * CSS; assert getters agree and the appropriate attributes are unset. + */ + public void testPartialCssReset() { + AbsoluteLayout layout = new AbsoluteLayout(); + Button b = new Button(); + layout.addComponent(b, CSS); + + layout.getPosition(b).setCSSString(PARTIAL_CSS); + + assertEquals(CSS_VALUE, layout.getPosition(b).getTopValue()); + assertNull(layout.getPosition(b).getBottomValue()); + assertEquals(CSS_VALUE, layout.getPosition(b).getLeftValue()); + assertNull(layout.getPosition(b).getRightValue()); + + assertEquals(Sizeable.Unit.PIXELS, layout.getPosition(b).getTopUnits()); + assertEquals(UNIT_UNSET, layout.getPosition(b).getBottomUnits()); + assertEquals(Sizeable.Unit.EM, layout.getPosition(b).getLeftUnits()); + assertEquals(UNIT_UNSET, layout.getPosition(b).getRightUnits()); + + assertEquals(-1, layout.getPosition(b).getZIndex()); + + assertEquals(PARTIAL_CSS, layout.getPosition(b).getCSSString()); + + } + + /** + * Add component, then set all position attributes with individual setters + * for value and units; assert getters agree. + */ + public void testSetPosition() { + final Float SIZE = Float.valueOf(12); + + AbsoluteLayout layout = new AbsoluteLayout(); + Button b = new Button(); + layout.addComponent(b); + + layout.getPosition(b).setTopValue(SIZE); + layout.getPosition(b).setRightValue(SIZE); + layout.getPosition(b).setBottomValue(SIZE); + layout.getPosition(b).setLeftValue(SIZE); + + layout.getPosition(b).setTopUnits(Sizeable.Unit.CM); + layout.getPosition(b).setRightUnits(Sizeable.Unit.EX); + layout.getPosition(b).setBottomUnits(Sizeable.Unit.INCH); + layout.getPosition(b).setLeftUnits(Sizeable.Unit.MM); + + assertEquals(SIZE, layout.getPosition(b).getTopValue()); + assertEquals(SIZE, layout.getPosition(b).getRightValue()); + assertEquals(SIZE, layout.getPosition(b).getBottomValue()); + assertEquals(SIZE, layout.getPosition(b).getLeftValue()); + + assertEquals(Sizeable.Unit.CM, layout.getPosition(b).getTopUnits()); + assertEquals(Sizeable.Unit.EX, layout.getPosition(b).getRightUnits()); + assertEquals(Sizeable.Unit.INCH, layout.getPosition(b).getBottomUnits()); + assertEquals(Sizeable.Unit.MM, layout.getPosition(b).getLeftUnits()); + + } + + /** + * Add component, then set all position attributes with combined setters for + * value and units; assert getters agree. + */ + public void testSetPosition2() { + final Float SIZE = Float.valueOf(12); + AbsoluteLayout layout = new AbsoluteLayout(); + Button b = new Button(); + layout.addComponent(b); + + layout.getPosition(b).setTop(SIZE, Sizeable.Unit.CM); + layout.getPosition(b).setRight(SIZE, Sizeable.Unit.EX); + layout.getPosition(b).setBottom(SIZE, Sizeable.Unit.INCH); + layout.getPosition(b).setLeft(SIZE, Sizeable.Unit.MM); + + assertEquals(SIZE, layout.getPosition(b).getTopValue()); + assertEquals(SIZE, layout.getPosition(b).getRightValue()); + assertEquals(SIZE, layout.getPosition(b).getBottomValue()); + assertEquals(SIZE, layout.getPosition(b).getLeftValue()); + + assertEquals(Sizeable.Unit.CM, layout.getPosition(b).getTopUnits()); + assertEquals(Sizeable.Unit.EX, layout.getPosition(b).getRightUnits()); + assertEquals(Sizeable.Unit.INCH, layout.getPosition(b).getBottomUnits()); + assertEquals(Sizeable.Unit.MM, layout.getPosition(b).getLeftUnits()); + + } + + /** + * Add component, set all attributes using CSS, unset some using method + * calls, assert getters agree. + */ + public void testUnsetPosition() { + AbsoluteLayout layout = new AbsoluteLayout(); + Button b = new Button(); + layout.addComponent(b, CSS); + + layout.getPosition(b).setTopValue(null); + layout.getPosition(b).setRightValue(null); + layout.getPosition(b).setBottomValue(null); + layout.getPosition(b).setLeftValue(null); + + layout.getPosition(b).setZIndex(-1); + + assertNull(layout.getPosition(b).getTopValue()); + assertNull(layout.getPosition(b).getBottomValue()); + assertNull(layout.getPosition(b).getLeftValue()); + assertNull(layout.getPosition(b).getRightValue()); + + assertEquals("", layout.getPosition(b).getCSSString()); + + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/component/absolutelayout/ReadDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/absolutelayout/ReadDesignTest.java new file mode 100644 index 0000000000..f17e1ada44 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/absolutelayout/ReadDesignTest.java @@ -0,0 +1,110 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.absolutelayout; + +import java.util.Iterator; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Attributes; +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; + +import com.vaadin.server.Sizeable; +import com.vaadin.ui.AbsoluteLayout; +import com.vaadin.ui.AbsoluteLayout.ComponentPosition; +import com.vaadin.ui.Component; +import com.vaadin.ui.declarative.DesignContext; + +/** + * Test case for reading AbsoluteLayout from design + * + * @since + * @author Vaadin Ltd + */ +public class ReadDesignTest extends TestCase { + + private AbsoluteLayout root; + + @Override + public void setUp() throws Exception { + super.setUp(); + root = createLayout(); + } + + public void testAttributes() { + assertEquals("test-layout", root.getCaption()); + Iterator children = root.iterator(); + assertEquals("test-label", children.next().getCaption()); + assertEquals("test-button", children.next().getCaption()); + } + + public void testTopLeftPosition() { + ComponentPosition position = root.getPosition(root.iterator().next()); + assertEquals(Sizeable.Unit.PIXELS, position.getTopUnits()); + assertEquals(100.0f, position.getTopValue()); + assertEquals(Sizeable.Unit.PERCENTAGE, position.getLeftUnits()); + assertEquals(50.0f, position.getLeftValue()); + } + + public void testBottomRightPosition() { + Iterator children = root.iterator(); + children.next(); + ComponentPosition position = root.getPosition(children.next()); + assertEquals(Sizeable.Unit.PIXELS, position.getBottomUnits()); + assertEquals(100.0f, position.getBottomValue()); + assertEquals(Sizeable.Unit.PERCENTAGE, position.getRightUnits()); + assertEquals(50.0f, position.getRightValue()); + } + + public void testZIndex() { + ComponentPosition position = root.getPosition(root.iterator().next()); + assertEquals(2, position.getZIndex()); + } + + private AbsoluteLayout createLayout() { + DesignContext ctx = new DesignContext(); + Element design = createDesign(); + Component child = ctx.readDesign(design); + return (AbsoluteLayout) child; + } + + private Element createDesign() { + + Attributes rootAttributes = new Attributes(); + rootAttributes.put("caption", "test-layout"); + Element node = new Element(Tag.valueOf("v-absolute-layout"), "", + rootAttributes); + + Attributes firstChildAttributes = new Attributes(); + firstChildAttributes.put("caption", "test-label"); + firstChildAttributes.put(":top", "100px"); + firstChildAttributes.put(":left", "50%"); + firstChildAttributes.put(":z-index", "2"); + Element firstChild = new Element(Tag.valueOf("v-label"), "", + firstChildAttributes); + node.appendChild(firstChild); + + Attributes secondChildAttributes = new Attributes(); + secondChildAttributes.put(":bottom", "100px"); + secondChildAttributes.put(":right", "50%"); + Element secondChild = new Element(Tag.valueOf("v-button"), "", + secondChildAttributes); + secondChild.html("test-button"); + node.appendChild(secondChild); + return node; + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/absolutelayout/TestReadDesign.java b/server/tests/src/com/vaadin/tests/server/component/absolutelayout/TestReadDesign.java deleted file mode 100644 index f8af0a992e..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/absolutelayout/TestReadDesign.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.absolutelayout; - -import java.util.Iterator; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Attributes; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; - -import com.vaadin.server.Sizeable; -import com.vaadin.ui.AbsoluteLayout; -import com.vaadin.ui.AbsoluteLayout.ComponentPosition; -import com.vaadin.ui.Component; -import com.vaadin.ui.declarative.DesignContext; - -/** - * Test case for reading AbsoluteLayout from design - * - * @since - * @author Vaadin Ltd - */ -public class TestReadDesign extends TestCase { - - private AbsoluteLayout root; - - @Override - public void setUp() throws Exception { - super.setUp(); - root = createLayout(); - } - - public void testAttributes() { - assertEquals("test-layout", root.getCaption()); - Iterator children = root.iterator(); - assertEquals("test-label", children.next().getCaption()); - assertEquals("test-button", children.next().getCaption()); - } - - public void testTopLeftPosition() { - ComponentPosition position = root.getPosition(root.iterator().next()); - assertEquals(Sizeable.Unit.PIXELS, position.getTopUnits()); - assertEquals(100.0f, position.getTopValue()); - assertEquals(Sizeable.Unit.PERCENTAGE, position.getLeftUnits()); - assertEquals(50.0f, position.getLeftValue()); - } - - public void testBottomRightPosition() { - Iterator children = root.iterator(); - children.next(); - ComponentPosition position = root.getPosition(children.next()); - assertEquals(Sizeable.Unit.PIXELS, position.getBottomUnits()); - assertEquals(100.0f, position.getBottomValue()); - assertEquals(Sizeable.Unit.PERCENTAGE, position.getRightUnits()); - assertEquals(50.0f, position.getRightValue()); - } - - public void testZIndex() { - ComponentPosition position = root.getPosition(root.iterator().next()); - assertEquals(2, position.getZIndex()); - } - - private AbsoluteLayout createLayout() { - DesignContext ctx = new DesignContext(); - Element design = createDesign(); - Component child = ctx.readDesign(design); - return (AbsoluteLayout) child; - } - - private Element createDesign() { - - Attributes rootAttributes = new Attributes(); - rootAttributes.put("caption", "test-layout"); - Element node = new Element(Tag.valueOf("v-absolute-layout"), "", - rootAttributes); - - Attributes firstChildAttributes = new Attributes(); - firstChildAttributes.put("caption", "test-label"); - firstChildAttributes.put(":top", "100px"); - firstChildAttributes.put(":left", "50%"); - firstChildAttributes.put(":z-index", "2"); - Element firstChild = new Element(Tag.valueOf("v-label"), "", - firstChildAttributes); - node.appendChild(firstChild); - - Attributes secondChildAttributes = new Attributes(); - secondChildAttributes.put(":bottom", "100px"); - secondChildAttributes.put(":right", "50%"); - Element secondChild = new Element(Tag.valueOf("v-button"), "", - secondChildAttributes); - secondChild.html("test-button"); - node.appendChild(secondChild); - return node; - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/absolutelayout/TestWriteDesign.java b/server/tests/src/com/vaadin/tests/server/component/absolutelayout/TestWriteDesign.java deleted file mode 100644 index 5f42b1fa81..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/absolutelayout/TestWriteDesign.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.absolutelayout; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Attributes; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; - -import com.vaadin.ui.AbsoluteLayout; -import com.vaadin.ui.Label; -import com.vaadin.ui.declarative.DesignContext; - -/** - * Test case for writing AbsoluteLayout to design - * - * @since - * @author Vaadin Ltd - */ -public class TestWriteDesign extends TestCase { - - public void testSynchronizeEmptyLayout() { - AbsoluteLayout layout = createTestLayout(); - layout.removeAllComponents(); - Element design = createDesign(); - layout.writeDesign(design, createDesignContext()); - assertEquals(0, design.childNodes().size()); - assertEquals("changed-caption", design.attr("caption")); - } - - public void testSynchronizeLayoutWithChildren() { - AbsoluteLayout layout = createTestLayout(); - Element design = createDesign(); - layout.writeDesign(design, createDesignContext()); - assertEquals(2, design.childNodes().size()); - assertEquals("v-label", ((Element) design.childNode(0)).tagName()); - assertEquals("v-label", ((Element) design.childNode(1)).tagName()); - } - - public void testSynchronizePosition() { - AbsoluteLayout layout = createTestLayout(); - Element design = createDesign(); - layout.writeDesign(design, createDesignContext()); - Attributes attributes = design.childNode(0).attributes(); - assertEquals("50px", attributes.get(":top")); - assertEquals("50%", attributes.get(":left")); - assertEquals("2", attributes.get(":z-index")); - attributes = design.childNode(1).attributes(); - assertEquals("50px", attributes.get(":bottom")); - assertEquals("50%", attributes.get(":right")); - } - - private AbsoluteLayout createTestLayout() { - AbsoluteLayout layout = new AbsoluteLayout(); - layout.setCaption("changed-caption"); - layout.addComponent(new Label("test-label"), - "top:50px;left:50%;z-index:2"); - layout.addComponent(new Label("test-label-2"), - "bottom:50px;right:50%;z-index:3"); - return layout; - } - - private Element createDesign() { - // make sure that the design node has old content that should be removed - Attributes rootAttributes = new Attributes(); - rootAttributes.put("caption", "test-layout"); - Element node = new Element(Tag.valueOf("v-absolute-layout"), "", - rootAttributes); - Attributes firstChildAttributes = new Attributes(); - firstChildAttributes.put("caption", "test-label"); - Element firstChild = new Element(Tag.valueOf("v-label"), "", - firstChildAttributes); - node.appendChild(firstChild); - - Attributes secondChildAttributes = new Attributes(); - secondChildAttributes.put("caption", "test-button"); - Element secondChild = new Element(Tag.valueOf("v-button"), "", - secondChildAttributes); - node.appendChild(secondChild); - return node; - } - - private DesignContext createDesignContext() { - return new DesignContext(); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/absolutelayout/WriteDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/absolutelayout/WriteDesignTest.java new file mode 100644 index 0000000000..39a2207819 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/absolutelayout/WriteDesignTest.java @@ -0,0 +1,100 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.absolutelayout; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Attributes; +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; + +import com.vaadin.ui.AbsoluteLayout; +import com.vaadin.ui.Label; +import com.vaadin.ui.declarative.DesignContext; + +/** + * Test case for writing AbsoluteLayout to design + * + * @since + * @author Vaadin Ltd + */ +public class WriteDesignTest extends TestCase { + + public void testSynchronizeEmptyLayout() { + AbsoluteLayout layout = createTestLayout(); + layout.removeAllComponents(); + Element design = createDesign(); + layout.writeDesign(design, createDesignContext()); + assertEquals(0, design.childNodes().size()); + assertEquals("changed-caption", design.attr("caption")); + } + + public void testSynchronizeLayoutWithChildren() { + AbsoluteLayout layout = createTestLayout(); + Element design = createDesign(); + layout.writeDesign(design, createDesignContext()); + assertEquals(2, design.childNodes().size()); + assertEquals("v-label", ((Element) design.childNode(0)).tagName()); + assertEquals("v-label", ((Element) design.childNode(1)).tagName()); + } + + public void testSynchronizePosition() { + AbsoluteLayout layout = createTestLayout(); + Element design = createDesign(); + layout.writeDesign(design, createDesignContext()); + Attributes attributes = design.childNode(0).attributes(); + assertEquals("50px", attributes.get(":top")); + assertEquals("50%", attributes.get(":left")); + assertEquals("2", attributes.get(":z-index")); + attributes = design.childNode(1).attributes(); + assertEquals("50px", attributes.get(":bottom")); + assertEquals("50%", attributes.get(":right")); + } + + private AbsoluteLayout createTestLayout() { + AbsoluteLayout layout = new AbsoluteLayout(); + layout.setCaption("changed-caption"); + layout.addComponent(new Label("test-label"), + "top:50px;left:50%;z-index:2"); + layout.addComponent(new Label("test-label-2"), + "bottom:50px;right:50%;z-index:3"); + return layout; + } + + private Element createDesign() { + // make sure that the design node has old content that should be removed + Attributes rootAttributes = new Attributes(); + rootAttributes.put("caption", "test-layout"); + Element node = new Element(Tag.valueOf("v-absolute-layout"), "", + rootAttributes); + Attributes firstChildAttributes = new Attributes(); + firstChildAttributes.put("caption", "test-label"); + Element firstChild = new Element(Tag.valueOf("v-label"), "", + firstChildAttributes); + node.appendChild(firstChild); + + Attributes secondChildAttributes = new Attributes(); + secondChildAttributes.put("caption", "test-button"); + Element secondChild = new Element(Tag.valueOf("v-button"), "", + secondChildAttributes); + node.appendChild(secondChild); + return node; + } + + private DesignContext createDesignContext() { + return new DesignContext(); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractcomponent/AbstractComponentStyleNamesTest.java b/server/tests/src/com/vaadin/tests/server/component/abstractcomponent/AbstractComponentStyleNamesTest.java new file mode 100644 index 0000000000..18eb79aadc --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstractcomponent/AbstractComponentStyleNamesTest.java @@ -0,0 +1,61 @@ +package com.vaadin.tests.server.component.abstractcomponent; + +import junit.framework.TestCase; + +import com.vaadin.ui.AbstractComponent; + +public class AbstractComponentStyleNamesTest extends TestCase { + + public void testSetMultiple() { + AbstractComponent component = getComponent(); + component.setStyleName("style1 style2"); + assertEquals(component.getStyleName(), "style1 style2"); + } + + public void testSetAdd() { + AbstractComponent component = getComponent(); + component.setStyleName("style1"); + component.addStyleName("style2"); + assertEquals(component.getStyleName(), "style1 style2"); + } + + public void testAddSame() { + AbstractComponent component = getComponent(); + component.setStyleName("style1 style2"); + component.addStyleName("style1"); + assertEquals(component.getStyleName(), "style1 style2"); + } + + public void testSetRemove() { + AbstractComponent component = getComponent(); + component.setStyleName("style1 style2"); + component.removeStyleName("style1"); + assertEquals(component.getStyleName(), "style2"); + } + + public void testAddRemove() { + AbstractComponent component = getComponent(); + component.addStyleName("style1"); + component.addStyleName("style2"); + component.removeStyleName("style1"); + assertEquals(component.getStyleName(), "style2"); + } + + public void testRemoveMultipleWithExtraSpaces() { + AbstractComponent component = getComponent(); + component.setStyleName("style1 style2 style3"); + component.removeStyleName(" style1 style3 "); + assertEquals(component.getStyleName(), "style2"); + } + + public void testSetWithExtraSpaces() { + AbstractComponent component = getComponent(); + component.setStyleName(" style1 style2 "); + assertEquals(component.getStyleName(), "style1 style2"); + } + + private AbstractComponent getComponent() { + return new AbstractComponent() { + }; + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractcomponent/ReadDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/abstractcomponent/ReadDesignTest.java new file mode 100644 index 0000000000..79979e03d9 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstractcomponent/ReadDesignTest.java @@ -0,0 +1,256 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.abstractcomponent; + +import java.lang.reflect.Field; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Attributes; +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; + +import com.vaadin.server.ExternalResource; +import com.vaadin.server.FileResource; +import com.vaadin.server.Responsive; +import com.vaadin.server.ThemeResource; +import com.vaadin.ui.AbstractComponent; +import com.vaadin.ui.Label; +import com.vaadin.ui.declarative.DesignContext; + +/** + * Test case for reading the attributes of the AbstractComponent from design + * + * @author Vaadin Ltd + */ +public class ReadDesignTest extends TestCase { + + private DesignContext ctx; + + @Override + protected void setUp() throws Exception { + super.setUp(); + ctx = new DesignContext(); + } + + public void testSynchronizeId() { + Element design = createDesign("id", "testId"); + AbstractComponent component = getComponent(); + component.readDesign(design, ctx); + assertEquals("testId", component.getId()); + } + + public void testSynchronizePrimaryStyleName() { + Element design = createDesign("primary-style-name", "test-style"); + AbstractComponent component = getComponent(); + component.readDesign(design, ctx); + assertEquals("test-style", component.getPrimaryStyleName()); + } + + public void testSynchronizeCaption() { + Element design = createDesign("caption", "test-caption"); + AbstractComponent component = getComponent(); + component.readDesign(design, ctx); + assertEquals("test-caption", component.getCaption()); + } + + public void testSynchronizeLocale() { + Element design = createDesign("locale", "fi_FI"); + AbstractComponent component = getComponent(); + component.readDesign(design, ctx); + assertEquals("fi", component.getLocale().getLanguage()); + assertEquals("FI", component.getLocale().getCountry()); + } + + public void testSynchronizeExternalIcon() { + Element design = createDesign("icon", "http://example.com/example.gif"); + AbstractComponent component = getComponent(); + component.readDesign(design, ctx); + assertTrue("Incorrect resource type returned", component.getIcon() + .getClass().isAssignableFrom(ExternalResource.class)); + assertEquals("http://example.com/example.gif", + ((ExternalResource) component.getIcon()).getURL()); + } + + public void testSynchronizeThemeIcon() { + Element design = createDesign("icon", "theme://example.gif"); + AbstractComponent component = getComponent(); + component.readDesign(design, ctx); + assertTrue("Incorrect resource type returned", component.getIcon() + .getClass().isAssignableFrom(ThemeResource.class)); + } + + public void testSynchronizeFileResource() { + Element design = createDesign("icon", "img/example.gif"); + AbstractComponent component = getComponent(); + component.readDesign(design, ctx); + assertTrue("Incorrect resource type returned", component.getIcon() + .getClass().isAssignableFrom(FileResource.class)); + } + + public void testSynchronizeImmediate() { + Element design = createDesign("immediate", "true"); + AbstractComponent component = getComponent(); + component.readDesign(design, ctx); + assertEquals(true, component.isImmediate()); + assertEquals(Boolean.TRUE, getExplicitImmediate(component)); + // Synchronize with a design having no immediate attribute - + // explicitImmediate should then be null. + design = createDesign("description", "test-description"); + component = getComponent(); + component.readDesign(design, ctx); + // Synchronize with a design having immediate = false + design = createDesign("immediate", "false"); + component.readDesign(design, ctx); + assertEquals(false, component.isImmediate()); + assertEquals(Boolean.FALSE, getExplicitImmediate(component)); + // Synchronize with a design having immediate = "" - should correspond + // to + // true. + design = createDesign("immediate", ""); + component.readDesign(design, ctx); + assertEquals(true, component.isImmediate()); + assertEquals(Boolean.TRUE, getExplicitImmediate(component)); + } + + public void testSynchronizeDescription() { + Element design = createDesign("description", "test-description"); + AbstractComponent component = getComponent(); + component.readDesign(design, ctx); + assertEquals("test-description", component.getDescription()); + } + + public void testSynchronizeComponentError() { + Element design = createDesign("error", "
    test-error
    "); + AbstractComponent component = getComponent(); + component.readDesign(design, ctx); + assertEquals("
    test-error
    ", component.getComponentError() + .getFormattedHtmlMessage()); + } + + public void testSynchronizeSizeFull() { + Element design = createDesign("size-full", ""); + AbstractComponent component = getComponent(); + component.readDesign(design, ctx); + assertEquals(100, component.getWidth(), 0.1f); + assertEquals(100, component.getHeight(), 0.1f); + } + + public void testSynchronizeSizeAuto() { + Element design = createDesign("size-auto", ""); + AbstractComponent component = getComponent(); + component.readDesign(design, ctx); + assertEquals(-1, component.getWidth(), 0.1f); + assertEquals(-1, component.getHeight(), 0.1f); + } + + public void testSynchronizeHeightFull() { + Element design = createDesign("height-full", ""); + AbstractComponent component = getComponent(); + component.readDesign(design, ctx); + assertEquals(100, component.getHeight(), 0.1f); + } + + public void testSynchronizeHeightAuto() { + Element design = createDesign("height-auto", ""); + AbstractComponent component = getComponent(); + component.readDesign(design, ctx); + assertEquals(-1, component.getHeight(), 0.1f); + } + + public void testSynchronizeWidthFull() { + Element design = createDesign("width-full", ""); + AbstractComponent component = getComponent(); + component.readDesign(design, ctx); + assertEquals(100, component.getWidth(), 0.1f); + } + + public void testSynchronizeWidthAuto() { + Element design = createDesign("width-auto", ""); + AbstractComponent component = getComponent(); + component.readDesign(design, ctx); + assertEquals(-1, component.getWidth(), 0.1f); + } + + public void testSynchronizeWidth() { + Element design = createDesign("width", "12px"); + AbstractComponent component = getComponent(); + component.readDesign(design, ctx); + assertEquals(12, component.getWidth(), 0.1f); + assertEquals(com.vaadin.server.Sizeable.Unit.PIXELS, + component.getWidthUnits()); + } + + public void testSynchronizeHeight() { + Element design = createDesign("height", "12px"); + AbstractComponent component = getComponent(); + component.readDesign(design, ctx); + assertEquals(12, component.getHeight(), 0.1f); + assertEquals(com.vaadin.server.Sizeable.Unit.PIXELS, + component.getHeightUnits()); + } + + public void testSynchronizeNotResponsive() { + AbstractComponent component = getComponent(); + Responsive.makeResponsive(component); + Element design = createDesign("responsive", "false"); + component.readDesign(design, ctx); + assertEquals("Component should not have extensions", 0, component + .getExtensions().size()); + } + + public void testSynchronizeResponsive() { + AbstractComponent component = getComponent(); + Element design = createDesign("responsive", ""); + component.readDesign(design, ctx); + assertEquals("Component should have one extension", 1, component + .getExtensions().size()); + assertTrue("Extension should be responsive", component.getExtensions() + .iterator().next() instanceof Responsive); + } + + public void testSynchronizeAlreadyResponsive() { + AbstractComponent component = getComponent(); + Responsive.makeResponsive(component); + Element design = createDesign("responsive", ""); + component.readDesign(design, ctx); + assertEquals("Component should have only one extension", 1, component + .getExtensions().size()); + } + + private AbstractComponent getComponent() { + return new Label(); + } + + private Element createDesign(String key, String value) { + Attributes attributes = new Attributes(); + attributes.put(key, value); + Element node = new Element(Tag.valueOf("v-label"), "", attributes); + return node; + } + + private Boolean getExplicitImmediate(AbstractComponent component) { + try { + Field immediate = AbstractComponent.class + .getDeclaredField("explicitImmediateValue"); + immediate.setAccessible(true); + return (Boolean) immediate.get(component); + } catch (Exception e) { + throw new RuntimeException( + "Getting the field explicitImmediateValue failed."); + } + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractcomponent/TestAbstractComponentStyleNames.java b/server/tests/src/com/vaadin/tests/server/component/abstractcomponent/TestAbstractComponentStyleNames.java deleted file mode 100644 index 1903e66f92..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstractcomponent/TestAbstractComponentStyleNames.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.vaadin.tests.server.component.abstractcomponent; - -import junit.framework.TestCase; - -import com.vaadin.ui.AbstractComponent; - -public class TestAbstractComponentStyleNames extends TestCase { - - public void testSetMultiple() { - AbstractComponent component = getComponent(); - component.setStyleName("style1 style2"); - assertEquals(component.getStyleName(), "style1 style2"); - } - - public void testSetAdd() { - AbstractComponent component = getComponent(); - component.setStyleName("style1"); - component.addStyleName("style2"); - assertEquals(component.getStyleName(), "style1 style2"); - } - - public void testAddSame() { - AbstractComponent component = getComponent(); - component.setStyleName("style1 style2"); - component.addStyleName("style1"); - assertEquals(component.getStyleName(), "style1 style2"); - } - - public void testSetRemove() { - AbstractComponent component = getComponent(); - component.setStyleName("style1 style2"); - component.removeStyleName("style1"); - assertEquals(component.getStyleName(), "style2"); - } - - public void testAddRemove() { - AbstractComponent component = getComponent(); - component.addStyleName("style1"); - component.addStyleName("style2"); - component.removeStyleName("style1"); - assertEquals(component.getStyleName(), "style2"); - } - - public void testRemoveMultipleWithExtraSpaces() { - AbstractComponent component = getComponent(); - component.setStyleName("style1 style2 style3"); - component.removeStyleName(" style1 style3 "); - assertEquals(component.getStyleName(), "style2"); - } - - public void testSetWithExtraSpaces() { - AbstractComponent component = getComponent(); - component.setStyleName(" style1 style2 "); - assertEquals(component.getStyleName(), "style1 style2"); - } - - private AbstractComponent getComponent() { - return new AbstractComponent() { - }; - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractcomponent/TestReadDesign.java b/server/tests/src/com/vaadin/tests/server/component/abstractcomponent/TestReadDesign.java deleted file mode 100644 index 43a050ba80..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstractcomponent/TestReadDesign.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.abstractcomponent; - -import java.lang.reflect.Field; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Attributes; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; - -import com.vaadin.server.ExternalResource; -import com.vaadin.server.FileResource; -import com.vaadin.server.Responsive; -import com.vaadin.server.ThemeResource; -import com.vaadin.ui.AbstractComponent; -import com.vaadin.ui.Label; -import com.vaadin.ui.declarative.DesignContext; - -/** - * Test case for reading the attributes of the AbstractComponent from design - * - * @author Vaadin Ltd - */ -public class TestReadDesign extends TestCase { - - private DesignContext ctx; - - @Override - protected void setUp() throws Exception { - super.setUp(); - ctx = new DesignContext(); - } - - public void testSynchronizeId() { - Element design = createDesign("id", "testId"); - AbstractComponent component = getComponent(); - component.readDesign(design, ctx); - assertEquals("testId", component.getId()); - } - - public void testSynchronizePrimaryStyleName() { - Element design = createDesign("primary-style-name", "test-style"); - AbstractComponent component = getComponent(); - component.readDesign(design, ctx); - assertEquals("test-style", component.getPrimaryStyleName()); - } - - public void testSynchronizeCaption() { - Element design = createDesign("caption", "test-caption"); - AbstractComponent component = getComponent(); - component.readDesign(design, ctx); - assertEquals("test-caption", component.getCaption()); - } - - public void testSynchronizeLocale() { - Element design = createDesign("locale", "fi_FI"); - AbstractComponent component = getComponent(); - component.readDesign(design, ctx); - assertEquals("fi", component.getLocale().getLanguage()); - assertEquals("FI", component.getLocale().getCountry()); - } - - public void testSynchronizeExternalIcon() { - Element design = createDesign("icon", "http://example.com/example.gif"); - AbstractComponent component = getComponent(); - component.readDesign(design, ctx); - assertTrue("Incorrect resource type returned", component.getIcon() - .getClass().isAssignableFrom(ExternalResource.class)); - assertEquals("http://example.com/example.gif", - ((ExternalResource) component.getIcon()).getURL()); - } - - public void testSynchronizeThemeIcon() { - Element design = createDesign("icon", "theme://example.gif"); - AbstractComponent component = getComponent(); - component.readDesign(design, ctx); - assertTrue("Incorrect resource type returned", component.getIcon() - .getClass().isAssignableFrom(ThemeResource.class)); - } - - public void testSynchronizeFileResource() { - Element design = createDesign("icon", "img/example.gif"); - AbstractComponent component = getComponent(); - component.readDesign(design, ctx); - assertTrue("Incorrect resource type returned", component.getIcon() - .getClass().isAssignableFrom(FileResource.class)); - } - - public void testSynchronizeImmediate() { - Element design = createDesign("immediate", "true"); - AbstractComponent component = getComponent(); - component.readDesign(design, ctx); - assertEquals(true, component.isImmediate()); - assertEquals(Boolean.TRUE, getExplicitImmediate(component)); - // Synchronize with a design having no immediate attribute - - // explicitImmediate should then be null. - design = createDesign("description", "test-description"); - component = getComponent(); - component.readDesign(design, ctx); - // Synchronize with a design having immediate = false - design = createDesign("immediate", "false"); - component.readDesign(design, ctx); - assertEquals(false, component.isImmediate()); - assertEquals(Boolean.FALSE, getExplicitImmediate(component)); - // Synchronize with a design having immediate = "" - should correspond - // to - // true. - design = createDesign("immediate", ""); - component.readDesign(design, ctx); - assertEquals(true, component.isImmediate()); - assertEquals(Boolean.TRUE, getExplicitImmediate(component)); - } - - public void testSynchronizeDescription() { - Element design = createDesign("description", "test-description"); - AbstractComponent component = getComponent(); - component.readDesign(design, ctx); - assertEquals("test-description", component.getDescription()); - } - - public void testSynchronizeComponentError() { - Element design = createDesign("error", "
    test-error
    "); - AbstractComponent component = getComponent(); - component.readDesign(design, ctx); - assertEquals("
    test-error
    ", component.getComponentError() - .getFormattedHtmlMessage()); - } - - public void testSynchronizeSizeFull() { - Element design = createDesign("size-full", ""); - AbstractComponent component = getComponent(); - component.readDesign(design, ctx); - assertEquals(100, component.getWidth(), 0.1f); - assertEquals(100, component.getHeight(), 0.1f); - } - - public void testSynchronizeSizeAuto() { - Element design = createDesign("size-auto", ""); - AbstractComponent component = getComponent(); - component.readDesign(design, ctx); - assertEquals(-1, component.getWidth(), 0.1f); - assertEquals(-1, component.getHeight(), 0.1f); - } - - public void testSynchronizeHeightFull() { - Element design = createDesign("height-full", ""); - AbstractComponent component = getComponent(); - component.readDesign(design, ctx); - assertEquals(100, component.getHeight(), 0.1f); - } - - public void testSynchronizeHeightAuto() { - Element design = createDesign("height-auto", ""); - AbstractComponent component = getComponent(); - component.readDesign(design, ctx); - assertEquals(-1, component.getHeight(), 0.1f); - } - - public void testSynchronizeWidthFull() { - Element design = createDesign("width-full", ""); - AbstractComponent component = getComponent(); - component.readDesign(design, ctx); - assertEquals(100, component.getWidth(), 0.1f); - } - - public void testSynchronizeWidthAuto() { - Element design = createDesign("width-auto", ""); - AbstractComponent component = getComponent(); - component.readDesign(design, ctx); - assertEquals(-1, component.getWidth(), 0.1f); - } - - public void testSynchronizeWidth() { - Element design = createDesign("width", "12px"); - AbstractComponent component = getComponent(); - component.readDesign(design, ctx); - assertEquals(12, component.getWidth(), 0.1f); - assertEquals(com.vaadin.server.Sizeable.Unit.PIXELS, - component.getWidthUnits()); - } - - public void testSynchronizeHeight() { - Element design = createDesign("height", "12px"); - AbstractComponent component = getComponent(); - component.readDesign(design, ctx); - assertEquals(12, component.getHeight(), 0.1f); - assertEquals(com.vaadin.server.Sizeable.Unit.PIXELS, - component.getHeightUnits()); - } - - public void testSynchronizeNotResponsive() { - AbstractComponent component = getComponent(); - Responsive.makeResponsive(component); - Element design = createDesign("responsive", "false"); - component.readDesign(design, ctx); - assertEquals("Component should not have extensions", 0, component - .getExtensions().size()); - } - - public void testSynchronizeResponsive() { - AbstractComponent component = getComponent(); - Element design = createDesign("responsive", ""); - component.readDesign(design, ctx); - assertEquals("Component should have one extension", 1, component - .getExtensions().size()); - assertTrue("Extension should be responsive", component.getExtensions() - .iterator().next() instanceof Responsive); - } - - public void testSynchronizeAlreadyResponsive() { - AbstractComponent component = getComponent(); - Responsive.makeResponsive(component); - Element design = createDesign("responsive", ""); - component.readDesign(design, ctx); - assertEquals("Component should have only one extension", 1, component - .getExtensions().size()); - } - - private AbstractComponent getComponent() { - return new Label(); - } - - private Element createDesign(String key, String value) { - Attributes attributes = new Attributes(); - attributes.put(key, value); - Element node = new Element(Tag.valueOf("v-label"), "", attributes); - return node; - } - - private Boolean getExplicitImmediate(AbstractComponent component) { - try { - Field immediate = AbstractComponent.class - .getDeclaredField("explicitImmediateValue"); - immediate.setAccessible(true); - return (Boolean) immediate.get(component); - } catch (Exception e) { - throw new RuntimeException( - "Getting the field explicitImmediateValue failed."); - } - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractcomponent/TestWriteDesign.java b/server/tests/src/com/vaadin/tests/server/component/abstractcomponent/TestWriteDesign.java deleted file mode 100644 index 7f207a25ae..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstractcomponent/TestWriteDesign.java +++ /dev/null @@ -1,281 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.abstractcomponent; - -import java.io.File; -import java.util.Locale; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Attributes; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; - -import com.vaadin.server.AbstractErrorMessage.ContentMode; -import com.vaadin.server.ErrorMessage.ErrorLevel; -import com.vaadin.server.ExternalResource; -import com.vaadin.server.FileResource; -import com.vaadin.server.Responsive; -import com.vaadin.server.ThemeResource; -import com.vaadin.server.UserError; -import com.vaadin.ui.AbstractComponent; -import com.vaadin.ui.Button; -import com.vaadin.ui.HorizontalSplitPanel; -import com.vaadin.ui.TabSheet; -import com.vaadin.ui.declarative.DesignContext; - -/** - * Test case for writing the attributes of the AbstractComponent to design - * - * @author Vaadin Ltd - */ -public class TestWriteDesign extends TestCase { - - private DesignContext ctx; - - @Override - protected void setUp() throws Exception { - super.setUp(); - ctx = new DesignContext(); - } - - public void testSynchronizeId() { - Element design = createDesign(); - AbstractComponent component = getComponent(); - component.setId("testId"); - component.writeDesign(design, ctx); - // we only changed one of the attributes, others are at default values - assertEquals(1, design.attributes().size()); - assertEquals("testId", design.attr("id")); - } - - public void testSynchronizePrimaryStyleName() { - Element design = createDesign(); - AbstractComponent component = getComponent(); - component.setPrimaryStyleName("test-style"); - component.writeDesign(design, ctx); - // we only changed one of the attributes, others are at default values - assertEquals(1, design.attributes().size()); - assertEquals("test-style", design.attr("primary-style-name")); - } - - public void testSynchronizeCaption() { - Element design = createDesign(); - AbstractComponent component = getComponent(); - component.setCaption("test-caption"); - component.writeDesign(design, ctx); - // We only changed the caption, which is not - // an attribute. - assertEquals(0, design.attributes().size()); - assertEquals("test-caption", design.html()); - } - - public void testSynchronizeLocale() { - Element design = createDesign(); - AbstractComponent component = getComponent(); - component.setLocale(new Locale("fi", "FI")); - component.writeDesign(design, ctx); - // we only changed one of the attributes, others are at default values - assertEquals(1, design.attributes().size()); - assertEquals("fi_FI", design.attr("locale")); - } - - public void testSynchronizeExternalIcon() { - Element design = createDesign(); - AbstractComponent component = getComponent(); - component - .setIcon(new ExternalResource("http://example.com/example.gif")); - component.writeDesign(design, ctx); - // we only changed one of the attributes, others are at default values - assertEquals(1, design.attributes().size()); - assertEquals("http://example.com/example.gif", design.attr("icon")); - } - - public void testSynchronizeThemeIcon() { - Element design = createDesign(); - AbstractComponent component = getComponent(); - component.setIcon(new ThemeResource("example.gif")); - component.writeDesign(design, ctx); - // we only changed one of the attributes, others are at default values - assertEquals(1, design.attributes().size()); - assertEquals("theme://example.gif", design.attr("icon")); - } - - public void testSynchronizeFileResource() { - Element design = createDesign(); - AbstractComponent component = getComponent(); - component.setIcon(new FileResource(new File("img/example.gif"))); - component.writeDesign(design, ctx); - // we only changed one of the attributes, others are at default values - assertEquals(1, design.attributes().size()); - assertEquals("img/example.gif", design.attr("icon")); - } - - public void testSynchronizeImmediate() { - Element design = createDesign(); - AbstractComponent component = getComponent(); - // no immediate attribute should be written before setting immediate to - // some value - component.writeDesign(design, ctx); - assertFalse(design.hasAttr("immediate")); - component.setImmediate(true); - component.writeDesign(design, ctx); - // we only changed one of the attributes, others are at default values - assertEquals(1, design.attributes().size()); - assertEquals("true", design.attr("immediate")); - } - - public void testSynchronizeImmediateByDefault() { - Element design = createDesign(); - TabSheet byDefaultImmediate = new TabSheet(); - // no immediate attribute should be written before setting immediate to - // false - byDefaultImmediate.writeDesign(design, ctx); - assertFalse(design.hasAttr("immediate")); - byDefaultImmediate.setImmediate(false); - byDefaultImmediate.writeDesign(design, ctx); - // we only changed one of the attributes, others are at default values - assertEquals(1, design.attributes().size()); - assertEquals("false", design.attr("immediate")); - } - - public void testSynchronizeDescription() { - Element design = createDesign(); - AbstractComponent component = getComponent(); - component.setDescription("test-description"); - component.writeDesign(design, ctx); - // we only changed one of the attributes, others are at default values - assertEquals(1, design.attributes().size()); - assertEquals("test-description", design.attr("description")); - } - - public void testSynchronizeComponentError() { - Element design = createDesign(); - AbstractComponent component = getComponent(); - component.setComponentError(new UserError("
    test-error
    ", - ContentMode.HTML, ErrorLevel.ERROR)); - component.writeDesign(design, ctx); - // we only changed one of the attributes, others are at default values - assertEquals(1, design.attributes().size()); - assertEquals("
    test-error
    ", design.attr("error")); - } - - public void testSynchronizeSizeFull() { - Element design = createDesign(); - AbstractComponent component = getComponent(); - component.setSizeFull(); - component.writeDesign(design, ctx); - // there should be only size full - assertEquals(1, design.attributes().size()); - assertEquals("true", design.attr("size-full")); - } - - public void testSynchronizeSizeAuto() { - Element design = createDesign(); - AbstractComponent component = getPanel(); - component.setSizeUndefined(); - component.writeDesign(design, ctx); - // there should be only size auto - assertEquals(1, design.attributes().size()); - assertEquals("true", design.attr("size-auto")); - } - - public void testSynchronizeHeightFull() { - Element design = createDesign(); - AbstractComponent component = getComponent(); - component.setHeight("100%"); - component.setWidth("20px"); - component.writeDesign(design, ctx); - assertEquals("true", design.attr("height-full")); - } - - public void testSynchronizeHeightAuto() { - Element design = createDesign(); - // we need to have default height of 100% -> use split panel - AbstractComponent component = getPanel(); - component.setHeight(null); - component.setWidth("20px"); - component.writeDesign(design, ctx); - assertEquals("true", design.attr("height-auto")); - } - - public void testSynchronizeWidthFull() { - Element design = createDesign(); - AbstractComponent component = getComponent(); - component.setHeight("20px"); - component.setWidth("100%"); - component.writeDesign(design, ctx); - assertEquals("true", design.attr("width-full")); - } - - public void testSynchronizeWidthAuto() { - Element design = createDesign(); - // need to get label, otherwise the default would be auto - AbstractComponent component = getPanel(); - component.setHeight("20px"); - component.setWidth(null); - component.writeDesign(design, ctx); - assertEquals("true", design.attr("width-auto")); - } - - public void testSynchronizeWidth() { - Element design = createDesign(); - AbstractComponent component = getComponent(); - component.setHeight("20px"); - component.setWidth("70%"); - component.writeDesign(design, ctx); - assertEquals("70%", design.attr("width")); - } - - public void testSynchronizeHeight() { - Element design = createDesign(); - AbstractComponent component = getComponent(); - component.setHeight("20px"); - component.setWidth("70%"); - component.writeDesign(design, ctx); - assertEquals("20px", design.attr("height")); - } - - public void testSynchronizeResponsive() { - Element design = createDesign(); - AbstractComponent component = getComponent(); - Responsive.makeResponsive(component); - component.writeDesign(design, ctx); - assertTrue("Design attributes should have key 'responsive'", design - .attributes().hasKey("responsive")); - assertFalse("Responsive attribute should not be 'false'", - design.attr("responsive").equalsIgnoreCase("false")); - } - - private AbstractComponent getComponent() { - Button button = new Button(); - button.setHtmlContentAllowed(true); - return button; - } - - private AbstractComponent getPanel() { - return new HorizontalSplitPanel(); - } - - private Element createDesign() { - Attributes attr = new Attributes(); - attr.put("should_be_removed", "foo"); - Element node = new Element(Tag.valueOf("v-button"), "", attr); - Element child = new Element(Tag.valueOf("to-be-removed"), "foo", attr); - node.appendChild(child); - return node; - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractcomponent/WriteDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/abstractcomponent/WriteDesignTest.java new file mode 100644 index 0000000000..68b7a46cde --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstractcomponent/WriteDesignTest.java @@ -0,0 +1,281 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.abstractcomponent; + +import java.io.File; +import java.util.Locale; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Attributes; +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; + +import com.vaadin.server.AbstractErrorMessage.ContentMode; +import com.vaadin.server.ErrorMessage.ErrorLevel; +import com.vaadin.server.ExternalResource; +import com.vaadin.server.FileResource; +import com.vaadin.server.Responsive; +import com.vaadin.server.ThemeResource; +import com.vaadin.server.UserError; +import com.vaadin.ui.AbstractComponent; +import com.vaadin.ui.Button; +import com.vaadin.ui.HorizontalSplitPanel; +import com.vaadin.ui.TabSheet; +import com.vaadin.ui.declarative.DesignContext; + +/** + * Test case for writing the attributes of the AbstractComponent to design + * + * @author Vaadin Ltd + */ +public class WriteDesignTest extends TestCase { + + private DesignContext ctx; + + @Override + protected void setUp() throws Exception { + super.setUp(); + ctx = new DesignContext(); + } + + public void testSynchronizeId() { + Element design = createDesign(); + AbstractComponent component = getComponent(); + component.setId("testId"); + component.writeDesign(design, ctx); + // we only changed one of the attributes, others are at default values + assertEquals(1, design.attributes().size()); + assertEquals("testId", design.attr("id")); + } + + public void testSynchronizePrimaryStyleName() { + Element design = createDesign(); + AbstractComponent component = getComponent(); + component.setPrimaryStyleName("test-style"); + component.writeDesign(design, ctx); + // we only changed one of the attributes, others are at default values + assertEquals(1, design.attributes().size()); + assertEquals("test-style", design.attr("primary-style-name")); + } + + public void testSynchronizeCaption() { + Element design = createDesign(); + AbstractComponent component = getComponent(); + component.setCaption("test-caption"); + component.writeDesign(design, ctx); + // We only changed the caption, which is not + // an attribute. + assertEquals(0, design.attributes().size()); + assertEquals("test-caption", design.html()); + } + + public void testSynchronizeLocale() { + Element design = createDesign(); + AbstractComponent component = getComponent(); + component.setLocale(new Locale("fi", "FI")); + component.writeDesign(design, ctx); + // we only changed one of the attributes, others are at default values + assertEquals(1, design.attributes().size()); + assertEquals("fi_FI", design.attr("locale")); + } + + public void testSynchronizeExternalIcon() { + Element design = createDesign(); + AbstractComponent component = getComponent(); + component + .setIcon(new ExternalResource("http://example.com/example.gif")); + component.writeDesign(design, ctx); + // we only changed one of the attributes, others are at default values + assertEquals(1, design.attributes().size()); + assertEquals("http://example.com/example.gif", design.attr("icon")); + } + + public void testSynchronizeThemeIcon() { + Element design = createDesign(); + AbstractComponent component = getComponent(); + component.setIcon(new ThemeResource("example.gif")); + component.writeDesign(design, ctx); + // we only changed one of the attributes, others are at default values + assertEquals(1, design.attributes().size()); + assertEquals("theme://example.gif", design.attr("icon")); + } + + public void testSynchronizeFileResource() { + Element design = createDesign(); + AbstractComponent component = getComponent(); + component.setIcon(new FileResource(new File("img/example.gif"))); + component.writeDesign(design, ctx); + // we only changed one of the attributes, others are at default values + assertEquals(1, design.attributes().size()); + assertEquals("img/example.gif", design.attr("icon")); + } + + public void testSynchronizeImmediate() { + Element design = createDesign(); + AbstractComponent component = getComponent(); + // no immediate attribute should be written before setting immediate to + // some value + component.writeDesign(design, ctx); + assertFalse(design.hasAttr("immediate")); + component.setImmediate(true); + component.writeDesign(design, ctx); + // we only changed one of the attributes, others are at default values + assertEquals(1, design.attributes().size()); + assertEquals("true", design.attr("immediate")); + } + + public void testSynchronizeImmediateByDefault() { + Element design = createDesign(); + TabSheet byDefaultImmediate = new TabSheet(); + // no immediate attribute should be written before setting immediate to + // false + byDefaultImmediate.writeDesign(design, ctx); + assertFalse(design.hasAttr("immediate")); + byDefaultImmediate.setImmediate(false); + byDefaultImmediate.writeDesign(design, ctx); + // we only changed one of the attributes, others are at default values + assertEquals(1, design.attributes().size()); + assertEquals("false", design.attr("immediate")); + } + + public void testSynchronizeDescription() { + Element design = createDesign(); + AbstractComponent component = getComponent(); + component.setDescription("test-description"); + component.writeDesign(design, ctx); + // we only changed one of the attributes, others are at default values + assertEquals(1, design.attributes().size()); + assertEquals("test-description", design.attr("description")); + } + + public void testSynchronizeComponentError() { + Element design = createDesign(); + AbstractComponent component = getComponent(); + component.setComponentError(new UserError("
    test-error
    ", + ContentMode.HTML, ErrorLevel.ERROR)); + component.writeDesign(design, ctx); + // we only changed one of the attributes, others are at default values + assertEquals(1, design.attributes().size()); + assertEquals("
    test-error
    ", design.attr("error")); + } + + public void testSynchronizeSizeFull() { + Element design = createDesign(); + AbstractComponent component = getComponent(); + component.setSizeFull(); + component.writeDesign(design, ctx); + // there should be only size full + assertEquals(1, design.attributes().size()); + assertEquals("true", design.attr("size-full")); + } + + public void testSynchronizeSizeAuto() { + Element design = createDesign(); + AbstractComponent component = getPanel(); + component.setSizeUndefined(); + component.writeDesign(design, ctx); + // there should be only size auto + assertEquals(1, design.attributes().size()); + assertEquals("true", design.attr("size-auto")); + } + + public void testSynchronizeHeightFull() { + Element design = createDesign(); + AbstractComponent component = getComponent(); + component.setHeight("100%"); + component.setWidth("20px"); + component.writeDesign(design, ctx); + assertEquals("true", design.attr("height-full")); + } + + public void testSynchronizeHeightAuto() { + Element design = createDesign(); + // we need to have default height of 100% -> use split panel + AbstractComponent component = getPanel(); + component.setHeight(null); + component.setWidth("20px"); + component.writeDesign(design, ctx); + assertEquals("true", design.attr("height-auto")); + } + + public void testSynchronizeWidthFull() { + Element design = createDesign(); + AbstractComponent component = getComponent(); + component.setHeight("20px"); + component.setWidth("100%"); + component.writeDesign(design, ctx); + assertEquals("true", design.attr("width-full")); + } + + public void testSynchronizeWidthAuto() { + Element design = createDesign(); + // need to get label, otherwise the default would be auto + AbstractComponent component = getPanel(); + component.setHeight("20px"); + component.setWidth(null); + component.writeDesign(design, ctx); + assertEquals("true", design.attr("width-auto")); + } + + public void testSynchronizeWidth() { + Element design = createDesign(); + AbstractComponent component = getComponent(); + component.setHeight("20px"); + component.setWidth("70%"); + component.writeDesign(design, ctx); + assertEquals("70%", design.attr("width")); + } + + public void testSynchronizeHeight() { + Element design = createDesign(); + AbstractComponent component = getComponent(); + component.setHeight("20px"); + component.setWidth("70%"); + component.writeDesign(design, ctx); + assertEquals("20px", design.attr("height")); + } + + public void testSynchronizeResponsive() { + Element design = createDesign(); + AbstractComponent component = getComponent(); + Responsive.makeResponsive(component); + component.writeDesign(design, ctx); + assertTrue("Design attributes should have key 'responsive'", design + .attributes().hasKey("responsive")); + assertFalse("Responsive attribute should not be 'false'", + design.attr("responsive").equalsIgnoreCase("false")); + } + + private AbstractComponent getComponent() { + Button button = new Button(); + button.setHtmlContentAllowed(true); + return button; + } + + private AbstractComponent getPanel() { + return new HorizontalSplitPanel(); + } + + private Element createDesign() { + Attributes attr = new Attributes(); + attr.put("should_be_removed", "foo"); + Element node = new Element(Tag.valueOf("v-button"), "", attr); + Element child = new Element(Tag.valueOf("to-be-removed"), "foo", attr); + node.appendChild(child); + return node; + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractcomponentcontainer/AbstractComponentContainerListenersTest.java b/server/tests/src/com/vaadin/tests/server/component/abstractcomponentcontainer/AbstractComponentContainerListenersTest.java new file mode 100644 index 0000000000..3a2150b700 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstractcomponentcontainer/AbstractComponentContainerListenersTest.java @@ -0,0 +1,22 @@ +package com.vaadin.tests.server.component.abstractcomponentcontainer; + +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; +import com.vaadin.ui.HasComponents.ComponentAttachEvent; +import com.vaadin.ui.HasComponents.ComponentAttachListener; +import com.vaadin.ui.HasComponents.ComponentDetachEvent; +import com.vaadin.ui.HasComponents.ComponentDetachListener; +import com.vaadin.ui.HorizontalLayout; +import com.vaadin.ui.VerticalLayout; + +public class AbstractComponentContainerListenersTest extends + AbstractListenerMethodsTestBase { + public void testComponentDetachListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(HorizontalLayout.class, + ComponentDetachEvent.class, ComponentDetachListener.class); + } + + public void testComponentAttachListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(VerticalLayout.class, + ComponentAttachEvent.class, ComponentAttachListener.class); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractcomponentcontainer/AddParentAsChild.java b/server/tests/src/com/vaadin/tests/server/component/abstractcomponentcontainer/AddParentAsChild.java deleted file mode 100644 index 67e6d09adc..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstractcomponentcontainer/AddParentAsChild.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.abstractcomponentcontainer; - -import java.util.Iterator; - -import org.easymock.EasyMock; -import org.junit.Test; - -import com.vaadin.ui.AbstractComponentContainer; -import com.vaadin.ui.Component; -import com.vaadin.ui.HasComponents; - -/** - * Tests for avoiding add parent as child for - * {@link AbstractComponentContainer#addComponent(Component)} - * - * @author Vaadin Ltd - */ -public class AddParentAsChild { - - @Test(expected = IllegalArgumentException.class) - public void testAddComponent() { - AbstractComponentContainer container = new ComponentContainer(); - HasComponents hasComponentsMock = EasyMock - .createMock(HasComponents.class); - container.setParent(hasComponentsMock); - - container.addComponent(hasComponentsMock); - } - - class ComponentContainer extends AbstractComponentContainer { - - @Override - public void replaceComponent(Component oldComponent, - Component newComponent) { - } - - @Override - public int getComponentCount() { - return 0; - } - - @Override - public Iterator iterator() { - return null; - } - - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractcomponentcontainer/AddParentAsChildTest.java b/server/tests/src/com/vaadin/tests/server/component/abstractcomponentcontainer/AddParentAsChildTest.java new file mode 100644 index 0000000000..176d178112 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstractcomponentcontainer/AddParentAsChildTest.java @@ -0,0 +1,64 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.abstractcomponentcontainer; + +import java.util.Iterator; + +import org.easymock.EasyMock; +import org.junit.Test; + +import com.vaadin.ui.AbstractComponentContainer; +import com.vaadin.ui.Component; +import com.vaadin.ui.HasComponents; + +/** + * Tests for avoiding add parent as child for + * {@link AbstractComponentContainer#addComponent(Component)} + * + * @author Vaadin Ltd + */ +public class AddParentAsChildTest { + + @Test(expected = IllegalArgumentException.class) + public void testAddComponent() { + AbstractComponentContainer container = new ComponentContainer(); + HasComponents hasComponentsMock = EasyMock + .createMock(HasComponents.class); + container.setParent(hasComponentsMock); + + container.addComponent(hasComponentsMock); + } + + class ComponentContainer extends AbstractComponentContainer { + + @Override + public void replaceComponent(Component oldComponent, + Component newComponent) { + } + + @Override + public int getComponentCount() { + return 0; + } + + @Override + public Iterator iterator() { + return null; + } + + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractcomponentcontainer/TestAbstractComponentContainerListeners.java b/server/tests/src/com/vaadin/tests/server/component/abstractcomponentcontainer/TestAbstractComponentContainerListeners.java deleted file mode 100644 index 9763354b57..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstractcomponentcontainer/TestAbstractComponentContainerListeners.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.vaadin.tests.server.component.abstractcomponentcontainer; - -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; -import com.vaadin.ui.HasComponents.ComponentAttachEvent; -import com.vaadin.ui.HasComponents.ComponentAttachListener; -import com.vaadin.ui.HasComponents.ComponentDetachEvent; -import com.vaadin.ui.HasComponents.ComponentDetachListener; -import com.vaadin.ui.HorizontalLayout; -import com.vaadin.ui.VerticalLayout; - -public class TestAbstractComponentContainerListeners extends - AbstractListenerMethodsTest { - public void testComponentDetachListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(HorizontalLayout.class, - ComponentDetachEvent.class, ComponentDetachListener.class); - } - - public void testComponentAttachListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(VerticalLayout.class, - ComponentAttachEvent.class, ComponentAttachListener.class); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractfield/AbsFieldValidators.java b/server/tests/src/com/vaadin/tests/server/component/abstractfield/AbsFieldValidators.java deleted file mode 100644 index 764446f7aa..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstractfield/AbsFieldValidators.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.vaadin.tests.server.component.abstractfield; - -import junit.framework.TestCase; - -import org.easymock.EasyMock; - -import com.vaadin.data.Validator; -import com.vaadin.ui.AbstractField; -import com.vaadin.ui.Field; - -public class AbsFieldValidators extends TestCase { - - Field field = new AbstractField() { - @Override - public Class getType() { - return Object.class; - } - }; - - Validator validator = EasyMock.createMock(Validator.class); - Validator validator2 = EasyMock.createMock(Validator.class); - - public void testAddValidator() { - assertNotNull(field.getValidators()); - assertEquals(0, field.getValidators().size()); - - field.addValidator(validator); - assertEquals(1, field.getValidators().size()); - assertTrue(field.getValidators().contains(validator)); - - field.addValidator(validator2); - assertEquals(2, field.getValidators().size()); - assertTrue(field.getValidators().contains(validator)); - assertTrue(field.getValidators().contains(validator2)); - } - - public void testRemoveValidator() { - field.addValidator(validator); - field.addValidator(validator2); - - field.removeValidator(validator); - assertNotNull(field.getValidators()); - assertEquals(1, field.getValidators().size()); - assertFalse(field.getValidators().contains(validator)); - assertTrue(field.getValidators().contains(validator2)); - - field.removeValidator(validator2); - assertNotNull(field.getValidators()); - assertEquals(0, field.getValidators().size()); - assertFalse(field.getValidators().contains(validator)); - assertFalse(field.getValidators().contains(validator2)); - } - - public void testRemoveAllValidators() { - field.addValidator(validator); - field.addValidator(validator2); - - field.removeAllValidators(); - assertNotNull(field.getValidators()); - assertEquals(0, field.getValidators().size()); - assertFalse(field.getValidators().contains(validator)); - assertFalse(field.getValidators().contains(validator2)); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractfield/AbsFieldValidatorsTest.java b/server/tests/src/com/vaadin/tests/server/component/abstractfield/AbsFieldValidatorsTest.java new file mode 100644 index 0000000000..61aafe317d --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstractfield/AbsFieldValidatorsTest.java @@ -0,0 +1,64 @@ +package com.vaadin.tests.server.component.abstractfield; + +import junit.framework.TestCase; + +import org.easymock.EasyMock; + +import com.vaadin.data.Validator; +import com.vaadin.ui.AbstractField; +import com.vaadin.ui.Field; + +public class AbsFieldValidatorsTest extends TestCase { + + Field field = new AbstractField() { + @Override + public Class getType() { + return Object.class; + } + }; + + Validator validator = EasyMock.createMock(Validator.class); + Validator validator2 = EasyMock.createMock(Validator.class); + + public void testAddValidator() { + assertNotNull(field.getValidators()); + assertEquals(0, field.getValidators().size()); + + field.addValidator(validator); + assertEquals(1, field.getValidators().size()); + assertTrue(field.getValidators().contains(validator)); + + field.addValidator(validator2); + assertEquals(2, field.getValidators().size()); + assertTrue(field.getValidators().contains(validator)); + assertTrue(field.getValidators().contains(validator2)); + } + + public void testRemoveValidator() { + field.addValidator(validator); + field.addValidator(validator2); + + field.removeValidator(validator); + assertNotNull(field.getValidators()); + assertEquals(1, field.getValidators().size()); + assertFalse(field.getValidators().contains(validator)); + assertTrue(field.getValidators().contains(validator2)); + + field.removeValidator(validator2); + assertNotNull(field.getValidators()); + assertEquals(0, field.getValidators().size()); + assertFalse(field.getValidators().contains(validator)); + assertFalse(field.getValidators().contains(validator2)); + } + + public void testRemoveAllValidators() { + field.addValidator(validator); + field.addValidator(validator2); + + field.removeAllValidators(); + assertNotNull(field.getValidators()); + assertEquals(0, field.getValidators().size()); + assertFalse(field.getValidators().contains(validator)); + assertFalse(field.getValidators().contains(validator2)); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractfield/AbsFieldValueConversionError.java b/server/tests/src/com/vaadin/tests/server/component/abstractfield/AbsFieldValueConversionError.java deleted file mode 100644 index 887f1b8ff3..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstractfield/AbsFieldValueConversionError.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.vaadin.tests.server.component.abstractfield; - -import junit.framework.TestCase; - -import org.junit.Assert; - -import com.vaadin.data.Validator.InvalidValueException; -import com.vaadin.data.util.MethodProperty; -import com.vaadin.data.util.converter.Converter.ConversionException; -import com.vaadin.data.util.converter.StringToIntegerConverter; -import com.vaadin.tests.data.bean.Address; -import com.vaadin.tests.data.bean.Country; -import com.vaadin.tests.data.bean.Person; -import com.vaadin.tests.data.bean.Sex; -import com.vaadin.ui.TextField; - -public class AbsFieldValueConversionError extends TestCase { - - Person paulaBean = new Person("Paula", "Brilliant", "paula@brilliant.com", - 34, Sex.FEMALE, new Address("Paula street 1", 12345, "P-town", - Country.FINLAND)); - - public void testValidateConversionErrorParameters() { - TextField tf = new TextField(); - tf.setConverter(new StringToIntegerConverter()); - tf.setPropertyDataSource(new MethodProperty(paulaBean, "age")); - tf.setConversionError("(Type: {0}) Converter exception message: {1}"); - tf.setValue("abc"); - try { - tf.validate(); - fail(); - } catch (InvalidValueException e) { - Assert.assertEquals( - "(Type: Integer) Converter exception message: Could not convert 'abc' to java.lang.Integer", - e.getMessage()); - } - - } - - public void testConvertToModelConversionErrorParameters() { - TextField tf = new TextField(); - tf.setConverter(new StringToIntegerConverter()); - tf.setPropertyDataSource(new MethodProperty(paulaBean, "age")); - tf.setConversionError("(Type: {0}) Converter exception message: {1}"); - tf.setValue("abc"); - try { - tf.getConvertedValue(); - fail(); - } catch (ConversionException e) { - Assert.assertEquals( - "(Type: Integer) Converter exception message: Could not convert 'abc' to java.lang.Integer", - e.getMessage()); - } - - } - - public void testNullConversionMessages() { - TextField tf = new TextField(); - tf.setConverter(new StringToIntegerConverter()); - tf.setPropertyDataSource(new MethodProperty(paulaBean, "age")); - tf.setConversionError(null); - tf.setValue("abc"); - try { - tf.validate(); - fail(); - } catch (InvalidValueException e) { - Assert.assertEquals(null, e.getMessage()); - } - - } - - public void testDefaultConversionErrorMessage() { - TextField tf = new TextField(); - tf.setConverter(new StringToIntegerConverter()); - tf.setPropertyDataSource(new MethodProperty(paulaBean, "age")); - tf.setValue("abc"); - - try { - tf.validate(); - fail(); - } catch (InvalidValueException e) { - Assert.assertEquals("Could not convert value to Integer", - e.getMessage()); - } - - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractfield/AbsFieldValueConversionErrorTest.java b/server/tests/src/com/vaadin/tests/server/component/abstractfield/AbsFieldValueConversionErrorTest.java new file mode 100644 index 0000000000..02aa6afe07 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstractfield/AbsFieldValueConversionErrorTest.java @@ -0,0 +1,87 @@ +package com.vaadin.tests.server.component.abstractfield; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.vaadin.data.Validator.InvalidValueException; +import com.vaadin.data.util.MethodProperty; +import com.vaadin.data.util.converter.Converter.ConversionException; +import com.vaadin.data.util.converter.StringToIntegerConverter; +import com.vaadin.tests.data.bean.Address; +import com.vaadin.tests.data.bean.Country; +import com.vaadin.tests.data.bean.Person; +import com.vaadin.tests.data.bean.Sex; +import com.vaadin.ui.TextField; + +public class AbsFieldValueConversionErrorTest extends TestCase { + + Person paulaBean = new Person("Paula", "Brilliant", "paula@brilliant.com", + 34, Sex.FEMALE, new Address("Paula street 1", 12345, "P-town", + Country.FINLAND)); + + public void testValidateConversionErrorParameters() { + TextField tf = new TextField(); + tf.setConverter(new StringToIntegerConverter()); + tf.setPropertyDataSource(new MethodProperty(paulaBean, "age")); + tf.setConversionError("(Type: {0}) Converter exception message: {1}"); + tf.setValue("abc"); + try { + tf.validate(); + fail(); + } catch (InvalidValueException e) { + Assert.assertEquals( + "(Type: Integer) Converter exception message: Could not convert 'abc' to java.lang.Integer", + e.getMessage()); + } + + } + + public void testConvertToModelConversionErrorParameters() { + TextField tf = new TextField(); + tf.setConverter(new StringToIntegerConverter()); + tf.setPropertyDataSource(new MethodProperty(paulaBean, "age")); + tf.setConversionError("(Type: {0}) Converter exception message: {1}"); + tf.setValue("abc"); + try { + tf.getConvertedValue(); + fail(); + } catch (ConversionException e) { + Assert.assertEquals( + "(Type: Integer) Converter exception message: Could not convert 'abc' to java.lang.Integer", + e.getMessage()); + } + + } + + public void testNullConversionMessages() { + TextField tf = new TextField(); + tf.setConverter(new StringToIntegerConverter()); + tf.setPropertyDataSource(new MethodProperty(paulaBean, "age")); + tf.setConversionError(null); + tf.setValue("abc"); + try { + tf.validate(); + fail(); + } catch (InvalidValueException e) { + Assert.assertEquals(null, e.getMessage()); + } + + } + + public void testDefaultConversionErrorMessage() { + TextField tf = new TextField(); + tf.setConverter(new StringToIntegerConverter()); + tf.setPropertyDataSource(new MethodProperty(paulaBean, "age")); + tf.setValue("abc"); + + try { + tf.validate(); + fail(); + } catch (InvalidValueException e) { + Assert.assertEquals("Could not convert value to Integer", + e.getMessage()); + } + + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractfield/AbsFieldValueConversions.java b/server/tests/src/com/vaadin/tests/server/component/abstractfield/AbsFieldValueConversions.java deleted file mode 100644 index beb32e7dba..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstractfield/AbsFieldValueConversions.java +++ /dev/null @@ -1,266 +0,0 @@ -package com.vaadin.tests.server.component.abstractfield; - -import java.util.Locale; - -import junit.framework.TestCase; - -import org.junit.Assert; -import org.junit.Test; - -import com.vaadin.data.util.MethodProperty; -import com.vaadin.data.util.ObjectProperty; -import com.vaadin.data.util.converter.Converter; -import com.vaadin.data.util.converter.Converter.ConversionException; -import com.vaadin.data.util.converter.StringToIntegerConverter; -import com.vaadin.server.VaadinSession; -import com.vaadin.tests.data.bean.Address; -import com.vaadin.tests.data.bean.Country; -import com.vaadin.tests.data.bean.Person; -import com.vaadin.tests.data.bean.Sex; -import com.vaadin.tests.util.AlwaysLockedVaadinSession; -import com.vaadin.ui.CheckBox; -import com.vaadin.ui.TextField; - -public class AbsFieldValueConversions extends TestCase { - - Person paulaBean = new Person("Paula", "Brilliant", "paula@brilliant.com", - 34, Sex.FEMALE, new Address("Paula street 1", 12345, "P-town", - Country.FINLAND)); - - /** - * Java uses a non-breaking space (ascii 160) instead of space when - * formatting - */ - private static final char FORMATTED_SPACE = 160; - - public void testWithoutConversion() { - TextField tf = new TextField(); - tf.setPropertyDataSource(new MethodProperty(paulaBean, - "firstName")); - assertEquals("Paula", tf.getValue()); - assertEquals("Paula", tf.getPropertyDataSource().getValue()); - tf.setValue("abc"); - assertEquals("abc", tf.getValue()); - assertEquals("abc", tf.getPropertyDataSource().getValue()); - assertEquals("abc", paulaBean.getFirstName()); - } - - public void testNonmodifiedBufferedFieldConversion() { - VaadinSession.setCurrent(new AlwaysLockedVaadinSession(null)); - TextField tf = new TextField("salary"); - tf.setBuffered(true); - tf.setLocale(new Locale("en", "US")); - ObjectProperty ds = new ObjectProperty(123456789); - tf.setPropertyDataSource(ds); - assertEquals((Integer) 123456789, ds.getValue()); - assertEquals("123,456,789", tf.getValue()); - tf.setLocale(new Locale("fi", "FI")); - assertEquals((Integer) 123456789, ds.getValue()); - assertEquals("123" + FORMATTED_SPACE + "456" + FORMATTED_SPACE + "789", - tf.getValue()); - - } - - public void testModifiedBufferedFieldConversion() { - VaadinSession.setCurrent(new AlwaysLockedVaadinSession(null)); - TextField tf = new TextField("salary"); - tf.setBuffered(true); - tf.setLocale(new Locale("en", "US")); - ObjectProperty ds = new ObjectProperty(123456789); - tf.setPropertyDataSource(ds); - assertEquals((Integer) 123456789, ds.getValue()); - assertEquals("123,456,789", tf.getValue()); - tf.setValue("123,123"); - assertEquals((Integer) 123456789, ds.getValue()); - assertEquals("123,123", tf.getValue()); - - tf.setLocale(new Locale("fi", "FI")); - assertEquals((Integer) 123456789, ds.getValue()); - // Value should not be updated when field is buffered - assertEquals("123,123", tf.getValue()); - } - - public void testStringIdentityConversion() { - TextField tf = new TextField(); - tf.setConverter(new Converter() { - - @Override - public String convertToModel(String value, - Class targetType, Locale locale) { - return value; - } - - @Override - public String convertToPresentation(String value, - Class targetType, Locale locale) { - return value; - } - - @Override - public Class getModelType() { - return String.class; - } - - @Override - public Class getPresentationType() { - return String.class; - } - }); - tf.setPropertyDataSource(new MethodProperty(paulaBean, - "firstName")); - assertEquals("Paula", tf.getValue()); - assertEquals("Paula", tf.getPropertyDataSource().getValue()); - tf.setValue("abc"); - assertEquals("abc", tf.getValue()); - assertEquals("abc", tf.getPropertyDataSource().getValue()); - assertEquals("abc", paulaBean.getFirstName()); - } - - public void testIntegerStringConversion() { - TextField tf = new TextField(); - - tf.setConverter(new StringToIntegerConverter()); - tf.setPropertyDataSource(new MethodProperty(paulaBean, "age")); - assertEquals(34, tf.getPropertyDataSource().getValue()); - assertEquals("34", tf.getValue()); - tf.setValue("12"); - assertEquals(12, tf.getPropertyDataSource().getValue()); - assertEquals("12", tf.getValue()); - tf.getPropertyDataSource().setValue(42); - assertEquals(42, tf.getPropertyDataSource().getValue()); - assertEquals("42", tf.getValue()); - } - - public void testChangeReadOnlyFieldLocale() { - VaadinSession.setCurrent(new AlwaysLockedVaadinSession(null)); - - TextField tf = new TextField("salary"); - tf.setLocale(new Locale("en", "US")); - ObjectProperty ds = new ObjectProperty(123456789); - ds.setReadOnly(true); - tf.setPropertyDataSource(ds); - assertEquals((Integer) 123456789, ds.getValue()); - assertEquals("123,456,789", tf.getValue()); - tf.setLocale(new Locale("fi", "FI")); - assertEquals((Integer) 123456789, ds.getValue()); - assertEquals("123" + FORMATTED_SPACE + "456" + FORMATTED_SPACE + "789", - tf.getValue()); - } - - public void testBooleanNullConversion() { - CheckBox cb = new CheckBox(); - cb.setConverter(new Converter() { - - @Override - public Boolean convertToModel(Boolean value, - Class targetType, Locale locale) { - // value from a CheckBox should never be null as long as it is - // not set to null (handled by conversion below). - assertNotNull(value); - return value; - } - - @Override - public Boolean convertToPresentation(Boolean value, - Class targetType, Locale locale) { - // Datamodel -> field - if (value == null) { - return false; - } - - return value; - } - - @Override - public Class getModelType() { - return Boolean.class; - } - - @Override - public Class getPresentationType() { - return Boolean.class; - } - - }); - MethodProperty property = new MethodProperty( - paulaBean, "deceased"); - cb.setPropertyDataSource(property); - assertEquals(Boolean.FALSE, property.getValue()); - assertEquals(Boolean.FALSE, cb.getValue()); - Boolean newDmValue = cb.getConverter().convertToPresentation( - cb.getValue(), Boolean.class, new Locale("fi", "FI")); - assertEquals(Boolean.FALSE, newDmValue); - - // FIXME: Should be able to set to false here to cause datamodel to be - // set to false but the change will not be propagated to the Property - // (field value is already false) - - cb.setValue(true); - assertEquals(Boolean.TRUE, cb.getValue()); - assertEquals(Boolean.TRUE, property.getValue()); - - cb.setValue(false); - assertEquals(Boolean.FALSE, cb.getValue()); - assertEquals(Boolean.FALSE, property.getValue()); - - } - - // Now specific to Integer because StringToNumberConverter has been removed - public static class NumberBean { - private Integer number; - - public Integer getNumber() { - return number; - } - - public void setNumber(Integer number) { - this.number = number; - } - - } - - public void testNumberDoubleConverterChange() { - final VaadinSession a = new AlwaysLockedVaadinSession(null); - VaadinSession.setCurrent(a); - TextField tf = new TextField() { - @Override - public VaadinSession getSession() { - return a; - } - }; - NumberBean nb = new NumberBean(); - nb.setNumber(490); - - tf.setPropertyDataSource(new MethodProperty(nb, "number")); - assertEquals(490, tf.getPropertyDataSource().getValue()); - assertEquals("490", tf.getValue()); - - Converter c1 = tf.getConverter(); - - tf.setPropertyDataSource(new MethodProperty(nb, "number")); - Converter c2 = tf.getConverter(); - assertTrue( - "StringToInteger converter is ok for integer types and should stay even though property is changed", - c1 == c2); - assertEquals(490, tf.getPropertyDataSource().getValue()); - assertEquals("490", tf.getValue()); - - } - - @Test - public void testNullConverter() { - TextField tf = new TextField("foo"); - tf.setConverter(new StringToIntegerConverter()); - tf.setPropertyDataSource(new ObjectProperty(12)); - tf.setConverter((Converter) null); - try { - Object v = tf.getConvertedValue(); - System.out.println(v); - Assert.fail("Trying to convert String -> Integer should fail when there is no converter"); - } catch (ConversionException e) { - // ok, should happen when there is no converter but conversion is - // needed - } - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractfield/AbsFieldValueConversionsTest.java b/server/tests/src/com/vaadin/tests/server/component/abstractfield/AbsFieldValueConversionsTest.java new file mode 100644 index 0000000000..94ff10926f --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstractfield/AbsFieldValueConversionsTest.java @@ -0,0 +1,266 @@ +package com.vaadin.tests.server.component.abstractfield; + +import java.util.Locale; + +import junit.framework.TestCase; + +import org.junit.Assert; +import org.junit.Test; + +import com.vaadin.data.util.MethodProperty; +import com.vaadin.data.util.ObjectProperty; +import com.vaadin.data.util.converter.Converter; +import com.vaadin.data.util.converter.Converter.ConversionException; +import com.vaadin.data.util.converter.StringToIntegerConverter; +import com.vaadin.server.VaadinSession; +import com.vaadin.tests.data.bean.Address; +import com.vaadin.tests.data.bean.Country; +import com.vaadin.tests.data.bean.Person; +import com.vaadin.tests.data.bean.Sex; +import com.vaadin.tests.util.AlwaysLockedVaadinSession; +import com.vaadin.ui.CheckBox; +import com.vaadin.ui.TextField; + +public class AbsFieldValueConversionsTest extends TestCase { + + Person paulaBean = new Person("Paula", "Brilliant", "paula@brilliant.com", + 34, Sex.FEMALE, new Address("Paula street 1", 12345, "P-town", + Country.FINLAND)); + + /** + * Java uses a non-breaking space (ascii 160) instead of space when + * formatting + */ + private static final char FORMATTED_SPACE = 160; + + public void testWithoutConversion() { + TextField tf = new TextField(); + tf.setPropertyDataSource(new MethodProperty(paulaBean, + "firstName")); + assertEquals("Paula", tf.getValue()); + assertEquals("Paula", tf.getPropertyDataSource().getValue()); + tf.setValue("abc"); + assertEquals("abc", tf.getValue()); + assertEquals("abc", tf.getPropertyDataSource().getValue()); + assertEquals("abc", paulaBean.getFirstName()); + } + + public void testNonmodifiedBufferedFieldConversion() { + VaadinSession.setCurrent(new AlwaysLockedVaadinSession(null)); + TextField tf = new TextField("salary"); + tf.setBuffered(true); + tf.setLocale(new Locale("en", "US")); + ObjectProperty ds = new ObjectProperty(123456789); + tf.setPropertyDataSource(ds); + assertEquals((Integer) 123456789, ds.getValue()); + assertEquals("123,456,789", tf.getValue()); + tf.setLocale(new Locale("fi", "FI")); + assertEquals((Integer) 123456789, ds.getValue()); + assertEquals("123" + FORMATTED_SPACE + "456" + FORMATTED_SPACE + "789", + tf.getValue()); + + } + + public void testModifiedBufferedFieldConversion() { + VaadinSession.setCurrent(new AlwaysLockedVaadinSession(null)); + TextField tf = new TextField("salary"); + tf.setBuffered(true); + tf.setLocale(new Locale("en", "US")); + ObjectProperty ds = new ObjectProperty(123456789); + tf.setPropertyDataSource(ds); + assertEquals((Integer) 123456789, ds.getValue()); + assertEquals("123,456,789", tf.getValue()); + tf.setValue("123,123"); + assertEquals((Integer) 123456789, ds.getValue()); + assertEquals("123,123", tf.getValue()); + + tf.setLocale(new Locale("fi", "FI")); + assertEquals((Integer) 123456789, ds.getValue()); + // Value should not be updated when field is buffered + assertEquals("123,123", tf.getValue()); + } + + public void testStringIdentityConversion() { + TextField tf = new TextField(); + tf.setConverter(new Converter() { + + @Override + public String convertToModel(String value, + Class targetType, Locale locale) { + return value; + } + + @Override + public String convertToPresentation(String value, + Class targetType, Locale locale) { + return value; + } + + @Override + public Class getModelType() { + return String.class; + } + + @Override + public Class getPresentationType() { + return String.class; + } + }); + tf.setPropertyDataSource(new MethodProperty(paulaBean, + "firstName")); + assertEquals("Paula", tf.getValue()); + assertEquals("Paula", tf.getPropertyDataSource().getValue()); + tf.setValue("abc"); + assertEquals("abc", tf.getValue()); + assertEquals("abc", tf.getPropertyDataSource().getValue()); + assertEquals("abc", paulaBean.getFirstName()); + } + + public void testIntegerStringConversion() { + TextField tf = new TextField(); + + tf.setConverter(new StringToIntegerConverter()); + tf.setPropertyDataSource(new MethodProperty(paulaBean, "age")); + assertEquals(34, tf.getPropertyDataSource().getValue()); + assertEquals("34", tf.getValue()); + tf.setValue("12"); + assertEquals(12, tf.getPropertyDataSource().getValue()); + assertEquals("12", tf.getValue()); + tf.getPropertyDataSource().setValue(42); + assertEquals(42, tf.getPropertyDataSource().getValue()); + assertEquals("42", tf.getValue()); + } + + public void testChangeReadOnlyFieldLocale() { + VaadinSession.setCurrent(new AlwaysLockedVaadinSession(null)); + + TextField tf = new TextField("salary"); + tf.setLocale(new Locale("en", "US")); + ObjectProperty ds = new ObjectProperty(123456789); + ds.setReadOnly(true); + tf.setPropertyDataSource(ds); + assertEquals((Integer) 123456789, ds.getValue()); + assertEquals("123,456,789", tf.getValue()); + tf.setLocale(new Locale("fi", "FI")); + assertEquals((Integer) 123456789, ds.getValue()); + assertEquals("123" + FORMATTED_SPACE + "456" + FORMATTED_SPACE + "789", + tf.getValue()); + } + + public void testBooleanNullConversion() { + CheckBox cb = new CheckBox(); + cb.setConverter(new Converter() { + + @Override + public Boolean convertToModel(Boolean value, + Class targetType, Locale locale) { + // value from a CheckBox should never be null as long as it is + // not set to null (handled by conversion below). + assertNotNull(value); + return value; + } + + @Override + public Boolean convertToPresentation(Boolean value, + Class targetType, Locale locale) { + // Datamodel -> field + if (value == null) { + return false; + } + + return value; + } + + @Override + public Class getModelType() { + return Boolean.class; + } + + @Override + public Class getPresentationType() { + return Boolean.class; + } + + }); + MethodProperty property = new MethodProperty( + paulaBean, "deceased"); + cb.setPropertyDataSource(property); + assertEquals(Boolean.FALSE, property.getValue()); + assertEquals(Boolean.FALSE, cb.getValue()); + Boolean newDmValue = cb.getConverter().convertToPresentation( + cb.getValue(), Boolean.class, new Locale("fi", "FI")); + assertEquals(Boolean.FALSE, newDmValue); + + // FIXME: Should be able to set to false here to cause datamodel to be + // set to false but the change will not be propagated to the Property + // (field value is already false) + + cb.setValue(true); + assertEquals(Boolean.TRUE, cb.getValue()); + assertEquals(Boolean.TRUE, property.getValue()); + + cb.setValue(false); + assertEquals(Boolean.FALSE, cb.getValue()); + assertEquals(Boolean.FALSE, property.getValue()); + + } + + // Now specific to Integer because StringToNumberConverter has been removed + public static class NumberBean { + private Integer number; + + public Integer getNumber() { + return number; + } + + public void setNumber(Integer number) { + this.number = number; + } + + } + + public void testNumberDoubleConverterChange() { + final VaadinSession a = new AlwaysLockedVaadinSession(null); + VaadinSession.setCurrent(a); + TextField tf = new TextField() { + @Override + public VaadinSession getSession() { + return a; + } + }; + NumberBean nb = new NumberBean(); + nb.setNumber(490); + + tf.setPropertyDataSource(new MethodProperty(nb, "number")); + assertEquals(490, tf.getPropertyDataSource().getValue()); + assertEquals("490", tf.getValue()); + + Converter c1 = tf.getConverter(); + + tf.setPropertyDataSource(new MethodProperty(nb, "number")); + Converter c2 = tf.getConverter(); + assertTrue( + "StringToInteger converter is ok for integer types and should stay even though property is changed", + c1 == c2); + assertEquals(490, tf.getPropertyDataSource().getValue()); + assertEquals("490", tf.getValue()); + + } + + @Test + public void testNullConverter() { + TextField tf = new TextField("foo"); + tf.setConverter(new StringToIntegerConverter()); + tf.setPropertyDataSource(new ObjectProperty(12)); + tf.setConverter((Converter) null); + try { + Object v = tf.getConvertedValue(); + System.out.println(v); + Assert.fail("Trying to convert String -> Integer should fail when there is no converter"); + } catch (ConversionException e) { + // ok, should happen when there is no converter but conversion is + // needed + } + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractfield/AbstractFieldListenersTest.java b/server/tests/src/com/vaadin/tests/server/component/abstractfield/AbstractFieldListenersTest.java new file mode 100644 index 0000000000..def3ceb643 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstractfield/AbstractFieldListenersTest.java @@ -0,0 +1,21 @@ +package com.vaadin.tests.server.component.abstractfield; + +import com.vaadin.data.Property.ReadOnlyStatusChangeEvent; +import com.vaadin.data.Property.ReadOnlyStatusChangeListener; +import com.vaadin.data.Property.ValueChangeEvent; +import com.vaadin.data.Property.ValueChangeListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; +import com.vaadin.ui.CheckBox; + +public class AbstractFieldListenersTest extends AbstractListenerMethodsTestBase { + public void testReadOnlyStatusChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(CheckBox.class, + ReadOnlyStatusChangeEvent.class, + ReadOnlyStatusChangeListener.class); + } + + public void testValueChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(CheckBox.class, ValueChangeEvent.class, + ValueChangeListener.class); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractfield/DefaultConverterFactory.java b/server/tests/src/com/vaadin/tests/server/component/abstractfield/DefaultConverterFactory.java deleted file mode 100644 index 99397e9e8f..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstractfield/DefaultConverterFactory.java +++ /dev/null @@ -1,133 +0,0 @@ -package com.vaadin.tests.server.component.abstractfield; - -import java.math.BigDecimal; -import java.util.Locale; - -import junit.framework.TestCase; - -import com.vaadin.data.util.MethodProperty; -import com.vaadin.server.VaadinSession; -import com.vaadin.tests.data.bean.Address; -import com.vaadin.tests.data.bean.Country; -import com.vaadin.tests.data.bean.Person; -import com.vaadin.tests.data.bean.Sex; -import com.vaadin.tests.util.AlwaysLockedVaadinSession; -import com.vaadin.ui.TextField; - -public class DefaultConverterFactory extends TestCase { - - public static class FloatBean { - float f1; - Float f2; - - public FloatBean(float f1, Float f2) { - this.f1 = f1; - this.f2 = f2; - } - - public float getF1() { - return f1; - } - - public void setF1(float f1) { - this.f1 = f1; - } - - public Float getF2() { - return f2; - } - - public void setF2(Float f2) { - this.f2 = f2; - } - - } - - public static class LongBean { - long l1; - Long l2; - - public LongBean(long l1, Long l2) { - this.l1 = l1; - this.l2 = l2; - } - - public long getL1() { - return l1; - } - - public void setL1(long l1) { - this.l1 = l1; - } - - public Long getL2() { - return l2; - } - - public void setL2(Long l2) { - this.l2 = l2; - } - - } - - Person paulaBean = new Person("Paula", "Brilliant", "paula@brilliant.com", - 34, Sex.FEMALE, new Address("Paula street 1", 12345, "P-town", - Country.FINLAND)); - { - paulaBean.setSalary(49000); - BigDecimal rent = new BigDecimal(57223); - rent = rent.scaleByPowerOfTen(-2); - paulaBean.setRent(rent); - } - - public void testFloatConversion() { - VaadinSession sess = new AlwaysLockedVaadinSession(null); - VaadinSession.setCurrent(sess); - - TextField tf = new TextField(); - tf.setLocale(new Locale("en", "US")); - tf.setPropertyDataSource(new MethodProperty(new FloatBean(12f, - 23f), "f2")); - assertEquals("23", tf.getValue()); - tf.setValue("24"); - assertEquals("24", tf.getValue()); - assertEquals(24f, tf.getConvertedValue()); - assertEquals(24f, tf.getPropertyDataSource().getValue()); - } - - public void testLongConversion() { - VaadinSession sess = new AlwaysLockedVaadinSession(null); - VaadinSession.setCurrent(sess); - - TextField tf = new TextField(); - tf.setLocale(new Locale("en", "US")); - tf.setPropertyDataSource(new MethodProperty(new LongBean(12, - 1982739187238L), "l2")); - assertEquals("1,982,739,187,238", tf.getValue()); - tf.setValue("1982739187239"); - assertEquals("1,982,739,187,239", tf.getValue()); - assertEquals(1982739187239L, tf.getConvertedValue()); - assertEquals(1982739187239L, tf.getPropertyDataSource().getValue()); - } - - public void testDefaultNumberConversion() { - VaadinSession app = new AlwaysLockedVaadinSession(null); - VaadinSession.setCurrent(app); - TextField tf = new TextField(); - tf.setLocale(new Locale("en", "US")); - tf.setPropertyDataSource(new MethodProperty(paulaBean, - "salary")); - assertEquals("49,000", tf.getValue()); - - tf.setLocale(new Locale("fi", "FI")); - // FIXME: The following line should not be necessary and should be - // removed - tf.setPropertyDataSource(new MethodProperty(paulaBean, - "salary")); - String value = tf.getValue(); - // Java uses a non-breaking space (ascii 160) instead of space when - // formatting - String expected = "49" + (char) 160 + "000"; - assertEquals(expected, value); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractfield/DefaultConverterFactoryTest.java b/server/tests/src/com/vaadin/tests/server/component/abstractfield/DefaultConverterFactoryTest.java new file mode 100644 index 0000000000..68e198c37a --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstractfield/DefaultConverterFactoryTest.java @@ -0,0 +1,133 @@ +package com.vaadin.tests.server.component.abstractfield; + +import java.math.BigDecimal; +import java.util.Locale; + +import junit.framework.TestCase; + +import com.vaadin.data.util.MethodProperty; +import com.vaadin.server.VaadinSession; +import com.vaadin.tests.data.bean.Address; +import com.vaadin.tests.data.bean.Country; +import com.vaadin.tests.data.bean.Person; +import com.vaadin.tests.data.bean.Sex; +import com.vaadin.tests.util.AlwaysLockedVaadinSession; +import com.vaadin.ui.TextField; + +public class DefaultConverterFactoryTest extends TestCase { + + public static class FloatBean { + float f1; + Float f2; + + public FloatBean(float f1, Float f2) { + this.f1 = f1; + this.f2 = f2; + } + + public float getF1() { + return f1; + } + + public void setF1(float f1) { + this.f1 = f1; + } + + public Float getF2() { + return f2; + } + + public void setF2(Float f2) { + this.f2 = f2; + } + + } + + public static class LongBean { + long l1; + Long l2; + + public LongBean(long l1, Long l2) { + this.l1 = l1; + this.l2 = l2; + } + + public long getL1() { + return l1; + } + + public void setL1(long l1) { + this.l1 = l1; + } + + public Long getL2() { + return l2; + } + + public void setL2(Long l2) { + this.l2 = l2; + } + + } + + Person paulaBean = new Person("Paula", "Brilliant", "paula@brilliant.com", + 34, Sex.FEMALE, new Address("Paula street 1", 12345, "P-town", + Country.FINLAND)); + { + paulaBean.setSalary(49000); + BigDecimal rent = new BigDecimal(57223); + rent = rent.scaleByPowerOfTen(-2); + paulaBean.setRent(rent); + } + + public void testFloatConversion() { + VaadinSession sess = new AlwaysLockedVaadinSession(null); + VaadinSession.setCurrent(sess); + + TextField tf = new TextField(); + tf.setLocale(new Locale("en", "US")); + tf.setPropertyDataSource(new MethodProperty(new FloatBean(12f, + 23f), "f2")); + assertEquals("23", tf.getValue()); + tf.setValue("24"); + assertEquals("24", tf.getValue()); + assertEquals(24f, tf.getConvertedValue()); + assertEquals(24f, tf.getPropertyDataSource().getValue()); + } + + public void testLongConversion() { + VaadinSession sess = new AlwaysLockedVaadinSession(null); + VaadinSession.setCurrent(sess); + + TextField tf = new TextField(); + tf.setLocale(new Locale("en", "US")); + tf.setPropertyDataSource(new MethodProperty(new LongBean(12, + 1982739187238L), "l2")); + assertEquals("1,982,739,187,238", tf.getValue()); + tf.setValue("1982739187239"); + assertEquals("1,982,739,187,239", tf.getValue()); + assertEquals(1982739187239L, tf.getConvertedValue()); + assertEquals(1982739187239L, tf.getPropertyDataSource().getValue()); + } + + public void testDefaultNumberConversion() { + VaadinSession app = new AlwaysLockedVaadinSession(null); + VaadinSession.setCurrent(app); + TextField tf = new TextField(); + tf.setLocale(new Locale("en", "US")); + tf.setPropertyDataSource(new MethodProperty(paulaBean, + "salary")); + assertEquals("49,000", tf.getValue()); + + tf.setLocale(new Locale("fi", "FI")); + // FIXME: The following line should not be necessary and should be + // removed + tf.setPropertyDataSource(new MethodProperty(paulaBean, + "salary")); + String value = tf.getValue(); + // Java uses a non-breaking space (ascii 160) instead of space when + // formatting + String expected = "49" + (char) 160 + "000"; + assertEquals(expected, value); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractfield/ReadDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/abstractfield/ReadDesignTest.java new file mode 100644 index 0000000000..4fa3400af5 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstractfield/ReadDesignTest.java @@ -0,0 +1,71 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.abstractfield; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Attributes; +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; + +import com.vaadin.ui.AbstractField; +import com.vaadin.ui.TextField; +import com.vaadin.ui.declarative.DesignContext; + +/** + * + * Test case for reading the attributes of the AbstractField from design + * + * @author Vaadin Ltd + */ +public class ReadDesignTest extends TestCase { + + private DesignContext ctx; + + @Override + protected void setUp() throws Exception { + super.setUp(); + ctx = new DesignContext(); + } + + public void testSynchronizeReadOnly() { + Element design = createDesign("readonly", ""); + AbstractField component = getComponent(); + component.readDesign(design, ctx); + assertEquals(true, component.isReadOnly()); + design = createDesign("readonly", "false"); + component.readDesign(design, ctx); + assertEquals(false, component.isReadOnly()); + } + + public void testSynchronizeTabIndex() { + Element design = createDesign("tabindex", "2"); + AbstractField component = getComponent(); + component.readDesign(design, ctx); + assertEquals("Tab index must be 2", 2, component.getTabIndex()); + } + + private AbstractField getComponent() { + return new TextField(); + } + + private Element createDesign(String key, String value) { + Attributes attributes = new Attributes(); + attributes.put(key, value); + Element node = new Element(Tag.valueOf("v-text-field"), "", attributes); + return node; + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractfield/RemoveListenersOnDetach.java b/server/tests/src/com/vaadin/tests/server/component/abstractfield/RemoveListenersOnDetach.java deleted file mode 100644 index f391d15fb3..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstractfield/RemoveListenersOnDetach.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.vaadin.tests.server.component.abstractfield; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -import com.vaadin.data.Property; -import com.vaadin.data.util.AbstractProperty; -import com.vaadin.data.util.converter.Converter.ConversionException; -import com.vaadin.server.VaadinRequest; -import com.vaadin.server.VaadinSession; -import com.vaadin.tests.util.AlwaysLockedVaadinSession; -import com.vaadin.ui.AbstractField; -import com.vaadin.ui.UI; - -public class RemoveListenersOnDetach { - - int numValueChanges = 0; - int numReadOnlyChanges = 0; - - AbstractField field = new AbstractField() { - final private VaadinSession application = new AlwaysLockedVaadinSession( - null); - private UI uI = new UI() { - - @Override - protected void init(VaadinRequest request) { - - } - - @Override - public VaadinSession getSession() { - return application; - } - - }; - - @Override - public Class getType() { - return String.class; - } - - @Override - public void valueChange(Property.ValueChangeEvent event) { - super.valueChange(event); - numValueChanges++; - } - - @Override - public void readOnlyStatusChange( - Property.ReadOnlyStatusChangeEvent event) { - super.readOnlyStatusChange(event); - numReadOnlyChanges++; - } - - @Override - public com.vaadin.ui.UI getUI() { - return uI; - } - - @Override - public VaadinSession getSession() { - return application; - } - }; - - Property property = new AbstractProperty() { - @Override - public String getValue() { - return null; - } - - @Override - public void setValue(String newValue) throws ReadOnlyException, - ConversionException { - fireValueChange(); - } - - @Override - public Class getType() { - return String.class; - } - }; - - @Test - public void testAttachDetach() { - field.setPropertyDataSource(property); - - property.setValue(null); - property.setReadOnly(true); - assertEquals(1, numValueChanges); - assertEquals(1, numReadOnlyChanges); - - field.attach(); - property.setValue(null); - property.setReadOnly(false); - assertEquals(2, numValueChanges); - assertEquals(2, numReadOnlyChanges); - - field.detach(); - property.setValue(null); - property.setReadOnly(true); - assertEquals(2, numValueChanges); - assertEquals(2, numReadOnlyChanges); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractfield/RemoveListenersOnDetachTest.java b/server/tests/src/com/vaadin/tests/server/component/abstractfield/RemoveListenersOnDetachTest.java new file mode 100644 index 0000000000..f547f2c66b --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstractfield/RemoveListenersOnDetachTest.java @@ -0,0 +1,106 @@ +package com.vaadin.tests.server.component.abstractfield; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.vaadin.data.Property; +import com.vaadin.data.util.AbstractProperty; +import com.vaadin.data.util.converter.Converter.ConversionException; +import com.vaadin.server.VaadinRequest; +import com.vaadin.server.VaadinSession; +import com.vaadin.tests.util.AlwaysLockedVaadinSession; +import com.vaadin.ui.AbstractField; +import com.vaadin.ui.UI; + +public class RemoveListenersOnDetachTest { + + int numValueChanges = 0; + int numReadOnlyChanges = 0; + + AbstractField field = new AbstractField() { + final private VaadinSession application = new AlwaysLockedVaadinSession( + null); + private UI uI = new UI() { + + @Override + protected void init(VaadinRequest request) { + + } + + @Override + public VaadinSession getSession() { + return application; + } + + }; + + @Override + public Class getType() { + return String.class; + } + + @Override + public void valueChange(Property.ValueChangeEvent event) { + super.valueChange(event); + numValueChanges++; + } + + @Override + public void readOnlyStatusChange( + Property.ReadOnlyStatusChangeEvent event) { + super.readOnlyStatusChange(event); + numReadOnlyChanges++; + } + + @Override + public com.vaadin.ui.UI getUI() { + return uI; + } + + @Override + public VaadinSession getSession() { + return application; + } + }; + + Property property = new AbstractProperty() { + @Override + public String getValue() { + return null; + } + + @Override + public void setValue(String newValue) throws ReadOnlyException, + ConversionException { + fireValueChange(); + } + + @Override + public Class getType() { + return String.class; + } + }; + + @Test + public void testAttachDetach() { + field.setPropertyDataSource(property); + + property.setValue(null); + property.setReadOnly(true); + assertEquals(1, numValueChanges); + assertEquals(1, numReadOnlyChanges); + + field.attach(); + property.setValue(null); + property.setReadOnly(false); + assertEquals(2, numValueChanges); + assertEquals(2, numReadOnlyChanges); + + field.detach(); + property.setValue(null); + property.setReadOnly(true); + assertEquals(2, numValueChanges); + assertEquals(2, numReadOnlyChanges); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractfield/TestAbstractFieldListeners.java b/server/tests/src/com/vaadin/tests/server/component/abstractfield/TestAbstractFieldListeners.java deleted file mode 100644 index 9937bf92d5..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstractfield/TestAbstractFieldListeners.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.vaadin.tests.server.component.abstractfield; - -import com.vaadin.data.Property.ReadOnlyStatusChangeEvent; -import com.vaadin.data.Property.ReadOnlyStatusChangeListener; -import com.vaadin.data.Property.ValueChangeEvent; -import com.vaadin.data.Property.ValueChangeListener; -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; -import com.vaadin.ui.CheckBox; - -public class TestAbstractFieldListeners extends AbstractListenerMethodsTest { - public void testReadOnlyStatusChangeListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(CheckBox.class, - ReadOnlyStatusChangeEvent.class, - ReadOnlyStatusChangeListener.class); - } - - public void testValueChangeListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(CheckBox.class, ValueChangeEvent.class, - ValueChangeListener.class); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractfield/TestReadDesign.java b/server/tests/src/com/vaadin/tests/server/component/abstractfield/TestReadDesign.java deleted file mode 100644 index dd0e629199..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstractfield/TestReadDesign.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.abstractfield; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Attributes; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; - -import com.vaadin.ui.AbstractField; -import com.vaadin.ui.TextField; -import com.vaadin.ui.declarative.DesignContext; - -/** - * - * Test case for reading the attributes of the AbstractField from design - * - * @author Vaadin Ltd - */ -public class TestReadDesign extends TestCase { - - private DesignContext ctx; - - @Override - protected void setUp() throws Exception { - super.setUp(); - ctx = new DesignContext(); - } - - public void testSynchronizeReadOnly() { - Element design = createDesign("readonly", ""); - AbstractField component = getComponent(); - component.readDesign(design, ctx); - assertEquals(true, component.isReadOnly()); - design = createDesign("readonly", "false"); - component.readDesign(design, ctx); - assertEquals(false, component.isReadOnly()); - } - - public void testSynchronizeTabIndex() { - Element design = createDesign("tabindex", "2"); - AbstractField component = getComponent(); - component.readDesign(design, ctx); - assertEquals("Tab index must be 2", 2, component.getTabIndex()); - } - - private AbstractField getComponent() { - return new TextField(); - } - - private Element createDesign(String key, String value) { - Attributes attributes = new Attributes(); - attributes.put(key, value); - Element node = new Element(Tag.valueOf("v-text-field"), "", attributes); - return node; - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractfield/TestWriteDesign.java b/server/tests/src/com/vaadin/tests/server/component/abstractfield/TestWriteDesign.java deleted file mode 100644 index 969713abe6..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstractfield/TestWriteDesign.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.abstractfield; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Attributes; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; - -import com.vaadin.data.util.ObjectProperty; -import com.vaadin.ui.AbstractField; -import com.vaadin.ui.TextField; -import com.vaadin.ui.declarative.DesignContext; - -/** - * Test case for writing the attributes of the AbstractField to design - * - * @author Vaadin Ltd - */ -public class TestWriteDesign extends TestCase { - - private DesignContext ctx; - - @Override - protected void setUp() throws Exception { - super.setUp(); - ctx = new DesignContext(); - } - - public void testSynchronizeReadOnly() { - Element design = createDesign(); - AbstractField component = getComponent(); - component.setReadOnly(true); - component.writeDesign(design, ctx); - // we only changed one of the attributes, others are at default values - assertEquals(1, design.attributes().size()); - assertTrue("Design must contain readonly", design.hasAttr("readonly")); - assertTrue("Readonly must be true", design.attr("readonly").equals("") - || design.attr("readonly").equals("true")); - } - - public void testSynchronizeModelReadOnly() { - Element design = createDesign(); - AbstractField component = getComponent(); - ObjectProperty property = new ObjectProperty("test"); - property.setReadOnly(true); - component.setPropertyDataSource(property); - component.writeDesign(design, ctx); - // make sure that property readonly is not written to design - assertFalse("Design must not contain readonly", - design.hasAttr("readonly")); - } - - private AbstractField getComponent() { - return new TextField(); - } - - private Element createDesign() { - Attributes attr = new Attributes(); - attr.put("should_be_removed", "foo"); - return new Element(Tag.valueOf("v-text-field"), "", attr); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractfield/WriteDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/abstractfield/WriteDesignTest.java new file mode 100644 index 0000000000..37ff8cf3aa --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstractfield/WriteDesignTest.java @@ -0,0 +1,77 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.abstractfield; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Attributes; +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; + +import com.vaadin.data.util.ObjectProperty; +import com.vaadin.ui.AbstractField; +import com.vaadin.ui.TextField; +import com.vaadin.ui.declarative.DesignContext; + +/** + * Test case for writing the attributes of the AbstractField to design + * + * @author Vaadin Ltd + */ +public class WriteDesignTest extends TestCase { + + private DesignContext ctx; + + @Override + protected void setUp() throws Exception { + super.setUp(); + ctx = new DesignContext(); + } + + public void testSynchronizeReadOnly() { + Element design = createDesign(); + AbstractField component = getComponent(); + component.setReadOnly(true); + component.writeDesign(design, ctx); + // we only changed one of the attributes, others are at default values + assertEquals(1, design.attributes().size()); + assertTrue("Design must contain readonly", design.hasAttr("readonly")); + assertTrue("Readonly must be true", design.attr("readonly").equals("") + || design.attr("readonly").equals("true")); + } + + public void testSynchronizeModelReadOnly() { + Element design = createDesign(); + AbstractField component = getComponent(); + ObjectProperty property = new ObjectProperty("test"); + property.setReadOnly(true); + component.setPropertyDataSource(property); + component.writeDesign(design, ctx); + // make sure that property readonly is not written to design + assertFalse("Design must not contain readonly", + design.hasAttr("readonly")); + } + + private AbstractField getComponent() { + return new TextField(); + } + + private Element createDesign() { + Attributes attr = new Attributes(); + attr.put("should_be_removed", "foo"); + return new Element(Tag.valueOf("v-text-field"), "", attr); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/AbstractOrderedLayoutListenersTest.java b/server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/AbstractOrderedLayoutListenersTest.java new file mode 100644 index 0000000000..e7393e5f7d --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/AbstractOrderedLayoutListenersTest.java @@ -0,0 +1,14 @@ +package com.vaadin.tests.server.component.abstractorderedlayout; + +import com.vaadin.event.LayoutEvents.LayoutClickEvent; +import com.vaadin.event.LayoutEvents.LayoutClickListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; +import com.vaadin.ui.VerticalLayout; + +public class AbstractOrderedLayoutListenersTest extends + AbstractListenerMethodsTestBase { + public void testLayoutClickListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(VerticalLayout.class, LayoutClickEvent.class, + LayoutClickListener.class); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/LayoutSettingsOnReplace.java b/server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/LayoutSettingsOnReplace.java deleted file mode 100644 index fd951f1692..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/LayoutSettingsOnReplace.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.abstractorderedlayout; - -import org.junit.Assert; -import org.junit.Test; - -import com.vaadin.ui.AbstractComponent; -import com.vaadin.ui.AbstractOrderedLayout; -import com.vaadin.ui.Alignment; - -/** - * Tests for abstract layout settings which should be preserved on replace - * component - * - * @since 7.2 - * @author Vaadin Ltd - */ -public class LayoutSettingsOnReplace { - - @Test - public void testExpandRatio() { - AbstractOrderedLayout layout = new AbstractOrderedLayout() { - }; - - AbstractComponent first = new AbstractComponent() { - }; - AbstractComponent second = new AbstractComponent() { - }; - - layout.addComponent(first); - layout.addComponent(second); - - int ratio = 2; - layout.setExpandRatio(first, ratio); - layout.setExpandRatio(second, 1); - - AbstractComponent replace = new AbstractComponent() { - }; - layout.replaceComponent(first, replace); - - Assert.assertEquals("Expand ratio for replaced component is not " - + "the same as for previous one", ratio, - layout.getExpandRatio(replace), 0.0001); - } - - @Test - public void testAlignment() { - AbstractOrderedLayout layout = new AbstractOrderedLayout() { - }; - - AbstractComponent first = new AbstractComponent() { - }; - AbstractComponent second = new AbstractComponent() { - }; - - layout.addComponent(first); - layout.addComponent(second); - - Alignment alignment = Alignment.BOTTOM_RIGHT; - layout.setComponentAlignment(first, alignment); - layout.setComponentAlignment(second, Alignment.MIDDLE_CENTER); - - AbstractComponent replace = new AbstractComponent() { - }; - layout.replaceComponent(first, replace); - - Assert.assertEquals("Alignment for replaced component is not " - + "the same as for previous one", alignment, - layout.getComponentAlignment(replace)); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/LayoutSettingsOnReplaceTest.java b/server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/LayoutSettingsOnReplaceTest.java new file mode 100644 index 0000000000..9d1972c232 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/LayoutSettingsOnReplaceTest.java @@ -0,0 +1,85 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.abstractorderedlayout; + +import org.junit.Assert; +import org.junit.Test; + +import com.vaadin.ui.AbstractComponent; +import com.vaadin.ui.AbstractOrderedLayout; +import com.vaadin.ui.Alignment; + +/** + * Tests for abstract layout settings which should be preserved on replace + * component + * + * @since 7.2 + * @author Vaadin Ltd + */ +public class LayoutSettingsOnReplaceTest { + + @Test + public void testExpandRatio() { + AbstractOrderedLayout layout = new AbstractOrderedLayout() { + }; + + AbstractComponent first = new AbstractComponent() { + }; + AbstractComponent second = new AbstractComponent() { + }; + + layout.addComponent(first); + layout.addComponent(second); + + int ratio = 2; + layout.setExpandRatio(first, ratio); + layout.setExpandRatio(second, 1); + + AbstractComponent replace = new AbstractComponent() { + }; + layout.replaceComponent(first, replace); + + Assert.assertEquals("Expand ratio for replaced component is not " + + "the same as for previous one", ratio, + layout.getExpandRatio(replace), 0.0001); + } + + @Test + public void testAlignment() { + AbstractOrderedLayout layout = new AbstractOrderedLayout() { + }; + + AbstractComponent first = new AbstractComponent() { + }; + AbstractComponent second = new AbstractComponent() { + }; + + layout.addComponent(first); + layout.addComponent(second); + + Alignment alignment = Alignment.BOTTOM_RIGHT; + layout.setComponentAlignment(first, alignment); + layout.setComponentAlignment(second, Alignment.MIDDLE_CENTER); + + AbstractComponent replace = new AbstractComponent() { + }; + layout.replaceComponent(first, replace); + + Assert.assertEquals("Alignment for replaced component is not " + + "the same as for previous one", alignment, + layout.getComponentAlignment(replace)); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/ReadDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/ReadDesignTest.java new file mode 100644 index 0000000000..b0a2e678c2 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/ReadDesignTest.java @@ -0,0 +1,119 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.abstractorderedlayout; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Attributes; +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; + +import com.vaadin.ui.Alignment; +import com.vaadin.ui.Component; +import com.vaadin.ui.VerticalLayout; +import com.vaadin.ui.declarative.DesignContext; + +/** + * Test case from reading AbstractOrdered layouts from design + * + * @since + * @author Vaadin Ltd + */ +public class ReadDesignTest extends TestCase { + + public void testChildCount() { + VerticalLayout root = createLayout(0f, false); + assertEquals(2, root.getComponentCount()); + } + + public void testMargin() { + VerticalLayout root = createLayout(0f, true); + assertTrue(root.getMargin().getBitMask() != 0); + root = createLayout(0f, false); + assertTrue(root.getMargin().getBitMask() == 0); + } + + public void testAttributes() { + VerticalLayout root = createLayout(0f, false); + assertEquals("test-layout", root.getCaption()); + assertEquals("test-label", root.getComponent(0).getCaption()); + assertEquals("test-button", root.getComponent(1).getCaption()); + } + + public void testExpandRatio() { + VerticalLayout root = createLayout(1f, false); + assertEquals(1f, root.getExpandRatio(root.getComponent(0))); + assertEquals(1f, root.getExpandRatio(root.getComponent(1))); + + root = createLayout(0f, false); + assertEquals(0f, root.getExpandRatio(root.getComponent(0))); + assertEquals(0f, root.getExpandRatio(root.getComponent(1))); + } + + public void testAlignment() { + VerticalLayout root = createLayout(0f, false, ":top", ":left"); + assertEquals(Alignment.TOP_LEFT, + root.getComponentAlignment(root.getComponent(0))); + root = createLayout(0f, false, ":middle", ":center"); + assertEquals(Alignment.MIDDLE_CENTER, + root.getComponentAlignment(root.getComponent(0))); + root = createLayout(0f, false, ":bottom", ":right"); + assertEquals(Alignment.BOTTOM_RIGHT, + root.getComponentAlignment(root.getComponent(0))); + + } + + private VerticalLayout createLayout(float expandRatio, boolean margin, + String... alignments) { + DesignContext ctx = new DesignContext(); + Element design = createDesign(expandRatio, margin, alignments); + Component child = ctx.readDesign(design); + return (VerticalLayout) child; + } + + private Element createDesign(float expandRatio, boolean margin, + String... alignments) { + + Attributes rootAttributes = new Attributes(); + rootAttributes.put("caption", "test-layout"); + if (margin) { + rootAttributes.put("margin", ""); + } + Element node = new Element(Tag.valueOf("v-vertical-layout"), "", + rootAttributes); + + Attributes firstChildAttributes = new Attributes(); + firstChildAttributes.put("caption", "test-label"); + firstChildAttributes.put(":expand", String.valueOf(expandRatio)); + for (String alignment : alignments) { + firstChildAttributes.put(alignment, ""); + } + Element firstChild = new Element(Tag.valueOf("v-label"), "", + firstChildAttributes); + node.appendChild(firstChild); + + Attributes secondChildAttributes = new Attributes(); + secondChildAttributes.put(":expand", String.valueOf(expandRatio)); + for (String alignment : alignments) { + secondChildAttributes.put(alignment, ""); + } + Element secondChild = new Element(Tag.valueOf("v-button"), "", + secondChildAttributes); + secondChild.html("test-button"); + node.appendChild(secondChild); + return node; + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/TestAbstractOrderedLayoutListeners.java b/server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/TestAbstractOrderedLayoutListeners.java deleted file mode 100644 index a0b34aca78..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/TestAbstractOrderedLayoutListeners.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.vaadin.tests.server.component.abstractorderedlayout; - -import com.vaadin.event.LayoutEvents.LayoutClickEvent; -import com.vaadin.event.LayoutEvents.LayoutClickListener; -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; -import com.vaadin.ui.VerticalLayout; - -public class TestAbstractOrderedLayoutListeners extends - AbstractListenerMethodsTest { - public void testLayoutClickListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(VerticalLayout.class, LayoutClickEvent.class, - LayoutClickListener.class); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/TestReadDesign.java b/server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/TestReadDesign.java deleted file mode 100644 index 874fbd83b2..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/TestReadDesign.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.abstractorderedlayout; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Attributes; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; - -import com.vaadin.ui.Alignment; -import com.vaadin.ui.Component; -import com.vaadin.ui.VerticalLayout; -import com.vaadin.ui.declarative.DesignContext; - -/** - * Test case from reading AbstractOrdered layouts from design - * - * @since - * @author Vaadin Ltd - */ -public class TestReadDesign extends TestCase { - - public void testChildCount() { - VerticalLayout root = createLayout(0f, false); - assertEquals(2, root.getComponentCount()); - } - - public void testMargin() { - VerticalLayout root = createLayout(0f, true); - assertTrue(root.getMargin().getBitMask() != 0); - root = createLayout(0f, false); - assertTrue(root.getMargin().getBitMask() == 0); - } - - public void testAttributes() { - VerticalLayout root = createLayout(0f, false); - assertEquals("test-layout", root.getCaption()); - assertEquals("test-label", root.getComponent(0).getCaption()); - assertEquals("test-button", root.getComponent(1).getCaption()); - } - - public void testExpandRatio() { - VerticalLayout root = createLayout(1f, false); - assertEquals(1f, root.getExpandRatio(root.getComponent(0))); - assertEquals(1f, root.getExpandRatio(root.getComponent(1))); - - root = createLayout(0f, false); - assertEquals(0f, root.getExpandRatio(root.getComponent(0))); - assertEquals(0f, root.getExpandRatio(root.getComponent(1))); - } - - public void testAlignment() { - VerticalLayout root = createLayout(0f, false, ":top", ":left"); - assertEquals(Alignment.TOP_LEFT, - root.getComponentAlignment(root.getComponent(0))); - root = createLayout(0f, false, ":middle", ":center"); - assertEquals(Alignment.MIDDLE_CENTER, - root.getComponentAlignment(root.getComponent(0))); - root = createLayout(0f, false, ":bottom", ":right"); - assertEquals(Alignment.BOTTOM_RIGHT, - root.getComponentAlignment(root.getComponent(0))); - - } - - private VerticalLayout createLayout(float expandRatio, boolean margin, - String... alignments) { - DesignContext ctx = new DesignContext(); - Element design = createDesign(expandRatio, margin, alignments); - Component child = ctx.readDesign(design); - return (VerticalLayout) child; - } - - private Element createDesign(float expandRatio, boolean margin, - String... alignments) { - - Attributes rootAttributes = new Attributes(); - rootAttributes.put("caption", "test-layout"); - if (margin) { - rootAttributes.put("margin", ""); - } - Element node = new Element(Tag.valueOf("v-vertical-layout"), "", - rootAttributes); - - Attributes firstChildAttributes = new Attributes(); - firstChildAttributes.put("caption", "test-label"); - firstChildAttributes.put(":expand", String.valueOf(expandRatio)); - for (String alignment : alignments) { - firstChildAttributes.put(alignment, ""); - } - Element firstChild = new Element(Tag.valueOf("v-label"), "", - firstChildAttributes); - node.appendChild(firstChild); - - Attributes secondChildAttributes = new Attributes(); - secondChildAttributes.put(":expand", String.valueOf(expandRatio)); - for (String alignment : alignments) { - secondChildAttributes.put(alignment, ""); - } - Element secondChild = new Element(Tag.valueOf("v-button"), "", - secondChildAttributes); - secondChild.html("test-button"); - node.appendChild(secondChild); - return node; - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/TestWriteDesign.java b/server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/TestWriteDesign.java deleted file mode 100644 index 302cf985bd..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/TestWriteDesign.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.abstractorderedlayout; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Attributes; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; - -import com.vaadin.ui.Alignment; -import com.vaadin.ui.Label; -import com.vaadin.ui.VerticalLayout; -import com.vaadin.ui.declarative.DesignContext; - -/** - * Test case for writing abstract ordered layout to design - * - * @since - * @author Vaadin Ltd - */ -public class TestWriteDesign extends TestCase { - - public void testSynchronizeMargin() { - VerticalLayout layout = new VerticalLayout(); - layout.setMargin(true); - Element design = createDesign(); - layout.writeDesign(design, createDesignContext()); - assertTrue("The margin must be written", design.hasAttr("margin")); - assertTrue("The margin must be empty or true", design.attr("margin") - .equals("") || design.attr("margin").equalsIgnoreCase("true")); - } - - public void testSynchronizeEmptyLayout() { - VerticalLayout layout = new VerticalLayout(); - layout.setCaption("changed-caption"); - Element design = createDesign(); - layout.writeDesign(design, createDesignContext()); - assertEquals(0, design.childNodes().size()); - assertEquals("changed-caption", design.attr("caption")); - } - - public void testSynchronizeLayoutWithChildren() { - VerticalLayout layout = new VerticalLayout(); - layout.addComponent(new Label("test-label")); - layout.getComponent(0).setCaption("test-caption"); - layout.addComponent(new Label("test-label-2")); - Element design = createDesign(); - layout.writeDesign(design, createDesignContext()); - assertEquals(2, design.childNodes().size()); - assertEquals("v-label", ((Element) design.childNode(0)).tagName()); - assertEquals("test-caption", design.childNode(0).attr("caption")); - } - - public void testSynchronizeUnitExpandRatio() { - VerticalLayout layout = new VerticalLayout(); - layout.addComponent(new Label("test-label")); - layout.setExpandRatio(layout.getComponent(0), 1.0f); - Element design = createDesign(); - layout.writeDesign(design, createDesignContext()); - assertTrue(design.childNode(0).hasAttr(":expand")); - assertEquals("", design.childNode(0).attr(":expand")); - } - - public void testSynchronizeArbitraryExpandRatio() { - VerticalLayout layout = new VerticalLayout(); - layout.addComponent(new Label("test-label")); - layout.setExpandRatio(layout.getComponent(0), 2.40f); - Element design = createDesign(); - layout.writeDesign(design, createDesignContext()); - assertTrue(design.childNode(0).hasAttr(":expand")); - assertEquals("2.4", design.childNode(0).attr(":expand")); - } - - public void testSynchronizeDefaultAlignment() { - Element design = createDesign(); - VerticalLayout layout = createLayoutWithAlignment(design, null); - layout.writeDesign(design, createDesignContext()); - assertFalse(design.childNode(0).hasAttr(":top")); - assertFalse(design.childNode(0).hasAttr(":left")); - } - - public void testSynchronizeMiddleCenter() { - Element design = createDesign(); - VerticalLayout layout = createLayoutWithAlignment(design, - Alignment.MIDDLE_CENTER); - layout.writeDesign(design, createDesignContext()); - assertTrue(design.childNode(0).hasAttr(":middle")); - assertTrue(design.childNode(0).hasAttr(":center")); - } - - public void testSynchronizeBottomRight() { - Element design = createDesign(); - VerticalLayout layout = createLayoutWithAlignment(design, - Alignment.BOTTOM_RIGHT); - layout.writeDesign(design, createDesignContext()); - assertTrue(design.childNode(0).hasAttr(":bottom")); - assertTrue(design.childNode(0).hasAttr(":right")); - } - - private VerticalLayout createLayoutWithAlignment(Element design, - Alignment alignment) { - VerticalLayout layout = new VerticalLayout(); - layout.addComponent(new Label("test-label")); - if (alignment != null) { - layout.setComponentAlignment(layout.getComponent(0), alignment); - } - layout.writeDesign(design, createDesignContext()); - return layout; - } - - private Element createDesign() { - // make sure that the design node has old content that should be removed - Attributes rootAttributes = new Attributes(); - rootAttributes.put("caption", "test-layout"); - Element node = new Element(Tag.valueOf("v-vertical-layout"), "", - rootAttributes); - Attributes firstChildAttributes = new Attributes(); - firstChildAttributes.put("caption", "test-label"); - Element firstChild = new Element(Tag.valueOf("v-label"), "", - firstChildAttributes); - node.appendChild(firstChild); - - Attributes secondChildAttributes = new Attributes(); - secondChildAttributes.put("caption", "test-button"); - Element secondChild = new Element(Tag.valueOf("v-button"), "", - secondChildAttributes); - node.appendChild(secondChild); - return node; - } - - private DesignContext createDesignContext() { - return new DesignContext(); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/WriteDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/WriteDesignTest.java new file mode 100644 index 0000000000..96697af3cd --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstractorderedlayout/WriteDesignTest.java @@ -0,0 +1,148 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.abstractorderedlayout; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Attributes; +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; + +import com.vaadin.ui.Alignment; +import com.vaadin.ui.Label; +import com.vaadin.ui.VerticalLayout; +import com.vaadin.ui.declarative.DesignContext; + +/** + * Test case for writing abstract ordered layout to design + * + * @since + * @author Vaadin Ltd + */ +public class WriteDesignTest extends TestCase { + + public void testSynchronizeMargin() { + VerticalLayout layout = new VerticalLayout(); + layout.setMargin(true); + Element design = createDesign(); + layout.writeDesign(design, createDesignContext()); + assertTrue("The margin must be written", design.hasAttr("margin")); + assertTrue("The margin must be empty or true", design.attr("margin") + .equals("") || design.attr("margin").equalsIgnoreCase("true")); + } + + public void testSynchronizeEmptyLayout() { + VerticalLayout layout = new VerticalLayout(); + layout.setCaption("changed-caption"); + Element design = createDesign(); + layout.writeDesign(design, createDesignContext()); + assertEquals(0, design.childNodes().size()); + assertEquals("changed-caption", design.attr("caption")); + } + + public void testSynchronizeLayoutWithChildren() { + VerticalLayout layout = new VerticalLayout(); + layout.addComponent(new Label("test-label")); + layout.getComponent(0).setCaption("test-caption"); + layout.addComponent(new Label("test-label-2")); + Element design = createDesign(); + layout.writeDesign(design, createDesignContext()); + assertEquals(2, design.childNodes().size()); + assertEquals("v-label", ((Element) design.childNode(0)).tagName()); + assertEquals("test-caption", design.childNode(0).attr("caption")); + } + + public void testSynchronizeUnitExpandRatio() { + VerticalLayout layout = new VerticalLayout(); + layout.addComponent(new Label("test-label")); + layout.setExpandRatio(layout.getComponent(0), 1.0f); + Element design = createDesign(); + layout.writeDesign(design, createDesignContext()); + assertTrue(design.childNode(0).hasAttr(":expand")); + assertEquals("", design.childNode(0).attr(":expand")); + } + + public void testSynchronizeArbitraryExpandRatio() { + VerticalLayout layout = new VerticalLayout(); + layout.addComponent(new Label("test-label")); + layout.setExpandRatio(layout.getComponent(0), 2.40f); + Element design = createDesign(); + layout.writeDesign(design, createDesignContext()); + assertTrue(design.childNode(0).hasAttr(":expand")); + assertEquals("2.4", design.childNode(0).attr(":expand")); + } + + public void testSynchronizeDefaultAlignment() { + Element design = createDesign(); + VerticalLayout layout = createLayoutWithAlignment(design, null); + layout.writeDesign(design, createDesignContext()); + assertFalse(design.childNode(0).hasAttr(":top")); + assertFalse(design.childNode(0).hasAttr(":left")); + } + + public void testSynchronizeMiddleCenter() { + Element design = createDesign(); + VerticalLayout layout = createLayoutWithAlignment(design, + Alignment.MIDDLE_CENTER); + layout.writeDesign(design, createDesignContext()); + assertTrue(design.childNode(0).hasAttr(":middle")); + assertTrue(design.childNode(0).hasAttr(":center")); + } + + public void testSynchronizeBottomRight() { + Element design = createDesign(); + VerticalLayout layout = createLayoutWithAlignment(design, + Alignment.BOTTOM_RIGHT); + layout.writeDesign(design, createDesignContext()); + assertTrue(design.childNode(0).hasAttr(":bottom")); + assertTrue(design.childNode(0).hasAttr(":right")); + } + + private VerticalLayout createLayoutWithAlignment(Element design, + Alignment alignment) { + VerticalLayout layout = new VerticalLayout(); + layout.addComponent(new Label("test-label")); + if (alignment != null) { + layout.setComponentAlignment(layout.getComponent(0), alignment); + } + layout.writeDesign(design, createDesignContext()); + return layout; + } + + private Element createDesign() { + // make sure that the design node has old content that should be removed + Attributes rootAttributes = new Attributes(); + rootAttributes.put("caption", "test-layout"); + Element node = new Element(Tag.valueOf("v-vertical-layout"), "", + rootAttributes); + Attributes firstChildAttributes = new Attributes(); + firstChildAttributes.put("caption", "test-label"); + Element firstChild = new Element(Tag.valueOf("v-label"), "", + firstChildAttributes); + node.appendChild(firstChild); + + Attributes secondChildAttributes = new Attributes(); + secondChildAttributes.put("caption", "test-button"); + Element secondChild = new Element(Tag.valueOf("v-button"), "", + secondChildAttributes); + node.appendChild(secondChild); + return node; + } + + private DesignContext createDesignContext() { + return new DesignContext(); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractselect/AbstractSelectListenersTest.java b/server/tests/src/com/vaadin/tests/server/component/abstractselect/AbstractSelectListenersTest.java new file mode 100644 index 0000000000..8ec0414e03 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstractselect/AbstractSelectListenersTest.java @@ -0,0 +1,20 @@ +package com.vaadin.tests.server.component.abstractselect; + +import com.vaadin.data.Container.ItemSetChangeEvent; +import com.vaadin.data.Container.ItemSetChangeListener; +import com.vaadin.data.Container.PropertySetChangeEvent; +import com.vaadin.data.Container.PropertySetChangeListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; +import com.vaadin.ui.ComboBox; + +public class AbstractSelectListenersTest extends AbstractListenerMethodsTestBase { + public void testItemSetChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(ComboBox.class, ItemSetChangeEvent.class, + ItemSetChangeListener.class); + } + + public void testPropertySetChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(ComboBox.class, PropertySetChangeEvent.class, + PropertySetChangeListener.class); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractselect/TestAbstractSelectListeners.java b/server/tests/src/com/vaadin/tests/server/component/abstractselect/TestAbstractSelectListeners.java deleted file mode 100644 index 75c19b0517..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstractselect/TestAbstractSelectListeners.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.vaadin.tests.server.component.abstractselect; - -import com.vaadin.data.Container.ItemSetChangeEvent; -import com.vaadin.data.Container.ItemSetChangeListener; -import com.vaadin.data.Container.PropertySetChangeEvent; -import com.vaadin.data.Container.PropertySetChangeListener; -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; -import com.vaadin.ui.ComboBox; - -public class TestAbstractSelectListeners extends AbstractListenerMethodsTest { - public void testItemSetChangeListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(ComboBox.class, ItemSetChangeEvent.class, - ItemSetChangeListener.class); - } - - public void testPropertySetChangeListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(ComboBox.class, PropertySetChangeEvent.class, - PropertySetChangeListener.class); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractsinglecomponentcontainer/RemoveFromParentLockingTest.java b/server/tests/src/com/vaadin/tests/server/component/abstractsinglecomponentcontainer/RemoveFromParentLockingTest.java new file mode 100644 index 0000000000..e277d4e075 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstractsinglecomponentcontainer/RemoveFromParentLockingTest.java @@ -0,0 +1,125 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.abstractsinglecomponentcontainer; + +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +import org.junit.Assert; +import org.junit.Test; + +import com.vaadin.server.VaadinRequest; +import com.vaadin.server.VaadinSession; +import com.vaadin.ui.UI; +import com.vaadin.ui.VerticalLayout; + +public class RemoveFromParentLockingTest { + + private static VerticalLayout createTestComponent() { + VaadinSession session = new VaadinSession(null) { + private final ReentrantLock lock = new ReentrantLock(); + + @Override + public Lock getLockInstance() { + return lock; + } + }; + + session.getLockInstance().lock(); + + UI ui = new UI() { + @Override + protected void init(VaadinRequest request) { + } + }; + ui.setSession(session); + + VerticalLayout layout = new VerticalLayout(); + ui.setContent(layout); + + session.getLockInstance().unlock(); + return layout; + } + + @Test + public void attachNoSessionLocked() { + VerticalLayout testComponent = createTestComponent(); + + VerticalLayout target = new VerticalLayout(); + + try { + target.addComponent(testComponent); + throw new AssertionError( + "Moving component when not holding its sessions's lock should throw"); + } catch (IllegalStateException e) { + Assert.assertEquals( + "Cannot remove from parent when the session is not locked.", + e.getMessage()); + } + } + + @Test + public void attachSessionLocked() { + VerticalLayout testComponent = createTestComponent(); + + VerticalLayout target = new VerticalLayout(); + + testComponent.getUI().getSession().getLockInstance().lock(); + + target.addComponent(testComponent); + // OK if we get here without any exception + } + + @Test + public void crossAttachOtherSessionLocked() { + VerticalLayout notLockedComponent = createTestComponent(); + + VerticalLayout lockedComponent = createTestComponent(); + + // Simulate the situation when attaching cross sessions + lockedComponent.getUI().getSession().getLockInstance().lock(); + VaadinSession.setCurrent(lockedComponent.getUI().getSession()); + + try { + lockedComponent.addComponent(notLockedComponent); + throw new AssertionError( + "Moving component when not holding its sessions's lock should throw"); + } catch (IllegalStateException e) { + Assert.assertEquals( + "Cannot remove from parent when the session is not locked." + + " Furthermore, there is another locked session, indicating that the component might be about to be moved from one session to another.", + e.getMessage()); + } + } + + @Test + public void crossAttachThisSessionLocked() { + VerticalLayout notLockedComponent = createTestComponent(); + + VerticalLayout lockedComponent = createTestComponent(); + + // Simulate the situation when attaching cross sessions + lockedComponent.getUI().getSession().getLockInstance().lock(); + VaadinSession.setCurrent(lockedComponent.getUI().getSession()); + + try { + notLockedComponent.addComponent(lockedComponent); + } catch (AssertionError e) { + // All is fine, don't care about the exact wording in this case + } + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractsinglecomponentcontainer/SetParentAsContent.java b/server/tests/src/com/vaadin/tests/server/component/abstractsinglecomponentcontainer/SetParentAsContent.java deleted file mode 100644 index dae0e57d02..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstractsinglecomponentcontainer/SetParentAsContent.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.abstractsinglecomponentcontainer; - -import org.easymock.EasyMock; -import org.junit.Test; - -import com.vaadin.ui.AbstractSingleComponentContainer; -import com.vaadin.ui.Component; -import com.vaadin.ui.HasComponents; - -/** - * - * Tests for avoiding set parent as child for - * {@link AbstractSingleComponentContainer#setContent(Component)} - * - * @author Vaadin Ltd - */ -public class SetParentAsContent { - - @Test(expected = IllegalArgumentException.class) - public void testSetContent() { - AbstractSingleComponentContainer container = new AbstractSingleComponentContainer() { - }; - HasComponents hasComponentsMock = EasyMock - .createMock(HasComponents.class); - container.setParent(hasComponentsMock); - - container.setContent(hasComponentsMock); - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractsinglecomponentcontainer/SetParentAsContentTest.java b/server/tests/src/com/vaadin/tests/server/component/abstractsinglecomponentcontainer/SetParentAsContentTest.java new file mode 100644 index 0000000000..b84794d58a --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstractsinglecomponentcontainer/SetParentAsContentTest.java @@ -0,0 +1,45 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.abstractsinglecomponentcontainer; + +import org.easymock.EasyMock; +import org.junit.Test; + +import com.vaadin.ui.AbstractSingleComponentContainer; +import com.vaadin.ui.Component; +import com.vaadin.ui.HasComponents; + +/** + * + * Tests for avoiding set parent as child for + * {@link AbstractSingleComponentContainer#setContent(Component)} + * + * @author Vaadin Ltd + */ +public class SetParentAsContentTest { + + @Test(expected = IllegalArgumentException.class) + public void testSetContent() { + AbstractSingleComponentContainer container = new AbstractSingleComponentContainer() { + }; + HasComponents hasComponentsMock = EasyMock + .createMock(HasComponents.class); + container.setParent(hasComponentsMock); + + container.setContent(hasComponentsMock); + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractsinglecomponentcontainer/TestRemoveFromParentLocking.java b/server/tests/src/com/vaadin/tests/server/component/abstractsinglecomponentcontainer/TestRemoveFromParentLocking.java deleted file mode 100644 index fd4a1df766..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstractsinglecomponentcontainer/TestRemoveFromParentLocking.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.abstractsinglecomponentcontainer; - -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -import org.junit.Assert; -import org.junit.Test; - -import com.vaadin.server.VaadinRequest; -import com.vaadin.server.VaadinSession; -import com.vaadin.ui.UI; -import com.vaadin.ui.VerticalLayout; - -public class TestRemoveFromParentLocking { - - private static VerticalLayout createTestComponent() { - VaadinSession session = new VaadinSession(null) { - private final ReentrantLock lock = new ReentrantLock(); - - @Override - public Lock getLockInstance() { - return lock; - } - }; - - session.getLockInstance().lock(); - - UI ui = new UI() { - @Override - protected void init(VaadinRequest request) { - } - }; - ui.setSession(session); - - VerticalLayout layout = new VerticalLayout(); - ui.setContent(layout); - - session.getLockInstance().unlock(); - return layout; - } - - @Test - public void attachNoSessionLocked() { - VerticalLayout testComponent = createTestComponent(); - - VerticalLayout target = new VerticalLayout(); - - try { - target.addComponent(testComponent); - throw new AssertionError( - "Moving component when not holding its sessions's lock should throw"); - } catch (IllegalStateException e) { - Assert.assertEquals( - "Cannot remove from parent when the session is not locked.", - e.getMessage()); - } - } - - @Test - public void attachSessionLocked() { - VerticalLayout testComponent = createTestComponent(); - - VerticalLayout target = new VerticalLayout(); - - testComponent.getUI().getSession().getLockInstance().lock(); - - target.addComponent(testComponent); - // OK if we get here without any exception - } - - @Test - public void crossAttachOtherSessionLocked() { - VerticalLayout notLockedComponent = createTestComponent(); - - VerticalLayout lockedComponent = createTestComponent(); - - // Simulate the situation when attaching cross sessions - lockedComponent.getUI().getSession().getLockInstance().lock(); - VaadinSession.setCurrent(lockedComponent.getUI().getSession()); - - try { - lockedComponent.addComponent(notLockedComponent); - throw new AssertionError( - "Moving component when not holding its sessions's lock should throw"); - } catch (IllegalStateException e) { - Assert.assertEquals( - "Cannot remove from parent when the session is not locked." - + " Furthermore, there is another locked session, indicating that the component might be about to be moved from one session to another.", - e.getMessage()); - } - } - - @Test - public void crossAttachThisSessionLocked() { - VerticalLayout notLockedComponent = createTestComponent(); - - VerticalLayout lockedComponent = createTestComponent(); - - // Simulate the situation when attaching cross sessions - lockedComponent.getUI().getSession().getLockInstance().lock(); - VaadinSession.setCurrent(lockedComponent.getUI().getSession()); - - try { - notLockedComponent.addComponent(lockedComponent); - } catch (AssertionError e) { - // All is fine, don't care about the exact wording in this case - } - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractsplitpanel/AbstractSplitPanelListenersTest.java b/server/tests/src/com/vaadin/tests/server/component/abstractsplitpanel/AbstractSplitPanelListenersTest.java new file mode 100644 index 0000000000..5dd2f406bc --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstractsplitpanel/AbstractSplitPanelListenersTest.java @@ -0,0 +1,14 @@ +package com.vaadin.tests.server.component.abstractsplitpanel; + +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; +import com.vaadin.ui.AbstractSplitPanel.SplitterClickEvent; +import com.vaadin.ui.AbstractSplitPanel.SplitterClickListener; +import com.vaadin.ui.HorizontalSplitPanel; + +public class AbstractSplitPanelListenersTest extends + AbstractListenerMethodsTestBase { + public void testSplitterClickListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(HorizontalSplitPanel.class, + SplitterClickEvent.class, SplitterClickListener.class); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractsplitpanel/ReadDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/abstractsplitpanel/ReadDesignTest.java new file mode 100644 index 0000000000..f3a7e32e96 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstractsplitpanel/ReadDesignTest.java @@ -0,0 +1,158 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.abstractsplitpanel; + +import java.lang.reflect.Method; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Attributes; +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; + +import com.vaadin.server.Sizeable.Unit; +import com.vaadin.shared.ui.splitpanel.AbstractSplitPanelState.SplitterState; +import com.vaadin.ui.AbstractSplitPanel; +import com.vaadin.ui.HorizontalSplitPanel; +import com.vaadin.ui.Table; +import com.vaadin.ui.VerticalLayout; +import com.vaadin.ui.VerticalSplitPanel; +import com.vaadin.ui.declarative.DesignContext; + +/** + * Tests synchronizing the attributes and children of horizontal and vertical + * split panels from a design. + * + * @author Vaadin Ltd + */ +public class ReadDesignTest extends TestCase { + DesignContext ctx; + + @Override + protected void setUp() { + ctx = new DesignContext(); + } + + public void testAttributes() throws Exception { + // Create a design with non-default attributes values. + Element design = createDesign(true, false, true, true); + HorizontalSplitPanel sp = new HorizontalSplitPanel(); + sp.readDesign(design, ctx); + // Check that the attributes are correctly parsed. + assertEquals(20.5f, sp.getSplitPosition()); + assertEquals(Unit.PERCENTAGE, sp.getSplitPositionUnit()); + assertEquals(20f, sp.getMinSplitPosition()); + assertEquals(Unit.PERCENTAGE, sp.getMinSplitPositionUnit()); + assertEquals(50f, sp.getMaxSplitPosition()); + assertEquals(Unit.PIXELS, sp.getMaxSplitPositionUnit()); + assertEquals(true, sp.isLocked()); + checkReversed(sp, true); + } + + public void testWithNoChildren() { + Element design = createDesign(true, false, false, false); + HorizontalSplitPanel sp = new HorizontalSplitPanel(); + sp.readDesign(design, ctx); + assertEquals("Unexpected child count for the split panel.", 0, + sp.getComponentCount()); + } + + public void testWithFirstChild() { + Element design = createDesign(false, false, true, false); + VerticalSplitPanel sp = new VerticalSplitPanel(); + sp.readDesign(design, ctx); + assertEquals("Unexpected child count for the split panel.", 1, + sp.getComponentCount()); + Object obj = sp.getFirstComponent(); + assertEquals("Wrong component in split panel.", Table.class, + obj.getClass()); + } + + public void testWithSecondChild() { + Element design = createDesign(true, false, false, true); + HorizontalSplitPanel sp = new HorizontalSplitPanel(); + sp.readDesign(design, ctx); + assertEquals("Unexpected child count for the split panel.", 1, + sp.getComponentCount()); + Object obj = sp.getSecondComponent(); + assertEquals("Wrong component in split panel.", VerticalLayout.class, + obj.getClass()); + } + + public void testWithBothChildren() { + Element design = createDesign(false, false, true, true); + VerticalSplitPanel sp = new VerticalSplitPanel(); + sp.readDesign(design, ctx); + assertEquals("Unexpected child count for the split panel.", 2, + sp.getComponentCount()); + Object first = sp.getFirstComponent(); + Object second = sp.getSecondComponent(); + assertEquals("Wrong first component in split panel.", Table.class, + first.getClass()); + assertEquals("Wrong second component in split panel.", + VerticalLayout.class, second.getClass()); + } + + /* + * Creates an html tree node structure representing a split panel and its + * contents. The parameters are used for controlling whether the split panel + * is horizontal or vertical, whether attributes are set for the design and + * whether the split panel should have the first and the second child + * component. + */ + private Element createDesign(boolean horizontal, + boolean useDefaultAttributes, boolean hasFirstChild, + boolean hasSecondChild) { + Attributes attributes = new Attributes(); + if (!useDefaultAttributes) { + attributes.put("split-position", "20.5%"); + // The unitless number should correspond to 20% + attributes.put("min-split-position", "20"); + attributes.put("max-split-position", "50px"); + attributes.put("locked", ""); + attributes.put("reversed", ""); + } + String tagName = horizontal ? "v-horizontal-split-panel" + : "v-vertical-split-panel"; + Element element = new Element(Tag.valueOf(tagName), "", attributes); + // Create the children + if (hasFirstChild) { + Element child = new Element(Tag.valueOf("v-table"), ""); + element.appendChild(child); + } + if (hasSecondChild) { + Element child = new Element(Tag.valueOf("v-vertical-layout"), ""); + if (!hasFirstChild) { + child.attr(":second", ""); + } + element.appendChild(child); + } + return element; + } + + /* + * Checks the reversed property of a split panel. + */ + private void checkReversed(AbstractSplitPanel sp, boolean expected) + throws Exception { + Method getter = AbstractSplitPanel.class + .getDeclaredMethod("getSplitterState"); + getter.setAccessible(true); + SplitterState state = (SplitterState) getter.invoke(sp); + assertEquals("Wrong value for split panel property reversed.", + expected, state.positionReversed); + } +} \ No newline at end of file diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractsplitpanel/TestAbstractSplitPanelListeners.java b/server/tests/src/com/vaadin/tests/server/component/abstractsplitpanel/TestAbstractSplitPanelListeners.java deleted file mode 100644 index 2b6cdaa6cc..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstractsplitpanel/TestAbstractSplitPanelListeners.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.vaadin.tests.server.component.abstractsplitpanel; - -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; -import com.vaadin.ui.AbstractSplitPanel.SplitterClickEvent; -import com.vaadin.ui.AbstractSplitPanel.SplitterClickListener; -import com.vaadin.ui.HorizontalSplitPanel; - -public class TestAbstractSplitPanelListeners extends - AbstractListenerMethodsTest { - public void testSplitterClickListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(HorizontalSplitPanel.class, - SplitterClickEvent.class, SplitterClickListener.class); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractsplitpanel/TestReadDesign.java b/server/tests/src/com/vaadin/tests/server/component/abstractsplitpanel/TestReadDesign.java deleted file mode 100644 index db30f05c5f..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstractsplitpanel/TestReadDesign.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.abstractsplitpanel; - -import java.lang.reflect.Method; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Attributes; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; - -import com.vaadin.server.Sizeable.Unit; -import com.vaadin.shared.ui.splitpanel.AbstractSplitPanelState.SplitterState; -import com.vaadin.ui.AbstractSplitPanel; -import com.vaadin.ui.HorizontalSplitPanel; -import com.vaadin.ui.Table; -import com.vaadin.ui.VerticalLayout; -import com.vaadin.ui.VerticalSplitPanel; -import com.vaadin.ui.declarative.DesignContext; - -/** - * Tests synchronizing the attributes and children of horizontal and vertical - * split panels from a design. - * - * @author Vaadin Ltd - */ -public class TestReadDesign extends TestCase { - DesignContext ctx; - - @Override - protected void setUp() { - ctx = new DesignContext(); - } - - public void testAttributes() throws Exception { - // Create a design with non-default attributes values. - Element design = createDesign(true, false, true, true); - HorizontalSplitPanel sp = new HorizontalSplitPanel(); - sp.readDesign(design, ctx); - // Check that the attributes are correctly parsed. - assertEquals(20.5f, sp.getSplitPosition()); - assertEquals(Unit.PERCENTAGE, sp.getSplitPositionUnit()); - assertEquals(20f, sp.getMinSplitPosition()); - assertEquals(Unit.PERCENTAGE, sp.getMinSplitPositionUnit()); - assertEquals(50f, sp.getMaxSplitPosition()); - assertEquals(Unit.PIXELS, sp.getMaxSplitPositionUnit()); - assertEquals(true, sp.isLocked()); - checkReversed(sp, true); - } - - public void testWithNoChildren() { - Element design = createDesign(true, false, false, false); - HorizontalSplitPanel sp = new HorizontalSplitPanel(); - sp.readDesign(design, ctx); - assertEquals("Unexpected child count for the split panel.", 0, - sp.getComponentCount()); - } - - public void testWithFirstChild() { - Element design = createDesign(false, false, true, false); - VerticalSplitPanel sp = new VerticalSplitPanel(); - sp.readDesign(design, ctx); - assertEquals("Unexpected child count for the split panel.", 1, - sp.getComponentCount()); - Object obj = sp.getFirstComponent(); - assertEquals("Wrong component in split panel.", Table.class, - obj.getClass()); - } - - public void testWithSecondChild() { - Element design = createDesign(true, false, false, true); - HorizontalSplitPanel sp = new HorizontalSplitPanel(); - sp.readDesign(design, ctx); - assertEquals("Unexpected child count for the split panel.", 1, - sp.getComponentCount()); - Object obj = sp.getSecondComponent(); - assertEquals("Wrong component in split panel.", VerticalLayout.class, - obj.getClass()); - } - - public void testWithBothChildren() { - Element design = createDesign(false, false, true, true); - VerticalSplitPanel sp = new VerticalSplitPanel(); - sp.readDesign(design, ctx); - assertEquals("Unexpected child count for the split panel.", 2, - sp.getComponentCount()); - Object first = sp.getFirstComponent(); - Object second = sp.getSecondComponent(); - assertEquals("Wrong first component in split panel.", Table.class, - first.getClass()); - assertEquals("Wrong second component in split panel.", - VerticalLayout.class, second.getClass()); - } - - /* - * Creates an html tree node structure representing a split panel and its - * contents. The parameters are used for controlling whether the split panel - * is horizontal or vertical, whether attributes are set for the design and - * whether the split panel should have the first and the second child - * component. - */ - private Element createDesign(boolean horizontal, - boolean useDefaultAttributes, boolean hasFirstChild, - boolean hasSecondChild) { - Attributes attributes = new Attributes(); - if (!useDefaultAttributes) { - attributes.put("split-position", "20.5%"); - // The unitless number should correspond to 20% - attributes.put("min-split-position", "20"); - attributes.put("max-split-position", "50px"); - attributes.put("locked", ""); - attributes.put("reversed", ""); - } - String tagName = horizontal ? "v-horizontal-split-panel" - : "v-vertical-split-panel"; - Element element = new Element(Tag.valueOf(tagName), "", attributes); - // Create the children - if (hasFirstChild) { - Element child = new Element(Tag.valueOf("v-table"), ""); - element.appendChild(child); - } - if (hasSecondChild) { - Element child = new Element(Tag.valueOf("v-vertical-layout"), ""); - if (!hasFirstChild) { - child.attr(":second", ""); - } - element.appendChild(child); - } - return element; - } - - /* - * Checks the reversed property of a split panel. - */ - private void checkReversed(AbstractSplitPanel sp, boolean expected) - throws Exception { - Method getter = AbstractSplitPanel.class - .getDeclaredMethod("getSplitterState"); - getter.setAccessible(true); - SplitterState state = (SplitterState) getter.invoke(sp); - assertEquals("Wrong value for split panel property reversed.", - expected, state.positionReversed); - } -} \ No newline at end of file diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractsplitpanel/TestWriteDesign.java b/server/tests/src/com/vaadin/tests/server/component/abstractsplitpanel/TestWriteDesign.java deleted file mode 100644 index 649498c20b..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstractsplitpanel/TestWriteDesign.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.abstractsplitpanel; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Element; - -import com.vaadin.server.Sizeable.Unit; -import com.vaadin.ui.Button; -import com.vaadin.ui.HorizontalSplitPanel; -import com.vaadin.ui.Label; -import com.vaadin.ui.VerticalSplitPanel; -import com.vaadin.ui.declarative.DesignContext; - -/** - * Tests synchronizing the properties and child components of split panels to a - * design. - * - * @author Vaadin Ltd - */ -public class TestWriteDesign extends TestCase { - private DesignContext ctx; - - @Override - public void setUp() { - ctx = new DesignContext(); - } - - public void testHorizontalWithDefaultValues() { - // no attributes or child elements should appear - HorizontalSplitPanel sp = new HorizontalSplitPanel(); - Element e = ctx.createElement(sp); - assertEquals("Wrong tag name.", "v-horizontal-split-panel", - e.nodeName()); - assertEquals("The split panel should not have attributes.", 0, e - .attributes().size()); - assertEquals("The split panel should not have children.", 0, e - .children().size()); - } - - public void testVerticalWithAttributes() { - // All defined attributes should be output in the tree node. No child - // components are present in this test. - VerticalSplitPanel sp = new VerticalSplitPanel(); - sp.setSplitPosition(27f, Unit.PIXELS, true); - sp.setMinSplitPosition(5.5f, Unit.PERCENTAGE); - sp.setMaxSplitPosition(95, Unit.PERCENTAGE); - sp.setLocked(true); - Element e = ctx.createElement(sp); - assertEquals("Wrong tag name.", "v-vertical-split-panel", e.nodeName()); - assertEquals("Unexpected number of attributes.", 5, e.attributes() - .size()); - assertEquals("Wrong split position.", "27px", e.attr("split-position")); - assertEquals("Wrong minimum split position.", "5.5%", - e.attr("min-split-position")); - assertEquals("Wrong maximum split position.", "95%", - e.attr("max-split-position")); - assertTrue("Unexpected value for locked: " + e.attr("locked"), - "true".equals(e.attr("locked")) || "".equals(e.attr("locked"))); - assertTrue( - "Unexpected value for reversed: " + e.attr("reversed"), - "true".equals(e.attr("reversed")) - || "".equals(e.attr("reversed"))); - } - - public void testHorizontalWithFirstChild() { - // The split panel contains only the first child. - HorizontalSplitPanel sp = new HorizontalSplitPanel(); - sp.setSplitPosition(25f); - sp.setFirstComponent(new Button("First slot")); - Element e = ctx.createElement(sp); - assertEquals("Wrong split position.", "25%", e.attr("split-position")); - assertEquals("Wrong number of child elements.", 1, e.children().size()); - Element eb = e.children().get(0); - assertEquals("Wrong tag name of first child element.", "v-button", - eb.nodeName()); - assertEquals("Wrong text in the button element.", "First slot", - eb.html()); - } - - public void testVerticalWithSecondChild() { - // The split panel contains only the second child. - VerticalSplitPanel sp = new VerticalSplitPanel(); - sp.setMinSplitPosition(25f, Unit.PIXELS); - sp.setSecondComponent(new Label("Second slot")); - Element e = ctx.createElement(sp); - assertEquals("Wrong minimum split position.", "25px", - e.attr("min-split-position")); - assertEquals("Wrong number of child elements.", 1, e.children().size()); - Element el = e.children().get(0); - assertEquals("Wrong tag name of child element.", "v-label", - el.nodeName()); - assertEquals("Wrong text in the label element.", "Second slot", - el.html()); - assertTrue("Missing attribute :second in the label element.", - el.hasAttr(":second")); - } - - public void testVerticalWithBothChildren() { - // The split panel has both child components. - VerticalSplitPanel sp = new VerticalSplitPanel(); - sp.setFirstComponent(new Button("First slot")); - sp.setSecondComponent(new Label("Second slot")); - Element e = ctx.createElement(sp); - assertEquals("Wrong number of child elements.", 2, e.children().size()); - Element eb = e.children().get(0); - assertEquals("Wrong tag name of first child element.", "v-button", - eb.nodeName()); - assertEquals("Wrong text in the button element.", "First slot", - eb.html()); - Element el = e.children().get(1); - assertEquals("Wrong tag name of second child element.", "v-label", - el.nodeName()); - assertEquals("Wrong text in the label element.", "Second slot", - el.html()); - assertFalse( - "There should be no :second attribute when a split panel has both children.", - el.hasAttr(":second")); - } - - public void testReSynchronize() { - // Test that old children and attributes are removed when an element is - // synchronized to a new component. - VerticalSplitPanel sp = new VerticalSplitPanel(); - sp.setMinSplitPosition(5.5f, Unit.PERCENTAGE); - sp.setMaxSplitPosition(95, Unit.PERCENTAGE); - sp.setFirstComponent(new Button("First slot")); - sp.setSecondComponent(new Label("Second slot")); - Element e = ctx.createElement(sp); - sp = new VerticalSplitPanel(); - sp.writeDesign(e, ctx); - assertTrue("There should be no attributes in the node.", e.attributes() - .size() == 0); - assertTrue("There should be no child elements.", - e.children().size() == 0); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstractsplitpanel/WriteDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/abstractsplitpanel/WriteDesignTest.java new file mode 100644 index 0000000000..a75fe911f8 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstractsplitpanel/WriteDesignTest.java @@ -0,0 +1,151 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.abstractsplitpanel; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Element; + +import com.vaadin.server.Sizeable.Unit; +import com.vaadin.ui.Button; +import com.vaadin.ui.HorizontalSplitPanel; +import com.vaadin.ui.Label; +import com.vaadin.ui.VerticalSplitPanel; +import com.vaadin.ui.declarative.DesignContext; + +/** + * Tests synchronizing the properties and child components of split panels to a + * design. + * + * @author Vaadin Ltd + */ +public class WriteDesignTest extends TestCase { + private DesignContext ctx; + + @Override + public void setUp() { + ctx = new DesignContext(); + } + + public void testHorizontalWithDefaultValues() { + // no attributes or child elements should appear + HorizontalSplitPanel sp = new HorizontalSplitPanel(); + Element e = ctx.createElement(sp); + assertEquals("Wrong tag name.", "v-horizontal-split-panel", + e.nodeName()); + assertEquals("The split panel should not have attributes.", 0, e + .attributes().size()); + assertEquals("The split panel should not have children.", 0, e + .children().size()); + } + + public void testVerticalWithAttributes() { + // All defined attributes should be output in the tree node. No child + // components are present in this test. + VerticalSplitPanel sp = new VerticalSplitPanel(); + sp.setSplitPosition(27f, Unit.PIXELS, true); + sp.setMinSplitPosition(5.5f, Unit.PERCENTAGE); + sp.setMaxSplitPosition(95, Unit.PERCENTAGE); + sp.setLocked(true); + Element e = ctx.createElement(sp); + assertEquals("Wrong tag name.", "v-vertical-split-panel", e.nodeName()); + assertEquals("Unexpected number of attributes.", 5, e.attributes() + .size()); + assertEquals("Wrong split position.", "27px", e.attr("split-position")); + assertEquals("Wrong minimum split position.", "5.5%", + e.attr("min-split-position")); + assertEquals("Wrong maximum split position.", "95%", + e.attr("max-split-position")); + assertTrue("Unexpected value for locked: " + e.attr("locked"), + "true".equals(e.attr("locked")) || "".equals(e.attr("locked"))); + assertTrue( + "Unexpected value for reversed: " + e.attr("reversed"), + "true".equals(e.attr("reversed")) + || "".equals(e.attr("reversed"))); + } + + public void testHorizontalWithFirstChild() { + // The split panel contains only the first child. + HorizontalSplitPanel sp = new HorizontalSplitPanel(); + sp.setSplitPosition(25f); + sp.setFirstComponent(new Button("First slot")); + Element e = ctx.createElement(sp); + assertEquals("Wrong split position.", "25%", e.attr("split-position")); + assertEquals("Wrong number of child elements.", 1, e.children().size()); + Element eb = e.children().get(0); + assertEquals("Wrong tag name of first child element.", "v-button", + eb.nodeName()); + assertEquals("Wrong text in the button element.", "First slot", + eb.html()); + } + + public void testVerticalWithSecondChild() { + // The split panel contains only the second child. + VerticalSplitPanel sp = new VerticalSplitPanel(); + sp.setMinSplitPosition(25f, Unit.PIXELS); + sp.setSecondComponent(new Label("Second slot")); + Element e = ctx.createElement(sp); + assertEquals("Wrong minimum split position.", "25px", + e.attr("min-split-position")); + assertEquals("Wrong number of child elements.", 1, e.children().size()); + Element el = e.children().get(0); + assertEquals("Wrong tag name of child element.", "v-label", + el.nodeName()); + assertEquals("Wrong text in the label element.", "Second slot", + el.html()); + assertTrue("Missing attribute :second in the label element.", + el.hasAttr(":second")); + } + + public void testVerticalWithBothChildren() { + // The split panel has both child components. + VerticalSplitPanel sp = new VerticalSplitPanel(); + sp.setFirstComponent(new Button("First slot")); + sp.setSecondComponent(new Label("Second slot")); + Element e = ctx.createElement(sp); + assertEquals("Wrong number of child elements.", 2, e.children().size()); + Element eb = e.children().get(0); + assertEquals("Wrong tag name of first child element.", "v-button", + eb.nodeName()); + assertEquals("Wrong text in the button element.", "First slot", + eb.html()); + Element el = e.children().get(1); + assertEquals("Wrong tag name of second child element.", "v-label", + el.nodeName()); + assertEquals("Wrong text in the label element.", "Second slot", + el.html()); + assertFalse( + "There should be no :second attribute when a split panel has both children.", + el.hasAttr(":second")); + } + + public void testReSynchronize() { + // Test that old children and attributes are removed when an element is + // synchronized to a new component. + VerticalSplitPanel sp = new VerticalSplitPanel(); + sp.setMinSplitPosition(5.5f, Unit.PERCENTAGE); + sp.setMaxSplitPosition(95, Unit.PERCENTAGE); + sp.setFirstComponent(new Button("First slot")); + sp.setSecondComponent(new Label("Second slot")); + Element e = ctx.createElement(sp); + sp = new VerticalSplitPanel(); + sp.writeDesign(e, ctx); + assertTrue("There should be no attributes in the node.", e.attributes() + .size() == 0); + assertTrue("There should be no child elements.", + e.children().size() == 0); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstracttextfield/AbstractTextFieldListenersTest.java b/server/tests/src/com/vaadin/tests/server/component/abstracttextfield/AbstractTextFieldListenersTest.java new file mode 100644 index 0000000000..1b7f4fdce1 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstracttextfield/AbstractTextFieldListenersTest.java @@ -0,0 +1,27 @@ +package com.vaadin.tests.server.component.abstracttextfield; + +import com.vaadin.event.FieldEvents.BlurEvent; +import com.vaadin.event.FieldEvents.BlurListener; +import com.vaadin.event.FieldEvents.FocusEvent; +import com.vaadin.event.FieldEvents.FocusListener; +import com.vaadin.event.FieldEvents.TextChangeEvent; +import com.vaadin.event.FieldEvents.TextChangeListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; +import com.vaadin.ui.TextField; + +public class AbstractTextFieldListenersTest extends AbstractListenerMethodsTestBase { + public void testTextChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(TextField.class, TextChangeEvent.class, + TextChangeListener.class); + } + + public void testFocusListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(TextField.class, FocusEvent.class, + FocusListener.class); + } + + public void testBlurListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(TextField.class, BlurEvent.class, + BlurListener.class); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstracttextfield/ReadDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/abstracttextfield/ReadDesignTest.java new file mode 100644 index 0000000000..2645ce4255 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstracttextfield/ReadDesignTest.java @@ -0,0 +1,73 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.abstracttextfield; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Attributes; +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; + +import com.vaadin.ui.AbstractTextField; +import com.vaadin.ui.AbstractTextField.TextChangeEventMode; +import com.vaadin.ui.TextField; +import com.vaadin.ui.declarative.DesignContext; + +/** + * Test case for reading the attributes of the AbstractTextField from design + */ +public class ReadDesignTest extends TestCase { + + private DesignContext ctx; + + @Override + protected void setUp() throws Exception { + super.setUp(); + ctx = new DesignContext(); + } + + public void testAttributes() { + Element design = createDesign(); + AbstractTextField component = getComponent(); + component.readDesign(design, ctx); + assertEquals("this-is-null", component.getNullRepresentation()); + assertEquals(true, component.isNullSettingAllowed()); + assertEquals(5, component.getMaxLength()); + assertEquals(3, component.getColumns()); + assertEquals("input", component.getInputPrompt()); + assertEquals(TextChangeEventMode.EAGER, + component.getTextChangeEventMode()); + assertEquals(100, component.getTextChangeTimeout()); + } + + private AbstractTextField getComponent() { + return new TextField(); + } + + private Element createDesign() { + Attributes attributes = new Attributes(); + attributes.put("null-representation", "this-is-null"); + attributes.put("null-setting-allowed", "true"); + attributes.put("maxlength", "5"); + attributes.put("columns", "3"); + attributes.put("input-prompt", "input"); + attributes.put("text-change-event-mode", "eager"); + attributes.put("text-change-timeout", "100"); + Element node = new Element(Tag.valueOf("v-text-field"), "", attributes); + return node; + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstracttextfield/TestAbstractTextFieldListeners.java b/server/tests/src/com/vaadin/tests/server/component/abstracttextfield/TestAbstractTextFieldListeners.java deleted file mode 100644 index 9868d6ebfd..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstracttextfield/TestAbstractTextFieldListeners.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.vaadin.tests.server.component.abstracttextfield; - -import com.vaadin.event.FieldEvents.BlurEvent; -import com.vaadin.event.FieldEvents.BlurListener; -import com.vaadin.event.FieldEvents.FocusEvent; -import com.vaadin.event.FieldEvents.FocusListener; -import com.vaadin.event.FieldEvents.TextChangeEvent; -import com.vaadin.event.FieldEvents.TextChangeListener; -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; -import com.vaadin.ui.TextField; - -public class TestAbstractTextFieldListeners extends AbstractListenerMethodsTest { - public void testTextChangeListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(TextField.class, TextChangeEvent.class, - TextChangeListener.class); - } - - public void testFocusListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(TextField.class, FocusEvent.class, - FocusListener.class); - } - - public void testBlurListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(TextField.class, BlurEvent.class, - BlurListener.class); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstracttextfield/TestReadDesign.java b/server/tests/src/com/vaadin/tests/server/component/abstracttextfield/TestReadDesign.java deleted file mode 100644 index 3b4b6f1f03..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstracttextfield/TestReadDesign.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.abstracttextfield; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Attributes; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; - -import com.vaadin.ui.AbstractTextField; -import com.vaadin.ui.AbstractTextField.TextChangeEventMode; -import com.vaadin.ui.TextField; -import com.vaadin.ui.declarative.DesignContext; - -/** - * Test case for reading the attributes of the AbstractTextField from design - */ -public class TestReadDesign extends TestCase { - - private DesignContext ctx; - - @Override - protected void setUp() throws Exception { - super.setUp(); - ctx = new DesignContext(); - } - - public void testAttributes() { - Element design = createDesign(); - AbstractTextField component = getComponent(); - component.readDesign(design, ctx); - assertEquals("this-is-null", component.getNullRepresentation()); - assertEquals(true, component.isNullSettingAllowed()); - assertEquals(5, component.getMaxLength()); - assertEquals(3, component.getColumns()); - assertEquals("input", component.getInputPrompt()); - assertEquals(TextChangeEventMode.EAGER, - component.getTextChangeEventMode()); - assertEquals(100, component.getTextChangeTimeout()); - } - - private AbstractTextField getComponent() { - return new TextField(); - } - - private Element createDesign() { - Attributes attributes = new Attributes(); - attributes.put("null-representation", "this-is-null"); - attributes.put("null-setting-allowed", "true"); - attributes.put("maxlength", "5"); - attributes.put("columns", "3"); - attributes.put("input-prompt", "input"); - attributes.put("text-change-event-mode", "eager"); - attributes.put("text-change-timeout", "100"); - Element node = new Element(Tag.valueOf("v-text-field"), "", attributes); - return node; - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstracttextfield/TestWriteDesign.java b/server/tests/src/com/vaadin/tests/server/component/abstracttextfield/TestWriteDesign.java deleted file mode 100644 index be5c384d3b..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/abstracttextfield/TestWriteDesign.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.abstracttextfield; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Attributes; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; - -import com.vaadin.ui.AbstractTextField; -import com.vaadin.ui.AbstractTextField.TextChangeEventMode; -import com.vaadin.ui.TextField; -import com.vaadin.ui.declarative.DesignContext; - -/** - * Test case for writing the attributes of the AbstractTextField to design - * - * @author Vaadin Ltd - */ -public class TestWriteDesign extends TestCase { - - private DesignContext ctx; - - @Override - protected void setUp() throws Exception { - super.setUp(); - ctx = new DesignContext(); - } - - public void testSynchronizetestAttributes() { - Element design = createDesign(); - AbstractTextField component = getComponent(); - component.setNullRepresentation("this-is-null"); - component.setNullSettingAllowed(true); - component.setMaxLength(5); - component.setColumns(3); - component.setInputPrompt("input"); - component.setTextChangeEventMode(TextChangeEventMode.EAGER); - component.setTextChangeTimeout(100); - component.writeDesign(design, ctx); - assertEquals("this-is-null", design.attr("null-representation")); - assertEquals("true", design.attr("null-setting-allowed")); - assertEquals("5", design.attr("maxlength")); - assertEquals("3", design.attr("columns")); - assertEquals("input", design.attr("input-prompt")); - assertEquals("EAGER", design.attr("text-change-event-mode")); - assertEquals("100", design.attr("text-change-timeout")); - } - - private AbstractTextField getComponent() { - return new TextField(); - } - - private Element createDesign() { - Attributes attr = new Attributes(); - return new Element(Tag.valueOf("v-text-field"), "", attr); - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/component/abstracttextfield/WriteDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/abstracttextfield/WriteDesignTest.java new file mode 100644 index 0000000000..9b1129ce14 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/abstracttextfield/WriteDesignTest.java @@ -0,0 +1,73 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.abstracttextfield; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Attributes; +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; + +import com.vaadin.ui.AbstractTextField; +import com.vaadin.ui.AbstractTextField.TextChangeEventMode; +import com.vaadin.ui.TextField; +import com.vaadin.ui.declarative.DesignContext; + +/** + * Test case for writing the attributes of the AbstractTextField to design + * + * @author Vaadin Ltd + */ +public class WriteDesignTest extends TestCase { + + private DesignContext ctx; + + @Override + protected void setUp() throws Exception { + super.setUp(); + ctx = new DesignContext(); + } + + public void testSynchronizetestAttributes() { + Element design = createDesign(); + AbstractTextField component = getComponent(); + component.setNullRepresentation("this-is-null"); + component.setNullSettingAllowed(true); + component.setMaxLength(5); + component.setColumns(3); + component.setInputPrompt("input"); + component.setTextChangeEventMode(TextChangeEventMode.EAGER); + component.setTextChangeTimeout(100); + component.writeDesign(design, ctx); + assertEquals("this-is-null", design.attr("null-representation")); + assertEquals("true", design.attr("null-setting-allowed")); + assertEquals("5", design.attr("maxlength")); + assertEquals("3", design.attr("columns")); + assertEquals("input", design.attr("input-prompt")); + assertEquals("EAGER", design.attr("text-change-event-mode")); + assertEquals("100", design.attr("text-change-timeout")); + } + + private AbstractTextField getComponent() { + return new TextField(); + } + + private Element createDesign() { + Attributes attr = new Attributes(); + return new Element(Tag.valueOf("v-text-field"), "", attr); + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/component/button/ButtonClick.java b/server/tests/src/com/vaadin/tests/server/component/button/ButtonClick.java deleted file mode 100644 index 3d5fe77f8e..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/button/ButtonClick.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.vaadin.tests.server.component.button; - -import org.junit.Assert; -import org.junit.Test; - -import com.vaadin.data.util.ObjectProperty; -import com.vaadin.server.VaadinRequest; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.Button.ClickListener; -import com.vaadin.ui.UI; - -/** - * Tests the public click() method. - */ -public class ButtonClick { - private boolean clicked = false; - - @Test - public void clickDetachedButton() { - Button b = new Button(); - final ObjectProperty counter = new ObjectProperty(0); - b.addClickListener(new ClickListener() { - - @Override - public void buttonClick(ClickEvent event) { - counter.setValue(counter.getValue() + 1); - } - }); - - b.click(); - Assert.assertEquals(Integer.valueOf(1), counter.getValue()); - } - - @Test - public void testClick() { - getButton().click(); - Assert.assertTrue("Button doesn't fire clicks", clicked); - } - - @Test - public void testClickDisabled() { - Button b = getButton(); - b.setEnabled(false); - b.click(); - Assert.assertFalse("Disabled button fires click events", clicked); - } - - @Test - public void testClickReadOnly() { - Button b = getButton(); - b.setReadOnly(true); - b.click(); - Assert.assertFalse("Read only button fires click events", clicked); - } - - private Button getButton() { - Button b = new Button(); - UI ui = createUI(); - b.setParent(ui); - addClickListener(b); - return b; - } - - private UI createUI() { - UI ui = new UI() { - - @Override - protected void init(VaadinRequest request) { - } - }; - return ui; - } - - private void addClickListener(Button b) { - clicked = false; - b.addClickListener(new Button.ClickListener() { - @Override - public void buttonClick(ClickEvent ev) { - clicked = true; - } - }); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/button/ButtonClickTest.java b/server/tests/src/com/vaadin/tests/server/component/button/ButtonClickTest.java new file mode 100644 index 0000000000..6283ccf6af --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/button/ButtonClickTest.java @@ -0,0 +1,84 @@ +package com.vaadin.tests.server.component.button; + +import org.junit.Assert; +import org.junit.Test; + +import com.vaadin.data.util.ObjectProperty; +import com.vaadin.server.VaadinRequest; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.Button.ClickListener; +import com.vaadin.ui.UI; + +/** + * Tests the public click() method. + */ +public class ButtonClickTest { + private boolean clicked = false; + + @Test + public void clickDetachedButton() { + Button b = new Button(); + final ObjectProperty counter = new ObjectProperty(0); + b.addClickListener(new ClickListener() { + + @Override + public void buttonClick(ClickEvent event) { + counter.setValue(counter.getValue() + 1); + } + }); + + b.click(); + Assert.assertEquals(Integer.valueOf(1), counter.getValue()); + } + + @Test + public void testClick() { + getButton().click(); + Assert.assertTrue("Button doesn't fire clicks", clicked); + } + + @Test + public void testClickDisabled() { + Button b = getButton(); + b.setEnabled(false); + b.click(); + Assert.assertFalse("Disabled button fires click events", clicked); + } + + @Test + public void testClickReadOnly() { + Button b = getButton(); + b.setReadOnly(true); + b.click(); + Assert.assertFalse("Read only button fires click events", clicked); + } + + private Button getButton() { + Button b = new Button(); + UI ui = createUI(); + b.setParent(ui); + addClickListener(b); + return b; + } + + private UI createUI() { + UI ui = new UI() { + + @Override + protected void init(VaadinRequest request) { + } + }; + return ui; + } + + private void addClickListener(Button b) { + clicked = false; + b.addClickListener(new Button.ClickListener() { + @Override + public void buttonClick(ClickEvent ev) { + clicked = true; + } + }); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/button/ButtonListeners.java b/server/tests/src/com/vaadin/tests/server/component/button/ButtonListeners.java deleted file mode 100644 index dc37312eea..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/button/ButtonListeners.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.vaadin.tests.server.component.button; - -import com.vaadin.event.FieldEvents.BlurEvent; -import com.vaadin.event.FieldEvents.BlurListener; -import com.vaadin.event.FieldEvents.FocusEvent; -import com.vaadin.event.FieldEvents.FocusListener; -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickEvent; -import com.vaadin.ui.Button.ClickListener; - -public class ButtonListeners extends AbstractListenerMethodsTest { - public void testFocusListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(Button.class, FocusEvent.class, - FocusListener.class); - } - - public void testBlurListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(Button.class, BlurEvent.class, - BlurListener.class); - } - - public void testClickListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(Button.class, ClickEvent.class, - ClickListener.class); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/button/ButtonListenersTest.java b/server/tests/src/com/vaadin/tests/server/component/button/ButtonListenersTest.java new file mode 100644 index 0000000000..4478048b12 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/button/ButtonListenersTest.java @@ -0,0 +1,27 @@ +package com.vaadin.tests.server.component.button; + +import com.vaadin.event.FieldEvents.BlurEvent; +import com.vaadin.event.FieldEvents.BlurListener; +import com.vaadin.event.FieldEvents.FocusEvent; +import com.vaadin.event.FieldEvents.FocusListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.Button.ClickListener; + +public class ButtonListenersTest extends AbstractListenerMethodsTestBase { + public void testFocusListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Button.class, FocusEvent.class, + FocusListener.class); + } + + public void testBlurListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Button.class, BlurEvent.class, + BlurListener.class); + } + + public void testClickListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Button.class, ClickEvent.class, + ClickListener.class); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/button/ReadDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/button/ReadDesignTest.java new file mode 100644 index 0000000000..0e503b54b8 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/button/ReadDesignTest.java @@ -0,0 +1,129 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.button; + +import java.lang.reflect.Field; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Attributes; +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; +import org.junit.Test; + +import com.vaadin.event.ShortcutAction.KeyCode; +import com.vaadin.event.ShortcutAction.ModifierKey; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickShortcut; +import com.vaadin.ui.NativeButton; +import com.vaadin.ui.declarative.DesignContext; + +/** + * + * Test cases for reading the contents of a Button and a NativeButton from a + * design. + * + */ +public class ReadDesignTest extends TestCase { + + private DesignContext ctx; + + @Override + protected void setUp() throws Exception { + super.setUp(); + ctx = new DesignContext(); + } + + @Test + public void testWithContent() { + createAndTestButtons("Click", null); + } + + @Test + public void testWithHtmlCaption() { + createAndTestButtons("Click me", null); + } + + @Test + public void testWithContentAndCaption() { + createAndTestButtons("Click me", "caption"); + } + + @Test + public void testWithCaption() { + createAndTestButtons(null, "Click me"); + } + + @Test + public void testAttributes() throws IllegalArgumentException, + SecurityException, IllegalAccessException, NoSuchFieldException { + Attributes attributes = new Attributes(); + attributes.put("tabindex", "3"); + attributes.put("plain-text", ""); + attributes.put("icon-alt", "OK"); + attributes.put("click-shortcut", "ctrl-shift-o"); + Button button = (Button) ctx + .readDesign(createButtonWithAttributes(attributes)); + assertEquals(3, button.getTabIndex()); + assertEquals(false, button.isHtmlContentAllowed()); + assertEquals("OK", button.getIconAlternateText()); + Field field = Button.class.getDeclaredField("clickShortcut"); + field.setAccessible(true); + ClickShortcut value = (ClickShortcut) field.get(button); + assertEquals(KeyCode.O, value.getKeyCode()); + assertEquals(ModifierKey.CTRL, value.getModifiers()[0]); + assertEquals(ModifierKey.SHIFT, value.getModifiers()[1]); + } + + /* + * Test both Button and NativeButton. Caption should always be ignored. If + * content is null, the created button should have empty content. + */ + private void createAndTestButtons(String content, String caption) { + Element e1 = createElement("v-button", content, caption); + Button b1 = (Button) ctx.readDesign(e1); + Element e2 = createElement("v-native-button", content, caption); + NativeButton b2 = (NativeButton) ctx.readDesign(e2); + if (content != null) { + assertEquals("The button has the wrong text content.", content, + b1.getCaption()); + assertEquals("The button has the wrong text content.", content, + b2.getCaption()); + } else { + assertTrue("The button has the wrong content.", + b1.getCaption() == null || "".equals(b1.getCaption())); + assertTrue("The button has the wrong content.", + b2.getCaption() == null || "".equals(b2.getCaption())); + } + } + + private Element createButtonWithAttributes(Attributes attributes) { + return new Element(Tag.valueOf("v-button"), "", attributes); + } + + private Element createElement(String elementName, String content, + String caption) { + Attributes attributes = new Attributes(); + if (caption != null) { + attributes.put("caption", caption); + } + Element node = new Element(Tag.valueOf(elementName), "", attributes); + if (content != null) { + node.html(content); + } + return node; + } +} \ No newline at end of file diff --git a/server/tests/src/com/vaadin/tests/server/component/button/TestReadDesign.java b/server/tests/src/com/vaadin/tests/server/component/button/TestReadDesign.java deleted file mode 100644 index e194232742..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/button/TestReadDesign.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.button; - -import java.lang.reflect.Field; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Attributes; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; -import org.junit.Test; - -import com.vaadin.event.ShortcutAction.KeyCode; -import com.vaadin.event.ShortcutAction.ModifierKey; -import com.vaadin.ui.Button; -import com.vaadin.ui.Button.ClickShortcut; -import com.vaadin.ui.NativeButton; -import com.vaadin.ui.declarative.DesignContext; - -/** - * - * Test cases for reading the contents of a Button and a NativeButton from a - * design. - * - */ -public class TestReadDesign extends TestCase { - - private DesignContext ctx; - - @Override - protected void setUp() throws Exception { - super.setUp(); - ctx = new DesignContext(); - } - - @Test - public void testWithContent() { - createAndTestButtons("Click", null); - } - - @Test - public void testWithHtmlCaption() { - createAndTestButtons("Click me", null); - } - - @Test - public void testWithContentAndCaption() { - createAndTestButtons("Click me", "caption"); - } - - @Test - public void testWithCaption() { - createAndTestButtons(null, "Click me"); - } - - @Test - public void testAttributes() throws IllegalArgumentException, - SecurityException, IllegalAccessException, NoSuchFieldException { - Attributes attributes = new Attributes(); - attributes.put("tabindex", "3"); - attributes.put("plain-text", ""); - attributes.put("icon-alt", "OK"); - attributes.put("click-shortcut", "ctrl-shift-o"); - Button button = (Button) ctx - .readDesign(createButtonWithAttributes(attributes)); - assertEquals(3, button.getTabIndex()); - assertEquals(false, button.isHtmlContentAllowed()); - assertEquals("OK", button.getIconAlternateText()); - Field field = Button.class.getDeclaredField("clickShortcut"); - field.setAccessible(true); - ClickShortcut value = (ClickShortcut) field.get(button); - assertEquals(KeyCode.O, value.getKeyCode()); - assertEquals(ModifierKey.CTRL, value.getModifiers()[0]); - assertEquals(ModifierKey.SHIFT, value.getModifiers()[1]); - } - - /* - * Test both Button and NativeButton. Caption should always be ignored. If - * content is null, the created button should have empty content. - */ - private void createAndTestButtons(String content, String caption) { - Element e1 = createElement("v-button", content, caption); - Button b1 = (Button) ctx.readDesign(e1); - Element e2 = createElement("v-native-button", content, caption); - NativeButton b2 = (NativeButton) ctx.readDesign(e2); - if (content != null) { - assertEquals("The button has the wrong text content.", content, - b1.getCaption()); - assertEquals("The button has the wrong text content.", content, - b2.getCaption()); - } else { - assertTrue("The button has the wrong content.", - b1.getCaption() == null || "".equals(b1.getCaption())); - assertTrue("The button has the wrong content.", - b2.getCaption() == null || "".equals(b2.getCaption())); - } - } - - private Element createButtonWithAttributes(Attributes attributes) { - return new Element(Tag.valueOf("v-button"), "", attributes); - } - - private Element createElement(String elementName, String content, - String caption) { - Attributes attributes = new Attributes(); - if (caption != null) { - attributes.put("caption", caption); - } - Element node = new Element(Tag.valueOf(elementName), "", attributes); - if (content != null) { - node.html(content); - } - return node; - } -} \ No newline at end of file diff --git a/server/tests/src/com/vaadin/tests/server/component/button/TestWriteDesign.java b/server/tests/src/com/vaadin/tests/server/component/button/TestWriteDesign.java deleted file mode 100644 index dff80769f4..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/button/TestWriteDesign.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.button; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Attributes; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; -import org.junit.Test; - -import com.vaadin.event.ShortcutAction.KeyCode; -import com.vaadin.event.ShortcutAction.ModifierKey; -import com.vaadin.ui.Button; -import com.vaadin.ui.NativeButton; -import com.vaadin.ui.declarative.DesignContext; - -/** - * Tests generating html tree nodes corresponding to the contents of a Button - * and a NativeButton. - */ -public class TestWriteDesign extends TestCase { - - private DesignContext ctx; - - @Override - protected void setUp() throws Exception { - super.setUp(); - ctx = new DesignContext(); - } - - @Test - public void testWithTextContent() { - createAndTestButtons("Click me"); - } - - @Test - public void testWithHtmlContent() { - createAndTestButtons("Click"); - } - - @Test - public void testAttributes() { - Button button = new Button(); - button.setTabIndex(3); - button.setIconAlternateText("OK"); - button.setClickShortcut(KeyCode.O, ModifierKey.CTRL, ModifierKey.SHIFT); - Element e = new Element(Tag.valueOf("v-button"), "", new Attributes()); - button.writeDesign(e, ctx); - assertEquals("3", e.attr("tabindex")); - assertTrue("Button is plain text by default", e.hasAttr("plain-text")); - assertEquals("OK", e.attr("icon-alt")); - assertEquals("ctrl-shift-o", e.attr("click-shortcut")); - } - - @Test - public void testUpdateContentMode() { - Button button = new Button("OK"); - Element e = new Element(Tag.valueOf("v-button"), "", new Attributes()); - button.writeDesign(e, ctx); - assertTrue("Button is plain text by default", e.hasAttr("plain-text")); - - button.setHtmlContentAllowed(true); - button.writeDesign(e, ctx); - assertTrue("Button is updated to HTML", !e.hasAttr("plain-text")); - - } - - private void createAndTestButtons(String content) { - Button b1 = new Button(content); - // we need to set this on, since the plain-text attribute will appear - // otherwise - b1.setHtmlContentAllowed(true); - Element e1 = ctx.createElement(b1); - assertEquals("Wrong tag name for button.", "v-button", e1.tagName()); - assertEquals("Unexpected content in the v-button element.", content, - e1.html()); - assertTrue("The v-button element should not have attributes.", e1 - .attributes().size() == 0); - NativeButton b2 = new NativeButton(content); - b2.setHtmlContentAllowed(true); - Element e2 = ctx.createElement(b2); - assertEquals("Wrong tag name for button.", "v-native-button", - e2.tagName()); - assertEquals("Unexpected content in the v-button element.", content, - e2.html()); - assertTrue("The v-button element should not have attributes.", e2 - .attributes().size() == 0); - } -} \ No newline at end of file diff --git a/server/tests/src/com/vaadin/tests/server/component/button/WriteDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/button/WriteDesignTest.java new file mode 100644 index 0000000000..6d553da835 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/button/WriteDesignTest.java @@ -0,0 +1,103 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.button; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Attributes; +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; +import org.junit.Test; + +import com.vaadin.event.ShortcutAction.KeyCode; +import com.vaadin.event.ShortcutAction.ModifierKey; +import com.vaadin.ui.Button; +import com.vaadin.ui.NativeButton; +import com.vaadin.ui.declarative.DesignContext; + +/** + * Tests generating html tree nodes corresponding to the contents of a Button + * and a NativeButton. + */ +public class WriteDesignTest extends TestCase { + + private DesignContext ctx; + + @Override + protected void setUp() throws Exception { + super.setUp(); + ctx = new DesignContext(); + } + + @Test + public void testWithTextContent() { + createAndTestButtons("Click me"); + } + + @Test + public void testWithHtmlContent() { + createAndTestButtons("Click"); + } + + @Test + public void testAttributes() { + Button button = new Button(); + button.setTabIndex(3); + button.setIconAlternateText("OK"); + button.setClickShortcut(KeyCode.O, ModifierKey.CTRL, ModifierKey.SHIFT); + Element e = new Element(Tag.valueOf("v-button"), "", new Attributes()); + button.writeDesign(e, ctx); + assertEquals("3", e.attr("tabindex")); + assertTrue("Button is plain text by default", e.hasAttr("plain-text")); + assertEquals("OK", e.attr("icon-alt")); + assertEquals("ctrl-shift-o", e.attr("click-shortcut")); + } + + @Test + public void testUpdateContentMode() { + Button button = new Button("OK"); + Element e = new Element(Tag.valueOf("v-button"), "", new Attributes()); + button.writeDesign(e, ctx); + assertTrue("Button is plain text by default", e.hasAttr("plain-text")); + + button.setHtmlContentAllowed(true); + button.writeDesign(e, ctx); + assertTrue("Button is updated to HTML", !e.hasAttr("plain-text")); + + } + + private void createAndTestButtons(String content) { + Button b1 = new Button(content); + // we need to set this on, since the plain-text attribute will appear + // otherwise + b1.setHtmlContentAllowed(true); + Element e1 = ctx.createElement(b1); + assertEquals("Wrong tag name for button.", "v-button", e1.tagName()); + assertEquals("Unexpected content in the v-button element.", content, + e1.html()); + assertTrue("The v-button element should not have attributes.", e1 + .attributes().size() == 0); + NativeButton b2 = new NativeButton(content); + b2.setHtmlContentAllowed(true); + Element e2 = ctx.createElement(b2); + assertEquals("Wrong tag name for button.", "v-native-button", + e2.tagName()); + assertEquals("Unexpected content in the v-button element.", content, + e2.html()); + assertTrue("The v-button element should not have attributes.", e2 + .attributes().size() == 0); + } +} \ No newline at end of file diff --git a/server/tests/src/com/vaadin/tests/server/component/calendar/CalendarBasics.java b/server/tests/src/com/vaadin/tests/server/component/calendar/CalendarBasics.java deleted file mode 100644 index 773631642a..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/calendar/CalendarBasics.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.calendar; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.Locale; -import java.util.TimeZone; - -import org.junit.Assert; -import org.junit.Test; - -import com.vaadin.ui.Calendar; -import com.vaadin.ui.Calendar.TimeFormat; -import com.vaadin.ui.components.calendar.CalendarComponentEvents.BackwardEvent; -import com.vaadin.ui.components.calendar.CalendarComponentEvents.DateClickEvent; -import com.vaadin.ui.components.calendar.CalendarComponentEvents.EventResize; -import com.vaadin.ui.components.calendar.CalendarComponentEvents.ForwardEvent; -import com.vaadin.ui.components.calendar.CalendarComponentEvents.MoveEvent; -import com.vaadin.ui.components.calendar.CalendarComponentEvents.WeekClick; -import com.vaadin.ui.components.calendar.event.BasicEventProvider; -import com.vaadin.ui.components.calendar.event.CalendarEventProvider; - -/** - * Basic API tests for the calendar - */ -public class CalendarBasics { - - @Test - public void testEmptyConstructorInitialization() { - - Calendar calendar = new Calendar(); - - // The calendar should have a basic event provider with no events - CalendarEventProvider provider = calendar.getEventProvider(); - assertNotNull("Event provider should not be null", provider); - - // Basic event handlers should be registered - assertNotNull(calendar.getHandler(BackwardEvent.EVENT_ID)); - assertNotNull(calendar.getHandler(ForwardEvent.EVENT_ID)); - assertNotNull(calendar.getHandler(WeekClick.EVENT_ID)); - assertNotNull(calendar.getHandler(DateClickEvent.EVENT_ID)); - assertNotNull(calendar.getHandler(MoveEvent.EVENT_ID)); - assertNotNull(calendar.getHandler(EventResize.EVENT_ID)); - - // Calendar should have undefined size - assertTrue(calendar.getWidth() < 0); - assertTrue(calendar.getHeight() < 0); - } - - @Test - public void testConstructorWithCaption() { - final String caption = "My Calendar Caption"; - Calendar calendar = new Calendar(caption); - assertEquals(caption, calendar.getCaption()); - } - - @Test - public void testConstructorWithCustomEventProvider() { - BasicEventProvider myProvider = new BasicEventProvider(); - Calendar calendar = new Calendar(myProvider); - assertEquals(myProvider, calendar.getEventProvider()); - } - - @Test - public void testConstructorWithCustomEventProviderAndCaption() { - BasicEventProvider myProvider = new BasicEventProvider(); - final String caption = "My Calendar Caption"; - Calendar calendar = new Calendar(caption, myProvider); - assertEquals(caption, calendar.getCaption()); - assertEquals(myProvider, calendar.getEventProvider()); - } - - @Test - public void testDefaultStartAndEndDates() { - Calendar calendar = new Calendar(); - - // If no start and end date is set the calendar will display the current - // week - java.util.Calendar c = new GregorianCalendar(); - java.util.Calendar c2 = new GregorianCalendar(); - - c2.setTime(calendar.getStartDate()); - assertEquals(c.getFirstDayOfWeek(), - c2.get(java.util.Calendar.DAY_OF_WEEK)); - c2.setTime(calendar.getEndDate()); - - c.set(java.util.Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); - assertEquals(c.get(java.util.Calendar.DAY_OF_WEEK), - c2.get(java.util.Calendar.DAY_OF_WEEK)); - } - - @Test - public void testCustomStartAndEndDates() { - Calendar calendar = new Calendar(); - java.util.Calendar c = new GregorianCalendar(); - - Date start = c.getTime(); - c.add(java.util.Calendar.DATE, 3); - Date end = c.getTime(); - - calendar.setStartDate(start); - calendar.setEndDate(end); - - assertEquals(start.getTime(), calendar.getStartDate().getTime()); - assertEquals(end.getTime(), calendar.getEndDate().getTime()); - } - - @Test - public void testCustomLocale() { - Calendar calendar = new Calendar(); - calendar.setLocale(Locale.CANADA_FRENCH); - - // Setting the locale should set the internal calendars locale - assertEquals(Locale.CANADA_FRENCH, calendar.getLocale()); - java.util.Calendar c = new GregorianCalendar(Locale.CANADA_FRENCH); - assertEquals(c.getTimeZone().getRawOffset(), calendar - .getInternalCalendar().getTimeZone().getRawOffset()); - } - - @Test - public void testTimeFormat() { - Calendar calendar = new Calendar(); - - // The default timeformat depends on the current locale - calendar.setLocale(Locale.ENGLISH); - assertEquals(TimeFormat.Format12H, calendar.getTimeFormat()); - - calendar.setLocale(Locale.ITALIAN); - assertEquals(TimeFormat.Format24H, calendar.getTimeFormat()); - - // Setting a specific time format overrides the locale - calendar.setTimeFormat(TimeFormat.Format12H); - assertEquals(TimeFormat.Format12H, calendar.getTimeFormat()); - } - - @Test - public void testTimeZone() { - Calendar calendar = new Calendar(); - calendar.setLocale(Locale.CANADA_FRENCH); - - // By default the calendars timezone is returned - assertEquals(calendar.getInternalCalendar().getTimeZone(), - calendar.getTimeZone()); - - // One can override the default behaviour by specifying a timezone - TimeZone customTimeZone = TimeZone.getTimeZone("Europe/Helsinki"); - calendar.setTimeZone(customTimeZone); - assertEquals(customTimeZone, calendar.getTimeZone()); - } - - @Test - public void testVisibleDaysOfWeek() { - Calendar calendar = new Calendar(); - - // The defaults are the whole week - assertEquals(1, calendar.getFirstVisibleDayOfWeek()); - assertEquals(7, calendar.getLastVisibleDayOfWeek()); - - calendar.setFirstVisibleDayOfWeek(0); // Invalid input - assertEquals(1, calendar.getFirstVisibleDayOfWeek()); - - calendar.setLastVisibleDayOfWeek(0); // Invalid input - assertEquals(7, calendar.getLastVisibleDayOfWeek()); - - calendar.setFirstVisibleDayOfWeek(8); // Invalid input - assertEquals(1, calendar.getFirstVisibleDayOfWeek()); - - calendar.setLastVisibleDayOfWeek(8); // Invalid input - assertEquals(7, calendar.getLastVisibleDayOfWeek()); - - calendar.setFirstVisibleDayOfWeek(4); - assertEquals(4, calendar.getFirstVisibleDayOfWeek()); - - calendar.setLastVisibleDayOfWeek(6); - assertEquals(6, calendar.getLastVisibleDayOfWeek()); - - calendar.setFirstVisibleDayOfWeek(7); // Invalid since last day is 6 - assertEquals(4, calendar.getFirstVisibleDayOfWeek()); - - calendar.setLastVisibleDayOfWeek(2); // Invalid since first day is 4 - assertEquals(6, calendar.getLastVisibleDayOfWeek()); - } - - @Test - public void testVisibleHoursInDay() { - Calendar calendar = new Calendar(); - - // Defaults are the whole day - assertEquals(0, calendar.getFirstVisibleHourOfDay()); - assertEquals(23, calendar.getLastVisibleHourOfDay()); - } - - @Test - public void isClientChangeAllowed_connectorEnabled() { - TestCalendar calendar = new TestCalendar(true); - Assert.assertTrue( - "Calendar with enabled connector doesn't allow client change", - calendar.isClientChangeAllowed()); - } - - private static class TestCalendar extends Calendar { - TestCalendar(boolean connectorEnabled) { - isConnectorEnabled = connectorEnabled; - } - - @Override - public boolean isConnectorEnabled() { - return isConnectorEnabled; - } - - @Override - public boolean isClientChangeAllowed() { - return super.isClientChangeAllowed(); - } - - private final boolean isConnectorEnabled; - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/calendar/CalendarBasicsTest.java b/server/tests/src/com/vaadin/tests/server/component/calendar/CalendarBasicsTest.java new file mode 100644 index 0000000000..95b4aecdb3 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/calendar/CalendarBasicsTest.java @@ -0,0 +1,236 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.calendar; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.Assert; +import org.junit.Test; + +import com.vaadin.ui.Calendar; +import com.vaadin.ui.Calendar.TimeFormat; +import com.vaadin.ui.components.calendar.CalendarComponentEvents.BackwardEvent; +import com.vaadin.ui.components.calendar.CalendarComponentEvents.DateClickEvent; +import com.vaadin.ui.components.calendar.CalendarComponentEvents.EventResize; +import com.vaadin.ui.components.calendar.CalendarComponentEvents.ForwardEvent; +import com.vaadin.ui.components.calendar.CalendarComponentEvents.MoveEvent; +import com.vaadin.ui.components.calendar.CalendarComponentEvents.WeekClick; +import com.vaadin.ui.components.calendar.event.BasicEventProvider; +import com.vaadin.ui.components.calendar.event.CalendarEventProvider; + +/** + * Basic API tests for the calendar + */ +public class CalendarBasicsTest { + + @Test + public void testEmptyConstructorInitialization() { + + Calendar calendar = new Calendar(); + + // The calendar should have a basic event provider with no events + CalendarEventProvider provider = calendar.getEventProvider(); + assertNotNull("Event provider should not be null", provider); + + // Basic event handlers should be registered + assertNotNull(calendar.getHandler(BackwardEvent.EVENT_ID)); + assertNotNull(calendar.getHandler(ForwardEvent.EVENT_ID)); + assertNotNull(calendar.getHandler(WeekClick.EVENT_ID)); + assertNotNull(calendar.getHandler(DateClickEvent.EVENT_ID)); + assertNotNull(calendar.getHandler(MoveEvent.EVENT_ID)); + assertNotNull(calendar.getHandler(EventResize.EVENT_ID)); + + // Calendar should have undefined size + assertTrue(calendar.getWidth() < 0); + assertTrue(calendar.getHeight() < 0); + } + + @Test + public void testConstructorWithCaption() { + final String caption = "My Calendar Caption"; + Calendar calendar = new Calendar(caption); + assertEquals(caption, calendar.getCaption()); + } + + @Test + public void testConstructorWithCustomEventProvider() { + BasicEventProvider myProvider = new BasicEventProvider(); + Calendar calendar = new Calendar(myProvider); + assertEquals(myProvider, calendar.getEventProvider()); + } + + @Test + public void testConstructorWithCustomEventProviderAndCaption() { + BasicEventProvider myProvider = new BasicEventProvider(); + final String caption = "My Calendar Caption"; + Calendar calendar = new Calendar(caption, myProvider); + assertEquals(caption, calendar.getCaption()); + assertEquals(myProvider, calendar.getEventProvider()); + } + + @Test + public void testDefaultStartAndEndDates() { + Calendar calendar = new Calendar(); + + // If no start and end date is set the calendar will display the current + // week + java.util.Calendar c = new GregorianCalendar(); + java.util.Calendar c2 = new GregorianCalendar(); + + c2.setTime(calendar.getStartDate()); + assertEquals(c.getFirstDayOfWeek(), + c2.get(java.util.Calendar.DAY_OF_WEEK)); + c2.setTime(calendar.getEndDate()); + + c.set(java.util.Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); + assertEquals(c.get(java.util.Calendar.DAY_OF_WEEK), + c2.get(java.util.Calendar.DAY_OF_WEEK)); + } + + @Test + public void testCustomStartAndEndDates() { + Calendar calendar = new Calendar(); + java.util.Calendar c = new GregorianCalendar(); + + Date start = c.getTime(); + c.add(java.util.Calendar.DATE, 3); + Date end = c.getTime(); + + calendar.setStartDate(start); + calendar.setEndDate(end); + + assertEquals(start.getTime(), calendar.getStartDate().getTime()); + assertEquals(end.getTime(), calendar.getEndDate().getTime()); + } + + @Test + public void testCustomLocale() { + Calendar calendar = new Calendar(); + calendar.setLocale(Locale.CANADA_FRENCH); + + // Setting the locale should set the internal calendars locale + assertEquals(Locale.CANADA_FRENCH, calendar.getLocale()); + java.util.Calendar c = new GregorianCalendar(Locale.CANADA_FRENCH); + assertEquals(c.getTimeZone().getRawOffset(), calendar + .getInternalCalendar().getTimeZone().getRawOffset()); + } + + @Test + public void testTimeFormat() { + Calendar calendar = new Calendar(); + + // The default timeformat depends on the current locale + calendar.setLocale(Locale.ENGLISH); + assertEquals(TimeFormat.Format12H, calendar.getTimeFormat()); + + calendar.setLocale(Locale.ITALIAN); + assertEquals(TimeFormat.Format24H, calendar.getTimeFormat()); + + // Setting a specific time format overrides the locale + calendar.setTimeFormat(TimeFormat.Format12H); + assertEquals(TimeFormat.Format12H, calendar.getTimeFormat()); + } + + @Test + public void testTimeZone() { + Calendar calendar = new Calendar(); + calendar.setLocale(Locale.CANADA_FRENCH); + + // By default the calendars timezone is returned + assertEquals(calendar.getInternalCalendar().getTimeZone(), + calendar.getTimeZone()); + + // One can override the default behaviour by specifying a timezone + TimeZone customTimeZone = TimeZone.getTimeZone("Europe/Helsinki"); + calendar.setTimeZone(customTimeZone); + assertEquals(customTimeZone, calendar.getTimeZone()); + } + + @Test + public void testVisibleDaysOfWeek() { + Calendar calendar = new Calendar(); + + // The defaults are the whole week + assertEquals(1, calendar.getFirstVisibleDayOfWeek()); + assertEquals(7, calendar.getLastVisibleDayOfWeek()); + + calendar.setFirstVisibleDayOfWeek(0); // Invalid input + assertEquals(1, calendar.getFirstVisibleDayOfWeek()); + + calendar.setLastVisibleDayOfWeek(0); // Invalid input + assertEquals(7, calendar.getLastVisibleDayOfWeek()); + + calendar.setFirstVisibleDayOfWeek(8); // Invalid input + assertEquals(1, calendar.getFirstVisibleDayOfWeek()); + + calendar.setLastVisibleDayOfWeek(8); // Invalid input + assertEquals(7, calendar.getLastVisibleDayOfWeek()); + + calendar.setFirstVisibleDayOfWeek(4); + assertEquals(4, calendar.getFirstVisibleDayOfWeek()); + + calendar.setLastVisibleDayOfWeek(6); + assertEquals(6, calendar.getLastVisibleDayOfWeek()); + + calendar.setFirstVisibleDayOfWeek(7); // Invalid since last day is 6 + assertEquals(4, calendar.getFirstVisibleDayOfWeek()); + + calendar.setLastVisibleDayOfWeek(2); // Invalid since first day is 4 + assertEquals(6, calendar.getLastVisibleDayOfWeek()); + } + + @Test + public void testVisibleHoursInDay() { + Calendar calendar = new Calendar(); + + // Defaults are the whole day + assertEquals(0, calendar.getFirstVisibleHourOfDay()); + assertEquals(23, calendar.getLastVisibleHourOfDay()); + } + + @Test + public void isClientChangeAllowed_connectorEnabled() { + TestCalendar calendar = new TestCalendar(true); + Assert.assertTrue( + "Calendar with enabled connector doesn't allow client change", + calendar.isClientChangeAllowed()); + } + + private static class TestCalendar extends Calendar { + TestCalendar(boolean connectorEnabled) { + isConnectorEnabled = connectorEnabled; + } + + @Override + public boolean isConnectorEnabled() { + return isConnectorEnabled; + } + + @Override + public boolean isClientChangeAllowed() { + return super.isClientChangeAllowed(); + } + + private final boolean isConnectorEnabled; + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/calendar/ContainerDataSource.java b/server/tests/src/com/vaadin/tests/server/component/calendar/ContainerDataSource.java deleted file mode 100644 index 030abc0eb2..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/calendar/ContainerDataSource.java +++ /dev/null @@ -1,394 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.calendar; - -import java.util.Date; -import java.util.List; - -import junit.framework.TestCase; - -import org.junit.Test; - -import com.vaadin.data.Container.Indexed; -import com.vaadin.data.Container.Sortable; -import com.vaadin.data.Item; -import com.vaadin.data.Property; -import com.vaadin.data.util.BeanItemContainer; -import com.vaadin.data.util.IndexedContainer; -import com.vaadin.ui.Calendar; -import com.vaadin.ui.components.calendar.ContainerEventProvider; -import com.vaadin.ui.components.calendar.event.BasicEvent; -import com.vaadin.ui.components.calendar.event.CalendarEvent; - -public class ContainerDataSource extends TestCase { - - private Calendar calendar; - - @Override - public void setUp() { - calendar = new Calendar(); - } - - /** - * Tests adding a bean item container to the Calendar - */ - @Test - public void testWithBeanItemContainer() { - - // Create a container to use as a datasource - Indexed container = createTestBeanItemContainer(); - - // Set datasource - calendar.setContainerDataSource(container); - - // Start and end dates to query for - java.util.Calendar cal = java.util.Calendar.getInstance(); - cal.setTime(((CalendarEvent) container.getIdByIndex(0)).getStart()); - Date start = cal.getTime(); - cal.add(java.util.Calendar.MONTH, 1); - Date end = cal.getTime(); - - // Test the all events are returned - List events = calendar.getEventProvider().getEvents( - start, end); - assertEquals(container.size(), events.size()); - - // Test that a certain range is returned - cal.setTime(((CalendarEvent) container.getIdByIndex(6)).getStart()); - end = cal.getTime(); - events = calendar.getEventProvider().getEvents(start, end); - assertEquals(6, events.size()); - } - - /** - * This tests tests that if you give the Calendar an unsorted (== not sorted - * by starting date) container then the calendar should gracefully handle - * it. In this case the size of the container will be wrong. The test is - * exactly the same as {@link #testWithBeanItemContainer()} except that the - * beans has been intentionally sorted by caption instead of date. - */ - @Test - public void testWithUnsortedBeanItemContainer() { - // Create a container to use as a datasource - Indexed container = createTestBeanItemContainer(); - - // Make the container sorted by caption - ((Sortable) container).sort(new Object[] { "caption" }, - new boolean[] { true }); - - // Set data source - calendar.setContainerDataSource(container); - - // Start and end dates to query for - java.util.Calendar cal = java.util.Calendar.getInstance(); - cal.setTime(((CalendarEvent) container.getIdByIndex(0)).getStart()); - Date start = cal.getTime(); - cal.add(java.util.Calendar.MONTH, 1); - Date end = cal.getTime(); - - // Test the all events are returned - List events = calendar.getEventProvider().getEvents( - start, end); - assertEquals(container.size(), events.size()); - - // Test that a certain range is returned - cal.setTime(((CalendarEvent) container.getIdByIndex(6)).getStart()); - end = cal.getTime(); - events = calendar.getEventProvider().getEvents(start, end); - - // The events size is 1 since the getEvents returns the wrong range - assertEquals(1, events.size()); - } - - /** - * Tests adding a Indexed container to the Calendar - */ - @Test - public void testWithIndexedContainer() { - - // Create a container to use as a datasource - Indexed container = createTestIndexedContainer(); - - // Set datasource - calendar.setContainerDataSource(container, "testCaption", - "testDescription", "testStartDate", "testEndDate", null); - - // Start and end dates to query for - java.util.Calendar cal = java.util.Calendar.getInstance(); - cal.setTime((Date) container.getItem(container.getIdByIndex(0)) - .getItemProperty("testStartDate").getValue()); - Date start = cal.getTime(); - cal.add(java.util.Calendar.MONTH, 1); - Date end = cal.getTime(); - - // Test the all events are returned - List events = calendar.getEventProvider().getEvents( - start, end); - assertEquals(container.size(), events.size()); - - // Check that event values are present - CalendarEvent e = events.get(0); - assertEquals("Test 1", e.getCaption()); - assertEquals("Description 1", e.getDescription()); - assertTrue(e.getStart().compareTo(start) == 0); - - // Test that a certain range is returned - cal.setTime((Date) container.getItem(container.getIdByIndex(6)) - .getItemProperty("testStartDate").getValue()); - end = cal.getTime(); - events = calendar.getEventProvider().getEvents(start, end); - assertEquals(6, events.size()); - } - - @Test - public void testNullLimitsBeanItemContainer() { - // Create a container to use as a datasource - Indexed container = createTestBeanItemContainer(); - - // Start and end dates to query for - java.util.Calendar cal = java.util.Calendar.getInstance(); - cal.setTime(((CalendarEvent) container.getIdByIndex(0)).getStart()); - Date start = cal.getTime(); - cal.add(java.util.Calendar.MONTH, 1); - Date end = cal.getTime(); - - // Set datasource - calendar.setContainerDataSource(container); - - // Test null start time - List events = calendar.getEventProvider().getEvents( - null, end); - assertEquals(container.size(), events.size()); - - // Test null end time - events = calendar.getEventProvider().getEvents(start, null); - assertEquals(container.size(), events.size()); - - // Test both null times - events = calendar.getEventProvider().getEvents(null, null); - assertEquals(container.size(), events.size()); - } - - @Test - public void testNullLimitsIndexedContainer() { - // Create a container to use as a datasource - Indexed container = createTestIndexedContainer(); - - // Start and end dates to query for - java.util.Calendar cal = java.util.Calendar.getInstance(); - cal.setTime((Date) container.getItem(container.getIdByIndex(0)) - .getItemProperty("testStartDate").getValue()); - Date start = cal.getTime(); - cal.add(java.util.Calendar.MONTH, 1); - Date end = cal.getTime(); - - // Set datasource - calendar.setContainerDataSource(container, "testCaption", - "testDescription", "testStartDate", "testEndDate", null); - - // Test null start time - List events = calendar.getEventProvider().getEvents( - null, end); - assertEquals(container.size(), events.size()); - - // Test null end time - events = calendar.getEventProvider().getEvents(start, null); - assertEquals(container.size(), events.size()); - - // Test both null times - events = calendar.getEventProvider().getEvents(null, null); - assertEquals(container.size(), events.size()); - } - - /** - * Tests the addEvent convenience method with the default event provider - */ - @Test - public void testAddEventConvinienceMethod() { - - // Start and end dates to query for - java.util.Calendar cal = java.util.Calendar.getInstance(); - Date start = cal.getTime(); - cal.add(java.util.Calendar.MONTH, 1); - Date end = cal.getTime(); - - // Ensure no events - assertEquals(0, calendar.getEvents(start, end).size()); - - // Add an event - BasicEvent event = new BasicEvent("Test", "Test", start); - calendar.addEvent(event); - - // Ensure event exists - List events = calendar.getEvents(start, end); - assertEquals(1, events.size()); - assertEquals(events.get(0).getCaption(), event.getCaption()); - assertEquals(events.get(0).getDescription(), event.getDescription()); - assertEquals(events.get(0).getStart(), event.getStart()); - } - - /** - * Test the removeEvent convenience method with the default event provider - */ - @Test - public void testRemoveEventConvinienceMethod() { - - // Start and end dates to query for - java.util.Calendar cal = java.util.Calendar.getInstance(); - Date start = cal.getTime(); - cal.add(java.util.Calendar.MONTH, 1); - Date end = cal.getTime(); - - // Ensure no events - assertEquals(0, calendar.getEvents(start, end).size()); - - // Add an event - CalendarEvent event = new BasicEvent("Test", "Test", start); - calendar.addEvent(event); - - // Ensure event exists - assertEquals(1, calendar.getEvents(start, end).size()); - - // Remove event - calendar.removeEvent(event); - - // Ensure no events - assertEquals(0, calendar.getEvents(start, end).size()); - } - - @Test - public void testAddEventConvinienceMethodWithCustomEventProvider() { - - // Use a container data source - calendar.setEventProvider(new ContainerEventProvider( - new BeanItemContainer(BasicEvent.class))); - - // Start and end dates to query for - java.util.Calendar cal = java.util.Calendar.getInstance(); - Date start = cal.getTime(); - cal.add(java.util.Calendar.MONTH, 1); - Date end = cal.getTime(); - - // Ensure no events - assertEquals(0, calendar.getEvents(start, end).size()); - - // Add an event - BasicEvent event = new BasicEvent("Test", "Test", start); - calendar.addEvent(event); - - // Ensure event exists - List events = calendar.getEvents(start, end); - assertEquals(1, events.size()); - assertEquals(events.get(0).getCaption(), event.getCaption()); - assertEquals(events.get(0).getDescription(), event.getDescription()); - assertEquals(events.get(0).getStart(), event.getStart()); - } - - @Test - public void testRemoveEventConvinienceMethodWithCustomEventProvider() { - - // Use a container data source - calendar.setEventProvider(new ContainerEventProvider( - new BeanItemContainer(BasicEvent.class))); - - // Start and end dates to query for - java.util.Calendar cal = java.util.Calendar.getInstance(); - Date start = cal.getTime(); - cal.add(java.util.Calendar.MONTH, 1); - Date end = cal.getTime(); - - // Ensure no events - assertEquals(0, calendar.getEvents(start, end).size()); - - // Add an event - BasicEvent event = new BasicEvent("Test", "Test", start); - calendar.addEvent(event); - - // Ensure event exists - List events = calendar.getEvents(start, end); - assertEquals(1, events.size()); - - // Remove event - calendar.removeEvent(event); - - // Ensure no events - assertEquals(0, calendar.getEvents(start, end).size()); - } - - @Test - public void testStyleNamePropertyRetrieved() { - IndexedContainer ic = (IndexedContainer) createTestIndexedContainer(); - ic.addContainerProperty("testStyleName", String.class, ""); - for (int i = 0; i < 10; i++) { - Item item = ic.getItem(ic.getIdByIndex(i)); - @SuppressWarnings("unchecked") - Property itemProperty = item - .getItemProperty("testStyleName"); - itemProperty.setValue("testStyle"); - } - - ContainerEventProvider provider = new ContainerEventProvider(ic); - provider.setCaptionProperty("testCaption"); - provider.setDescriptionProperty("testDescription"); - provider.setStartDateProperty("testStartDate"); - provider.setEndDateProperty("testEndDate"); - provider.setStyleNameProperty("testStyleName"); - - calendar.setEventProvider(provider); - java.util.Calendar cal = java.util.Calendar.getInstance(); - Date now = cal.getTime(); - cal.add(java.util.Calendar.DAY_OF_MONTH, 20); - Date then = cal.getTime(); - List events = calendar.getEventProvider().getEvents(now, - then); - for (CalendarEvent ce : events) { - assertEquals("testStyle", ce.getStyleName()); - } - } - - private static Indexed createTestBeanItemContainer() { - BeanItemContainer eventContainer = new BeanItemContainer( - CalendarEvent.class); - java.util.Calendar cal = java.util.Calendar.getInstance(); - for (int i = 1; i <= 10; i++) { - eventContainer.addBean(new BasicEvent("Test " + i, "Description " - + i, cal.getTime())); - cal.add(java.util.Calendar.DAY_OF_MONTH, 2); - } - return eventContainer; - } - - private static Indexed createTestIndexedContainer() { - IndexedContainer container = new IndexedContainer(); - container.addContainerProperty("testCaption", String.class, ""); - container.addContainerProperty("testDescription", String.class, ""); - container.addContainerProperty("testStartDate", Date.class, null); - container.addContainerProperty("testEndDate", Date.class, null); - - java.util.Calendar cal = java.util.Calendar.getInstance(); - for (int i = 1; i <= 10; i++) { - Item item = container.getItem(container.addItem()); - item.getItemProperty("testCaption").setValue("Test " + i); - item.getItemProperty("testDescription") - .setValue("Description " + i); - item.getItemProperty("testStartDate").setValue(cal.getTime()); - item.getItemProperty("testEndDate").setValue(cal.getTime()); - cal.add(java.util.Calendar.DAY_OF_MONTH, 2); - } - return container; - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/component/calendar/ContainerDataSourceTest.java b/server/tests/src/com/vaadin/tests/server/component/calendar/ContainerDataSourceTest.java new file mode 100644 index 0000000000..8a066497cd --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/calendar/ContainerDataSourceTest.java @@ -0,0 +1,394 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.calendar; + +import java.util.Date; +import java.util.List; + +import junit.framework.TestCase; + +import org.junit.Test; + +import com.vaadin.data.Container.Indexed; +import com.vaadin.data.Container.Sortable; +import com.vaadin.data.Item; +import com.vaadin.data.Property; +import com.vaadin.data.util.BeanItemContainer; +import com.vaadin.data.util.IndexedContainer; +import com.vaadin.ui.Calendar; +import com.vaadin.ui.components.calendar.ContainerEventProvider; +import com.vaadin.ui.components.calendar.event.BasicEvent; +import com.vaadin.ui.components.calendar.event.CalendarEvent; + +public class ContainerDataSourceTest extends TestCase { + + private Calendar calendar; + + @Override + public void setUp() { + calendar = new Calendar(); + } + + /** + * Tests adding a bean item container to the Calendar + */ + @Test + public void testWithBeanItemContainer() { + + // Create a container to use as a datasource + Indexed container = createTestBeanItemContainer(); + + // Set datasource + calendar.setContainerDataSource(container); + + // Start and end dates to query for + java.util.Calendar cal = java.util.Calendar.getInstance(); + cal.setTime(((CalendarEvent) container.getIdByIndex(0)).getStart()); + Date start = cal.getTime(); + cal.add(java.util.Calendar.MONTH, 1); + Date end = cal.getTime(); + + // Test the all events are returned + List events = calendar.getEventProvider().getEvents( + start, end); + assertEquals(container.size(), events.size()); + + // Test that a certain range is returned + cal.setTime(((CalendarEvent) container.getIdByIndex(6)).getStart()); + end = cal.getTime(); + events = calendar.getEventProvider().getEvents(start, end); + assertEquals(6, events.size()); + } + + /** + * This tests tests that if you give the Calendar an unsorted (== not sorted + * by starting date) container then the calendar should gracefully handle + * it. In this case the size of the container will be wrong. The test is + * exactly the same as {@link #testWithBeanItemContainer()} except that the + * beans has been intentionally sorted by caption instead of date. + */ + @Test + public void testWithUnsortedBeanItemContainer() { + // Create a container to use as a datasource + Indexed container = createTestBeanItemContainer(); + + // Make the container sorted by caption + ((Sortable) container).sort(new Object[] { "caption" }, + new boolean[] { true }); + + // Set data source + calendar.setContainerDataSource(container); + + // Start and end dates to query for + java.util.Calendar cal = java.util.Calendar.getInstance(); + cal.setTime(((CalendarEvent) container.getIdByIndex(0)).getStart()); + Date start = cal.getTime(); + cal.add(java.util.Calendar.MONTH, 1); + Date end = cal.getTime(); + + // Test the all events are returned + List events = calendar.getEventProvider().getEvents( + start, end); + assertEquals(container.size(), events.size()); + + // Test that a certain range is returned + cal.setTime(((CalendarEvent) container.getIdByIndex(6)).getStart()); + end = cal.getTime(); + events = calendar.getEventProvider().getEvents(start, end); + + // The events size is 1 since the getEvents returns the wrong range + assertEquals(1, events.size()); + } + + /** + * Tests adding a Indexed container to the Calendar + */ + @Test + public void testWithIndexedContainer() { + + // Create a container to use as a datasource + Indexed container = createTestIndexedContainer(); + + // Set datasource + calendar.setContainerDataSource(container, "testCaption", + "testDescription", "testStartDate", "testEndDate", null); + + // Start and end dates to query for + java.util.Calendar cal = java.util.Calendar.getInstance(); + cal.setTime((Date) container.getItem(container.getIdByIndex(0)) + .getItemProperty("testStartDate").getValue()); + Date start = cal.getTime(); + cal.add(java.util.Calendar.MONTH, 1); + Date end = cal.getTime(); + + // Test the all events are returned + List events = calendar.getEventProvider().getEvents( + start, end); + assertEquals(container.size(), events.size()); + + // Check that event values are present + CalendarEvent e = events.get(0); + assertEquals("Test 1", e.getCaption()); + assertEquals("Description 1", e.getDescription()); + assertTrue(e.getStart().compareTo(start) == 0); + + // Test that a certain range is returned + cal.setTime((Date) container.getItem(container.getIdByIndex(6)) + .getItemProperty("testStartDate").getValue()); + end = cal.getTime(); + events = calendar.getEventProvider().getEvents(start, end); + assertEquals(6, events.size()); + } + + @Test + public void testNullLimitsBeanItemContainer() { + // Create a container to use as a datasource + Indexed container = createTestBeanItemContainer(); + + // Start and end dates to query for + java.util.Calendar cal = java.util.Calendar.getInstance(); + cal.setTime(((CalendarEvent) container.getIdByIndex(0)).getStart()); + Date start = cal.getTime(); + cal.add(java.util.Calendar.MONTH, 1); + Date end = cal.getTime(); + + // Set datasource + calendar.setContainerDataSource(container); + + // Test null start time + List events = calendar.getEventProvider().getEvents( + null, end); + assertEquals(container.size(), events.size()); + + // Test null end time + events = calendar.getEventProvider().getEvents(start, null); + assertEquals(container.size(), events.size()); + + // Test both null times + events = calendar.getEventProvider().getEvents(null, null); + assertEquals(container.size(), events.size()); + } + + @Test + public void testNullLimitsIndexedContainer() { + // Create a container to use as a datasource + Indexed container = createTestIndexedContainer(); + + // Start and end dates to query for + java.util.Calendar cal = java.util.Calendar.getInstance(); + cal.setTime((Date) container.getItem(container.getIdByIndex(0)) + .getItemProperty("testStartDate").getValue()); + Date start = cal.getTime(); + cal.add(java.util.Calendar.MONTH, 1); + Date end = cal.getTime(); + + // Set datasource + calendar.setContainerDataSource(container, "testCaption", + "testDescription", "testStartDate", "testEndDate", null); + + // Test null start time + List events = calendar.getEventProvider().getEvents( + null, end); + assertEquals(container.size(), events.size()); + + // Test null end time + events = calendar.getEventProvider().getEvents(start, null); + assertEquals(container.size(), events.size()); + + // Test both null times + events = calendar.getEventProvider().getEvents(null, null); + assertEquals(container.size(), events.size()); + } + + /** + * Tests the addEvent convenience method with the default event provider + */ + @Test + public void testAddEventConvinienceMethod() { + + // Start and end dates to query for + java.util.Calendar cal = java.util.Calendar.getInstance(); + Date start = cal.getTime(); + cal.add(java.util.Calendar.MONTH, 1); + Date end = cal.getTime(); + + // Ensure no events + assertEquals(0, calendar.getEvents(start, end).size()); + + // Add an event + BasicEvent event = new BasicEvent("Test", "Test", start); + calendar.addEvent(event); + + // Ensure event exists + List events = calendar.getEvents(start, end); + assertEquals(1, events.size()); + assertEquals(events.get(0).getCaption(), event.getCaption()); + assertEquals(events.get(0).getDescription(), event.getDescription()); + assertEquals(events.get(0).getStart(), event.getStart()); + } + + /** + * Test the removeEvent convenience method with the default event provider + */ + @Test + public void testRemoveEventConvinienceMethod() { + + // Start and end dates to query for + java.util.Calendar cal = java.util.Calendar.getInstance(); + Date start = cal.getTime(); + cal.add(java.util.Calendar.MONTH, 1); + Date end = cal.getTime(); + + // Ensure no events + assertEquals(0, calendar.getEvents(start, end).size()); + + // Add an event + CalendarEvent event = new BasicEvent("Test", "Test", start); + calendar.addEvent(event); + + // Ensure event exists + assertEquals(1, calendar.getEvents(start, end).size()); + + // Remove event + calendar.removeEvent(event); + + // Ensure no events + assertEquals(0, calendar.getEvents(start, end).size()); + } + + @Test + public void testAddEventConvinienceMethodWithCustomEventProvider() { + + // Use a container data source + calendar.setEventProvider(new ContainerEventProvider( + new BeanItemContainer(BasicEvent.class))); + + // Start and end dates to query for + java.util.Calendar cal = java.util.Calendar.getInstance(); + Date start = cal.getTime(); + cal.add(java.util.Calendar.MONTH, 1); + Date end = cal.getTime(); + + // Ensure no events + assertEquals(0, calendar.getEvents(start, end).size()); + + // Add an event + BasicEvent event = new BasicEvent("Test", "Test", start); + calendar.addEvent(event); + + // Ensure event exists + List events = calendar.getEvents(start, end); + assertEquals(1, events.size()); + assertEquals(events.get(0).getCaption(), event.getCaption()); + assertEquals(events.get(0).getDescription(), event.getDescription()); + assertEquals(events.get(0).getStart(), event.getStart()); + } + + @Test + public void testRemoveEventConvinienceMethodWithCustomEventProvider() { + + // Use a container data source + calendar.setEventProvider(new ContainerEventProvider( + new BeanItemContainer(BasicEvent.class))); + + // Start and end dates to query for + java.util.Calendar cal = java.util.Calendar.getInstance(); + Date start = cal.getTime(); + cal.add(java.util.Calendar.MONTH, 1); + Date end = cal.getTime(); + + // Ensure no events + assertEquals(0, calendar.getEvents(start, end).size()); + + // Add an event + BasicEvent event = new BasicEvent("Test", "Test", start); + calendar.addEvent(event); + + // Ensure event exists + List events = calendar.getEvents(start, end); + assertEquals(1, events.size()); + + // Remove event + calendar.removeEvent(event); + + // Ensure no events + assertEquals(0, calendar.getEvents(start, end).size()); + } + + @Test + public void testStyleNamePropertyRetrieved() { + IndexedContainer ic = (IndexedContainer) createTestIndexedContainer(); + ic.addContainerProperty("testStyleName", String.class, ""); + for (int i = 0; i < 10; i++) { + Item item = ic.getItem(ic.getIdByIndex(i)); + @SuppressWarnings("unchecked") + Property itemProperty = item + .getItemProperty("testStyleName"); + itemProperty.setValue("testStyle"); + } + + ContainerEventProvider provider = new ContainerEventProvider(ic); + provider.setCaptionProperty("testCaption"); + provider.setDescriptionProperty("testDescription"); + provider.setStartDateProperty("testStartDate"); + provider.setEndDateProperty("testEndDate"); + provider.setStyleNameProperty("testStyleName"); + + calendar.setEventProvider(provider); + java.util.Calendar cal = java.util.Calendar.getInstance(); + Date now = cal.getTime(); + cal.add(java.util.Calendar.DAY_OF_MONTH, 20); + Date then = cal.getTime(); + List events = calendar.getEventProvider().getEvents(now, + then); + for (CalendarEvent ce : events) { + assertEquals("testStyle", ce.getStyleName()); + } + } + + private static Indexed createTestBeanItemContainer() { + BeanItemContainer eventContainer = new BeanItemContainer( + CalendarEvent.class); + java.util.Calendar cal = java.util.Calendar.getInstance(); + for (int i = 1; i <= 10; i++) { + eventContainer.addBean(new BasicEvent("Test " + i, "Description " + + i, cal.getTime())); + cal.add(java.util.Calendar.DAY_OF_MONTH, 2); + } + return eventContainer; + } + + private static Indexed createTestIndexedContainer() { + IndexedContainer container = new IndexedContainer(); + container.addContainerProperty("testCaption", String.class, ""); + container.addContainerProperty("testDescription", String.class, ""); + container.addContainerProperty("testStartDate", Date.class, null); + container.addContainerProperty("testEndDate", Date.class, null); + + java.util.Calendar cal = java.util.Calendar.getInstance(); + for (int i = 1; i <= 10; i++) { + Item item = container.getItem(container.addItem()); + item.getItemProperty("testCaption").setValue("Test " + i); + item.getItemProperty("testDescription") + .setValue("Description " + i); + item.getItemProperty("testStartDate").setValue(cal.getTime()); + item.getItemProperty("testEndDate").setValue(cal.getTime()); + cal.add(java.util.Calendar.DAY_OF_MONTH, 2); + } + return container; + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/component/checkbox/ReadDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/checkbox/ReadDesignTest.java new file mode 100644 index 0000000000..9456fa4b31 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/checkbox/ReadDesignTest.java @@ -0,0 +1,67 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.checkbox; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Attributes; +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; +import org.junit.Test; + +import com.vaadin.ui.CheckBox; +import com.vaadin.ui.declarative.DesignContext; + +/** + * + * Test cases for reading the contents of a Checkbox from a design. + * + */ +public class ReadDesignTest extends TestCase { + + private DesignContext ctx; + + @Override + protected void setUp() throws Exception { + super.setUp(); + ctx = new DesignContext(); + } + + @Test + public void testChecked() { + Element e = createElement(true); + CheckBox box = (CheckBox) ctx.readDesign(e); + assertEquals("The checkbox must be checked", Boolean.TRUE, + box.getValue()); + } + + @Test + public void testUnchecked() { + Element e = createElement(false); + CheckBox box = (CheckBox) ctx.readDesign(e); + assertEquals("The checkbox must be unchecked", Boolean.FALSE, + box.getValue()); + } + + private Element createElement(boolean checked) { + Attributes attributes = new Attributes(); + if (checked) { + attributes.put("checked", ""); + } + Element node = new Element(Tag.valueOf("v-check-box"), "", attributes); + return node; + } +} \ No newline at end of file diff --git a/server/tests/src/com/vaadin/tests/server/component/checkbox/TestReadDesign.java b/server/tests/src/com/vaadin/tests/server/component/checkbox/TestReadDesign.java deleted file mode 100644 index c58b3b6bdd..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/checkbox/TestReadDesign.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.checkbox; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Attributes; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; -import org.junit.Test; - -import com.vaadin.ui.CheckBox; -import com.vaadin.ui.declarative.DesignContext; - -/** - * - * Test cases for reading the contents of a Checkbox from a design. - * - */ -public class TestReadDesign extends TestCase { - - private DesignContext ctx; - - @Override - protected void setUp() throws Exception { - super.setUp(); - ctx = new DesignContext(); - } - - @Test - public void testChecked() { - Element e = createElement(true); - CheckBox box = (CheckBox) ctx.readDesign(e); - assertEquals("The checkbox must be checked", Boolean.TRUE, - box.getValue()); - } - - @Test - public void testUnchecked() { - Element e = createElement(false); - CheckBox box = (CheckBox) ctx.readDesign(e); - assertEquals("The checkbox must be unchecked", Boolean.FALSE, - box.getValue()); - } - - private Element createElement(boolean checked) { - Attributes attributes = new Attributes(); - if (checked) { - attributes.put("checked", ""); - } - Element node = new Element(Tag.valueOf("v-check-box"), "", attributes); - return node; - } -} \ No newline at end of file diff --git a/server/tests/src/com/vaadin/tests/server/component/checkbox/TestWriteDesign.java b/server/tests/src/com/vaadin/tests/server/component/checkbox/TestWriteDesign.java deleted file mode 100644 index d187371db6..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/checkbox/TestWriteDesign.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.checkbox; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Element; -import org.junit.Test; - -import com.vaadin.ui.CheckBox; -import com.vaadin.ui.declarative.DesignContext; - -/** - * Tests generating html tree nodes corresponding to the contents of a Checkbox - */ -public class TestWriteDesign extends TestCase { - - private DesignContext ctx; - - @Override - protected void setUp() throws Exception { - super.setUp(); - ctx = new DesignContext(); - } - - @Test - public void testChecked() { - CheckBox box = new CheckBox(); - box.setValue(true); - Element e = ctx.createElement(box); - assertTrue("element must have checked attribute", e.hasAttr("checked")); - assertTrue("the checked attribute must be true", e.attr("checked") - .equals("true") || e.attr("checked").equals("")); - } - - @Test - public void testUnchecked() { - CheckBox box = new CheckBox(); - box.setValue(false); - Element e = ctx.createElement(box); - assertFalse("the element must not have checked attribute", - e.hasAttr("checked")); - } -} \ No newline at end of file diff --git a/server/tests/src/com/vaadin/tests/server/component/checkbox/WriteDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/checkbox/WriteDesignTest.java new file mode 100644 index 0000000000..4c41f67ac5 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/checkbox/WriteDesignTest.java @@ -0,0 +1,57 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.checkbox; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Element; +import org.junit.Test; + +import com.vaadin.ui.CheckBox; +import com.vaadin.ui.declarative.DesignContext; + +/** + * Tests generating html tree nodes corresponding to the contents of a Checkbox + */ +public class WriteDesignTest extends TestCase { + + private DesignContext ctx; + + @Override + protected void setUp() throws Exception { + super.setUp(); + ctx = new DesignContext(); + } + + @Test + public void testChecked() { + CheckBox box = new CheckBox(); + box.setValue(true); + Element e = ctx.createElement(box); + assertTrue("element must have checked attribute", e.hasAttr("checked")); + assertTrue("the checked attribute must be true", e.attr("checked") + .equals("true") || e.attr("checked").equals("")); + } + + @Test + public void testUnchecked() { + CheckBox box = new CheckBox(); + box.setValue(false); + Element e = ctx.createElement(box); + assertFalse("the element must not have checked attribute", + e.hasAttr("checked")); + } +} \ No newline at end of file diff --git a/server/tests/src/com/vaadin/tests/server/component/colorpicker/ColorConversions.java b/server/tests/src/com/vaadin/tests/server/component/colorpicker/ColorConversions.java deleted file mode 100644 index 46d72a6ae6..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/colorpicker/ColorConversions.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.colorpicker; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -import com.vaadin.shared.ui.colorpicker.Color; - -public class ColorConversions { - - @Test - public void convertHSL2RGB() { - - int rgb = Color.HSLtoRGB(100, 50, 50); - Color c = new Color(rgb); - assertEquals(106, c.getRed()); - assertEquals(191, c.getGreen()); - assertEquals(64, c.getBlue()); - assertEquals("#6abf40", c.getCSS()); - - rgb = Color.HSLtoRGB(0, 50, 50); - c = new Color(rgb); - assertEquals(191, c.getRed()); - assertEquals(64, c.getGreen()); - assertEquals(64, c.getBlue()); - assertEquals("#bf4040", c.getCSS()); - - rgb = Color.HSLtoRGB(50, 0, 50); - c = new Color(rgb); - assertEquals(128, c.getRed()); - assertEquals(128, c.getGreen()); - assertEquals(128, c.getBlue()); - assertEquals("#808080", c.getCSS()); - - rgb = Color.HSLtoRGB(50, 100, 0); - c = new Color(rgb); - assertEquals(0, c.getRed(), 0); - assertEquals(0, c.getGreen(), 0); - assertEquals(0, c.getBlue(), 0); - assertEquals("#000000", c.getCSS()); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/colorpicker/ColorConversionsTest.java b/server/tests/src/com/vaadin/tests/server/component/colorpicker/ColorConversionsTest.java new file mode 100644 index 0000000000..8c05e58b9c --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/colorpicker/ColorConversionsTest.java @@ -0,0 +1,57 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.colorpicker; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.vaadin.shared.ui.colorpicker.Color; + +public class ColorConversionsTest { + + @Test + public void convertHSL2RGB() { + + int rgb = Color.HSLtoRGB(100, 50, 50); + Color c = new Color(rgb); + assertEquals(106, c.getRed()); + assertEquals(191, c.getGreen()); + assertEquals(64, c.getBlue()); + assertEquals("#6abf40", c.getCSS()); + + rgb = Color.HSLtoRGB(0, 50, 50); + c = new Color(rgb); + assertEquals(191, c.getRed()); + assertEquals(64, c.getGreen()); + assertEquals(64, c.getBlue()); + assertEquals("#bf4040", c.getCSS()); + + rgb = Color.HSLtoRGB(50, 0, 50); + c = new Color(rgb); + assertEquals(128, c.getRed()); + assertEquals(128, c.getGreen()); + assertEquals(128, c.getBlue()); + assertEquals("#808080", c.getCSS()); + + rgb = Color.HSLtoRGB(50, 100, 0); + c = new Color(rgb); + assertEquals(0, c.getRed(), 0); + assertEquals(0, c.getGreen(), 0); + assertEquals(0, c.getBlue(), 0); + assertEquals("#000000", c.getCSS()); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/csslayout/CssLayoutListeners.java b/server/tests/src/com/vaadin/tests/server/component/csslayout/CssLayoutListeners.java deleted file mode 100644 index ee75d6ed59..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/csslayout/CssLayoutListeners.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.vaadin.tests.server.component.csslayout; - -import com.vaadin.event.LayoutEvents.LayoutClickEvent; -import com.vaadin.event.LayoutEvents.LayoutClickListener; -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; -import com.vaadin.ui.CssLayout; - -public class CssLayoutListeners extends AbstractListenerMethodsTest { - public void testLayoutClickListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(CssLayout.class, LayoutClickEvent.class, - LayoutClickListener.class); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/csslayout/CssLayoutListenersTest.java b/server/tests/src/com/vaadin/tests/server/component/csslayout/CssLayoutListenersTest.java new file mode 100644 index 0000000000..e000df593b --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/csslayout/CssLayoutListenersTest.java @@ -0,0 +1,13 @@ +package com.vaadin.tests.server.component.csslayout; + +import com.vaadin.event.LayoutEvents.LayoutClickEvent; +import com.vaadin.event.LayoutEvents.LayoutClickListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; +import com.vaadin.ui.CssLayout; + +public class CssLayoutListenersTest extends AbstractListenerMethodsTestBase { + public void testLayoutClickListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(CssLayout.class, LayoutClickEvent.class, + LayoutClickListener.class); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/csslayout/ReadDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/csslayout/ReadDesignTest.java new file mode 100644 index 0000000000..5c3517fa56 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/csslayout/ReadDesignTest.java @@ -0,0 +1,74 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.csslayout; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Attributes; +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; + +import com.vaadin.ui.Component; +import com.vaadin.ui.CssLayout; +import com.vaadin.ui.declarative.DesignContext; + +/** + * Test case for reading CssLayout from design + * + * @author Vaadin Ltd + */ +public class ReadDesignTest extends TestCase { + + public void testChildCount() { + CssLayout root = createLayout(); + assertEquals(2, root.getComponentCount()); + } + + public void testAttributes() { + CssLayout root = createLayout(); + assertEquals("test-layout", root.getCaption()); + assertEquals("test-label", root.getComponent(0).getCaption()); + assertEquals("test-button", root.getComponent(1).getCaption()); + } + + private CssLayout createLayout() { + DesignContext ctx = new DesignContext(); + Element design = createDesign(); + Component child = ctx.readDesign(design); + return (CssLayout) child; + } + + private Element createDesign() { + + Attributes rootAttributes = new Attributes(); + rootAttributes.put("caption", "test-layout"); + Element node = new Element(Tag.valueOf("v-css-layout"), "", + rootAttributes); + + Attributes firstChildAttributes = new Attributes(); + firstChildAttributes.put("caption", "test-label"); + Element firstChild = new Element(Tag.valueOf("v-label"), "", + firstChildAttributes); + node.appendChild(firstChild); + + Attributes secondChildAttributes = new Attributes(); + Element secondChild = new Element(Tag.valueOf("v-button"), "", + secondChildAttributes); + secondChild.html("test-button"); + node.appendChild(secondChild); + return node; + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/csslayout/TestReadDesign.java b/server/tests/src/com/vaadin/tests/server/component/csslayout/TestReadDesign.java deleted file mode 100644 index bac3dc70eb..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/csslayout/TestReadDesign.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.csslayout; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Attributes; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; - -import com.vaadin.ui.Component; -import com.vaadin.ui.CssLayout; -import com.vaadin.ui.declarative.DesignContext; - -/** - * Test case for reading CssLayout from design - * - * @author Vaadin Ltd - */ -public class TestReadDesign extends TestCase { - - public void testChildCount() { - CssLayout root = createLayout(); - assertEquals(2, root.getComponentCount()); - } - - public void testAttributes() { - CssLayout root = createLayout(); - assertEquals("test-layout", root.getCaption()); - assertEquals("test-label", root.getComponent(0).getCaption()); - assertEquals("test-button", root.getComponent(1).getCaption()); - } - - private CssLayout createLayout() { - DesignContext ctx = new DesignContext(); - Element design = createDesign(); - Component child = ctx.readDesign(design); - return (CssLayout) child; - } - - private Element createDesign() { - - Attributes rootAttributes = new Attributes(); - rootAttributes.put("caption", "test-layout"); - Element node = new Element(Tag.valueOf("v-css-layout"), "", - rootAttributes); - - Attributes firstChildAttributes = new Attributes(); - firstChildAttributes.put("caption", "test-label"); - Element firstChild = new Element(Tag.valueOf("v-label"), "", - firstChildAttributes); - node.appendChild(firstChild); - - Attributes secondChildAttributes = new Attributes(); - Element secondChild = new Element(Tag.valueOf("v-button"), "", - secondChildAttributes); - secondChild.html("test-button"); - node.appendChild(secondChild); - return node; - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/csslayout/TestWriteDesign.java b/server/tests/src/com/vaadin/tests/server/component/csslayout/TestWriteDesign.java deleted file mode 100644 index d660eb77ec..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/csslayout/TestWriteDesign.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.csslayout; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Attributes; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; - -import com.vaadin.ui.CssLayout; -import com.vaadin.ui.Label; -import com.vaadin.ui.declarative.DesignContext; - -/** - * Test case for writing CssLayout to design - * - * @author Vaadin Ltd - */ -public class TestWriteDesign extends TestCase { - - public void testSynchronizeEmptyLayout() { - CssLayout layout = new CssLayout(); - layout.setCaption("changed-caption"); - Element design = createDesign(); - layout.writeDesign(design, createDesignContext()); - assertEquals(0, design.childNodes().size()); - assertEquals("changed-caption", design.attr("caption")); - } - - public void testSynchronizeLayoutWithChildren() { - CssLayout layout = new CssLayout(); - layout.addComponent(new Label("test-label")); - layout.getComponent(0).setCaption("test-caption"); - layout.addComponent(new Label("test-label-2")); - Element design = createDesign(); - layout.writeDesign(design, createDesignContext()); - assertEquals(2, design.childNodes().size()); - assertEquals("v-label", ((Element) design.childNode(0)).tagName()); - assertEquals("test-caption", design.childNode(0).attr("caption")); - } - - private Element createDesign() { - // make sure that the design node has old content that should be removed - Attributes rootAttributes = new Attributes(); - rootAttributes.put("caption", "test-layout"); - Element node = new Element(Tag.valueOf("v-vertical-layout"), "", - rootAttributes); - Attributes firstChildAttributes = new Attributes(); - firstChildAttributes.put("caption", "test-label"); - Element firstChild = new Element(Tag.valueOf("v-label"), "", - firstChildAttributes); - node.appendChild(firstChild); - - Element secondChild = new Element(Tag.valueOf("v-button"), "", - new Attributes()); - secondChild.html("test-button"); - node.appendChild(secondChild); - return node; - } - - private DesignContext createDesignContext() { - return new DesignContext(); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/csslayout/WriteDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/csslayout/WriteDesignTest.java new file mode 100644 index 0000000000..0fdb1c8335 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/csslayout/WriteDesignTest.java @@ -0,0 +1,78 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.csslayout; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Attributes; +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; + +import com.vaadin.ui.CssLayout; +import com.vaadin.ui.Label; +import com.vaadin.ui.declarative.DesignContext; + +/** + * Test case for writing CssLayout to design + * + * @author Vaadin Ltd + */ +public class WriteDesignTest extends TestCase { + + public void testSynchronizeEmptyLayout() { + CssLayout layout = new CssLayout(); + layout.setCaption("changed-caption"); + Element design = createDesign(); + layout.writeDesign(design, createDesignContext()); + assertEquals(0, design.childNodes().size()); + assertEquals("changed-caption", design.attr("caption")); + } + + public void testSynchronizeLayoutWithChildren() { + CssLayout layout = new CssLayout(); + layout.addComponent(new Label("test-label")); + layout.getComponent(0).setCaption("test-caption"); + layout.addComponent(new Label("test-label-2")); + Element design = createDesign(); + layout.writeDesign(design, createDesignContext()); + assertEquals(2, design.childNodes().size()); + assertEquals("v-label", ((Element) design.childNode(0)).tagName()); + assertEquals("test-caption", design.childNode(0).attr("caption")); + } + + private Element createDesign() { + // make sure that the design node has old content that should be removed + Attributes rootAttributes = new Attributes(); + rootAttributes.put("caption", "test-layout"); + Element node = new Element(Tag.valueOf("v-vertical-layout"), "", + rootAttributes); + Attributes firstChildAttributes = new Attributes(); + firstChildAttributes.put("caption", "test-label"); + Element firstChild = new Element(Tag.valueOf("v-label"), "", + firstChildAttributes); + node.appendChild(firstChild); + + Element secondChild = new Element(Tag.valueOf("v-button"), "", + new Attributes()); + secondChild.html("test-button"); + node.appendChild(secondChild); + return node; + } + + private DesignContext createDesignContext() { + return new DesignContext(); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/datefield/DateFieldListeners.java b/server/tests/src/com/vaadin/tests/server/component/datefield/DateFieldListeners.java deleted file mode 100644 index 0f4aee35c7..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/datefield/DateFieldListeners.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.vaadin.tests.server.component.datefield; - -import com.vaadin.event.FieldEvents.BlurEvent; -import com.vaadin.event.FieldEvents.BlurListener; -import com.vaadin.event.FieldEvents.FocusEvent; -import com.vaadin.event.FieldEvents.FocusListener; -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; -import com.vaadin.ui.DateField; - -public class DateFieldListeners extends AbstractListenerMethodsTest { - public void testFocusListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(DateField.class, FocusEvent.class, - FocusListener.class); - } - - public void testBlurListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(DateField.class, BlurEvent.class, - BlurListener.class); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/datefield/DateFieldListenersTest.java b/server/tests/src/com/vaadin/tests/server/component/datefield/DateFieldListenersTest.java new file mode 100644 index 0000000000..6d774366a9 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/datefield/DateFieldListenersTest.java @@ -0,0 +1,20 @@ +package com.vaadin.tests.server.component.datefield; + +import com.vaadin.event.FieldEvents.BlurEvent; +import com.vaadin.event.FieldEvents.BlurListener; +import com.vaadin.event.FieldEvents.FocusEvent; +import com.vaadin.event.FieldEvents.FocusListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; +import com.vaadin.ui.DateField; + +public class DateFieldListenersTest extends AbstractListenerMethodsTestBase { + public void testFocusListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(DateField.class, FocusEvent.class, + FocusListener.class); + } + + public void testBlurListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(DateField.class, BlurEvent.class, + BlurListener.class); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/embedded/EmbeddedListeners.java b/server/tests/src/com/vaadin/tests/server/component/embedded/EmbeddedListeners.java deleted file mode 100644 index 7512f0f499..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/embedded/EmbeddedListeners.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.vaadin.tests.server.component.embedded; - -import com.vaadin.event.MouseEvents.ClickEvent; -import com.vaadin.event.MouseEvents.ClickListener; -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; -import com.vaadin.ui.Embedded; - -public class EmbeddedListeners extends AbstractListenerMethodsTest { - public void testClickListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(Embedded.class, ClickEvent.class, - ClickListener.class); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/embedded/EmbeddedListenersTest.java b/server/tests/src/com/vaadin/tests/server/component/embedded/EmbeddedListenersTest.java new file mode 100644 index 0000000000..b41d5e9e13 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/embedded/EmbeddedListenersTest.java @@ -0,0 +1,13 @@ +package com.vaadin.tests.server.component.embedded; + +import com.vaadin.event.MouseEvents.ClickEvent; +import com.vaadin.event.MouseEvents.ClickListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; +import com.vaadin.ui.Embedded; + +public class EmbeddedListenersTest extends AbstractListenerMethodsTestBase { + public void testClickListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Embedded.class, ClickEvent.class, + ClickListener.class); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/fieldgroup/CaseInsensitiveBinding.java b/server/tests/src/com/vaadin/tests/server/component/fieldgroup/CaseInsensitiveBinding.java deleted file mode 100644 index ea34d8b04e..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/fieldgroup/CaseInsensitiveBinding.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.vaadin.tests.server.component.fieldgroup; - -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -import com.vaadin.data.fieldgroup.FieldGroup; -import com.vaadin.data.util.ObjectProperty; -import com.vaadin.data.util.PropertysetItem; -import com.vaadin.ui.FormLayout; -import com.vaadin.ui.TextField; - -public class CaseInsensitiveBinding { - - @Test - public void caseInsensitivityAndUnderscoreRemoval() { - PropertysetItem item = new PropertysetItem(); - item.addItemProperty("LastName", new ObjectProperty("Sparrow")); - - class MyForm extends FormLayout { - TextField lastName = new TextField("Last name"); - - public MyForm() { - - // Should bind to the LastName property - addComponent(lastName); - } - } - - MyForm form = new MyForm(); - - FieldGroup binder = new FieldGroup(item); - binder.bindMemberFields(form); - - assertTrue("Sparrow".equals(form.lastName.getValue())); - } - - @Test - public void UnderscoreRemoval() { - PropertysetItem item = new PropertysetItem(); - item.addItemProperty("first_name", new ObjectProperty("Jack")); - - class MyForm extends FormLayout { - TextField firstName = new TextField("First name"); - - public MyForm() { - // Should bind to the first_name property - addComponent(firstName); - } - } - - MyForm form = new MyForm(); - - FieldGroup binder = new FieldGroup(item); - binder.bindMemberFields(form); - - assertTrue("Jack".equals(form.firstName.getValue())); - } - - @Test - public void perfectMatchPriority() { - PropertysetItem item = new PropertysetItem(); - item.addItemProperty("first_name", new ObjectProperty( - "Not this")); - item.addItemProperty("firstName", new ObjectProperty("This")); - - class MyForm extends FormLayout { - TextField firstName = new TextField("First name"); - - public MyForm() { - // should bind to the firstName property, not first_name - // property - addComponent(firstName); - } - } - - MyForm form = new MyForm(); - - FieldGroup binder = new FieldGroup(item); - binder.bindMemberFields(form); - - assertTrue("This".equals(form.firstName.getValue())); - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/component/fieldgroup/CaseInsensitiveBindingTest.java b/server/tests/src/com/vaadin/tests/server/component/fieldgroup/CaseInsensitiveBindingTest.java new file mode 100644 index 0000000000..cb29a84aa8 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/fieldgroup/CaseInsensitiveBindingTest.java @@ -0,0 +1,85 @@ +package com.vaadin.tests.server.component.fieldgroup; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.vaadin.data.fieldgroup.FieldGroup; +import com.vaadin.data.util.ObjectProperty; +import com.vaadin.data.util.PropertysetItem; +import com.vaadin.ui.FormLayout; +import com.vaadin.ui.TextField; + +public class CaseInsensitiveBindingTest { + + @Test + public void caseInsensitivityAndUnderscoreRemoval() { + PropertysetItem item = new PropertysetItem(); + item.addItemProperty("LastName", new ObjectProperty("Sparrow")); + + class MyForm extends FormLayout { + TextField lastName = new TextField("Last name"); + + public MyForm() { + + // Should bind to the LastName property + addComponent(lastName); + } + } + + MyForm form = new MyForm(); + + FieldGroup binder = new FieldGroup(item); + binder.bindMemberFields(form); + + assertTrue("Sparrow".equals(form.lastName.getValue())); + } + + @Test + public void UnderscoreRemoval() { + PropertysetItem item = new PropertysetItem(); + item.addItemProperty("first_name", new ObjectProperty("Jack")); + + class MyForm extends FormLayout { + TextField firstName = new TextField("First name"); + + public MyForm() { + // Should bind to the first_name property + addComponent(firstName); + } + } + + MyForm form = new MyForm(); + + FieldGroup binder = new FieldGroup(item); + binder.bindMemberFields(form); + + assertTrue("Jack".equals(form.firstName.getValue())); + } + + @Test + public void perfectMatchPriority() { + PropertysetItem item = new PropertysetItem(); + item.addItemProperty("first_name", new ObjectProperty( + "Not this")); + item.addItemProperty("firstName", new ObjectProperty("This")); + + class MyForm extends FormLayout { + TextField firstName = new TextField("First name"); + + public MyForm() { + // should bind to the firstName property, not first_name + // property + addComponent(firstName); + } + } + + MyForm form = new MyForm(); + + FieldGroup binder = new FieldGroup(item); + binder.bindMemberFields(form); + + assertTrue("This".equals(form.firstName.getValue())); + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/component/fieldgroup/FieldNamedDescription.java b/server/tests/src/com/vaadin/tests/server/component/fieldgroup/FieldNamedDescription.java deleted file mode 100644 index 033f1458e8..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/fieldgroup/FieldNamedDescription.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.vaadin.tests.server.component.fieldgroup; - -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -import com.vaadin.data.fieldgroup.FieldGroup; -import com.vaadin.data.fieldgroup.PropertyId; -import com.vaadin.data.util.ObjectProperty; -import com.vaadin.data.util.PropertysetItem; -import com.vaadin.ui.FormLayout; -import com.vaadin.ui.TextField; - -public class FieldNamedDescription { - - @Test - public void bindReadOnlyPropertyToFieldGroup() { - // Create an item - PropertysetItem item = new PropertysetItem(); - item.addItemProperty("name", new ObjectProperty("Zaphod")); - item.addItemProperty("description", new ObjectProperty( - "This is a description")); - - // Define a form as a class that extends some layout - class MyForm extends FormLayout { - // Member that will bind to the "name" property - TextField name = new TextField("Name"); - - // This member will not bind to the desctiptionProperty as the name - // description conflicts with something in the binding process - @PropertyId("description") - TextField description = new TextField("Description"); - - public MyForm() { - - // Add the fields - addComponent(name); - addComponent(description); - } - } - - // Create one - MyForm form = new MyForm(); - - // Now create a binder that can also creates the fields - // using the default field factory - FieldGroup binder = new FieldGroup(item); - binder.bindMemberFields(form); - - assertTrue(form.description.getValue().equals("This is a description")); - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/component/fieldgroup/FieldNamedDescriptionTest.java b/server/tests/src/com/vaadin/tests/server/component/fieldgroup/FieldNamedDescriptionTest.java new file mode 100644 index 0000000000..029dcc66a3 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/fieldgroup/FieldNamedDescriptionTest.java @@ -0,0 +1,53 @@ +package com.vaadin.tests.server.component.fieldgroup; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.vaadin.data.fieldgroup.FieldGroup; +import com.vaadin.data.fieldgroup.PropertyId; +import com.vaadin.data.util.ObjectProperty; +import com.vaadin.data.util.PropertysetItem; +import com.vaadin.ui.FormLayout; +import com.vaadin.ui.TextField; + +public class FieldNamedDescriptionTest { + + @Test + public void bindReadOnlyPropertyToFieldGroup() { + // Create an item + PropertysetItem item = new PropertysetItem(); + item.addItemProperty("name", new ObjectProperty("Zaphod")); + item.addItemProperty("description", new ObjectProperty( + "This is a description")); + + // Define a form as a class that extends some layout + class MyForm extends FormLayout { + // Member that will bind to the "name" property + TextField name = new TextField("Name"); + + // This member will not bind to the desctiptionProperty as the name + // description conflicts with something in the binding process + @PropertyId("description") + TextField description = new TextField("Description"); + + public MyForm() { + + // Add the fields + addComponent(name); + addComponent(description); + } + } + + // Create one + MyForm form = new MyForm(); + + // Now create a binder that can also creates the fields + // using the default field factory + FieldGroup binder = new FieldGroup(item); + binder.bindMemberFields(form); + + assertTrue(form.description.getValue().equals("This is a description")); + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/component/gridlayout/DefaultAlignment.java b/server/tests/src/com/vaadin/tests/server/component/gridlayout/DefaultAlignment.java deleted file mode 100644 index 244f1f9e45..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/gridlayout/DefaultAlignment.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.vaadin.tests.server.component.gridlayout; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.vaadin.ui.Alignment; -import com.vaadin.ui.GridLayout; -import com.vaadin.ui.Label; -import com.vaadin.ui.TextField; - -public class DefaultAlignment { - - private GridLayout gridLayout; - - @Before - public void setup() { - gridLayout = new GridLayout(2, 2); - } - - @Test - public void testDefaultAlignment() { - Label label = new Label("A label"); - TextField tf = new TextField("A TextField"); - gridLayout.addComponent(label); - gridLayout.addComponent(tf); - Assert.assertEquals(Alignment.TOP_LEFT, - gridLayout.getComponentAlignment(label)); - Assert.assertEquals(Alignment.TOP_LEFT, - gridLayout.getComponentAlignment(tf)); - } - - @Test - public void testAlteredDefaultAlignment() { - Label label = new Label("A label"); - TextField tf = new TextField("A TextField"); - gridLayout.setDefaultComponentAlignment(Alignment.MIDDLE_CENTER); - gridLayout.addComponent(label); - gridLayout.addComponent(tf); - Assert.assertEquals(Alignment.MIDDLE_CENTER, - gridLayout.getComponentAlignment(label)); - Assert.assertEquals(Alignment.MIDDLE_CENTER, - gridLayout.getComponentAlignment(tf)); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/gridlayout/DefaultAlignmentTest.java b/server/tests/src/com/vaadin/tests/server/component/gridlayout/DefaultAlignmentTest.java new file mode 100644 index 0000000000..9b6368474f --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/gridlayout/DefaultAlignmentTest.java @@ -0,0 +1,45 @@ +package com.vaadin.tests.server.component.gridlayout; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.vaadin.ui.Alignment; +import com.vaadin.ui.GridLayout; +import com.vaadin.ui.Label; +import com.vaadin.ui.TextField; + +public class DefaultAlignmentTest { + + private GridLayout gridLayout; + + @Before + public void setup() { + gridLayout = new GridLayout(2, 2); + } + + @Test + public void testDefaultAlignment() { + Label label = new Label("A label"); + TextField tf = new TextField("A TextField"); + gridLayout.addComponent(label); + gridLayout.addComponent(tf); + Assert.assertEquals(Alignment.TOP_LEFT, + gridLayout.getComponentAlignment(label)); + Assert.assertEquals(Alignment.TOP_LEFT, + gridLayout.getComponentAlignment(tf)); + } + + @Test + public void testAlteredDefaultAlignment() { + Label label = new Label("A label"); + TextField tf = new TextField("A TextField"); + gridLayout.setDefaultComponentAlignment(Alignment.MIDDLE_CENTER); + gridLayout.addComponent(label); + gridLayout.addComponent(tf); + Assert.assertEquals(Alignment.MIDDLE_CENTER, + gridLayout.getComponentAlignment(label)); + Assert.assertEquals(Alignment.MIDDLE_CENTER, + gridLayout.getComponentAlignment(tf)); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/gridlayout/GridLayoutListeners.java b/server/tests/src/com/vaadin/tests/server/component/gridlayout/GridLayoutListeners.java deleted file mode 100644 index ce3a9faa65..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/gridlayout/GridLayoutListeners.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.vaadin.tests.server.component.gridlayout; - -import com.vaadin.event.LayoutEvents.LayoutClickEvent; -import com.vaadin.event.LayoutEvents.LayoutClickListener; -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; -import com.vaadin.ui.GridLayout; - -public class GridLayoutListeners extends AbstractListenerMethodsTest { - public void testLayoutClickListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(GridLayout.class, LayoutClickEvent.class, - LayoutClickListener.class); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/gridlayout/GridLayoutListenersTest.java b/server/tests/src/com/vaadin/tests/server/component/gridlayout/GridLayoutListenersTest.java new file mode 100644 index 0000000000..ed18a24608 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/gridlayout/GridLayoutListenersTest.java @@ -0,0 +1,13 @@ +package com.vaadin.tests.server.component.gridlayout; + +import com.vaadin.event.LayoutEvents.LayoutClickEvent; +import com.vaadin.event.LayoutEvents.LayoutClickListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; +import com.vaadin.ui.GridLayout; + +public class GridLayoutListenersTest extends AbstractListenerMethodsTestBase { + public void testLayoutClickListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(GridLayout.class, LayoutClickEvent.class, + LayoutClickListener.class); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/label/LabelConverters.java b/server/tests/src/com/vaadin/tests/server/component/label/LabelConverters.java deleted file mode 100644 index e6cecee1bf..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/label/LabelConverters.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.label; - -import junit.framework.TestCase; - -import com.vaadin.data.Property; -import com.vaadin.data.util.MethodProperty; -import com.vaadin.server.VaadinSession; -import com.vaadin.tests.data.bean.Person; -import com.vaadin.tests.util.AlwaysLockedVaadinSession; -import com.vaadin.ui.Label; - -public class LabelConverters extends TestCase { - - public void testLabelSetDataSourceLaterOn() { - Person p = Person.createTestPerson1(); - Label l = new Label("My label"); - assertEquals("My label", l.getValue()); - assertNull(l.getConverter()); - l.setPropertyDataSource(new MethodProperty(p, "firstName")); - assertEquals(p.getFirstName(), l.getValue()); - p.setFirstName("123"); - assertEquals("123", l.getValue()); - } - - public void testIntegerDataSource() { - VaadinSession.setCurrent(new AlwaysLockedVaadinSession(null)); - Label l = new Label("Foo"); - Property ds = new MethodProperty(Person.createTestPerson1(), - "age"); - l.setPropertyDataSource(ds); - assertEquals(String.valueOf(Person.createTestPerson1().getAge()), - l.getValue()); - } - - public void testSetValueWithDataSource() { - try { - MethodProperty property = new MethodProperty( - Person.createTestPerson1(), "firstName"); - Label l = new Label(property); - l.setValue("Foo"); - fail("setValue should throw an exception when a data source is set"); - } catch (Exception e) { - } - - } - - public void testLabelWithoutDataSource() { - Label l = new Label("My label"); - assertEquals("My label", l.getValue()); - assertNull(l.getConverter()); - assertNull(l.getPropertyDataSource()); - l.setValue("New value"); - assertEquals("New value", l.getValue()); - assertNull(l.getConverter()); - assertNull(l.getPropertyDataSource()); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/label/LabelConvertersTest.java b/server/tests/src/com/vaadin/tests/server/component/label/LabelConvertersTest.java new file mode 100644 index 0000000000..7e65e6a044 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/label/LabelConvertersTest.java @@ -0,0 +1,72 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.label; + +import junit.framework.TestCase; + +import com.vaadin.data.Property; +import com.vaadin.data.util.MethodProperty; +import com.vaadin.server.VaadinSession; +import com.vaadin.tests.data.bean.Person; +import com.vaadin.tests.util.AlwaysLockedVaadinSession; +import com.vaadin.ui.Label; + +public class LabelConvertersTest extends TestCase { + + public void testLabelSetDataSourceLaterOn() { + Person p = Person.createTestPerson1(); + Label l = new Label("My label"); + assertEquals("My label", l.getValue()); + assertNull(l.getConverter()); + l.setPropertyDataSource(new MethodProperty(p, "firstName")); + assertEquals(p.getFirstName(), l.getValue()); + p.setFirstName("123"); + assertEquals("123", l.getValue()); + } + + public void testIntegerDataSource() { + VaadinSession.setCurrent(new AlwaysLockedVaadinSession(null)); + Label l = new Label("Foo"); + Property ds = new MethodProperty(Person.createTestPerson1(), + "age"); + l.setPropertyDataSource(ds); + assertEquals(String.valueOf(Person.createTestPerson1().getAge()), + l.getValue()); + } + + public void testSetValueWithDataSource() { + try { + MethodProperty property = new MethodProperty( + Person.createTestPerson1(), "firstName"); + Label l = new Label(property); + l.setValue("Foo"); + fail("setValue should throw an exception when a data source is set"); + } catch (Exception e) { + } + + } + + public void testLabelWithoutDataSource() { + Label l = new Label("My label"); + assertEquals("My label", l.getValue()); + assertNull(l.getConverter()); + assertNull(l.getPropertyDataSource()); + l.setValue("New value"); + assertEquals("New value", l.getValue()); + assertNull(l.getConverter()); + assertNull(l.getPropertyDataSource()); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/label/LabelListeners.java b/server/tests/src/com/vaadin/tests/server/component/label/LabelListeners.java deleted file mode 100644 index 9bb4c53ba2..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/label/LabelListeners.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.vaadin.tests.server.component.label; - -import static org.easymock.EasyMock.anyObject; -import static org.easymock.EasyMock.createStrictMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; - -import org.easymock.EasyMock; - -import com.vaadin.data.Property; -import com.vaadin.data.Property.ValueChangeListener; -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; -import com.vaadin.ui.Label; -import com.vaadin.ui.Label.ValueChangeEvent; - -public class LabelListeners extends AbstractListenerMethodsTest { - public void testValueChangeListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(Label.class, ValueChangeEvent.class, - ValueChangeListener.class); - } - - public void testValueChangeFiredWhenSettingValue() { - Label underTest = new Label(); - - // setup the mock listener - ValueChangeListener mockListener = createStrictMock(ValueChangeListener.class); - // record - mockListener - .valueChange(anyObject(com.vaadin.data.Property.ValueChangeEvent.class)); - - // test - underTest.addValueChangeListener(mockListener); - - replay(mockListener); - underTest.setValue("A new value"); - - verify(mockListener); - - } - - public void testValueChangeFiredWhenSettingPropertyDataSource() { - // setup - Label underTest = new Label(); - - Property mockProperty = EasyMock.createMock(Property.class); - - ValueChangeListener mockListener = createStrictMock(ValueChangeListener.class); - // record - mockListener - .valueChange(anyObject(com.vaadin.data.Property.ValueChangeEvent.class)); - - expect(mockProperty.getType()).andReturn(String.class).atLeastOnce(); - expect(mockProperty.getValue()).andReturn("Any").atLeastOnce(); - - // test - - replay(mockListener, mockProperty); - underTest.addValueChangeListener(mockListener); - underTest.setPropertyDataSource(mockProperty); - - verify(mockListener); - - } - - public void testValueChangeNotFiredWhenNotSettingValue() { - Label underTest = new Label(); - // setup the mock listener - ValueChangeListener mockListener = createStrictMock(ValueChangeListener.class); - // record: nothing to record - - // test - underTest.addValueChangeListener(mockListener); - replay(mockListener); - verify(mockListener); - } - - public void testNoValueChangeFiredWhenSettingPropertyDataSourceToNull() { - Label underTest = new Label(); - // setup the mock Listener - ValueChangeListener mockListener = createStrictMock(ValueChangeListener.class); - // record: nothing to record - - // test - underTest.addValueChangeListener(mockListener); - underTest.setPropertyDataSource(null); - - replay(mockListener); - verify(mockListener); - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/component/label/LabelListenersTest.java b/server/tests/src/com/vaadin/tests/server/component/label/LabelListenersTest.java new file mode 100644 index 0000000000..4287d58d9c --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/label/LabelListenersTest.java @@ -0,0 +1,92 @@ +package com.vaadin.tests.server.component.label; + +import static org.easymock.EasyMock.anyObject; +import static org.easymock.EasyMock.createStrictMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; + +import org.easymock.EasyMock; + +import com.vaadin.data.Property; +import com.vaadin.data.Property.ValueChangeListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; +import com.vaadin.ui.Label; +import com.vaadin.ui.Label.ValueChangeEvent; + +public class LabelListenersTest extends AbstractListenerMethodsTestBase { + public void testValueChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Label.class, ValueChangeEvent.class, + ValueChangeListener.class); + } + + public void testValueChangeFiredWhenSettingValue() { + Label underTest = new Label(); + + // setup the mock listener + ValueChangeListener mockListener = createStrictMock(ValueChangeListener.class); + // record + mockListener + .valueChange(anyObject(com.vaadin.data.Property.ValueChangeEvent.class)); + + // test + underTest.addValueChangeListener(mockListener); + + replay(mockListener); + underTest.setValue("A new value"); + + verify(mockListener); + + } + + public void testValueChangeFiredWhenSettingPropertyDataSource() { + // setup + Label underTest = new Label(); + + Property mockProperty = EasyMock.createMock(Property.class); + + ValueChangeListener mockListener = createStrictMock(ValueChangeListener.class); + // record + mockListener + .valueChange(anyObject(com.vaadin.data.Property.ValueChangeEvent.class)); + + expect(mockProperty.getType()).andReturn(String.class).atLeastOnce(); + expect(mockProperty.getValue()).andReturn("Any").atLeastOnce(); + + // test + + replay(mockListener, mockProperty); + underTest.addValueChangeListener(mockListener); + underTest.setPropertyDataSource(mockProperty); + + verify(mockListener); + + } + + public void testValueChangeNotFiredWhenNotSettingValue() { + Label underTest = new Label(); + // setup the mock listener + ValueChangeListener mockListener = createStrictMock(ValueChangeListener.class); + // record: nothing to record + + // test + underTest.addValueChangeListener(mockListener); + replay(mockListener); + verify(mockListener); + } + + public void testNoValueChangeFiredWhenSettingPropertyDataSourceToNull() { + Label underTest = new Label(); + // setup the mock Listener + ValueChangeListener mockListener = createStrictMock(ValueChangeListener.class); + // record: nothing to record + + // test + underTest.addValueChangeListener(mockListener); + underTest.setPropertyDataSource(null); + + replay(mockListener); + verify(mockListener); + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/component/label/ReadDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/label/ReadDesignTest.java new file mode 100644 index 0000000000..9ccaf43398 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/label/ReadDesignTest.java @@ -0,0 +1,102 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.label; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Attributes; +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; +import org.junit.Test; + +import com.vaadin.ui.Label; +import com.vaadin.ui.declarative.DesignContext; + +/** + * + * Test case for reading the contents of a Label from a design. + * + */ +public class ReadDesignTest extends TestCase { + + private DesignContext ctx; + + @Override + protected void setUp() throws Exception { + super.setUp(); + ctx = new DesignContext(); + } + + @Test + public void testWithContent() { + createAndTestLabel("A label", null); + } + + @Test + public void testWithHtmlContent() { + createAndTestLabel("A label", null); + } + + @Test + public void testWithContentAndCaption() { + createAndTestLabel("A label", "This is a label"); + } + + @Test + public void testWithCaption() { + createAndTestLabel(null, "This is a label"); + } + + @Test + public void testWithoutContentAndCaption() { + createAndTestLabel(null, null); + } + + /* + * Test creating a Label. A Label can have both caption and content. + */ + private void createAndTestLabel(String content, String caption) { + Element e = createElement("v-label", content, caption); + Label l = (Label) ctx.readDesign(e); + if (content != null) { + assertEquals("The label has wrong text content.", content, + l.getValue()); + } else { + assertTrue("The label has wrong text content.", + l.getValue() == null || "".equals(l.getValue())); + } + if (caption != null) { + assertEquals("The label has wrong caption.", caption, + l.getCaption()); + } else { + assertTrue("The label has wrong caption.", l.getCaption() == null + || "".equals(l.getCaption())); + } + } + + private Element createElement(String elementName, String content, + String caption) { + Attributes attributes = new Attributes(); + if (caption != null) { + attributes.put("caption", caption); + } + Element node = new Element(Tag.valueOf(elementName), "", attributes); + if (content != null) { + node.html(content); + } + return node; + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/label/TestReadDesign.java b/server/tests/src/com/vaadin/tests/server/component/label/TestReadDesign.java deleted file mode 100644 index 3e577b5578..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/label/TestReadDesign.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.label; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Attributes; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; -import org.junit.Test; - -import com.vaadin.ui.Label; -import com.vaadin.ui.declarative.DesignContext; - -/** - * - * Test case for reading the contents of a Label from a design. - * - */ -public class TestReadDesign extends TestCase { - - private DesignContext ctx; - - @Override - protected void setUp() throws Exception { - super.setUp(); - ctx = new DesignContext(); - } - - @Test - public void testWithContent() { - createAndTestLabel("A label", null); - } - - @Test - public void testWithHtmlContent() { - createAndTestLabel("A label", null); - } - - @Test - public void testWithContentAndCaption() { - createAndTestLabel("A label", "This is a label"); - } - - @Test - public void testWithCaption() { - createAndTestLabel(null, "This is a label"); - } - - @Test - public void testWithoutContentAndCaption() { - createAndTestLabel(null, null); - } - - /* - * Test creating a Label. A Label can have both caption and content. - */ - private void createAndTestLabel(String content, String caption) { - Element e = createElement("v-label", content, caption); - Label l = (Label) ctx.readDesign(e); - if (content != null) { - assertEquals("The label has wrong text content.", content, - l.getValue()); - } else { - assertTrue("The label has wrong text content.", - l.getValue() == null || "".equals(l.getValue())); - } - if (caption != null) { - assertEquals("The label has wrong caption.", caption, - l.getCaption()); - } else { - assertTrue("The label has wrong caption.", l.getCaption() == null - || "".equals(l.getCaption())); - } - } - - private Element createElement(String elementName, String content, - String caption) { - Attributes attributes = new Attributes(); - if (caption != null) { - attributes.put("caption", caption); - } - Element node = new Element(Tag.valueOf(elementName), "", attributes); - if (content != null) { - node.html(content); - } - return node; - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/label/TestWriteDesign.java b/server/tests/src/com/vaadin/tests/server/component/label/TestWriteDesign.java deleted file mode 100644 index 3368a7d22e..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/label/TestWriteDesign.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.label; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Attributes; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; -import org.junit.Test; - -import com.vaadin.shared.ui.label.ContentMode; -import com.vaadin.ui.Label; -import com.vaadin.ui.declarative.DesignContext; - -/** - * Tests generating an html tree node corresponding to a Label. - */ -public class TestWriteDesign extends TestCase { - - private DesignContext ctx; - - @Override - protected void setUp() throws Exception { - super.setUp(); - ctx = new DesignContext(); - } - - @Test - public void testWithContent() { - createAndTestLabel("A label", null); - } - - @Test - public void testWithHtmlContent() { - createAndTestLabel("A label", null); - } - - @Test - public void testWithCaption() { - createAndTestLabel(null, "Label caption"); - } - - @Test - public void testWithContentAndCaption() { - createAndTestLabel("A label", "Label caption"); - } - - @Test - public void testContentModeText() { - Label l = new Label("plain text label"); - Element e = new Element(Tag.valueOf("v-label"), "", new Attributes()); - l.writeDesign(e, ctx); - assertTrue("Label should be marked as plain text", - e.hasAttr("plain-text")); - } - - @Test - public void testContentModeHtml() { - Label l = new Label("html label"); - l.setContentMode(ContentMode.HTML); - - Element e = new Element(Tag.valueOf("v-label"), "", new Attributes()); - l.writeDesign(e, ctx); - assertFalse("Label should not be marked as plain text", - e.hasAttr("plain-text")); - } - - @Test - public void testChangeContentMode() { - Label l = new Label("html label"); - l.setContentMode(ContentMode.HTML); - - Element e = new Element(Tag.valueOf("v-label"), "", new Attributes()); - l.writeDesign(e, ctx); - - assertFalse("Label should not be marked as plain text", - e.hasAttr("plain-text")); - l.setContentMode(ContentMode.TEXT); - l.writeDesign(e, ctx); - - assertTrue("Label should be marked as plain text", - e.hasAttr("plain-text")); - } - - @Test - public void testWithoutContentAndCaption() { - createAndTestLabel(null, null); - } - - private void createAndTestLabel(String content, String caption) { - Label l = new Label(content); - if (caption != null) { - l.setCaption(caption); - } - Element e = ctx.createElement(l); - assertEquals("Wrong tag name for label.", "v-label", e.tagName()); - if (content != null) { - assertEquals("Unexpected content in the v-label element.", content, - e.html()); - } else { - assertTrue("Unexpected content in the v-label element.", - e.html() == null || "".equals(e.html())); - } - if (caption != null) { - assertEquals("Wrong caption in the v-label element.", caption, - e.attr("caption")); - } else { - assertTrue("Unexpected caption in the v-label element.", - e.attr("caption") == null || "".equals(e.attr("caption"))); - } - } -} \ No newline at end of file diff --git a/server/tests/src/com/vaadin/tests/server/component/label/WriteDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/label/WriteDesignTest.java new file mode 100644 index 0000000000..3d13767d35 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/label/WriteDesignTest.java @@ -0,0 +1,126 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.label; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Attributes; +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; +import org.junit.Test; + +import com.vaadin.shared.ui.label.ContentMode; +import com.vaadin.ui.Label; +import com.vaadin.ui.declarative.DesignContext; + +/** + * Tests generating an html tree node corresponding to a Label. + */ +public class WriteDesignTest extends TestCase { + + private DesignContext ctx; + + @Override + protected void setUp() throws Exception { + super.setUp(); + ctx = new DesignContext(); + } + + @Test + public void testWithContent() { + createAndTestLabel("A label", null); + } + + @Test + public void testWithHtmlContent() { + createAndTestLabel("A label", null); + } + + @Test + public void testWithCaption() { + createAndTestLabel(null, "Label caption"); + } + + @Test + public void testWithContentAndCaption() { + createAndTestLabel("A label", "Label caption"); + } + + @Test + public void testContentModeText() { + Label l = new Label("plain text label"); + Element e = new Element(Tag.valueOf("v-label"), "", new Attributes()); + l.writeDesign(e, ctx); + assertTrue("Label should be marked as plain text", + e.hasAttr("plain-text")); + } + + @Test + public void testContentModeHtml() { + Label l = new Label("html label"); + l.setContentMode(ContentMode.HTML); + + Element e = new Element(Tag.valueOf("v-label"), "", new Attributes()); + l.writeDesign(e, ctx); + assertFalse("Label should not be marked as plain text", + e.hasAttr("plain-text")); + } + + @Test + public void testChangeContentMode() { + Label l = new Label("html label"); + l.setContentMode(ContentMode.HTML); + + Element e = new Element(Tag.valueOf("v-label"), "", new Attributes()); + l.writeDesign(e, ctx); + + assertFalse("Label should not be marked as plain text", + e.hasAttr("plain-text")); + l.setContentMode(ContentMode.TEXT); + l.writeDesign(e, ctx); + + assertTrue("Label should be marked as plain text", + e.hasAttr("plain-text")); + } + + @Test + public void testWithoutContentAndCaption() { + createAndTestLabel(null, null); + } + + private void createAndTestLabel(String content, String caption) { + Label l = new Label(content); + if (caption != null) { + l.setCaption(caption); + } + Element e = ctx.createElement(l); + assertEquals("Wrong tag name for label.", "v-label", e.tagName()); + if (content != null) { + assertEquals("Unexpected content in the v-label element.", content, + e.html()); + } else { + assertTrue("Unexpected content in the v-label element.", + e.html() == null || "".equals(e.html())); + } + if (caption != null) { + assertEquals("Wrong caption in the v-label element.", caption, + e.attr("caption")); + } else { + assertTrue("Unexpected caption in the v-label element.", + e.attr("caption") == null || "".equals(e.attr("caption"))); + } + } +} \ No newline at end of file diff --git a/server/tests/src/com/vaadin/tests/server/component/loginform/LoginFormListeners.java b/server/tests/src/com/vaadin/tests/server/component/loginform/LoginFormListeners.java deleted file mode 100644 index fd3e02994c..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/loginform/LoginFormListeners.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.vaadin.tests.server.component.loginform; - -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; -import com.vaadin.ui.LoginForm; -import com.vaadin.ui.LoginForm.LoginEvent; -import com.vaadin.ui.LoginForm.LoginListener; - -public class LoginFormListeners extends AbstractListenerMethodsTest { - public void testLoginListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(LoginForm.class, LoginEvent.class, - LoginListener.class); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/loginform/LoginFormListenersTest.java b/server/tests/src/com/vaadin/tests/server/component/loginform/LoginFormListenersTest.java new file mode 100644 index 0000000000..1c06d2652a --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/loginform/LoginFormListenersTest.java @@ -0,0 +1,13 @@ +package com.vaadin.tests.server.component.loginform; + +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; +import com.vaadin.ui.LoginForm; +import com.vaadin.ui.LoginForm.LoginEvent; +import com.vaadin.ui.LoginForm.LoginListener; + +public class LoginFormListenersTest extends AbstractListenerMethodsTestBase { + public void testLoginListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(LoginForm.class, LoginEvent.class, + LoginListener.class); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/menubar/MenuBarIds.java b/server/tests/src/com/vaadin/tests/server/component/menubar/MenuBarIds.java deleted file mode 100644 index f304315ebc..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/menubar/MenuBarIds.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.vaadin.tests.server.component.menubar; - -import java.util.HashSet; -import java.util.Set; - -import junit.framework.TestCase; - -import com.vaadin.ui.MenuBar; -import com.vaadin.ui.MenuBar.Command; -import com.vaadin.ui.MenuBar.MenuItem; - -public class MenuBarIds extends TestCase implements Command { - - private MenuItem lastSelectedItem; - private MenuItem menuFile; - private MenuItem menuEdit; - private MenuItem menuEditCopy; - private MenuItem menuEditCut; - private MenuItem menuEditPaste; - private MenuItem menuEditFind; - private MenuItem menuFileOpen; - private MenuItem menuFileSave; - private MenuItem menuFileExit; - private Set menuItems = new HashSet(); - - private MenuBar menuBar; - - @Override - public void setUp() { - menuBar = new MenuBar(); - menuFile = menuBar.addItem("File", this); - menuEdit = menuBar.addItem("Edit", this); - menuEditCopy = menuEdit.addItem("Copy", this); - menuEditCut = menuEdit.addItem("Cut", this); - menuEditPaste = menuEdit.addItem("Paste", this); - menuEdit.addSeparator(); - menuEditFind = menuEdit.addItem("Find...", this); - menuFileOpen = menuFile.addItem("Open", this); - menuFileSave = menuFile.addItem("Save", this); - menuFile.addSeparator(); - menuFileExit = menuFile.addItem("Exit", this); - - menuItems.add(menuFile); - menuItems.add(menuEdit); - menuItems.add(menuEditCopy); - menuItems.add(menuEditCut); - menuItems.add(menuEditPaste); - menuItems.add(menuEditFind); - menuItems.add(menuFileOpen); - menuItems.add(menuFileSave); - menuItems.add(menuFileExit); - } - - public void testMenubarIdUniqueness() { - // Ids within a menubar must be unique - assertUniqueIds(menuBar); - - menuBar.removeItem(menuFile); - MenuItem file2 = menuBar.addItem("File2", this); - MenuItem file3 = menuBar.addItem("File3", this); - MenuItem file2sub = file2.addItem("File2 sub menu", this); - menuItems.add(file2); - menuItems.add(file2sub); - menuItems.add(file3); - - assertUniqueIds(menuBar); - } - - private static void assertUniqueIds(MenuBar menuBar) { - - Set ids = new HashSet(); - - for (MenuItem item : menuBar.getItems()) { - assertUniqueIds(ids, item); - } - } - - private static void assertUniqueIds(Set ids, MenuItem item) { - int id = item.getId(); - System.out.println("Item " + item.getText() + ", id: " + id); - assertFalse(ids.contains(id)); - ids.add(id); - if (item.getChildren() != null) { - for (MenuItem subItem : item.getChildren()) { - assertUniqueIds(ids, subItem); - } - } - } - - @Override - public void menuSelected(MenuItem selectedItem) { - assertNull("lastSelectedItem was not cleared before selecting an item", - lastSelectedItem); - - lastSelectedItem = selectedItem; - - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/menubar/MenuBarIdsTest.java b/server/tests/src/com/vaadin/tests/server/component/menubar/MenuBarIdsTest.java new file mode 100644 index 0000000000..68007bd870 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/menubar/MenuBarIdsTest.java @@ -0,0 +1,98 @@ +package com.vaadin.tests.server.component.menubar; + +import java.util.HashSet; +import java.util.Set; + +import junit.framework.TestCase; + +import com.vaadin.ui.MenuBar; +import com.vaadin.ui.MenuBar.Command; +import com.vaadin.ui.MenuBar.MenuItem; + +public class MenuBarIdsTest extends TestCase implements Command { + + private MenuItem lastSelectedItem; + private MenuItem menuFile; + private MenuItem menuEdit; + private MenuItem menuEditCopy; + private MenuItem menuEditCut; + private MenuItem menuEditPaste; + private MenuItem menuEditFind; + private MenuItem menuFileOpen; + private MenuItem menuFileSave; + private MenuItem menuFileExit; + private Set menuItems = new HashSet(); + + private MenuBar menuBar; + + @Override + public void setUp() { + menuBar = new MenuBar(); + menuFile = menuBar.addItem("File", this); + menuEdit = menuBar.addItem("Edit", this); + menuEditCopy = menuEdit.addItem("Copy", this); + menuEditCut = menuEdit.addItem("Cut", this); + menuEditPaste = menuEdit.addItem("Paste", this); + menuEdit.addSeparator(); + menuEditFind = menuEdit.addItem("Find...", this); + menuFileOpen = menuFile.addItem("Open", this); + menuFileSave = menuFile.addItem("Save", this); + menuFile.addSeparator(); + menuFileExit = menuFile.addItem("Exit", this); + + menuItems.add(menuFile); + menuItems.add(menuEdit); + menuItems.add(menuEditCopy); + menuItems.add(menuEditCut); + menuItems.add(menuEditPaste); + menuItems.add(menuEditFind); + menuItems.add(menuFileOpen); + menuItems.add(menuFileSave); + menuItems.add(menuFileExit); + } + + public void testMenubarIdUniqueness() { + // Ids within a menubar must be unique + assertUniqueIds(menuBar); + + menuBar.removeItem(menuFile); + MenuItem file2 = menuBar.addItem("File2", this); + MenuItem file3 = menuBar.addItem("File3", this); + MenuItem file2sub = file2.addItem("File2 sub menu", this); + menuItems.add(file2); + menuItems.add(file2sub); + menuItems.add(file3); + + assertUniqueIds(menuBar); + } + + private static void assertUniqueIds(MenuBar menuBar) { + + Set ids = new HashSet(); + + for (MenuItem item : menuBar.getItems()) { + assertUniqueIds(ids, item); + } + } + + private static void assertUniqueIds(Set ids, MenuItem item) { + int id = item.getId(); + System.out.println("Item " + item.getText() + ", id: " + id); + assertFalse(ids.contains(id)); + ids.add(id); + if (item.getChildren() != null) { + for (MenuItem subItem : item.getChildren()) { + assertUniqueIds(ids, subItem); + } + } + } + + @Override + public void menuSelected(MenuItem selectedItem) { + assertNull("lastSelectedItem was not cleared before selecting an item", + lastSelectedItem); + + lastSelectedItem = selectedItem; + + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/optiongroup/OptionGroupListeners.java b/server/tests/src/com/vaadin/tests/server/component/optiongroup/OptionGroupListeners.java deleted file mode 100644 index 7eb35c3882..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/optiongroup/OptionGroupListeners.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.vaadin.tests.server.component.optiongroup; - -import com.vaadin.event.FieldEvents.BlurEvent; -import com.vaadin.event.FieldEvents.BlurListener; -import com.vaadin.event.FieldEvents.FocusEvent; -import com.vaadin.event.FieldEvents.FocusListener; -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; -import com.vaadin.ui.OptionGroup; - -public class OptionGroupListeners extends AbstractListenerMethodsTest { - public void testFocusListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(OptionGroup.class, FocusEvent.class, - FocusListener.class); - } - - public void testBlurListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(OptionGroup.class, BlurEvent.class, - BlurListener.class); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/optiongroup/OptionGroupListenersTest.java b/server/tests/src/com/vaadin/tests/server/component/optiongroup/OptionGroupListenersTest.java new file mode 100644 index 0000000000..c2dc175c75 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/optiongroup/OptionGroupListenersTest.java @@ -0,0 +1,20 @@ +package com.vaadin.tests.server.component.optiongroup; + +import com.vaadin.event.FieldEvents.BlurEvent; +import com.vaadin.event.FieldEvents.BlurListener; +import com.vaadin.event.FieldEvents.FocusEvent; +import com.vaadin.event.FieldEvents.FocusListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; +import com.vaadin.ui.OptionGroup; + +public class OptionGroupListenersTest extends AbstractListenerMethodsTestBase { + public void testFocusListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(OptionGroup.class, FocusEvent.class, + FocusListener.class); + } + + public void testBlurListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(OptionGroup.class, BlurEvent.class, + BlurListener.class); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/orderedlayout/DefaultAlignment.java b/server/tests/src/com/vaadin/tests/server/component/orderedlayout/DefaultAlignment.java deleted file mode 100644 index 9497a13c0a..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/orderedlayout/DefaultAlignment.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.vaadin.tests.server.component.orderedlayout; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.vaadin.ui.AbstractOrderedLayout; -import com.vaadin.ui.Alignment; -import com.vaadin.ui.HorizontalLayout; -import com.vaadin.ui.Label; -import com.vaadin.ui.TextField; -import com.vaadin.ui.VerticalLayout; - -public class DefaultAlignment { - - private VerticalLayout verticalLayout; - private HorizontalLayout horizontalLayout; - - @Before - public void setup() { - verticalLayout = new VerticalLayout(); - horizontalLayout = new HorizontalLayout(); - } - - @Test - public void testDefaultAlignmentVerticalLayout() { - testDefaultAlignment(verticalLayout); - } - - @Test - public void testDefaultAlignmentHorizontalLayout() { - testDefaultAlignment(horizontalLayout); - } - - public void testDefaultAlignment(AbstractOrderedLayout layout) { - Label label = new Label("A label"); - TextField tf = new TextField("A TextField"); - layout.addComponent(label); - layout.addComponent(tf); - Assert.assertEquals(Alignment.TOP_LEFT, - layout.getComponentAlignment(label)); - Assert.assertEquals(Alignment.TOP_LEFT, - layout.getComponentAlignment(tf)); - } - - @Test - public void testAlteredDefaultAlignmentVerticalLayout() { - testAlteredDefaultAlignment(verticalLayout); - } - - @Test - public void testAlteredDefaultAlignmentHorizontalLayout() { - testAlteredDefaultAlignment(horizontalLayout); - } - - public void testAlteredDefaultAlignment(AbstractOrderedLayout layout) { - Label label = new Label("A label"); - TextField tf = new TextField("A TextField"); - layout.setDefaultComponentAlignment(Alignment.MIDDLE_CENTER); - layout.addComponent(label); - layout.addComponent(tf); - Assert.assertEquals(Alignment.MIDDLE_CENTER, - layout.getComponentAlignment(label)); - Assert.assertEquals(Alignment.MIDDLE_CENTER, - layout.getComponentAlignment(tf)); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/orderedlayout/DefaultAlignmentTest.java b/server/tests/src/com/vaadin/tests/server/component/orderedlayout/DefaultAlignmentTest.java new file mode 100644 index 0000000000..7560c21adb --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/orderedlayout/DefaultAlignmentTest.java @@ -0,0 +1,67 @@ +package com.vaadin.tests.server.component.orderedlayout; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.vaadin.ui.AbstractOrderedLayout; +import com.vaadin.ui.Alignment; +import com.vaadin.ui.HorizontalLayout; +import com.vaadin.ui.Label; +import com.vaadin.ui.TextField; +import com.vaadin.ui.VerticalLayout; + +public class DefaultAlignmentTest { + + private VerticalLayout verticalLayout; + private HorizontalLayout horizontalLayout; + + @Before + public void setup() { + verticalLayout = new VerticalLayout(); + horizontalLayout = new HorizontalLayout(); + } + + @Test + public void testDefaultAlignmentVerticalLayout() { + testDefaultAlignment(verticalLayout); + } + + @Test + public void testDefaultAlignmentHorizontalLayout() { + testDefaultAlignment(horizontalLayout); + } + + public void testDefaultAlignment(AbstractOrderedLayout layout) { + Label label = new Label("A label"); + TextField tf = new TextField("A TextField"); + layout.addComponent(label); + layout.addComponent(tf); + Assert.assertEquals(Alignment.TOP_LEFT, + layout.getComponentAlignment(label)); + Assert.assertEquals(Alignment.TOP_LEFT, + layout.getComponentAlignment(tf)); + } + + @Test + public void testAlteredDefaultAlignmentVerticalLayout() { + testAlteredDefaultAlignment(verticalLayout); + } + + @Test + public void testAlteredDefaultAlignmentHorizontalLayout() { + testAlteredDefaultAlignment(horizontalLayout); + } + + public void testAlteredDefaultAlignment(AbstractOrderedLayout layout) { + Label label = new Label("A label"); + TextField tf = new TextField("A TextField"); + layout.setDefaultComponentAlignment(Alignment.MIDDLE_CENTER); + layout.addComponent(label); + layout.addComponent(tf); + Assert.assertEquals(Alignment.MIDDLE_CENTER, + layout.getComponentAlignment(label)); + Assert.assertEquals(Alignment.MIDDLE_CENTER, + layout.getComponentAlignment(tf)); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/orderedlayout/OrderedLayoutTest.java b/server/tests/src/com/vaadin/tests/server/component/orderedlayout/OrderedLayoutTest.java new file mode 100644 index 0000000000..3b3dfb94d8 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/orderedlayout/OrderedLayoutTest.java @@ -0,0 +1,49 @@ +package com.vaadin.tests.server.component.orderedlayout; + +import java.util.Iterator; + +import junit.framework.TestCase; + +import com.vaadin.ui.AbstractOrderedLayout; +import com.vaadin.ui.Component; +import com.vaadin.ui.HorizontalLayout; +import com.vaadin.ui.Label; +import com.vaadin.ui.VerticalLayout; + +public class OrderedLayoutTest extends TestCase { + + public void testVLIteration() { + testIndexing(new VerticalLayout(), 10); + } + + public void testHLIteration() { + testIndexing(new HorizontalLayout(), 12); + } + + public void testIndexing(AbstractOrderedLayout aol, int nrComponents) { + Component[] components = generateComponents(nrComponents); + for (Component c : components) { + aol.addComponent(c); + } + for (int i = 0; i < nrComponents; i++) { + assert (aol.getComponent(i) == components[i]); + assert (aol.getComponentIndex(components[i]) == i); + } + + // Iteration should be in indexed order + int idx = 0; + for (Iterator i = aol.getComponentIterator(); i.hasNext();) { + Component c = i.next(); + assert (aol.getComponentIndex(c) == idx++); + } + } + + private Component[] generateComponents(int nr) { + Component[] components = new Component[nr]; + for (int i = 0; i < nr; i++) { + components[i] = new Label("" + i); + } + + return components; + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/orderedlayout/TestOrderedLayout.java b/server/tests/src/com/vaadin/tests/server/component/orderedlayout/TestOrderedLayout.java deleted file mode 100644 index 6a9d55d7e4..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/orderedlayout/TestOrderedLayout.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.vaadin.tests.server.component.orderedlayout; - -import java.util.Iterator; - -import junit.framework.TestCase; - -import com.vaadin.ui.AbstractOrderedLayout; -import com.vaadin.ui.Component; -import com.vaadin.ui.HorizontalLayout; -import com.vaadin.ui.Label; -import com.vaadin.ui.VerticalLayout; - -public class TestOrderedLayout extends TestCase { - - public void testVLIteration() { - testIndexing(new VerticalLayout(), 10); - } - - public void testHLIteration() { - testIndexing(new HorizontalLayout(), 12); - } - - public void testIndexing(AbstractOrderedLayout aol, int nrComponents) { - Component[] components = generateComponents(nrComponents); - for (Component c : components) { - aol.addComponent(c); - } - for (int i = 0; i < nrComponents; i++) { - assert (aol.getComponent(i) == components[i]); - assert (aol.getComponentIndex(components[i]) == i); - } - - // Iteration should be in indexed order - int idx = 0; - for (Iterator i = aol.getComponentIterator(); i.hasNext();) { - Component c = i.next(); - assert (aol.getComponentIndex(c) == idx++); - } - } - - private Component[] generateComponents(int nr) { - Component[] components = new Component[nr]; - for (int i = 0; i < nr; i++) { - components[i] = new Label("" + i); - } - - return components; - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/panel/PanelListeners.java b/server/tests/src/com/vaadin/tests/server/component/panel/PanelListeners.java deleted file mode 100644 index 275e90f5d1..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/panel/PanelListeners.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.vaadin.tests.server.component.panel; - -import com.vaadin.event.MouseEvents.ClickEvent; -import com.vaadin.event.MouseEvents.ClickListener; -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; -import com.vaadin.ui.Panel; - -public class PanelListeners extends AbstractListenerMethodsTest { - public void testClickListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(Panel.class, ClickEvent.class, - ClickListener.class); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/panel/PanelListenersTest.java b/server/tests/src/com/vaadin/tests/server/component/panel/PanelListenersTest.java new file mode 100644 index 0000000000..929553a682 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/panel/PanelListenersTest.java @@ -0,0 +1,13 @@ +package com.vaadin.tests.server.component.panel; + +import com.vaadin.event.MouseEvents.ClickEvent; +import com.vaadin.event.MouseEvents.ClickListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; +import com.vaadin.ui.Panel; + +public class PanelListenersTest extends AbstractListenerMethodsTestBase { + public void testClickListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Panel.class, ClickEvent.class, + ClickListener.class); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/panel/ReadDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/panel/ReadDesignTest.java new file mode 100644 index 0000000000..41b19c9778 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/panel/ReadDesignTest.java @@ -0,0 +1,98 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.panel; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; + +import com.vaadin.ui.Panel; +import com.vaadin.ui.VerticalLayout; +import com.vaadin.ui.declarative.DesignContext; +import com.vaadin.ui.declarative.DesignException; + +/** + * Test case for reading the attributes of a Panel from design. + * + * @author Vaadin Ltd + */ +public class ReadDesignTest extends TestCase { + DesignContext ctx; + + @Override + public void setUp() { + ctx = new DesignContext(); + } + + public void testAttributes() { + Element design = createDesign(); + Panel panel = new Panel(); + panel.readDesign(design, ctx); + assertEquals("A panel", panel.getCaption()); + assertEquals(2, panel.getTabIndex()); + assertEquals(10, panel.getScrollLeft()); + assertEquals(20, panel.getScrollTop()); + assertEquals(200f, panel.getWidth()); + assertEquals(150f, panel.getHeight()); + } + + public void testChild() { + Element design = createDesign(); + Panel panel = new Panel(); + panel.readDesign(design, ctx); + VerticalLayout vLayout = (VerticalLayout) panel.getContent(); + assertEquals(300f, vLayout.getWidth()); + assertEquals(400f, vLayout.getHeight()); + } + + public void testWithMoreThanOneChild() { + Element design = createDesign(); + // Add a new child to the panel element. An exception should be + // thrown when parsing the design. + Element newChild = new Element(Tag.valueOf("v-horizontal-layout"), ""); + design.appendChild(newChild); + Panel panel = new Panel(); + try { + panel.readDesign(design, ctx); + fail("Parsing a design containing a Panel with more than one child component should have failed."); + } catch (DesignException e) { + // Nothing needs to be done, this is the expected case. + } + } + + /* + * Creates an html document that can be parsed into a valid component + * hierarchy. + */ + private Element createDesign() { + // Create a node defining a Panel + Element panelElement = new Element(Tag.valueOf("v-panel"), ""); + panelElement.attr("caption", "A panel"); + panelElement.attr("tabindex", "2"); + panelElement.attr("scroll-left", "10"); + panelElement.attr("scroll-top", "20"); + panelElement.attr("width", "200px"); + panelElement.attr("height", "150px"); + // Add some content to the panel + Element layoutElement = new Element(Tag.valueOf("v-vertical-layout"), + ""); + layoutElement.attr("width", "300px"); + layoutElement.attr("height", "400px"); + panelElement.appendChild(layoutElement); + return panelElement; + } +} \ No newline at end of file diff --git a/server/tests/src/com/vaadin/tests/server/component/panel/TestReadDesign.java b/server/tests/src/com/vaadin/tests/server/component/panel/TestReadDesign.java deleted file mode 100644 index 3eb52309a8..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/panel/TestReadDesign.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.panel; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; - -import com.vaadin.ui.Panel; -import com.vaadin.ui.VerticalLayout; -import com.vaadin.ui.declarative.DesignContext; -import com.vaadin.ui.declarative.DesignException; - -/** - * Test case for reading the attributes of a Panel from design. - * - * @author Vaadin Ltd - */ -public class TestReadDesign extends TestCase { - DesignContext ctx; - - @Override - public void setUp() { - ctx = new DesignContext(); - } - - public void testAttributes() { - Element design = createDesign(); - Panel panel = new Panel(); - panel.readDesign(design, ctx); - assertEquals("A panel", panel.getCaption()); - assertEquals(2, panel.getTabIndex()); - assertEquals(10, panel.getScrollLeft()); - assertEquals(20, panel.getScrollTop()); - assertEquals(200f, panel.getWidth()); - assertEquals(150f, panel.getHeight()); - } - - public void testChild() { - Element design = createDesign(); - Panel panel = new Panel(); - panel.readDesign(design, ctx); - VerticalLayout vLayout = (VerticalLayout) panel.getContent(); - assertEquals(300f, vLayout.getWidth()); - assertEquals(400f, vLayout.getHeight()); - } - - public void testWithMoreThanOneChild() { - Element design = createDesign(); - // Add a new child to the panel element. An exception should be - // thrown when parsing the design. - Element newChild = new Element(Tag.valueOf("v-horizontal-layout"), ""); - design.appendChild(newChild); - Panel panel = new Panel(); - try { - panel.readDesign(design, ctx); - fail("Parsing a design containing a Panel with more than one child component should have failed."); - } catch (DesignException e) { - // Nothing needs to be done, this is the expected case. - } - } - - /* - * Creates an html document that can be parsed into a valid component - * hierarchy. - */ - private Element createDesign() { - // Create a node defining a Panel - Element panelElement = new Element(Tag.valueOf("v-panel"), ""); - panelElement.attr("caption", "A panel"); - panelElement.attr("tabindex", "2"); - panelElement.attr("scroll-left", "10"); - panelElement.attr("scroll-top", "20"); - panelElement.attr("width", "200px"); - panelElement.attr("height", "150px"); - // Add some content to the panel - Element layoutElement = new Element(Tag.valueOf("v-vertical-layout"), - ""); - layoutElement.attr("width", "300px"); - layoutElement.attr("height", "400px"); - panelElement.appendChild(layoutElement); - return panelElement; - } -} \ No newline at end of file diff --git a/server/tests/src/com/vaadin/tests/server/component/panel/TestWriteDesign.java b/server/tests/src/com/vaadin/tests/server/component/panel/TestWriteDesign.java deleted file mode 100644 index f81193d511..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/panel/TestWriteDesign.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.panel; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; - -import com.vaadin.ui.Panel; -import com.vaadin.ui.VerticalLayout; -import com.vaadin.ui.declarative.DesignContext; - -/** - * Test case for writing the attributes and the child element of a Panel to a - * design. - * - * @author Vaadin Ltd - */ -public class TestWriteDesign extends TestCase { - Element panelElement; - - @Override - public void setUp() { - // create a component hierarchy - Panel panel = new Panel("A panel"); - panel.setId("panelId"); - panel.setHeight("250px"); - panel.setScrollTop(50); - panel.setTabIndex(4); - VerticalLayout vLayout = new VerticalLayout(); - vLayout.setWidth("500px"); - panel.setContent(vLayout); - // synchronize to design - DesignContext ctx = new DesignContext(); - panelElement = new Element(Tag.valueOf("div"), ""); - panel.writeDesign(panelElement, ctx); - } - - public void testAttributes() { - // should have caption, id, height, scroll top and tab index - assertEquals(5, panelElement.attributes().size()); - // check the values of the attributes - assertEquals("A panel", panelElement.attr("caption")); - assertEquals("panelId", panelElement.attr("id")); - assertEquals("250px", panelElement.attr("height")); - assertEquals("50", panelElement.attr("scroll-top")); - assertEquals("4", panelElement.attr("tabindex")); - } - - public void testChild() { - // the panel element should have exactly one child, a v-vertical-layout - assertEquals(1, panelElement.childNodes().size()); - Element vLayoutElement = panelElement.child(0); - assertEquals("v-vertical-layout", vLayoutElement.nodeName()); - assertEquals("500px", vLayoutElement.attr("width")); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/panel/WriteDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/panel/WriteDesignTest.java new file mode 100644 index 0000000000..8b8c6e5e13 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/panel/WriteDesignTest.java @@ -0,0 +1,71 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.panel; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; + +import com.vaadin.ui.Panel; +import com.vaadin.ui.VerticalLayout; +import com.vaadin.ui.declarative.DesignContext; + +/** + * Test case for writing the attributes and the child element of a Panel to a + * design. + * + * @author Vaadin Ltd + */ +public class WriteDesignTest extends TestCase { + Element panelElement; + + @Override + public void setUp() { + // create a component hierarchy + Panel panel = new Panel("A panel"); + panel.setId("panelId"); + panel.setHeight("250px"); + panel.setScrollTop(50); + panel.setTabIndex(4); + VerticalLayout vLayout = new VerticalLayout(); + vLayout.setWidth("500px"); + panel.setContent(vLayout); + // synchronize to design + DesignContext ctx = new DesignContext(); + panelElement = new Element(Tag.valueOf("div"), ""); + panel.writeDesign(panelElement, ctx); + } + + public void testAttributes() { + // should have caption, id, height, scroll top and tab index + assertEquals(5, panelElement.attributes().size()); + // check the values of the attributes + assertEquals("A panel", panelElement.attr("caption")); + assertEquals("panelId", panelElement.attr("id")); + assertEquals("250px", panelElement.attr("height")); + assertEquals("50", panelElement.attr("scroll-top")); + assertEquals("4", panelElement.attr("tabindex")); + } + + public void testChild() { + // the panel element should have exactly one child, a v-vertical-layout + assertEquals(1, panelElement.childNodes().size()); + Element vLayoutElement = panelElement.child(0); + assertEquals("v-vertical-layout", vLayoutElement.nodeName()); + assertEquals("500px", vLayoutElement.attr("width")); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/popupview/PopupViewListeners.java b/server/tests/src/com/vaadin/tests/server/component/popupview/PopupViewListeners.java deleted file mode 100644 index 12a5a0f520..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/popupview/PopupViewListeners.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.vaadin.tests.server.component.popupview; - -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; -import com.vaadin.ui.Label; -import com.vaadin.ui.PopupView; -import com.vaadin.ui.PopupView.PopupVisibilityEvent; -import com.vaadin.ui.PopupView.PopupVisibilityListener; - -public class PopupViewListeners extends AbstractListenerMethodsTest { - public void testPopupVisibilityListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(PopupView.class, PopupVisibilityEvent.class, - PopupVisibilityListener.class, new PopupView("", new Label())); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/popupview/PopupViewListenersTest.java b/server/tests/src/com/vaadin/tests/server/component/popupview/PopupViewListenersTest.java new file mode 100644 index 0000000000..06782818a8 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/popupview/PopupViewListenersTest.java @@ -0,0 +1,14 @@ +package com.vaadin.tests.server.component.popupview; + +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; +import com.vaadin.ui.Label; +import com.vaadin.ui.PopupView; +import com.vaadin.ui.PopupView.PopupVisibilityEvent; +import com.vaadin.ui.PopupView.PopupVisibilityListener; + +public class PopupViewListenersTest extends AbstractListenerMethodsTestBase { + public void testPopupVisibilityListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(PopupView.class, PopupVisibilityEvent.class, + PopupVisibilityListener.class, new PopupView("", new Label())); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/select/SelectListeners.java b/server/tests/src/com/vaadin/tests/server/component/select/SelectListeners.java deleted file mode 100644 index 2a1cc0deb0..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/select/SelectListeners.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.vaadin.tests.server.component.select; - -import com.vaadin.event.FieldEvents.BlurEvent; -import com.vaadin.event.FieldEvents.BlurListener; -import com.vaadin.event.FieldEvents.FocusEvent; -import com.vaadin.event.FieldEvents.FocusListener; -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; -import com.vaadin.ui.Select; - -public class SelectListeners extends AbstractListenerMethodsTest { - public void testFocusListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(Select.class, FocusEvent.class, - FocusListener.class); - } - - public void testBlurListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(Select.class, BlurEvent.class, - BlurListener.class); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/select/SelectListenersTest.java b/server/tests/src/com/vaadin/tests/server/component/select/SelectListenersTest.java new file mode 100644 index 0000000000..9a2a5f1f50 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/select/SelectListenersTest.java @@ -0,0 +1,20 @@ +package com.vaadin.tests.server.component.select; + +import com.vaadin.event.FieldEvents.BlurEvent; +import com.vaadin.event.FieldEvents.BlurListener; +import com.vaadin.event.FieldEvents.FocusEvent; +import com.vaadin.event.FieldEvents.FocusListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; +import com.vaadin.ui.Select; + +public class SelectListenersTest extends AbstractListenerMethodsTestBase { + public void testFocusListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Select.class, FocusEvent.class, + FocusListener.class); + } + + public void testBlurListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Select.class, BlurEvent.class, + BlurListener.class); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/table/CacheUpdateExceptionCauses.java b/server/tests/src/com/vaadin/tests/server/component/table/CacheUpdateExceptionCauses.java deleted file mode 100644 index beb5da0885..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/table/CacheUpdateExceptionCauses.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2012 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.table; - -import org.junit.Assert; -import org.junit.Test; - -import com.vaadin.ui.Table; -import com.vaadin.ui.Table.CacheUpdateException; - -public class CacheUpdateExceptionCauses { - @Test - public void testSingleCauseException() { - Table table = new Table(); - Throwable[] causes = new Throwable[] { new RuntimeException( - "Broken in one way.") }; - - CacheUpdateException exception = new CacheUpdateException(table, - "Error during Table cache update.", causes); - - Assert.assertSame(causes[0], exception.getCause()); - Assert.assertEquals("Error during Table cache update.", - exception.getMessage()); - } - - @Test - public void testMultipleCauseException() { - Table table = new Table(); - Throwable[] causes = new Throwable[] { - new RuntimeException("Broken in the first way."), - new RuntimeException("Broken in the second way.") }; - - CacheUpdateException exception = new CacheUpdateException(table, - "Error during Table cache update.", causes); - - Assert.assertSame(causes[0], exception.getCause()); - Assert.assertEquals( - "Error during Table cache update. Additional causes not shown.", - exception.getMessage()); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/table/CacheUpdateExceptionCausesTest.java b/server/tests/src/com/vaadin/tests/server/component/table/CacheUpdateExceptionCausesTest.java new file mode 100644 index 0000000000..03f50c6b5f --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/table/CacheUpdateExceptionCausesTest.java @@ -0,0 +1,55 @@ +/* + * Copyright 2012 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.table; + +import org.junit.Assert; +import org.junit.Test; + +import com.vaadin.ui.Table; +import com.vaadin.ui.Table.CacheUpdateException; + +public class CacheUpdateExceptionCausesTest { + @Test + public void testSingleCauseException() { + Table table = new Table(); + Throwable[] causes = new Throwable[] { new RuntimeException( + "Broken in one way.") }; + + CacheUpdateException exception = new CacheUpdateException(table, + "Error during Table cache update.", causes); + + Assert.assertSame(causes[0], exception.getCause()); + Assert.assertEquals("Error during Table cache update.", + exception.getMessage()); + } + + @Test + public void testMultipleCauseException() { + Table table = new Table(); + Throwable[] causes = new Throwable[] { + new RuntimeException("Broken in the first way."), + new RuntimeException("Broken in the second way.") }; + + CacheUpdateException exception = new CacheUpdateException(table, + "Error during Table cache update.", causes); + + Assert.assertSame(causes[0], exception.getCause()); + Assert.assertEquals( + "Error during Table cache update. Additional causes not shown.", + exception.getMessage()); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/table/FooterTest.java b/server/tests/src/com/vaadin/tests/server/component/table/FooterTest.java new file mode 100644 index 0000000000..f9d373e864 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/table/FooterTest.java @@ -0,0 +1,94 @@ +package com.vaadin.tests.server.component.table; + +import junit.framework.TestCase; + +import com.vaadin.data.Container; +import com.vaadin.data.Item; +import com.vaadin.data.util.IndexedContainer; +import com.vaadin.ui.Table; + +/** + * Test case for testing the footer API + * + */ +public class FooterTest extends TestCase { + + /** + * Tests if setting the footer visibility works properly + */ + public void testFooterVisibility() { + Table table = new Table("Test table", createContainer()); + + // The footer should by default be hidden + assertFalse(table.isFooterVisible()); + + // Set footer visibility to tru should be reflected in the + // isFooterVisible() method + table.setFooterVisible(true); + assertTrue(table.isFooterVisible()); + } + + /** + * Tests adding footers to the columns + */ + public void testAddingFooters() { + Table table = new Table("Test table", createContainer()); + + // Table should not contain any footers at initialization + assertNull(table.getColumnFooter("col1")); + assertNull(table.getColumnFooter("col2")); + assertNull(table.getColumnFooter("col3")); + + // Adding column footer + table.setColumnFooter("col1", "Footer1"); + assertEquals("Footer1", table.getColumnFooter("col1")); + + // Add another footer + table.setColumnFooter("col2", "Footer2"); + assertEquals("Footer2", table.getColumnFooter("col2")); + + // Add footer for a non-existing column + table.setColumnFooter("fail", "FooterFail"); + } + + /** + * Test removing footers + */ + public void testRemovingFooters() { + Table table = new Table("Test table", createContainer()); + table.setColumnFooter("col1", "Footer1"); + table.setColumnFooter("col2", "Footer2"); + + // Test removing footer + assertNotNull(table.getColumnFooter("col1")); + table.setColumnFooter("col1", null); + assertNull(table.getColumnFooter("col1")); + + // The other footer should still be there + assertNotNull(table.getColumnFooter("col2")); + + // Remove non-existing footer + table.setColumnFooter("fail", null); + } + + /** + * Creates a container with three properties "col1,col2,col3" with 100 items + * + * @return Returns the created table + */ + private static Container createContainer() { + IndexedContainer container = new IndexedContainer(); + container.addContainerProperty("col1", String.class, ""); + container.addContainerProperty("col2", String.class, ""); + container.addContainerProperty("col3", String.class, ""); + + for (int i = 0; i < 100; i++) { + Item item = container.addItem("item " + i); + item.getItemProperty("col1").setValue("first" + i); + item.getItemProperty("col2").setValue("middle" + i); + item.getItemProperty("col3").setValue("last" + i); + } + + return container; + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/table/MultipleSelectionTest.java b/server/tests/src/com/vaadin/tests/server/component/table/MultipleSelectionTest.java new file mode 100644 index 0000000000..ceb4c865d2 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/table/MultipleSelectionTest.java @@ -0,0 +1,57 @@ +package com.vaadin.tests.server.component.table; + +import java.util.Arrays; +import java.util.Set; + +import junit.framework.TestCase; + +import com.vaadin.data.Container; +import com.vaadin.data.util.IndexedContainer; +import com.vaadin.shared.ui.MultiSelectMode; +import com.vaadin.ui.Table; + +public class MultipleSelectionTest extends TestCase { + + /** + * Tests weather the multiple select mode is set when using Table.set + */ + @SuppressWarnings("unchecked") + public void testSetMultipleItems() { + Table table = new Table("", createTestContainer()); + + // Tests if multiple selection is set + table.setMultiSelect(true); + assertTrue(table.isMultiSelect()); + + // Test multiselect by setting several items at once + + table.setValue(Arrays.asList("1", new String[] { "3" })); + assertEquals(2, ((Set) table.getValue()).size()); + } + + /** + * Tests setting the multiselect mode of the Table. The multiselect mode + * affects how mouse selection is made in the table by the user. + */ + public void testSetMultiSelectMode() { + Table table = new Table("", createTestContainer()); + + // Default multiselect mode should be MultiSelectMode.DEFAULT + assertEquals(MultiSelectMode.DEFAULT, table.getMultiSelectMode()); + + // Tests if multiselectmode is set + table.setMultiSelectMode(MultiSelectMode.SIMPLE); + assertEquals(MultiSelectMode.SIMPLE, table.getMultiSelectMode()); + } + + /** + * Creates a testing container for the tests + * + * @return A new container with test items + */ + private Container createTestContainer() { + IndexedContainer container = new IndexedContainer(Arrays.asList("1", + new String[] { "2", "3", "4" })); + return container; + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/table/TableColumnAlignments.java b/server/tests/src/com/vaadin/tests/server/component/table/TableColumnAlignments.java deleted file mode 100644 index 299f9c79d4..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/table/TableColumnAlignments.java +++ /dev/null @@ -1,143 +0,0 @@ -package com.vaadin.tests.server.component.table; - -import static org.junit.Assert.assertArrayEquals; - -import org.junit.Test; - -import com.vaadin.ui.Table; -import com.vaadin.ui.Table.Align; - -public class TableColumnAlignments { - - @Test - public void defaultColumnAlignments() { - for (int properties = 0; properties < 10; properties++) { - Table t = TableGenerator.createTableWithDefaultContainer( - properties, 10); - Object[] expected = new Object[properties]; - for (int i = 0; i < properties; i++) { - expected[i] = Align.LEFT; - } - org.junit.Assert.assertArrayEquals("getColumnAlignments", expected, - t.getColumnAlignments()); - } - } - - @Test - public void explicitColumnAlignments() { - int properties = 5; - Table t = TableGenerator - .createTableWithDefaultContainer(properties, 10); - Align[] explicitAlignments = new Align[] { Align.CENTER, Align.LEFT, - Align.RIGHT, Align.RIGHT, Align.LEFT }; - - t.setColumnAlignments(explicitAlignments); - - assertArrayEquals("Explicit visible columns, 5 properties", - explicitAlignments, t.getColumnAlignments()); - } - - @Test - public void invalidColumnAlignmentStrings() { - Table t = TableGenerator.createTableWithDefaultContainer(3, 7); - Align[] defaultAlignments = new Align[] { Align.LEFT, Align.LEFT, - Align.LEFT }; - try { - t.setColumnAlignments(new Align[] { Align.RIGHT, Align.RIGHT }); - junit.framework.Assert - .fail("No exception thrown for invalid array length"); - } catch (IllegalArgumentException e) { - // Ok, expected - } - - assertArrayEquals("Invalid change affected alignments", - defaultAlignments, t.getColumnAlignments()); - - } - - @Test - public void columnAlignmentForPropertyNotInContainer() { - Table t = TableGenerator.createTableWithDefaultContainer(3, 7); - Align[] defaultAlignments = new Align[] { Align.LEFT, Align.LEFT, - Align.LEFT }; - try { - t.setColumnAlignment("Property 1200", Align.LEFT); - // FIXME: Uncomment as there should be an exception (#6475) - // junit.framework.Assert - // .fail("No exception thrown for property not in container"); - } catch (IllegalArgumentException e) { - // Ok, expected - } - - assertArrayEquals("Invalid change affected alignments", - defaultAlignments, t.getColumnAlignments()); - - // FIXME: Uncomment as null should be returned (#6474) - // junit.framework.Assert.assertEquals( - // "Column alignment for property not in container returned", - // null, t.getColumnAlignment("Property 1200")); - - } - - @Test - public void invalidColumnAlignmentsLength() { - Table t = TableGenerator.createTableWithDefaultContainer(7, 7); - Align[] defaultAlignments = new Align[] { Align.LEFT, Align.LEFT, - Align.LEFT, Align.LEFT, Align.LEFT, Align.LEFT, Align.LEFT }; - - try { - t.setColumnAlignments(new Align[] { Align.LEFT }); - junit.framework.Assert - .fail("No exception thrown for invalid array length"); - } catch (IllegalArgumentException e) { - // Ok, expected - } - assertArrayEquals("Invalid change affected alignments", - defaultAlignments, t.getColumnAlignments()); - - try { - t.setColumnAlignments(new Align[] {}); - junit.framework.Assert - .fail("No exception thrown for invalid array length"); - } catch (IllegalArgumentException e) { - // Ok, expected - } - assertArrayEquals("Invalid change affected alignments", - defaultAlignments, t.getColumnAlignments()); - - try { - t.setColumnAlignments(new Align[] { Align.LEFT, Align.LEFT, - Align.LEFT, Align.LEFT, Align.LEFT, Align.LEFT, Align.LEFT, - Align.LEFT }); - junit.framework.Assert - .fail("No exception thrown for invalid array length"); - } catch (IllegalArgumentException e) { - // Ok, expected - } - assertArrayEquals("Invalid change affected alignments", - defaultAlignments, t.getColumnAlignments()); - - } - - @Test - public void explicitColumnAlignmentOneByOne() { - int properties = 5; - Table t = TableGenerator - .createTableWithDefaultContainer(properties, 10); - Align[] explicitAlignments = new Align[] { Align.CENTER, Align.LEFT, - Align.RIGHT, Align.RIGHT, Align.LEFT }; - - Align[] currentAlignments = new Align[] { Align.LEFT, Align.LEFT, - Align.LEFT, Align.LEFT, Align.LEFT }; - - for (int i = 0; i < properties; i++) { - t.setColumnAlignment("Property " + i, explicitAlignments[i]); - currentAlignments[i] = explicitAlignments[i]; - - assertArrayEquals("Explicit visible columns, " + i - + " alignments set", currentAlignments, - t.getColumnAlignments()); - } - - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/table/TableColumnAlignmentsTest.java b/server/tests/src/com/vaadin/tests/server/component/table/TableColumnAlignmentsTest.java new file mode 100644 index 0000000000..5e33ff2f4a --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/table/TableColumnAlignmentsTest.java @@ -0,0 +1,143 @@ +package com.vaadin.tests.server.component.table; + +import static org.junit.Assert.assertArrayEquals; + +import org.junit.Test; + +import com.vaadin.ui.Table; +import com.vaadin.ui.Table.Align; + +public class TableColumnAlignmentsTest { + + @Test + public void defaultColumnAlignments() { + for (int properties = 0; properties < 10; properties++) { + Table t = TableGeneratorTest.createTableWithDefaultContainer( + properties, 10); + Object[] expected = new Object[properties]; + for (int i = 0; i < properties; i++) { + expected[i] = Align.LEFT; + } + org.junit.Assert.assertArrayEquals("getColumnAlignments", expected, + t.getColumnAlignments()); + } + } + + @Test + public void explicitColumnAlignments() { + int properties = 5; + Table t = TableGeneratorTest + .createTableWithDefaultContainer(properties, 10); + Align[] explicitAlignments = new Align[] { Align.CENTER, Align.LEFT, + Align.RIGHT, Align.RIGHT, Align.LEFT }; + + t.setColumnAlignments(explicitAlignments); + + assertArrayEquals("Explicit visible columns, 5 properties", + explicitAlignments, t.getColumnAlignments()); + } + + @Test + public void invalidColumnAlignmentStrings() { + Table t = TableGeneratorTest.createTableWithDefaultContainer(3, 7); + Align[] defaultAlignments = new Align[] { Align.LEFT, Align.LEFT, + Align.LEFT }; + try { + t.setColumnAlignments(new Align[] { Align.RIGHT, Align.RIGHT }); + junit.framework.Assert + .fail("No exception thrown for invalid array length"); + } catch (IllegalArgumentException e) { + // Ok, expected + } + + assertArrayEquals("Invalid change affected alignments", + defaultAlignments, t.getColumnAlignments()); + + } + + @Test + public void columnAlignmentForPropertyNotInContainer() { + Table t = TableGeneratorTest.createTableWithDefaultContainer(3, 7); + Align[] defaultAlignments = new Align[] { Align.LEFT, Align.LEFT, + Align.LEFT }; + try { + t.setColumnAlignment("Property 1200", Align.LEFT); + // FIXME: Uncomment as there should be an exception (#6475) + // junit.framework.Assert + // .fail("No exception thrown for property not in container"); + } catch (IllegalArgumentException e) { + // Ok, expected + } + + assertArrayEquals("Invalid change affected alignments", + defaultAlignments, t.getColumnAlignments()); + + // FIXME: Uncomment as null should be returned (#6474) + // junit.framework.Assert.assertEquals( + // "Column alignment for property not in container returned", + // null, t.getColumnAlignment("Property 1200")); + + } + + @Test + public void invalidColumnAlignmentsLength() { + Table t = TableGeneratorTest.createTableWithDefaultContainer(7, 7); + Align[] defaultAlignments = new Align[] { Align.LEFT, Align.LEFT, + Align.LEFT, Align.LEFT, Align.LEFT, Align.LEFT, Align.LEFT }; + + try { + t.setColumnAlignments(new Align[] { Align.LEFT }); + junit.framework.Assert + .fail("No exception thrown for invalid array length"); + } catch (IllegalArgumentException e) { + // Ok, expected + } + assertArrayEquals("Invalid change affected alignments", + defaultAlignments, t.getColumnAlignments()); + + try { + t.setColumnAlignments(new Align[] {}); + junit.framework.Assert + .fail("No exception thrown for invalid array length"); + } catch (IllegalArgumentException e) { + // Ok, expected + } + assertArrayEquals("Invalid change affected alignments", + defaultAlignments, t.getColumnAlignments()); + + try { + t.setColumnAlignments(new Align[] { Align.LEFT, Align.LEFT, + Align.LEFT, Align.LEFT, Align.LEFT, Align.LEFT, Align.LEFT, + Align.LEFT }); + junit.framework.Assert + .fail("No exception thrown for invalid array length"); + } catch (IllegalArgumentException e) { + // Ok, expected + } + assertArrayEquals("Invalid change affected alignments", + defaultAlignments, t.getColumnAlignments()); + + } + + @Test + public void explicitColumnAlignmentOneByOne() { + int properties = 5; + Table t = TableGeneratorTest + .createTableWithDefaultContainer(properties, 10); + Align[] explicitAlignments = new Align[] { Align.CENTER, Align.LEFT, + Align.RIGHT, Align.RIGHT, Align.LEFT }; + + Align[] currentAlignments = new Align[] { Align.LEFT, Align.LEFT, + Align.LEFT, Align.LEFT, Align.LEFT }; + + for (int i = 0; i < properties; i++) { + t.setColumnAlignment("Property " + i, explicitAlignments[i]); + currentAlignments[i] = explicitAlignments[i]; + + assertArrayEquals("Explicit visible columns, " + i + + " alignments set", currentAlignments, + t.getColumnAlignments()); + } + + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/table/TableGenerator.java b/server/tests/src/com/vaadin/tests/server/component/table/TableGenerator.java deleted file mode 100644 index 0e63049944..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/table/TableGenerator.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.vaadin.tests.server.component.table; - -import org.junit.Test; - -import com.vaadin.data.Item; -import com.vaadin.ui.Table; - -public class TableGenerator { - public static Table createTableWithDefaultContainer(int properties, - int items) { - Table t = new Table(); - - for (int i = 0; i < properties; i++) { - t.addContainerProperty("Property " + i, String.class, null); - } - - for (int j = 0; j < items; j++) { - Item item = t.addItem("Item " + j); - for (int i = 0; i < properties; i++) { - item.getItemProperty("Property " + i).setValue( - "Item " + j + "/Property " + i); - } - } - - return t; - } - - @Test - public void testTableGenerator() { - Table t = createTableWithDefaultContainer(1, 1); - junit.framework.Assert.assertEquals(t.size(), 1); - junit.framework.Assert.assertEquals(t.getContainerPropertyIds().size(), - 1); - - t = createTableWithDefaultContainer(100, 50); - junit.framework.Assert.assertEquals(t.size(), 50); - junit.framework.Assert.assertEquals(t.getContainerPropertyIds().size(), - 100); - - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/component/table/TableGeneratorTest.java b/server/tests/src/com/vaadin/tests/server/component/table/TableGeneratorTest.java new file mode 100644 index 0000000000..f3c2589f4a --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/table/TableGeneratorTest.java @@ -0,0 +1,42 @@ +package com.vaadin.tests.server.component.table; + +import org.junit.Test; + +import com.vaadin.data.Item; +import com.vaadin.ui.Table; + +public class TableGeneratorTest { + public static Table createTableWithDefaultContainer(int properties, + int items) { + Table t = new Table(); + + for (int i = 0; i < properties; i++) { + t.addContainerProperty("Property " + i, String.class, null); + } + + for (int j = 0; j < items; j++) { + Item item = t.addItem("Item " + j); + for (int i = 0; i < properties; i++) { + item.getItemProperty("Property " + i).setValue( + "Item " + j + "/Property " + i); + } + } + + return t; + } + + @Test + public void testTableGenerator() { + Table t = createTableWithDefaultContainer(1, 1); + junit.framework.Assert.assertEquals(t.size(), 1); + junit.framework.Assert.assertEquals(t.getContainerPropertyIds().size(), + 1); + + t = createTableWithDefaultContainer(100, 50); + junit.framework.Assert.assertEquals(t.size(), 50); + junit.framework.Assert.assertEquals(t.getContainerPropertyIds().size(), + 100); + + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/component/table/TableListeners.java b/server/tests/src/com/vaadin/tests/server/component/table/TableListeners.java deleted file mode 100644 index fbe5bb3146..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/table/TableListeners.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.vaadin.tests.server.component.table; - -import com.vaadin.event.ItemClickEvent; -import com.vaadin.event.ItemClickEvent.ItemClickListener; -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; -import com.vaadin.ui.Table; -import com.vaadin.ui.Table.ColumnReorderEvent; -import com.vaadin.ui.Table.ColumnReorderListener; -import com.vaadin.ui.Table.ColumnResizeEvent; -import com.vaadin.ui.Table.ColumnResizeListener; -import com.vaadin.ui.Table.FooterClickEvent; -import com.vaadin.ui.Table.FooterClickListener; -import com.vaadin.ui.Table.HeaderClickEvent; -import com.vaadin.ui.Table.HeaderClickListener; - -public class TableListeners extends AbstractListenerMethodsTest { - public void testColumnResizeListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(Table.class, ColumnResizeEvent.class, - ColumnResizeListener.class); - } - - public void testItemClickListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(Table.class, ItemClickEvent.class, - ItemClickListener.class); - } - - public void testFooterClickListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(Table.class, FooterClickEvent.class, - FooterClickListener.class); - } - - public void testHeaderClickListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(Table.class, HeaderClickEvent.class, - HeaderClickListener.class); - } - - public void testColumnReorderListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(Table.class, ColumnReorderEvent.class, - ColumnReorderListener.class); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/table/TableListenersTest.java b/server/tests/src/com/vaadin/tests/server/component/table/TableListenersTest.java new file mode 100644 index 0000000000..fce514954a --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/table/TableListenersTest.java @@ -0,0 +1,41 @@ +package com.vaadin.tests.server.component.table; + +import com.vaadin.event.ItemClickEvent; +import com.vaadin.event.ItemClickEvent.ItemClickListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; +import com.vaadin.ui.Table; +import com.vaadin.ui.Table.ColumnReorderEvent; +import com.vaadin.ui.Table.ColumnReorderListener; +import com.vaadin.ui.Table.ColumnResizeEvent; +import com.vaadin.ui.Table.ColumnResizeListener; +import com.vaadin.ui.Table.FooterClickEvent; +import com.vaadin.ui.Table.FooterClickListener; +import com.vaadin.ui.Table.HeaderClickEvent; +import com.vaadin.ui.Table.HeaderClickListener; + +public class TableListenersTest extends AbstractListenerMethodsTestBase { + public void testColumnResizeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Table.class, ColumnResizeEvent.class, + ColumnResizeListener.class); + } + + public void testItemClickListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Table.class, ItemClickEvent.class, + ItemClickListener.class); + } + + public void testFooterClickListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Table.class, FooterClickEvent.class, + FooterClickListener.class); + } + + public void testHeaderClickListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Table.class, HeaderClickEvent.class, + HeaderClickListener.class); + } + + public void testColumnReorderListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Table.class, ColumnReorderEvent.class, + ColumnReorderListener.class); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/table/TablePropertyValueConverter.java b/server/tests/src/com/vaadin/tests/server/component/table/TablePropertyValueConverter.java deleted file mode 100644 index 418ca333bc..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/table/TablePropertyValueConverter.java +++ /dev/null @@ -1,380 +0,0 @@ -/* - * Copyright 2000-2013 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.table; - -import java.lang.reflect.Field; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Locale; -import java.util.Map.Entry; -import java.util.Set; - -import junit.framework.TestCase; - -import org.junit.Test; - -import com.vaadin.data.Container; -import com.vaadin.data.Item; -import com.vaadin.data.Property; -import com.vaadin.data.util.IndexedContainer; -import com.vaadin.data.util.converter.Converter; -import com.vaadin.ui.Table; - -/** - * - * @since - * @author Vaadin Ltd - */ -public class TablePropertyValueConverter extends TestCase { - protected TestableTable table; - protected Collection initialProperties; - - @Test - public void testRemovePropertyId() { - Collection converters = table.getCurrentConverters(); - assertTrue("Set of converters was empty at the start.", - converters.size() > 0); - - Object firstId = converters.iterator().next(); - - table.removeContainerProperty(firstId); - - Collection converters2 = table.getCurrentConverters(); - assertTrue("FirstId was not removed", !converters2.contains(firstId)); - - assertTrue("The number of removed converters was not one.", - converters.size() - converters2.size() == 1); - - for (Object originalId : converters) { - if (!originalId.equals(firstId)) { - assertTrue("The wrong converter was removed.", - converters2.contains(originalId)); - } - } - - } - - @Test - public void testSetContainer() { - table.setContainerDataSource(createContainer(new String[] { "col1", - "col3", "col4", "col5" })); - Collection converters = table.getCurrentConverters(); - assertTrue("There should only have been one converter left.", - converters.size() == 1); - Object onlyKey = converters.iterator().next(); - assertTrue("The incorrect key was left.", onlyKey.equals("col1")); - - } - - @Test - public void testSetContainerWithInexactButCompatibleTypes() { - TestableTable customTable = new TestableTable("Test table", - createContainer(new String[] { "col1", "col2", "col3" }, - new Class[] { String.class, BaseClass.class, - DerivedClass.class })); - customTable.setConverter("col1", new Converter() { - private static final long serialVersionUID = 1L; - - @Override - public String convertToModel(String value, - Class targetType, Locale locale) - throws com.vaadin.data.util.converter.Converter.ConversionException { - return "model"; - } - - @Override - public String convertToPresentation(String value, - Class targetType, Locale locale) - throws com.vaadin.data.util.converter.Converter.ConversionException { - return "presentation"; - } - - @Override - public Class getModelType() { - return String.class; - } - - @Override - public Class getPresentationType() { - return String.class; - } - - }); - customTable.setConverter("col2", new Converter() { - private static final long serialVersionUID = 1L; - - @Override - public BaseClass convertToModel(String value, - Class targetType, Locale locale) - throws com.vaadin.data.util.converter.Converter.ConversionException { - return new BaseClass("model"); - } - - @Override - public Class getModelType() { - return BaseClass.class; - } - - @Override - public Class getPresentationType() { - return String.class; - } - - @Override - public String convertToPresentation(BaseClass value, - Class targetType, Locale locale) - throws com.vaadin.data.util.converter.Converter.ConversionException { - return null; - } - }); - customTable.setConverter("col3", new Converter() { - private static final long serialVersionUID = 1L; - - @Override - public DerivedClass convertToModel(String value, - Class targetType, Locale locale) - throws com.vaadin.data.util.converter.Converter.ConversionException { - return new DerivedClass("derived" + 1001); - } - - @Override - public Class getModelType() { - return DerivedClass.class; - } - - @Override - public Class getPresentationType() { - return String.class; - } - - @Override - public String convertToPresentation(DerivedClass value, - Class targetType, Locale locale) - throws com.vaadin.data.util.converter.Converter.ConversionException { - return null; - } - }); - customTable.setContainerDataSource(createContainer(new String[] { - "col1", "col2", "col3" }, new Class[] { DerivedClass.class, - DerivedClass.class, BaseClass.class })); - Set converters = customTable.getCurrentConverters(); - // TODO Test temporarily disabled as this feature - // is not yet implemented in Table - /* - * assertTrue("Incompatible types were not removed.", converters.size() - * <= 1); assertTrue("Even compatible types were removed", - * converters.size() == 1); assertTrue("Compatible type was missing.", - * converters.contains("col2")); - */ - } - - @Test - public void testPrimitiveTypeConverters() { - TestableTable customTable = new TestableTable("Test table", - createContainer(new String[] { "col1", "col2", "col3" }, - new Class[] { int.class, BaseClass.class, - DerivedClass.class })); - customTable.setConverter("col1", new Converter() { - private static final long serialVersionUID = 1L; - - @Override - public Integer convertToModel(String value, - Class targetType, Locale locale) - throws com.vaadin.data.util.converter.Converter.ConversionException { - return 11; - } - - @Override - public String convertToPresentation(Integer value, - Class targetType, Locale locale) - throws com.vaadin.data.util.converter.Converter.ConversionException { - return "presentation"; - } - - @Override - public Class getModelType() { - return Integer.class; - } - - @Override - public Class getPresentationType() { - return String.class; - } - }); - Set converters = customTable.getCurrentConverters(); - assertTrue("Converter was not set.", converters.size() > 0); - } - - @Test - public void testInheritance() { - assertTrue("BaseClass isn't assignable from DerivedClass", - BaseClass.class.isAssignableFrom(DerivedClass.class)); - assertFalse("DerivedClass is assignable from BaseClass", - DerivedClass.class.isAssignableFrom(BaseClass.class)); - } - - @Override - public void setUp() { - table = new TestableTable("Test table", createContainer(new String[] { - "col1", "col2", "col3" })); - table.setConverter("col1", new Converter() { - private static final long serialVersionUID = 1L; - - @Override - public String convertToModel(String value, - Class targetType, Locale locale) - throws com.vaadin.data.util.converter.Converter.ConversionException { - return "model"; - } - - @Override - public String convertToPresentation(String value, - Class targetType, Locale locale) - throws com.vaadin.data.util.converter.Converter.ConversionException { - return "presentation"; - } - - @Override - public Class getModelType() { - return String.class; - } - - @Override - public Class getPresentationType() { - return String.class; - } - - }); - - table.setConverter("col2", new Converter() { - private static final long serialVersionUID = 1L; - - @Override - public String convertToModel(String value, - Class targetType, Locale locale) - throws com.vaadin.data.util.converter.Converter.ConversionException { - return "model2"; - } - - @Override - public String convertToPresentation(String value, - Class targetType, Locale locale) - throws com.vaadin.data.util.converter.Converter.ConversionException { - return "presentation2"; - } - - @Override - public Class getModelType() { - return String.class; - } - - @Override - public Class getPresentationType() { - return String.class; - } - - }); - - initialProperties = table.getContainerPropertyIds(); - } - - private static Container createContainer(Object[] ids) { - Class[] types = new Class[ids.length]; - for (int i = 0; i < types.length; ++i) { - types[i] = String.class; - } - return createContainer(ids, types); - } - - private static Container createContainer(Object[] ids, Class[] types) { - IndexedContainer container = new IndexedContainer(); - if (ids.length > types.length) { - throw new IllegalArgumentException("Too few defined types"); - } - for (int i = 0; i < ids.length; ++i) { - container.addContainerProperty(ids[i], types[i], ""); - } - - for (int i = 0; i < 100; i++) { - Item item = container.addItem("item " + i); - for (int j = 0; j < ids.length; ++j) { - Property itemProperty = item.getItemProperty(ids[j]); - if (types[j] == String.class) { - itemProperty.setValue(ids[j].toString() + i); - } else if (types[j] == BaseClass.class) { - itemProperty.setValue(new BaseClass("base" + i)); - } else if (types[j] == DerivedClass.class) { - itemProperty.setValue(new DerivedClass("derived" + i)); - } else if (types[j] == int.class) { - // FIXME can't set values because the int is autoboxed into - // an Integer and not unboxed prior to set - - // itemProperty.setValue(i); - } else { - throw new IllegalArgumentException( - "Unhandled type in createContainer: " + types[j]); - } - } - } - - return container; - } - - private class TestableTable extends Table { - /** - * @param string - * @param createContainer - */ - public TestableTable(String string, Container container) { - super(string, container); - } - - Set getCurrentConverters() { - try { - Field f = Table.class - .getDeclaredField("propertyValueConverters"); - f.setAccessible(true); - HashMap> pvc = (HashMap>) f - .get(this); - Set currentConverters = new HashSet(); - for (Entry> entry : pvc - .entrySet()) { - currentConverters.add(entry.getKey()); - } - return currentConverters; - - } catch (Exception e) { - fail("Unable to retrieve propertyValueConverters"); - return null; - } - } - } - - private static class BaseClass { - private String title; - - public BaseClass(String title) { - this.title = title; - } - } - - private static class DerivedClass extends BaseClass { - public DerivedClass(String title) { - super(title); - } - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/table/TablePropertyValueConverterTest.java b/server/tests/src/com/vaadin/tests/server/component/table/TablePropertyValueConverterTest.java new file mode 100644 index 0000000000..7fd5bc67f6 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/table/TablePropertyValueConverterTest.java @@ -0,0 +1,380 @@ +/* + * Copyright 2000-2013 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.table; + +import java.lang.reflect.Field; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Locale; +import java.util.Map.Entry; +import java.util.Set; + +import junit.framework.TestCase; + +import org.junit.Test; + +import com.vaadin.data.Container; +import com.vaadin.data.Item; +import com.vaadin.data.Property; +import com.vaadin.data.util.IndexedContainer; +import com.vaadin.data.util.converter.Converter; +import com.vaadin.ui.Table; + +/** + * + * @since + * @author Vaadin Ltd + */ +public class TablePropertyValueConverterTest extends TestCase { + protected TestableTable table; + protected Collection initialProperties; + + @Test + public void testRemovePropertyId() { + Collection converters = table.getCurrentConverters(); + assertTrue("Set of converters was empty at the start.", + converters.size() > 0); + + Object firstId = converters.iterator().next(); + + table.removeContainerProperty(firstId); + + Collection converters2 = table.getCurrentConverters(); + assertTrue("FirstId was not removed", !converters2.contains(firstId)); + + assertTrue("The number of removed converters was not one.", + converters.size() - converters2.size() == 1); + + for (Object originalId : converters) { + if (!originalId.equals(firstId)) { + assertTrue("The wrong converter was removed.", + converters2.contains(originalId)); + } + } + + } + + @Test + public void testSetContainer() { + table.setContainerDataSource(createContainer(new String[] { "col1", + "col3", "col4", "col5" })); + Collection converters = table.getCurrentConverters(); + assertTrue("There should only have been one converter left.", + converters.size() == 1); + Object onlyKey = converters.iterator().next(); + assertTrue("The incorrect key was left.", onlyKey.equals("col1")); + + } + + @Test + public void testSetContainerWithInexactButCompatibleTypes() { + TestableTable customTable = new TestableTable("Test table", + createContainer(new String[] { "col1", "col2", "col3" }, + new Class[] { String.class, BaseClass.class, + DerivedClass.class })); + customTable.setConverter("col1", new Converter() { + private static final long serialVersionUID = 1L; + + @Override + public String convertToModel(String value, + Class targetType, Locale locale) + throws com.vaadin.data.util.converter.Converter.ConversionException { + return "model"; + } + + @Override + public String convertToPresentation(String value, + Class targetType, Locale locale) + throws com.vaadin.data.util.converter.Converter.ConversionException { + return "presentation"; + } + + @Override + public Class getModelType() { + return String.class; + } + + @Override + public Class getPresentationType() { + return String.class; + } + + }); + customTable.setConverter("col2", new Converter() { + private static final long serialVersionUID = 1L; + + @Override + public BaseClass convertToModel(String value, + Class targetType, Locale locale) + throws com.vaadin.data.util.converter.Converter.ConversionException { + return new BaseClass("model"); + } + + @Override + public Class getModelType() { + return BaseClass.class; + } + + @Override + public Class getPresentationType() { + return String.class; + } + + @Override + public String convertToPresentation(BaseClass value, + Class targetType, Locale locale) + throws com.vaadin.data.util.converter.Converter.ConversionException { + return null; + } + }); + customTable.setConverter("col3", new Converter() { + private static final long serialVersionUID = 1L; + + @Override + public DerivedClass convertToModel(String value, + Class targetType, Locale locale) + throws com.vaadin.data.util.converter.Converter.ConversionException { + return new DerivedClass("derived" + 1001); + } + + @Override + public Class getModelType() { + return DerivedClass.class; + } + + @Override + public Class getPresentationType() { + return String.class; + } + + @Override + public String convertToPresentation(DerivedClass value, + Class targetType, Locale locale) + throws com.vaadin.data.util.converter.Converter.ConversionException { + return null; + } + }); + customTable.setContainerDataSource(createContainer(new String[] { + "col1", "col2", "col3" }, new Class[] { DerivedClass.class, + DerivedClass.class, BaseClass.class })); + Set converters = customTable.getCurrentConverters(); + // TODO Test temporarily disabled as this feature + // is not yet implemented in Table + /* + * assertTrue("Incompatible types were not removed.", converters.size() + * <= 1); assertTrue("Even compatible types were removed", + * converters.size() == 1); assertTrue("Compatible type was missing.", + * converters.contains("col2")); + */ + } + + @Test + public void testPrimitiveTypeConverters() { + TestableTable customTable = new TestableTable("Test table", + createContainer(new String[] { "col1", "col2", "col3" }, + new Class[] { int.class, BaseClass.class, + DerivedClass.class })); + customTable.setConverter("col1", new Converter() { + private static final long serialVersionUID = 1L; + + @Override + public Integer convertToModel(String value, + Class targetType, Locale locale) + throws com.vaadin.data.util.converter.Converter.ConversionException { + return 11; + } + + @Override + public String convertToPresentation(Integer value, + Class targetType, Locale locale) + throws com.vaadin.data.util.converter.Converter.ConversionException { + return "presentation"; + } + + @Override + public Class getModelType() { + return Integer.class; + } + + @Override + public Class getPresentationType() { + return String.class; + } + }); + Set converters = customTable.getCurrentConverters(); + assertTrue("Converter was not set.", converters.size() > 0); + } + + @Test + public void testInheritance() { + assertTrue("BaseClass isn't assignable from DerivedClass", + BaseClass.class.isAssignableFrom(DerivedClass.class)); + assertFalse("DerivedClass is assignable from BaseClass", + DerivedClass.class.isAssignableFrom(BaseClass.class)); + } + + @Override + public void setUp() { + table = new TestableTable("Test table", createContainer(new String[] { + "col1", "col2", "col3" })); + table.setConverter("col1", new Converter() { + private static final long serialVersionUID = 1L; + + @Override + public String convertToModel(String value, + Class targetType, Locale locale) + throws com.vaadin.data.util.converter.Converter.ConversionException { + return "model"; + } + + @Override + public String convertToPresentation(String value, + Class targetType, Locale locale) + throws com.vaadin.data.util.converter.Converter.ConversionException { + return "presentation"; + } + + @Override + public Class getModelType() { + return String.class; + } + + @Override + public Class getPresentationType() { + return String.class; + } + + }); + + table.setConverter("col2", new Converter() { + private static final long serialVersionUID = 1L; + + @Override + public String convertToModel(String value, + Class targetType, Locale locale) + throws com.vaadin.data.util.converter.Converter.ConversionException { + return "model2"; + } + + @Override + public String convertToPresentation(String value, + Class targetType, Locale locale) + throws com.vaadin.data.util.converter.Converter.ConversionException { + return "presentation2"; + } + + @Override + public Class getModelType() { + return String.class; + } + + @Override + public Class getPresentationType() { + return String.class; + } + + }); + + initialProperties = table.getContainerPropertyIds(); + } + + private static Container createContainer(Object[] ids) { + Class[] types = new Class[ids.length]; + for (int i = 0; i < types.length; ++i) { + types[i] = String.class; + } + return createContainer(ids, types); + } + + private static Container createContainer(Object[] ids, Class[] types) { + IndexedContainer container = new IndexedContainer(); + if (ids.length > types.length) { + throw new IllegalArgumentException("Too few defined types"); + } + for (int i = 0; i < ids.length; ++i) { + container.addContainerProperty(ids[i], types[i], ""); + } + + for (int i = 0; i < 100; i++) { + Item item = container.addItem("item " + i); + for (int j = 0; j < ids.length; ++j) { + Property itemProperty = item.getItemProperty(ids[j]); + if (types[j] == String.class) { + itemProperty.setValue(ids[j].toString() + i); + } else if (types[j] == BaseClass.class) { + itemProperty.setValue(new BaseClass("base" + i)); + } else if (types[j] == DerivedClass.class) { + itemProperty.setValue(new DerivedClass("derived" + i)); + } else if (types[j] == int.class) { + // FIXME can't set values because the int is autoboxed into + // an Integer and not unboxed prior to set + + // itemProperty.setValue(i); + } else { + throw new IllegalArgumentException( + "Unhandled type in createContainer: " + types[j]); + } + } + } + + return container; + } + + private class TestableTable extends Table { + /** + * @param string + * @param createContainer + */ + public TestableTable(String string, Container container) { + super(string, container); + } + + Set getCurrentConverters() { + try { + Field f = Table.class + .getDeclaredField("propertyValueConverters"); + f.setAccessible(true); + HashMap> pvc = (HashMap>) f + .get(this); + Set currentConverters = new HashSet(); + for (Entry> entry : pvc + .entrySet()) { + currentConverters.add(entry.getKey()); + } + return currentConverters; + + } catch (Exception e) { + fail("Unable to retrieve propertyValueConverters"); + return null; + } + } + } + + private static class BaseClass { + private String title; + + public BaseClass(String title) { + this.title = title; + } + } + + private static class DerivedClass extends BaseClass { + public DerivedClass(String title) { + super(title); + } + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/table/TableSerialization.java b/server/tests/src/com/vaadin/tests/server/component/table/TableSerialization.java deleted file mode 100644 index ee6349093c..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/table/TableSerialization.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.vaadin.tests.server.component.table; - -import junit.framework.TestCase; - -import org.apache.commons.lang.SerializationUtils; - -import com.vaadin.ui.Table; - -public class TableSerialization extends TestCase { - - public void testSerialization() { - Table t = new Table(); - byte[] ser = SerializationUtils.serialize(t); - Table t2 = (Table) SerializationUtils.deserialize(ser); - - } - - public void testSerializationWithRowHeaders() { - Table t = new Table(); - t.setRowHeaderMode(Table.ROW_HEADER_MODE_EXPLICIT); - t.setColumnWidth(null, 100); - byte[] ser = SerializationUtils.serialize(t); - Table t2 = (Table) SerializationUtils.deserialize(ser); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/table/TableSerializationTest.java b/server/tests/src/com/vaadin/tests/server/component/table/TableSerializationTest.java new file mode 100644 index 0000000000..3f3c52d6c0 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/table/TableSerializationTest.java @@ -0,0 +1,25 @@ +package com.vaadin.tests.server.component.table; + +import junit.framework.TestCase; + +import org.apache.commons.lang.SerializationUtils; + +import com.vaadin.ui.Table; + +public class TableSerializationTest extends TestCase { + + public void testSerialization() { + Table t = new Table(); + byte[] ser = SerializationUtils.serialize(t); + Table t2 = (Table) SerializationUtils.deserialize(ser); + + } + + public void testSerializationWithRowHeaders() { + Table t = new Table(); + t.setRowHeaderMode(Table.ROW_HEADER_MODE_EXPLICIT); + t.setColumnWidth(null, 100); + byte[] ser = SerializationUtils.serialize(t); + Table t2 = (Table) SerializationUtils.deserialize(ser); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/table/TableVisibleColumns.java b/server/tests/src/com/vaadin/tests/server/component/table/TableVisibleColumns.java deleted file mode 100644 index ee3eefba05..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/table/TableVisibleColumns.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.vaadin.tests.server.component.table; - -import static org.junit.Assert.assertArrayEquals; - -import org.junit.Test; - -import com.vaadin.ui.Table; - -public class TableVisibleColumns { - - String[] defaultColumns3 = new String[] { "Property 0", "Property 1", - "Property 2" }; - - @Test - public void defaultVisibleColumns() { - for (int properties = 0; properties < 10; properties++) { - Table t = TableGenerator.createTableWithDefaultContainer( - properties, 10); - Object[] expected = new Object[properties]; - for (int i = 0; i < properties; i++) { - expected[i] = "Property " + i; - } - org.junit.Assert.assertArrayEquals("getVisibleColumns", expected, - t.getVisibleColumns()); - } - } - - @Test - public void explicitVisibleColumns() { - Table t = TableGenerator.createTableWithDefaultContainer(5, 10); - Object[] newVisibleColumns = new Object[] { "Property 1", "Property 2" }; - t.setVisibleColumns(newVisibleColumns); - assertArrayEquals("Explicit visible columns, 5 properties", - newVisibleColumns, t.getVisibleColumns()); - - } - - @Test - public void invalidVisibleColumnIds() { - Table t = TableGenerator.createTableWithDefaultContainer(3, 10); - - try { - t.setVisibleColumns(new Object[] { "a", "Property 2", "Property 3" }); - junit.framework.Assert.fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException e) { - // OK, expected - } - assertArrayEquals(defaultColumns3, t.getVisibleColumns()); - } - - @Test - public void duplicateVisibleColumnIds() { - Table t = TableGenerator.createTableWithDefaultContainer(3, 10); - try { - t.setVisibleColumns(new Object[] { "Property 0", "Property 1", - "Property 2", "Property 1" }); - } catch (IllegalArgumentException e) { - // OK, expected - } - assertArrayEquals(defaultColumns3, t.getVisibleColumns()); - } - - @Test - public void noVisibleColumns() { - Table t = TableGenerator.createTableWithDefaultContainer(3, 10); - t.setVisibleColumns(new Object[] {}); - assertArrayEquals(new Object[] {}, t.getVisibleColumns()); - - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/table/TableVisibleColumnsTest.java b/server/tests/src/com/vaadin/tests/server/component/table/TableVisibleColumnsTest.java new file mode 100644 index 0000000000..e4f229590f --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/table/TableVisibleColumnsTest.java @@ -0,0 +1,70 @@ +package com.vaadin.tests.server.component.table; + +import static org.junit.Assert.assertArrayEquals; + +import org.junit.Test; + +import com.vaadin.ui.Table; + +public class TableVisibleColumnsTest { + + String[] defaultColumns3 = new String[] { "Property 0", "Property 1", + "Property 2" }; + + @Test + public void defaultVisibleColumns() { + for (int properties = 0; properties < 10; properties++) { + Table t = TableGeneratorTest.createTableWithDefaultContainer( + properties, 10); + Object[] expected = new Object[properties]; + for (int i = 0; i < properties; i++) { + expected[i] = "Property " + i; + } + org.junit.Assert.assertArrayEquals("getVisibleColumns", expected, + t.getVisibleColumns()); + } + } + + @Test + public void explicitVisibleColumns() { + Table t = TableGeneratorTest.createTableWithDefaultContainer(5, 10); + Object[] newVisibleColumns = new Object[] { "Property 1", "Property 2" }; + t.setVisibleColumns(newVisibleColumns); + assertArrayEquals("Explicit visible columns, 5 properties", + newVisibleColumns, t.getVisibleColumns()); + + } + + @Test + public void invalidVisibleColumnIds() { + Table t = TableGeneratorTest.createTableWithDefaultContainer(3, 10); + + try { + t.setVisibleColumns(new Object[] { "a", "Property 2", "Property 3" }); + junit.framework.Assert.fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException e) { + // OK, expected + } + assertArrayEquals(defaultColumns3, t.getVisibleColumns()); + } + + @Test + public void duplicateVisibleColumnIds() { + Table t = TableGeneratorTest.createTableWithDefaultContainer(3, 10); + try { + t.setVisibleColumns(new Object[] { "Property 0", "Property 1", + "Property 2", "Property 1" }); + } catch (IllegalArgumentException e) { + // OK, expected + } + assertArrayEquals(defaultColumns3, t.getVisibleColumns()); + } + + @Test + public void noVisibleColumns() { + Table t = TableGeneratorTest.createTableWithDefaultContainer(3, 10); + t.setVisibleColumns(new Object[] {}); + assertArrayEquals(new Object[] {}, t.getVisibleColumns()); + + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/table/TestFooter.java b/server/tests/src/com/vaadin/tests/server/component/table/TestFooter.java deleted file mode 100644 index 647d13855b..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/table/TestFooter.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.vaadin.tests.server.component.table; - -import junit.framework.TestCase; - -import com.vaadin.data.Container; -import com.vaadin.data.Item; -import com.vaadin.data.util.IndexedContainer; -import com.vaadin.ui.Table; - -/** - * Test case for testing the footer API - * - */ -public class TestFooter extends TestCase { - - /** - * Tests if setting the footer visibility works properly - */ - public void testFooterVisibility() { - Table table = new Table("Test table", createContainer()); - - // The footer should by default be hidden - assertFalse(table.isFooterVisible()); - - // Set footer visibility to tru should be reflected in the - // isFooterVisible() method - table.setFooterVisible(true); - assertTrue(table.isFooterVisible()); - } - - /** - * Tests adding footers to the columns - */ - public void testAddingFooters() { - Table table = new Table("Test table", createContainer()); - - // Table should not contain any footers at initialization - assertNull(table.getColumnFooter("col1")); - assertNull(table.getColumnFooter("col2")); - assertNull(table.getColumnFooter("col3")); - - // Adding column footer - table.setColumnFooter("col1", "Footer1"); - assertEquals("Footer1", table.getColumnFooter("col1")); - - // Add another footer - table.setColumnFooter("col2", "Footer2"); - assertEquals("Footer2", table.getColumnFooter("col2")); - - // Add footer for a non-existing column - table.setColumnFooter("fail", "FooterFail"); - } - - /** - * Test removing footers - */ - public void testRemovingFooters() { - Table table = new Table("Test table", createContainer()); - table.setColumnFooter("col1", "Footer1"); - table.setColumnFooter("col2", "Footer2"); - - // Test removing footer - assertNotNull(table.getColumnFooter("col1")); - table.setColumnFooter("col1", null); - assertNull(table.getColumnFooter("col1")); - - // The other footer should still be there - assertNotNull(table.getColumnFooter("col2")); - - // Remove non-existing footer - table.setColumnFooter("fail", null); - } - - /** - * Creates a container with three properties "col1,col2,col3" with 100 items - * - * @return Returns the created table - */ - private static Container createContainer() { - IndexedContainer container = new IndexedContainer(); - container.addContainerProperty("col1", String.class, ""); - container.addContainerProperty("col2", String.class, ""); - container.addContainerProperty("col3", String.class, ""); - - for (int i = 0; i < 100; i++) { - Item item = container.addItem("item " + i); - item.getItemProperty("col1").setValue("first" + i); - item.getItemProperty("col2").setValue("middle" + i); - item.getItemProperty("col3").setValue("last" + i); - } - - return container; - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/table/TestMultipleSelection.java b/server/tests/src/com/vaadin/tests/server/component/table/TestMultipleSelection.java deleted file mode 100644 index ff80cdb3c3..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/table/TestMultipleSelection.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.vaadin.tests.server.component.table; - -import java.util.Arrays; -import java.util.Set; - -import junit.framework.TestCase; - -import com.vaadin.data.Container; -import com.vaadin.data.util.IndexedContainer; -import com.vaadin.shared.ui.MultiSelectMode; -import com.vaadin.ui.Table; - -public class TestMultipleSelection extends TestCase { - - /** - * Tests weather the multiple select mode is set when using Table.set - */ - @SuppressWarnings("unchecked") - public void testSetMultipleItems() { - Table table = new Table("", createTestContainer()); - - // Tests if multiple selection is set - table.setMultiSelect(true); - assertTrue(table.isMultiSelect()); - - // Test multiselect by setting several items at once - - table.setValue(Arrays.asList("1", new String[] { "3" })); - assertEquals(2, ((Set) table.getValue()).size()); - } - - /** - * Tests setting the multiselect mode of the Table. The multiselect mode - * affects how mouse selection is made in the table by the user. - */ - public void testSetMultiSelectMode() { - Table table = new Table("", createTestContainer()); - - // Default multiselect mode should be MultiSelectMode.DEFAULT - assertEquals(MultiSelectMode.DEFAULT, table.getMultiSelectMode()); - - // Tests if multiselectmode is set - table.setMultiSelectMode(MultiSelectMode.SIMPLE); - assertEquals(MultiSelectMode.SIMPLE, table.getMultiSelectMode()); - } - - /** - * Creates a testing container for the tests - * - * @return A new container with test items - */ - private Container createTestContainer() { - IndexedContainer container = new IndexedContainer(Arrays.asList("1", - new String[] { "2", "3", "4" })); - return container; - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/tabsheet/ReadDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/tabsheet/ReadDesignTest.java new file mode 100644 index 0000000000..67533c8b11 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/tabsheet/ReadDesignTest.java @@ -0,0 +1,132 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.tabsheet; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Attributes; +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; + +import com.vaadin.server.ExternalResource; +import com.vaadin.ui.TabSheet; +import com.vaadin.ui.TabSheet.Tab; +import com.vaadin.ui.TextField; +import com.vaadin.ui.declarative.DesignContext; + +/** + * Test case from reading TabSheet from design + * + * @since + * @author Vaadin Ltd + */ +public class ReadDesignTest extends TestCase { + + private TabSheet sheet; + + @Override + protected void setUp() throws Exception { + super.setUp(); + sheet = createTabSheet(); + } + + public void testChildCount() { + assertEquals(1, sheet.getComponentCount()); + } + + public void testTabIndex() { + assertEquals(5, sheet.getTabIndex()); + } + + public void testTabAttributes() { + Tab tab = sheet.getTab(0); + assertEquals("test-caption", tab.getCaption()); + assertEquals(false, tab.isVisible()); + assertEquals(false, tab.isClosable()); + assertEquals(false, tab.isEnabled()); + assertEquals("http://www.vaadin.com/test.png", + ((ExternalResource) tab.getIcon()).getURL()); + assertEquals("OK", tab.getIconAlternateText()); + assertEquals("test-desc", tab.getDescription()); + assertEquals("test-style", tab.getStyleName()); + assertEquals("test-id", tab.getId()); + } + + public void testSelectedComponent() { + TabSheet tabSheet = new TabSheet(); + tabSheet.readDesign(createFirstTabSelectedDesign(), new DesignContext()); + assertEquals(tabSheet.getTab(0).getComponent(), + tabSheet.getSelectedTab()); + } + + public void testTabContent() { + assertTrue("The child for the tabsheet should be textfield", sheet + .getTab(0).getComponent() instanceof TextField); + } + + private TabSheet createTabSheet() { + TabSheet tabSheet = new TabSheet(); + DesignContext ctx = new DesignContext(); + Element design = createDesign(); + tabSheet.readDesign(design, ctx); + return tabSheet; + } + + private Element createDesign() { + // create root design + Attributes rootAttributes = new Attributes(); + rootAttributes.put("tabindex", "5"); + Element node = new Element(Tag.valueOf("v-tab-sheet"), "", + rootAttributes); + // create tab design + Attributes tabAttributes = new Attributes(); + tabAttributes.put("caption", "test-caption"); + tabAttributes.put("visible", "false"); + tabAttributes.put("closable", "false"); + tabAttributes.put("enabled", "false"); + tabAttributes.put("icon", "http://www.vaadin.com/test.png"); + tabAttributes.put("icon-alt", "OK"); + tabAttributes.put("description", "test-desc"); + tabAttributes.put("style-name", "test-style"); + tabAttributes.put("id", "test-id"); + Element tab = new Element(Tag.valueOf("tab"), "", tabAttributes); + // add child component to tab + tab.appendChild(new Element(Tag.valueOf("v-text-field"), "", + new Attributes())); + // add tab to root design + node.appendChild(tab); + return node; + } + + private Element createFirstTabSelectedDesign() { + // create root design + Attributes rootAttributes = new Attributes(); + Element node = new Element(Tag.valueOf("v-tab-sheet"), "", + rootAttributes); + // create tab design + Attributes tabAttributes = new Attributes(); + tabAttributes.put("selected", ""); + tabAttributes.put("caption", "test-caption"); + Element tab = new Element(Tag.valueOf("tab"), "", tabAttributes); + // add child component to tab + tab.appendChild(new Element(Tag.valueOf("v-text-field"), "", + new Attributes())); + // add tab to root design + node.appendChild(tab); + return node; + + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/tabsheet/TabSheetListeners.java b/server/tests/src/com/vaadin/tests/server/component/tabsheet/TabSheetListeners.java deleted file mode 100644 index 5c01a1c99f..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/tabsheet/TabSheetListeners.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.vaadin.tests.server.component.tabsheet; - -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; -import com.vaadin.ui.TabSheet; -import com.vaadin.ui.TabSheet.SelectedTabChangeEvent; -import com.vaadin.ui.TabSheet.SelectedTabChangeListener; - -public class TabSheetListeners extends AbstractListenerMethodsTest { - public void testSelectedTabChangeListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(TabSheet.class, SelectedTabChangeEvent.class, - SelectedTabChangeListener.class); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/tabsheet/TabSheetListenersTest.java b/server/tests/src/com/vaadin/tests/server/component/tabsheet/TabSheetListenersTest.java new file mode 100644 index 0000000000..b1acf05d63 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/tabsheet/TabSheetListenersTest.java @@ -0,0 +1,13 @@ +package com.vaadin.tests.server.component.tabsheet; + +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; +import com.vaadin.ui.TabSheet; +import com.vaadin.ui.TabSheet.SelectedTabChangeEvent; +import com.vaadin.ui.TabSheet.SelectedTabChangeListener; + +public class TabSheetListenersTest extends AbstractListenerMethodsTestBase { + public void testSelectedTabChangeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(TabSheet.class, SelectedTabChangeEvent.class, + SelectedTabChangeListener.class); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/tabsheet/TabSheetTest.java b/server/tests/src/com/vaadin/tests/server/component/tabsheet/TabSheetTest.java new file mode 100644 index 0000000000..29f12fa4b6 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/tabsheet/TabSheetTest.java @@ -0,0 +1,224 @@ +package com.vaadin.tests.server.component.tabsheet; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; + +import java.util.Iterator; + +import org.junit.Test; + +import com.vaadin.ui.Component; +import com.vaadin.ui.Label; +import com.vaadin.ui.TabSheet; +import com.vaadin.ui.TabSheet.Tab; + +public class TabSheetTest { + + @Test + public void addExistingComponent() { + Component c = new Label("abc"); + TabSheet tabSheet = new TabSheet(); + tabSheet.addComponent(c); + tabSheet.addComponent(c); + + Iterator iter = tabSheet.getComponentIterator(); + + assertEquals(c, iter.next()); + assertEquals(false, iter.hasNext()); + assertNotNull(tabSheet.getTab(c)); + } + + @Test + public void getComponentFromTab() { + Component c = new Label("abc"); + TabSheet tabSheet = new TabSheet(); + Tab tab = tabSheet.addTab(c); + assertEquals(c, tab.getComponent()); + } + + @Test + public void addTabWithComponentOnly() { + TabSheet tabSheet = new TabSheet(); + Tab tab1 = tabSheet.addTab(new Label("aaa")); + Tab tab2 = tabSheet.addTab(new Label("bbb")); + Tab tab3 = tabSheet.addTab(new Label("ccc")); + + // Check right order of tabs + assertEquals(0, tabSheet.getTabPosition(tab1)); + assertEquals(1, tabSheet.getTabPosition(tab2)); + assertEquals(2, tabSheet.getTabPosition(tab3)); + + // Calling addTab with existing component does not move tab + tabSheet.addTab(tab1.getComponent()); + + // Check right order of tabs + assertEquals(0, tabSheet.getTabPosition(tab1)); + assertEquals(1, tabSheet.getTabPosition(tab2)); + assertEquals(2, tabSheet.getTabPosition(tab3)); + } + + @Test + public void addTabWithComponentAndIndex() { + TabSheet tabSheet = new TabSheet(); + Tab tab1 = tabSheet.addTab(new Label("aaa")); + Tab tab2 = tabSheet.addTab(new Label("bbb")); + Tab tab3 = tabSheet.addTab(new Label("ccc")); + + Tab tab4 = tabSheet.addTab(new Label("ddd"), 1); + Tab tab5 = tabSheet.addTab(new Label("eee"), 3); + + assertEquals(0, tabSheet.getTabPosition(tab1)); + assertEquals(1, tabSheet.getTabPosition(tab4)); + assertEquals(2, tabSheet.getTabPosition(tab2)); + assertEquals(3, tabSheet.getTabPosition(tab5)); + assertEquals(4, tabSheet.getTabPosition(tab3)); + + // Calling addTab with existing component does not move tab + tabSheet.addTab(tab1.getComponent(), 3); + + assertEquals(0, tabSheet.getTabPosition(tab1)); + assertEquals(1, tabSheet.getTabPosition(tab4)); + assertEquals(2, tabSheet.getTabPosition(tab2)); + assertEquals(3, tabSheet.getTabPosition(tab5)); + assertEquals(4, tabSheet.getTabPosition(tab3)); + } + + @Test + public void addTabWithAllParameters() { + TabSheet tabSheet = new TabSheet(); + Tab tab1 = tabSheet.addTab(new Label("aaa")); + Tab tab2 = tabSheet.addTab(new Label("bbb")); + Tab tab3 = tabSheet.addTab(new Label("ccc")); + + Tab tab4 = tabSheet.addTab(new Label("ddd"), "ddd", null, 1); + Tab tab5 = tabSheet.addTab(new Label("eee"), "eee", null, 3); + + assertEquals(0, tabSheet.getTabPosition(tab1)); + assertEquals(1, tabSheet.getTabPosition(tab4)); + assertEquals(2, tabSheet.getTabPosition(tab2)); + assertEquals(3, tabSheet.getTabPosition(tab5)); + assertEquals(4, tabSheet.getTabPosition(tab3)); + + // Calling addTab with existing component does not move tab + tabSheet.addTab(tab1.getComponent(), "xxx", null, 3); + + assertEquals(0, tabSheet.getTabPosition(tab1)); + assertEquals(1, tabSheet.getTabPosition(tab4)); + assertEquals(2, tabSheet.getTabPosition(tab2)); + assertEquals(3, tabSheet.getTabPosition(tab5)); + assertEquals(4, tabSheet.getTabPosition(tab3)); + } + + @Test + public void getTabByPosition() { + TabSheet tabSheet = new TabSheet(); + Tab tab1 = tabSheet.addTab(new Label("aaa")); + Tab tab2 = tabSheet.addTab(new Label("bbb")); + Tab tab3 = tabSheet.addTab(new Label("ccc")); + + assertEquals(tab1, tabSheet.getTab(0)); + assertEquals(tab2, tabSheet.getTab(1)); + assertEquals(tab3, tabSheet.getTab(2)); + + assertEquals(null, tabSheet.getTab(3)); + } + + @Test + public void selectTab() { + TabSheet tabSheet = new TabSheet(); + Tab tab1 = tabSheet.addTab(new Label("aaa")); + Tab tab2 = tabSheet.addTab(new Label("bbb")); + Tab tab3 = tabSheet.addTab(new Label("ccc")); + Label componentNotInSheet = new Label("ddd"); + Tab tabNotInSheet = new TabSheet().addTab(new Label("eee")); + + assertEquals(tab1.getComponent(), tabSheet.getSelectedTab()); + + // Select tab by component... + tabSheet.setSelectedTab(tab2.getComponent()); + assertEquals(tab2.getComponent(), tabSheet.getSelectedTab()); + + // by tab instance + tabSheet.setSelectedTab(tab3); + assertEquals(tab3.getComponent(), tabSheet.getSelectedTab()); + + // by index + tabSheet.setSelectedTab(0); + assertEquals(tab1.getComponent(), tabSheet.getSelectedTab()); + + // Should be no-op... + tabSheet.setSelectedTab(componentNotInSheet); + assertEquals(tab1.getComponent(), tabSheet.getSelectedTab()); + + // this as well + tabSheet.setSelectedTab(tabNotInSheet); + assertEquals(tab1.getComponent(), tabSheet.getSelectedTab()); + + // and this + tabSheet.setSelectedTab(123); + assertEquals(tab1.getComponent(), tabSheet.getSelectedTab()); + } + + @Test + public void replaceComponent() { + TabSheet tabSheet = new TabSheet(); + Label lbl1 = new Label("aaa"); + Label lbl2 = new Label("bbb"); + Label lbl3 = new Label("ccc"); + Label lbl4 = new Label("ddd"); + + Tab tab1 = tabSheet.addTab(lbl1); + tab1.setCaption("tab1"); + tab1.setClosable(true); + Tab tab2 = tabSheet.addTab(lbl2); + tab2.setDescription("description"); + tab2.setEnabled(false); + + // Replace component not in tabsheet with one already in tabsheet - + // should be no-op + tabSheet.replaceComponent(lbl3, lbl2); + assertEquals(2, tabSheet.getComponentCount()); + assertSame(tab1, tabSheet.getTab(lbl1)); + assertSame(tab2, tabSheet.getTab(lbl2)); + assertNull(tabSheet.getTab(lbl3)); + + // Replace component not in tabsheet with one not in tabsheet either + // should add lbl4 as last tab + tabSheet.replaceComponent(lbl3, lbl4); + assertEquals(3, tabSheet.getComponentCount()); + assertSame(tab1, tabSheet.getTab(lbl1)); + assertSame(tab2, tabSheet.getTab(lbl2)); + assertEquals(2, tabSheet.getTabPosition(tabSheet.getTab(lbl4))); + + // Replace component in tabsheet with another + // should swap places, tab association should stay the same but tabs + // should swap metadata + tabSheet.replaceComponent(lbl1, lbl2); + assertSame(tab1, tabSheet.getTab(lbl1)); + assertSame(tab2, tabSheet.getTab(lbl2)); + assertEquals(false, tab1.isClosable()); + assertEquals(true, tab2.isClosable()); + assertEquals(false, tab1.isEnabled()); + assertEquals(true, tab2.isEnabled()); + assertEquals("description", tab1.getDescription()); + assertEquals(null, tab2.getDescription()); + assertEquals(3, tabSheet.getComponentCount()); + assertEquals(1, tabSheet.getTabPosition(tabSheet.getTab(lbl1))); + assertEquals(0, tabSheet.getTabPosition(tabSheet.getTab(lbl2))); + + // Replace component in tabsheet with one not in tabsheet + // should create a new tab instance for the new component, old tab + // instance should become unattached + // tab metadata should be copied from old to new + tabSheet.replaceComponent(lbl1, lbl3); + assertEquals(3, tabSheet.getComponentCount()); + assertNull(tabSheet.getTab(lbl1)); + assertNull(tab1.getComponent()); + assertNotNull(tabSheet.getTab(lbl3)); + assertEquals(false, tabSheet.getTab(lbl3).isEnabled()); + assertEquals("description", tab1.getDescription()); + assertEquals(1, tabSheet.getTabPosition(tabSheet.getTab(lbl3))); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/tabsheet/TestReadDesign.java b/server/tests/src/com/vaadin/tests/server/component/tabsheet/TestReadDesign.java deleted file mode 100644 index f7c4f16cdc..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/tabsheet/TestReadDesign.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.tabsheet; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Attributes; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; - -import com.vaadin.server.ExternalResource; -import com.vaadin.ui.TabSheet; -import com.vaadin.ui.TabSheet.Tab; -import com.vaadin.ui.TextField; -import com.vaadin.ui.declarative.DesignContext; - -/** - * Test case from reading TabSheet from design - * - * @since - * @author Vaadin Ltd - */ -public class TestReadDesign extends TestCase { - - private TabSheet sheet; - - @Override - protected void setUp() throws Exception { - super.setUp(); - sheet = createTabSheet(); - } - - public void testChildCount() { - assertEquals(1, sheet.getComponentCount()); - } - - public void testTabIndex() { - assertEquals(5, sheet.getTabIndex()); - } - - public void testTabAttributes() { - Tab tab = sheet.getTab(0); - assertEquals("test-caption", tab.getCaption()); - assertEquals(false, tab.isVisible()); - assertEquals(false, tab.isClosable()); - assertEquals(false, tab.isEnabled()); - assertEquals("http://www.vaadin.com/test.png", - ((ExternalResource) tab.getIcon()).getURL()); - assertEquals("OK", tab.getIconAlternateText()); - assertEquals("test-desc", tab.getDescription()); - assertEquals("test-style", tab.getStyleName()); - assertEquals("test-id", tab.getId()); - } - - public void testSelectedComponent() { - TabSheet tabSheet = new TabSheet(); - tabSheet.readDesign(createFirstTabSelectedDesign(), new DesignContext()); - assertEquals(tabSheet.getTab(0).getComponent(), - tabSheet.getSelectedTab()); - } - - public void testTabContent() { - assertTrue("The child for the tabsheet should be textfield", sheet - .getTab(0).getComponent() instanceof TextField); - } - - private TabSheet createTabSheet() { - TabSheet tabSheet = new TabSheet(); - DesignContext ctx = new DesignContext(); - Element design = createDesign(); - tabSheet.readDesign(design, ctx); - return tabSheet; - } - - private Element createDesign() { - // create root design - Attributes rootAttributes = new Attributes(); - rootAttributes.put("tabindex", "5"); - Element node = new Element(Tag.valueOf("v-tab-sheet"), "", - rootAttributes); - // create tab design - Attributes tabAttributes = new Attributes(); - tabAttributes.put("caption", "test-caption"); - tabAttributes.put("visible", "false"); - tabAttributes.put("closable", "false"); - tabAttributes.put("enabled", "false"); - tabAttributes.put("icon", "http://www.vaadin.com/test.png"); - tabAttributes.put("icon-alt", "OK"); - tabAttributes.put("description", "test-desc"); - tabAttributes.put("style-name", "test-style"); - tabAttributes.put("id", "test-id"); - Element tab = new Element(Tag.valueOf("tab"), "", tabAttributes); - // add child component to tab - tab.appendChild(new Element(Tag.valueOf("v-text-field"), "", - new Attributes())); - // add tab to root design - node.appendChild(tab); - return node; - } - - private Element createFirstTabSelectedDesign() { - // create root design - Attributes rootAttributes = new Attributes(); - Element node = new Element(Tag.valueOf("v-tab-sheet"), "", - rootAttributes); - // create tab design - Attributes tabAttributes = new Attributes(); - tabAttributes.put("selected", ""); - tabAttributes.put("caption", "test-caption"); - Element tab = new Element(Tag.valueOf("tab"), "", tabAttributes); - // add child component to tab - tab.appendChild(new Element(Tag.valueOf("v-text-field"), "", - new Attributes())); - // add tab to root design - node.appendChild(tab); - return node; - - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/tabsheet/TestTabSheet.java b/server/tests/src/com/vaadin/tests/server/component/tabsheet/TestTabSheet.java deleted file mode 100644 index 0ef8ae5a76..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/tabsheet/TestTabSheet.java +++ /dev/null @@ -1,224 +0,0 @@ -package com.vaadin.tests.server.component.tabsheet; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; - -import java.util.Iterator; - -import org.junit.Test; - -import com.vaadin.ui.Component; -import com.vaadin.ui.Label; -import com.vaadin.ui.TabSheet; -import com.vaadin.ui.TabSheet.Tab; - -public class TestTabSheet { - - @Test - public void addExistingComponent() { - Component c = new Label("abc"); - TabSheet tabSheet = new TabSheet(); - tabSheet.addComponent(c); - tabSheet.addComponent(c); - - Iterator iter = tabSheet.getComponentIterator(); - - assertEquals(c, iter.next()); - assertEquals(false, iter.hasNext()); - assertNotNull(tabSheet.getTab(c)); - } - - @Test - public void getComponentFromTab() { - Component c = new Label("abc"); - TabSheet tabSheet = new TabSheet(); - Tab tab = tabSheet.addTab(c); - assertEquals(c, tab.getComponent()); - } - - @Test - public void addTabWithComponentOnly() { - TabSheet tabSheet = new TabSheet(); - Tab tab1 = tabSheet.addTab(new Label("aaa")); - Tab tab2 = tabSheet.addTab(new Label("bbb")); - Tab tab3 = tabSheet.addTab(new Label("ccc")); - - // Check right order of tabs - assertEquals(0, tabSheet.getTabPosition(tab1)); - assertEquals(1, tabSheet.getTabPosition(tab2)); - assertEquals(2, tabSheet.getTabPosition(tab3)); - - // Calling addTab with existing component does not move tab - tabSheet.addTab(tab1.getComponent()); - - // Check right order of tabs - assertEquals(0, tabSheet.getTabPosition(tab1)); - assertEquals(1, tabSheet.getTabPosition(tab2)); - assertEquals(2, tabSheet.getTabPosition(tab3)); - } - - @Test - public void addTabWithComponentAndIndex() { - TabSheet tabSheet = new TabSheet(); - Tab tab1 = tabSheet.addTab(new Label("aaa")); - Tab tab2 = tabSheet.addTab(new Label("bbb")); - Tab tab3 = tabSheet.addTab(new Label("ccc")); - - Tab tab4 = tabSheet.addTab(new Label("ddd"), 1); - Tab tab5 = tabSheet.addTab(new Label("eee"), 3); - - assertEquals(0, tabSheet.getTabPosition(tab1)); - assertEquals(1, tabSheet.getTabPosition(tab4)); - assertEquals(2, tabSheet.getTabPosition(tab2)); - assertEquals(3, tabSheet.getTabPosition(tab5)); - assertEquals(4, tabSheet.getTabPosition(tab3)); - - // Calling addTab with existing component does not move tab - tabSheet.addTab(tab1.getComponent(), 3); - - assertEquals(0, tabSheet.getTabPosition(tab1)); - assertEquals(1, tabSheet.getTabPosition(tab4)); - assertEquals(2, tabSheet.getTabPosition(tab2)); - assertEquals(3, tabSheet.getTabPosition(tab5)); - assertEquals(4, tabSheet.getTabPosition(tab3)); - } - - @Test - public void addTabWithAllParameters() { - TabSheet tabSheet = new TabSheet(); - Tab tab1 = tabSheet.addTab(new Label("aaa")); - Tab tab2 = tabSheet.addTab(new Label("bbb")); - Tab tab3 = tabSheet.addTab(new Label("ccc")); - - Tab tab4 = tabSheet.addTab(new Label("ddd"), "ddd", null, 1); - Tab tab5 = tabSheet.addTab(new Label("eee"), "eee", null, 3); - - assertEquals(0, tabSheet.getTabPosition(tab1)); - assertEquals(1, tabSheet.getTabPosition(tab4)); - assertEquals(2, tabSheet.getTabPosition(tab2)); - assertEquals(3, tabSheet.getTabPosition(tab5)); - assertEquals(4, tabSheet.getTabPosition(tab3)); - - // Calling addTab with existing component does not move tab - tabSheet.addTab(tab1.getComponent(), "xxx", null, 3); - - assertEquals(0, tabSheet.getTabPosition(tab1)); - assertEquals(1, tabSheet.getTabPosition(tab4)); - assertEquals(2, tabSheet.getTabPosition(tab2)); - assertEquals(3, tabSheet.getTabPosition(tab5)); - assertEquals(4, tabSheet.getTabPosition(tab3)); - } - - @Test - public void getTabByPosition() { - TabSheet tabSheet = new TabSheet(); - Tab tab1 = tabSheet.addTab(new Label("aaa")); - Tab tab2 = tabSheet.addTab(new Label("bbb")); - Tab tab3 = tabSheet.addTab(new Label("ccc")); - - assertEquals(tab1, tabSheet.getTab(0)); - assertEquals(tab2, tabSheet.getTab(1)); - assertEquals(tab3, tabSheet.getTab(2)); - - assertEquals(null, tabSheet.getTab(3)); - } - - @Test - public void selectTab() { - TabSheet tabSheet = new TabSheet(); - Tab tab1 = tabSheet.addTab(new Label("aaa")); - Tab tab2 = tabSheet.addTab(new Label("bbb")); - Tab tab3 = tabSheet.addTab(new Label("ccc")); - Label componentNotInSheet = new Label("ddd"); - Tab tabNotInSheet = new TabSheet().addTab(new Label("eee")); - - assertEquals(tab1.getComponent(), tabSheet.getSelectedTab()); - - // Select tab by component... - tabSheet.setSelectedTab(tab2.getComponent()); - assertEquals(tab2.getComponent(), tabSheet.getSelectedTab()); - - // by tab instance - tabSheet.setSelectedTab(tab3); - assertEquals(tab3.getComponent(), tabSheet.getSelectedTab()); - - // by index - tabSheet.setSelectedTab(0); - assertEquals(tab1.getComponent(), tabSheet.getSelectedTab()); - - // Should be no-op... - tabSheet.setSelectedTab(componentNotInSheet); - assertEquals(tab1.getComponent(), tabSheet.getSelectedTab()); - - // this as well - tabSheet.setSelectedTab(tabNotInSheet); - assertEquals(tab1.getComponent(), tabSheet.getSelectedTab()); - - // and this - tabSheet.setSelectedTab(123); - assertEquals(tab1.getComponent(), tabSheet.getSelectedTab()); - } - - @Test - public void replaceComponent() { - TabSheet tabSheet = new TabSheet(); - Label lbl1 = new Label("aaa"); - Label lbl2 = new Label("bbb"); - Label lbl3 = new Label("ccc"); - Label lbl4 = new Label("ddd"); - - Tab tab1 = tabSheet.addTab(lbl1); - tab1.setCaption("tab1"); - tab1.setClosable(true); - Tab tab2 = tabSheet.addTab(lbl2); - tab2.setDescription("description"); - tab2.setEnabled(false); - - // Replace component not in tabsheet with one already in tabsheet - - // should be no-op - tabSheet.replaceComponent(lbl3, lbl2); - assertEquals(2, tabSheet.getComponentCount()); - assertSame(tab1, tabSheet.getTab(lbl1)); - assertSame(tab2, tabSheet.getTab(lbl2)); - assertNull(tabSheet.getTab(lbl3)); - - // Replace component not in tabsheet with one not in tabsheet either - // should add lbl4 as last tab - tabSheet.replaceComponent(lbl3, lbl4); - assertEquals(3, tabSheet.getComponentCount()); - assertSame(tab1, tabSheet.getTab(lbl1)); - assertSame(tab2, tabSheet.getTab(lbl2)); - assertEquals(2, tabSheet.getTabPosition(tabSheet.getTab(lbl4))); - - // Replace component in tabsheet with another - // should swap places, tab association should stay the same but tabs - // should swap metadata - tabSheet.replaceComponent(lbl1, lbl2); - assertSame(tab1, tabSheet.getTab(lbl1)); - assertSame(tab2, tabSheet.getTab(lbl2)); - assertEquals(false, tab1.isClosable()); - assertEquals(true, tab2.isClosable()); - assertEquals(false, tab1.isEnabled()); - assertEquals(true, tab2.isEnabled()); - assertEquals("description", tab1.getDescription()); - assertEquals(null, tab2.getDescription()); - assertEquals(3, tabSheet.getComponentCount()); - assertEquals(1, tabSheet.getTabPosition(tabSheet.getTab(lbl1))); - assertEquals(0, tabSheet.getTabPosition(tabSheet.getTab(lbl2))); - - // Replace component in tabsheet with one not in tabsheet - // should create a new tab instance for the new component, old tab - // instance should become unattached - // tab metadata should be copied from old to new - tabSheet.replaceComponent(lbl1, lbl3); - assertEquals(3, tabSheet.getComponentCount()); - assertNull(tabSheet.getTab(lbl1)); - assertNull(tab1.getComponent()); - assertNotNull(tabSheet.getTab(lbl3)); - assertEquals(false, tabSheet.getTab(lbl3).isEnabled()); - assertEquals("description", tab1.getDescription()); - assertEquals(1, tabSheet.getTabPosition(tabSheet.getTab(lbl3))); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/tabsheet/TestWriteDesign.java b/server/tests/src/com/vaadin/tests/server/component/tabsheet/TestWriteDesign.java deleted file mode 100644 index a46b33e2d6..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/tabsheet/TestWriteDesign.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.tabsheet; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Attributes; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; - -import com.vaadin.server.ExternalResource; -import com.vaadin.ui.TabSheet; -import com.vaadin.ui.TabSheet.Tab; -import com.vaadin.ui.TextField; -import com.vaadin.ui.declarative.DesignContext; - -/** - * Test case for writing TabSheet to design - * - * @since - * @author Vaadin Ltd - */ -public class TestWriteDesign extends TestCase { - - private TabSheet sheet; - private Element design; - - @Override - protected void setUp() throws Exception { - super.setUp(); - sheet = createTabSheet(); - design = createDesign(); - sheet.writeDesign(design, createDesignContext()); - } - - public void testOnlyOneTab() { - assertEquals("There should be only one child", 1, design.children() - .size()); - } - - public void testAttributes() { - Element tabDesign = design.child(0); - assertEquals("5", design.attr("tabindex")); - assertEquals("test-caption", tabDesign.attr("caption")); - assertEquals("false", tabDesign.attr("visible")); - assertTrue(tabDesign.hasAttr("closable")); - assertTrue(tabDesign.attr("closable").equals("true") - || tabDesign.attr("closable").equals("")); - assertEquals("false", tabDesign.attr("enabled")); - assertEquals("http://www.vaadin.com/test.png", tabDesign.attr("icon")); - assertEquals("OK", tabDesign.attr("icon-alt")); - assertEquals("test-desc", tabDesign.attr("description")); - assertEquals("test-style", tabDesign.attr("style-name")); - assertEquals("test-id", tabDesign.attr("id")); - } - - public void testContent() { - Element tabDesign = design.child(0); - Element content = tabDesign.child(0); - assertEquals("Tab must have only one child", 1, tabDesign.children() - .size()); - assertEquals("v-text-field", content.tagName()); - } - - private Element createDesign() { - // make sure that the design node has old content that should be removed - Element node = new Element(Tag.valueOf("v-tab-sheet"), "", - new Attributes()); - node.appendChild(new Element(Tag.valueOf("tab"), "", new Attributes())); - node.appendChild(new Element(Tag.valueOf("tab"), "", new Attributes())); - node.appendChild(new Element(Tag.valueOf("tab"), "", new Attributes())); - return node; - } - - private DesignContext createDesignContext() { - return new DesignContext(); - } - - private TabSheet createTabSheet() { - TabSheet sheet = new TabSheet(); - sheet.setTabIndex(5); - sheet.addTab(new TextField()); - Tab tab = sheet.getTab(0); - tab.setCaption("test-caption"); - tab.setVisible(false); - tab.setClosable(true); - tab.setEnabled(false); - tab.setIcon(new ExternalResource("http://www.vaadin.com/test.png")); - tab.setIconAlternateText("OK"); - tab.setDescription("test-desc"); - tab.setStyleName("test-style"); - tab.setId("test-id"); - return sheet; - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/component/tabsheet/WriteDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/tabsheet/WriteDesignTest.java new file mode 100644 index 0000000000..ab7ef9977c --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/tabsheet/WriteDesignTest.java @@ -0,0 +1,109 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.tabsheet; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Attributes; +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; + +import com.vaadin.server.ExternalResource; +import com.vaadin.ui.TabSheet; +import com.vaadin.ui.TabSheet.Tab; +import com.vaadin.ui.TextField; +import com.vaadin.ui.declarative.DesignContext; + +/** + * Test case for writing TabSheet to design + * + * @since + * @author Vaadin Ltd + */ +public class WriteDesignTest extends TestCase { + + private TabSheet sheet; + private Element design; + + @Override + protected void setUp() throws Exception { + super.setUp(); + sheet = createTabSheet(); + design = createDesign(); + sheet.writeDesign(design, createDesignContext()); + } + + public void testOnlyOneTab() { + assertEquals("There should be only one child", 1, design.children() + .size()); + } + + public void testAttributes() { + Element tabDesign = design.child(0); + assertEquals("5", design.attr("tabindex")); + assertEquals("test-caption", tabDesign.attr("caption")); + assertEquals("false", tabDesign.attr("visible")); + assertTrue(tabDesign.hasAttr("closable")); + assertTrue(tabDesign.attr("closable").equals("true") + || tabDesign.attr("closable").equals("")); + assertEquals("false", tabDesign.attr("enabled")); + assertEquals("http://www.vaadin.com/test.png", tabDesign.attr("icon")); + assertEquals("OK", tabDesign.attr("icon-alt")); + assertEquals("test-desc", tabDesign.attr("description")); + assertEquals("test-style", tabDesign.attr("style-name")); + assertEquals("test-id", tabDesign.attr("id")); + } + + public void testContent() { + Element tabDesign = design.child(0); + Element content = tabDesign.child(0); + assertEquals("Tab must have only one child", 1, tabDesign.children() + .size()); + assertEquals("v-text-field", content.tagName()); + } + + private Element createDesign() { + // make sure that the design node has old content that should be removed + Element node = new Element(Tag.valueOf("v-tab-sheet"), "", + new Attributes()); + node.appendChild(new Element(Tag.valueOf("tab"), "", new Attributes())); + node.appendChild(new Element(Tag.valueOf("tab"), "", new Attributes())); + node.appendChild(new Element(Tag.valueOf("tab"), "", new Attributes())); + return node; + } + + private DesignContext createDesignContext() { + return new DesignContext(); + } + + private TabSheet createTabSheet() { + TabSheet sheet = new TabSheet(); + sheet.setTabIndex(5); + sheet.addTab(new TextField()); + Tab tab = sheet.getTab(0); + tab.setCaption("test-caption"); + tab.setVisible(false); + tab.setClosable(true); + tab.setEnabled(false); + tab.setIcon(new ExternalResource("http://www.vaadin.com/test.png")); + tab.setIconAlternateText("OK"); + tab.setDescription("test-desc"); + tab.setStyleName("test-style"); + tab.setId("test-id"); + return sheet; + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/component/textarea/ReadDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/textarea/ReadDesignTest.java new file mode 100644 index 0000000000..aad831e91c --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/textarea/ReadDesignTest.java @@ -0,0 +1,59 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.textarea; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Attributes; +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; + +import com.vaadin.ui.AbstractTextField; +import com.vaadin.ui.TextArea; +import com.vaadin.ui.declarative.DesignContext; + +/** + * Test case for reading the value of the TextField from design + * + * @author Vaadin Ltd + */ +public class ReadDesignTest extends TestCase { + private DesignContext ctx; + + @Override + protected void setUp() throws Exception { + super.setUp(); + ctx = new DesignContext(); + } + + public void testValue() { + Element design = createDesign(); + AbstractTextField component = getComponent(); + component.readDesign(design, ctx); + assertEquals("test value", component.getValue()); + } + + private AbstractTextField getComponent() { + return new TextArea(); + } + + private Element createDesign() { + Attributes attributes = new Attributes(); + Element node = new Element(Tag.valueOf("v-text-area"), "", attributes); + node.html("test value"); + return node; + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/textarea/TestReadDesign.java b/server/tests/src/com/vaadin/tests/server/component/textarea/TestReadDesign.java deleted file mode 100644 index a31367008a..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/textarea/TestReadDesign.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.textarea; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Attributes; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; - -import com.vaadin.ui.AbstractTextField; -import com.vaadin.ui.TextArea; -import com.vaadin.ui.declarative.DesignContext; - -/** - * Test case for reading the value of the TextField from design - * - * @author Vaadin Ltd - */ -public class TestReadDesign extends TestCase { - private DesignContext ctx; - - @Override - protected void setUp() throws Exception { - super.setUp(); - ctx = new DesignContext(); - } - - public void testValue() { - Element design = createDesign(); - AbstractTextField component = getComponent(); - component.readDesign(design, ctx); - assertEquals("test value", component.getValue()); - } - - private AbstractTextField getComponent() { - return new TextArea(); - } - - private Element createDesign() { - Attributes attributes = new Attributes(); - Element node = new Element(Tag.valueOf("v-text-area"), "", attributes); - node.html("test value"); - return node; - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/textarea/TestWriteDesign.java b/server/tests/src/com/vaadin/tests/server/component/textarea/TestWriteDesign.java deleted file mode 100644 index 01b0095fe9..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/textarea/TestWriteDesign.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.textarea; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Attributes; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; - -import com.vaadin.ui.AbstractTextField; -import com.vaadin.ui.TextArea; -import com.vaadin.ui.declarative.DesignContext; - -/** - * Test case for writing the value of the TextField to design - * - * @author Vaadin Ltd - */ -public class TestWriteDesign extends TestCase { - private DesignContext ctx; - - @Override - protected void setUp() throws Exception { - super.setUp(); - ctx = new DesignContext(); - } - - public void testSynchronizeValue() { - Element design = createDesign(); - AbstractTextField component = getComponent(); - component.setValue("test value"); - component.writeDesign(design, ctx); - assertEquals("test value", design.html()); - assertFalse(design.hasAttr("value")); - } - - private AbstractTextField getComponent() { - return new TextArea(); - } - - private Element createDesign() { - Attributes attr = new Attributes(); - return new Element(Tag.valueOf("v-text-area"), "", attr); - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/component/textarea/WriteDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/textarea/WriteDesignTest.java new file mode 100644 index 0000000000..63712eba15 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/textarea/WriteDesignTest.java @@ -0,0 +1,60 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.textarea; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Attributes; +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; + +import com.vaadin.ui.AbstractTextField; +import com.vaadin.ui.TextArea; +import com.vaadin.ui.declarative.DesignContext; + +/** + * Test case for writing the value of the TextField to design + * + * @author Vaadin Ltd + */ +public class WriteDesignTest extends TestCase { + private DesignContext ctx; + + @Override + protected void setUp() throws Exception { + super.setUp(); + ctx = new DesignContext(); + } + + public void testSynchronizeValue() { + Element design = createDesign(); + AbstractTextField component = getComponent(); + component.setValue("test value"); + component.writeDesign(design, ctx); + assertEquals("test value", design.html()); + assertFalse(design.hasAttr("value")); + } + + private AbstractTextField getComponent() { + return new TextArea(); + } + + private Element createDesign() { + Attributes attr = new Attributes(); + return new Element(Tag.valueOf("v-text-area"), "", attr); + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/component/textfield/ReadDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/textfield/ReadDesignTest.java new file mode 100644 index 0000000000..d3da7fef8b --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/textfield/ReadDesignTest.java @@ -0,0 +1,59 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.textfield; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Attributes; +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; + +import com.vaadin.ui.AbstractTextField; +import com.vaadin.ui.TextField; +import com.vaadin.ui.declarative.DesignContext; + +/** + * Test case for reading the value of the TextField from design + * + * @author Vaadin Ltd + */ +public class ReadDesignTest extends TestCase { + private DesignContext ctx; + + @Override + protected void setUp() throws Exception { + super.setUp(); + ctx = new DesignContext(); + } + + public void testValue() { + Element design = createDesign(); + AbstractTextField component = getComponent(); + component.readDesign(design, ctx); + assertEquals("test value", component.getValue()); + } + + private AbstractTextField getComponent() { + return new TextField(); + } + + private Element createDesign() { + Attributes attributes = new Attributes(); + attributes.put("value", "test value"); + Element node = new Element(Tag.valueOf("v-text-field"), "", attributes); + return node; + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/textfield/TestReadDesign.java b/server/tests/src/com/vaadin/tests/server/component/textfield/TestReadDesign.java deleted file mode 100644 index 62cb1a53bc..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/textfield/TestReadDesign.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.textfield; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Attributes; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; - -import com.vaadin.ui.AbstractTextField; -import com.vaadin.ui.TextField; -import com.vaadin.ui.declarative.DesignContext; - -/** - * Test case for reading the value of the TextField from design - * - * @author Vaadin Ltd - */ -public class TestReadDesign extends TestCase { - private DesignContext ctx; - - @Override - protected void setUp() throws Exception { - super.setUp(); - ctx = new DesignContext(); - } - - public void testValue() { - Element design = createDesign(); - AbstractTextField component = getComponent(); - component.readDesign(design, ctx); - assertEquals("test value", component.getValue()); - } - - private AbstractTextField getComponent() { - return new TextField(); - } - - private Element createDesign() { - Attributes attributes = new Attributes(); - attributes.put("value", "test value"); - Element node = new Element(Tag.valueOf("v-text-field"), "", attributes); - return node; - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/textfield/TestWriteDesign.java b/server/tests/src/com/vaadin/tests/server/component/textfield/TestWriteDesign.java deleted file mode 100644 index 479c94f6a8..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/textfield/TestWriteDesign.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.textfield; - -import junit.framework.TestCase; - -import org.jsoup.nodes.Attributes; -import org.jsoup.nodes.Element; -import org.jsoup.parser.Tag; - -import com.vaadin.ui.AbstractTextField; -import com.vaadin.ui.TextField; -import com.vaadin.ui.declarative.DesignContext; - -/** - * Test case for writing the value of the TextField to design - * - * @author Vaadin Ltd - */ -public class TestWriteDesign extends TestCase { - private DesignContext ctx; - - @Override - protected void setUp() throws Exception { - super.setUp(); - ctx = new DesignContext(); - } - - public void testSynchronizeValue() { - Element design = createDesign(); - AbstractTextField component = getComponent(); - component.setValue("test value"); - component.writeDesign(design, ctx); - assertEquals("test value", design.attr("value")); - } - - private AbstractTextField getComponent() { - return new TextField(); - } - - private Element createDesign() { - Attributes attr = new Attributes(); - return new Element(Tag.valueOf("v-text-field"), "", attr); - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/component/textfield/TextFieldWithConverterAndValidator.java b/server/tests/src/com/vaadin/tests/server/component/textfield/TextFieldWithConverterAndValidator.java deleted file mode 100644 index cdb001e266..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/textfield/TextFieldWithConverterAndValidator.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.vaadin.tests.server.component.textfield; - -import junit.framework.TestCase; - -import com.vaadin.data.util.ObjectProperty; -import com.vaadin.data.validator.RangeValidator; -import com.vaadin.tests.data.converter.ConverterFactory.ConvertTo42; -import com.vaadin.ui.TextField; - -public class TextFieldWithConverterAndValidator extends TestCase { - - private TextField field; - private ObjectProperty property; - - @Override - protected void setUp() throws Exception { - super.setUp(); - - field = new TextField(); - field.setInvalidAllowed(false); - } - - public void testConvert42AndValidator() { - property = new ObjectProperty(123); - field.setConverter(new ConvertTo42()); - field.setPropertyDataSource(property); - - field.addValidator(new RangeValidator("Incorrect value", - Integer.class, 42, 42)); - - // succeeds - field.setValue("a"); - // succeeds - field.setValue("42"); - // succeeds - no validation - property.setValue(42); - - // nulls - - // succeeds - validate() converts field value back to property type - // before validation - property.setValue(null); - field.validate(); - // succeeds - field.setValue(null); - } - - // TODO test converter changing value to null with validator -} diff --git a/server/tests/src/com/vaadin/tests/server/component/textfield/TextFieldWithConverterAndValidatorTest.java b/server/tests/src/com/vaadin/tests/server/component/textfield/TextFieldWithConverterAndValidatorTest.java new file mode 100644 index 0000000000..83c45f94db --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/textfield/TextFieldWithConverterAndValidatorTest.java @@ -0,0 +1,49 @@ +package com.vaadin.tests.server.component.textfield; + +import junit.framework.TestCase; + +import com.vaadin.data.util.ObjectProperty; +import com.vaadin.data.validator.RangeValidator; +import com.vaadin.tests.data.converter.ConverterFactoryTest.ConvertTo42; +import com.vaadin.ui.TextField; + +public class TextFieldWithConverterAndValidatorTest extends TestCase { + + private TextField field; + private ObjectProperty property; + + @Override + protected void setUp() throws Exception { + super.setUp(); + + field = new TextField(); + field.setInvalidAllowed(false); + } + + public void testConvert42AndValidator() { + property = new ObjectProperty(123); + field.setConverter(new ConvertTo42()); + field.setPropertyDataSource(property); + + field.addValidator(new RangeValidator("Incorrect value", + Integer.class, 42, 42)); + + // succeeds + field.setValue("a"); + // succeeds + field.setValue("42"); + // succeeds - no validation + property.setValue(42); + + // nulls + + // succeeds - validate() converts field value back to property type + // before validation + property.setValue(null); + field.validate(); + // succeeds + field.setValue(null); + } + + // TODO test converter changing value to null with validator +} diff --git a/server/tests/src/com/vaadin/tests/server/component/textfield/TextFieldWithPropertyFormatter.java b/server/tests/src/com/vaadin/tests/server/component/textfield/TextFieldWithPropertyFormatter.java deleted file mode 100644 index 59922d819f..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/textfield/TextFieldWithPropertyFormatter.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.vaadin.tests.server.component.textfield; - -import java.util.Collections; - -import junit.framework.TestCase; - -import com.vaadin.data.Property; -import com.vaadin.data.Property.ValueChangeEvent; -import com.vaadin.data.Property.ValueChangeListener; -import com.vaadin.data.util.ObjectProperty; -import com.vaadin.data.util.PropertyFormatter; -import com.vaadin.ui.TextField; - -public class TextFieldWithPropertyFormatter extends TestCase { - - private static final String INPUT_VALUE = "foo"; - private static final String PARSED_VALUE = "BAR"; - private static final String FORMATTED_VALUE = "FOOBAR"; - private static final String ORIGINAL_VALUE = "Original"; - private TextField field; - private PropertyFormatter formatter; - private ObjectProperty property; - private ValueChangeListener listener; - private int listenerCalled; - private int repainted; - - @Override - protected void setUp() throws Exception { - super.setUp(); - - field = new TextField() { - @Override - public void markAsDirty() { - repainted++; - super.markAsDirty(); - } - }; - - formatter = new PropertyFormatter() { - - @Override - public String parse(String formattedValue) throws Exception { - assertEquals(INPUT_VALUE, formattedValue); - return PARSED_VALUE; - } - - @Override - public String format(String value) { - return FORMATTED_VALUE; - } - }; - - property = new ObjectProperty(ORIGINAL_VALUE); - - formatter.setPropertyDataSource(property); - field.setPropertyDataSource(formatter); - - listener = new Property.ValueChangeListener() { - - @Override - public void valueChange(ValueChangeEvent event) { - listenerCalled++; - assertEquals(1, listenerCalled); - assertEquals(FORMATTED_VALUE, event.getProperty().getValue()); - } - }; - - field.addListener(listener); - listenerCalled = 0; - repainted = 0; - } - - public void testWithServerApi() { - checkInitialState(); - - field.setValue(INPUT_VALUE); - - checkEndState(); - - } - - private void checkEndState() { - assertEquals(1, listenerCalled); - assertTrue(repainted >= 1); - assertEquals(FORMATTED_VALUE, field.getValue()); - assertEquals(FORMATTED_VALUE, formatter.getValue()); - assertEquals(PARSED_VALUE, property.getValue()); - } - - private void checkInitialState() { - assertEquals(ORIGINAL_VALUE, property.getValue()); - assertEquals(FORMATTED_VALUE, formatter.getValue()); - assertEquals(FORMATTED_VALUE, field.getValue()); - } - - public void testWithSimulatedClientSideChange() { - checkInitialState(); - - field.changeVariables(null, - Collections.singletonMap("text", (Object) INPUT_VALUE)); - - checkEndState(); - - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/component/textfield/TextFieldWithPropertyFormatterTest.java b/server/tests/src/com/vaadin/tests/server/component/textfield/TextFieldWithPropertyFormatterTest.java new file mode 100644 index 0000000000..8f2bec455b --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/textfield/TextFieldWithPropertyFormatterTest.java @@ -0,0 +1,106 @@ +package com.vaadin.tests.server.component.textfield; + +import java.util.Collections; + +import junit.framework.TestCase; + +import com.vaadin.data.Property; +import com.vaadin.data.Property.ValueChangeEvent; +import com.vaadin.data.Property.ValueChangeListener; +import com.vaadin.data.util.ObjectProperty; +import com.vaadin.data.util.PropertyFormatter; +import com.vaadin.ui.TextField; + +public class TextFieldWithPropertyFormatterTest extends TestCase { + + private static final String INPUT_VALUE = "foo"; + private static final String PARSED_VALUE = "BAR"; + private static final String FORMATTED_VALUE = "FOOBAR"; + private static final String ORIGINAL_VALUE = "Original"; + private TextField field; + private PropertyFormatter formatter; + private ObjectProperty property; + private ValueChangeListener listener; + private int listenerCalled; + private int repainted; + + @Override + protected void setUp() throws Exception { + super.setUp(); + + field = new TextField() { + @Override + public void markAsDirty() { + repainted++; + super.markAsDirty(); + } + }; + + formatter = new PropertyFormatter() { + + @Override + public String parse(String formattedValue) throws Exception { + assertEquals(INPUT_VALUE, formattedValue); + return PARSED_VALUE; + } + + @Override + public String format(String value) { + return FORMATTED_VALUE; + } + }; + + property = new ObjectProperty(ORIGINAL_VALUE); + + formatter.setPropertyDataSource(property); + field.setPropertyDataSource(formatter); + + listener = new Property.ValueChangeListener() { + + @Override + public void valueChange(ValueChangeEvent event) { + listenerCalled++; + assertEquals(1, listenerCalled); + assertEquals(FORMATTED_VALUE, event.getProperty().getValue()); + } + }; + + field.addListener(listener); + listenerCalled = 0; + repainted = 0; + } + + public void testWithServerApi() { + checkInitialState(); + + field.setValue(INPUT_VALUE); + + checkEndState(); + + } + + private void checkEndState() { + assertEquals(1, listenerCalled); + assertTrue(repainted >= 1); + assertEquals(FORMATTED_VALUE, field.getValue()); + assertEquals(FORMATTED_VALUE, formatter.getValue()); + assertEquals(PARSED_VALUE, property.getValue()); + } + + private void checkInitialState() { + assertEquals(ORIGINAL_VALUE, property.getValue()); + assertEquals(FORMATTED_VALUE, formatter.getValue()); + assertEquals(FORMATTED_VALUE, field.getValue()); + } + + public void testWithSimulatedClientSideChange() { + checkInitialState(); + + field.changeVariables(null, + Collections.singletonMap("text", (Object) INPUT_VALUE)); + + checkEndState(); + + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/component/textfield/TextFieldWithValidator.java b/server/tests/src/com/vaadin/tests/server/component/textfield/TextFieldWithValidator.java deleted file mode 100644 index 2a79d1fe27..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/textfield/TextFieldWithValidator.java +++ /dev/null @@ -1,172 +0,0 @@ -package com.vaadin.tests.server.component.textfield; - -import junit.framework.TestCase; - -import com.vaadin.data.Validator; -import com.vaadin.data.Validator.InvalidValueException; -import com.vaadin.data.util.ObjectProperty; -import com.vaadin.data.validator.EmailValidator; -import com.vaadin.data.validator.RegexpValidator; -import com.vaadin.data.validator.StringLengthValidator; -import com.vaadin.ui.TextField; - -public class TextFieldWithValidator extends TestCase { - - private TextField field; - private ObjectProperty property; - - @Override - protected void setUp() throws Exception { - super.setUp(); - - field = new TextField(); - field.setInvalidAllowed(false); - property = new ObjectProperty("original"); - field.setPropertyDataSource(property); - } - - public void testMultipleValidators() { - field.addValidator(new StringLengthValidator( - "Length not between 1 and 3", 1, 3, false)); - field.addValidator(new StringLengthValidator( - "Length not between 2 and 4", 2, 4, false)); - - // fails - try { - field.setValue("a"); - fail(); - } catch (InvalidValueException e) { - // should fail - } - // succeeds - field.setValue("ab"); - // fails - try { - field.setValue("abcd"); - fail(); - } catch (InvalidValueException e) { - // should fail - } - } - - public void testRemoveValidator() { - Validator validator1 = new StringLengthValidator( - "Length not between 1 and 3", 1, 3, false); - Validator validator2 = new StringLengthValidator( - "Length not between 2 and 4", 2, 4, false); - - field.addValidator(validator1); - field.addValidator(validator2); - field.removeValidator(validator1); - - // fails - try { - field.setValue("a"); - fail(); - } catch (InvalidValueException e) { - // should fail - } - // succeeds - field.setValue("ab"); - // succeeds - field.setValue("abcd"); - } - - public void testRemoveAllValidators() { - Validator validator1 = new StringLengthValidator( - "Length not between 1 and 3", 1, 3, false); - Validator validator2 = new StringLengthValidator( - "Length not between 2 and 4", 2, 4, false); - - field.addValidator(validator1); - field.addValidator(validator2); - field.removeAllValidators(); - - // all should succeed now - field.setValue("a"); - field.setValue("ab"); - field.setValue("abcd"); - } - - public void testEmailValidator() { - field.addValidator(new EmailValidator("Invalid e-mail address")); - - // not required - - field.setRequired(false); - // succeeds - field.setValue(""); - // needed as required flag not checked by setValue() - field.validate(); - // succeeds - field.setValue(null); - // needed as required flag not checked by setValue() - field.validate(); - // succeeds - field.setValue("test@example.com"); - // fails - try { - field.setValue("invalid e-mail"); - fail(); - } catch (InvalidValueException e) { - // should fail - } - - // required - - field.setRequired(true); - // fails - try { - field.setValue(""); - // needed as required flag not checked by setValue() - field.validate(); - fail(); - } catch (InvalidValueException e) { - // should fail - } - // fails - try { - field.setValue(null); - // needed as required flag not checked by setValue() - field.validate(); - fail(); - } catch (InvalidValueException e) { - // should fail - } - // succeeds - field.setValue("test@example.com"); - // fails - try { - field.setValue("invalid e-mail"); - fail(); - } catch (InvalidValueException e) { - // should fail - } - } - - public void testRegexpValidator() { - field.addValidator(new RegexpValidator("pattern", true, - "Validation failed")); - field.setRequired(false); - - // succeeds - field.setValue(""); - // needed as required flag not checked by setValue() - field.validate(); - // succeeds - field.setValue(null); - // needed as required flag not checked by setValue() - field.validate(); - // succeeds - field.setValue("pattern"); - - // fails - try { - field.setValue("mismatch"); - fail(); - } catch (InvalidValueException e) { - // should fail - } - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/component/textfield/TextFieldWithValidatorTest.java b/server/tests/src/com/vaadin/tests/server/component/textfield/TextFieldWithValidatorTest.java new file mode 100644 index 0000000000..b2a51aad8b --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/textfield/TextFieldWithValidatorTest.java @@ -0,0 +1,172 @@ +package com.vaadin.tests.server.component.textfield; + +import junit.framework.TestCase; + +import com.vaadin.data.Validator; +import com.vaadin.data.Validator.InvalidValueException; +import com.vaadin.data.util.ObjectProperty; +import com.vaadin.data.validator.EmailValidator; +import com.vaadin.data.validator.RegexpValidator; +import com.vaadin.data.validator.StringLengthValidator; +import com.vaadin.ui.TextField; + +public class TextFieldWithValidatorTest extends TestCase { + + private TextField field; + private ObjectProperty property; + + @Override + protected void setUp() throws Exception { + super.setUp(); + + field = new TextField(); + field.setInvalidAllowed(false); + property = new ObjectProperty("original"); + field.setPropertyDataSource(property); + } + + public void testMultipleValidators() { + field.addValidator(new StringLengthValidator( + "Length not between 1 and 3", 1, 3, false)); + field.addValidator(new StringLengthValidator( + "Length not between 2 and 4", 2, 4, false)); + + // fails + try { + field.setValue("a"); + fail(); + } catch (InvalidValueException e) { + // should fail + } + // succeeds + field.setValue("ab"); + // fails + try { + field.setValue("abcd"); + fail(); + } catch (InvalidValueException e) { + // should fail + } + } + + public void testRemoveValidator() { + Validator validator1 = new StringLengthValidator( + "Length not between 1 and 3", 1, 3, false); + Validator validator2 = new StringLengthValidator( + "Length not between 2 and 4", 2, 4, false); + + field.addValidator(validator1); + field.addValidator(validator2); + field.removeValidator(validator1); + + // fails + try { + field.setValue("a"); + fail(); + } catch (InvalidValueException e) { + // should fail + } + // succeeds + field.setValue("ab"); + // succeeds + field.setValue("abcd"); + } + + public void testRemoveAllValidators() { + Validator validator1 = new StringLengthValidator( + "Length not between 1 and 3", 1, 3, false); + Validator validator2 = new StringLengthValidator( + "Length not between 2 and 4", 2, 4, false); + + field.addValidator(validator1); + field.addValidator(validator2); + field.removeAllValidators(); + + // all should succeed now + field.setValue("a"); + field.setValue("ab"); + field.setValue("abcd"); + } + + public void testEmailValidator() { + field.addValidator(new EmailValidator("Invalid e-mail address")); + + // not required + + field.setRequired(false); + // succeeds + field.setValue(""); + // needed as required flag not checked by setValue() + field.validate(); + // succeeds + field.setValue(null); + // needed as required flag not checked by setValue() + field.validate(); + // succeeds + field.setValue("test@example.com"); + // fails + try { + field.setValue("invalid e-mail"); + fail(); + } catch (InvalidValueException e) { + // should fail + } + + // required + + field.setRequired(true); + // fails + try { + field.setValue(""); + // needed as required flag not checked by setValue() + field.validate(); + fail(); + } catch (InvalidValueException e) { + // should fail + } + // fails + try { + field.setValue(null); + // needed as required flag not checked by setValue() + field.validate(); + fail(); + } catch (InvalidValueException e) { + // should fail + } + // succeeds + field.setValue("test@example.com"); + // fails + try { + field.setValue("invalid e-mail"); + fail(); + } catch (InvalidValueException e) { + // should fail + } + } + + public void testRegexpValidator() { + field.addValidator(new RegexpValidator("pattern", true, + "Validation failed")); + field.setRequired(false); + + // succeeds + field.setValue(""); + // needed as required flag not checked by setValue() + field.validate(); + // succeeds + field.setValue(null); + // needed as required flag not checked by setValue() + field.validate(); + // succeeds + field.setValue("pattern"); + + // fails + try { + field.setValue("mismatch"); + fail(); + } catch (InvalidValueException e) { + // should fail + } + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/component/textfield/WriteDesignTest.java b/server/tests/src/com/vaadin/tests/server/component/textfield/WriteDesignTest.java new file mode 100644 index 0000000000..061b0ff402 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/textfield/WriteDesignTest.java @@ -0,0 +1,59 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.textfield; + +import junit.framework.TestCase; + +import org.jsoup.nodes.Attributes; +import org.jsoup.nodes.Element; +import org.jsoup.parser.Tag; + +import com.vaadin.ui.AbstractTextField; +import com.vaadin.ui.TextField; +import com.vaadin.ui.declarative.DesignContext; + +/** + * Test case for writing the value of the TextField to design + * + * @author Vaadin Ltd + */ +public class WriteDesignTest extends TestCase { + private DesignContext ctx; + + @Override + protected void setUp() throws Exception { + super.setUp(); + ctx = new DesignContext(); + } + + public void testSynchronizeValue() { + Element design = createDesign(); + AbstractTextField component = getComponent(); + component.setValue("test value"); + component.writeDesign(design, ctx); + assertEquals("test value", design.attr("value")); + } + + private AbstractTextField getComponent() { + return new TextField(); + } + + private Element createDesign() { + Attributes attr = new Attributes(); + return new Element(Tag.valueOf("v-text-field"), "", attr); + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/component/tree/ListenersTest.java b/server/tests/src/com/vaadin/tests/server/component/tree/ListenersTest.java new file mode 100644 index 0000000000..c327fe8c5f --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/tree/ListenersTest.java @@ -0,0 +1,137 @@ +package com.vaadin.tests.server.component.tree; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import com.vaadin.ui.Tree; +import com.vaadin.ui.Tree.CollapseEvent; +import com.vaadin.ui.Tree.CollapseListener; +import com.vaadin.ui.Tree.ExpandEvent; +import com.vaadin.ui.Tree.ExpandListener; + +public class ListenersTest extends TestCase implements ExpandListener, + CollapseListener { + private int expandCalled; + private int collapseCalled; + private Object lastExpanded; + private Object lastCollapsed; + + @Override + protected void setUp() { + expandCalled = 0; + } + + public void testExpandListener() { + Tree tree = createTree(10, 20, false); + tree.addListener((ExpandListener) this); + List rootIds = new ArrayList(tree.rootItemIds()); + + assertEquals(10, rootIds.size()); + assertEquals(10 + 10 * 20 + 10, tree.size()); + + // Expanding should send one expand event for the root item id + tree.expandItem(rootIds.get(0)); + assertEquals(1, expandCalled); + assertEquals(rootIds.get(0), lastExpanded); + + // Expand should send one event for each expanded item id. + // In this case root + child 4 + expandCalled = 0; + tree.expandItemsRecursively(rootIds.get(1)); + assertEquals(2, expandCalled); + List c = new ArrayList(tree.getChildren(rootIds.get(1))); + + assertEquals(c.get(4), lastExpanded); + + // Expanding an already expanded item should send no expand event + expandCalled = 0; + tree.expandItem(rootIds.get(0)); + assertEquals(0, expandCalled); + } + + /** + * Creates a tree with "rootItems" roots, each with "children" children, + * each with 1 child. + * + * @param rootItems + * @param children + * @param expand + * @return + */ + private Tree createTree(int rootItems, int children, boolean expand) { + Tree tree = new Tree(); + for (int i = 0; i < rootItems; i++) { + String rootId = "root " + i; + tree.addItem(rootId); + if (expand) { + tree.expandItemsRecursively(rootId); + } else { + tree.collapseItemsRecursively(rootId); + + } + for (int j = 0; j < children; j++) { + String childId = "child " + i + "/" + j; + tree.addItem(childId); + tree.setParent(childId, rootId); + tree.setChildrenAllowed(childId, false); + if (j == 4) { + tree.setChildrenAllowed(childId, true); + Object grandChildId = tree.addItem(); + tree.setParent(grandChildId, childId); + tree.setChildrenAllowed(grandChildId, false); + if (expand) { + tree.expandItemsRecursively(childId); + } else { + tree.collapseItemsRecursively(childId); + } + } + } + } + + return tree; + } + + public void testCollapseListener() { + Tree tree = createTree(7, 15, true); + tree.addListener((CollapseListener) this); + + List rootIds = new ArrayList(tree.rootItemIds()); + + assertEquals(7, rootIds.size()); + assertEquals(7 + 7 * 15 + 7, tree.size()); + + // Expanding should send one expand event for the root item id + tree.collapseItem(rootIds.get(0)); + assertEquals(1, collapseCalled); + assertEquals(rootIds.get(0), lastCollapsed); + + // Collapse sends one event for each collapsed node. + // In this case root + child 4 + collapseCalled = 0; + tree.collapseItemsRecursively(rootIds.get(1)); + assertEquals(2, collapseCalled); + List c = new ArrayList(tree.getChildren(rootIds.get(1))); + assertEquals(c.get(4), lastCollapsed); + + // Collapsing an already expanded item should send no expand event + collapseCalled = 0; + tree.collapseItem(rootIds.get(0)); + assertEquals(0, collapseCalled); + } + + @Override + public void nodeExpand(ExpandEvent event) { + lastExpanded = event.getItemId(); + expandCalled++; + + } + + @Override + public void nodeCollapse(CollapseEvent event) { + lastCollapsed = event.getItemId(); + collapseCalled++; + + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/tree/TestListeners.java b/server/tests/src/com/vaadin/tests/server/component/tree/TestListeners.java deleted file mode 100644 index 4984cf161b..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/tree/TestListeners.java +++ /dev/null @@ -1,137 +0,0 @@ -package com.vaadin.tests.server.component.tree; - -import java.util.ArrayList; -import java.util.List; - -import junit.framework.TestCase; - -import com.vaadin.ui.Tree; -import com.vaadin.ui.Tree.CollapseEvent; -import com.vaadin.ui.Tree.CollapseListener; -import com.vaadin.ui.Tree.ExpandEvent; -import com.vaadin.ui.Tree.ExpandListener; - -public class TestListeners extends TestCase implements ExpandListener, - CollapseListener { - private int expandCalled; - private int collapseCalled; - private Object lastExpanded; - private Object lastCollapsed; - - @Override - protected void setUp() { - expandCalled = 0; - } - - public void testExpandListener() { - Tree tree = createTree(10, 20, false); - tree.addListener((ExpandListener) this); - List rootIds = new ArrayList(tree.rootItemIds()); - - assertEquals(10, rootIds.size()); - assertEquals(10 + 10 * 20 + 10, tree.size()); - - // Expanding should send one expand event for the root item id - tree.expandItem(rootIds.get(0)); - assertEquals(1, expandCalled); - assertEquals(rootIds.get(0), lastExpanded); - - // Expand should send one event for each expanded item id. - // In this case root + child 4 - expandCalled = 0; - tree.expandItemsRecursively(rootIds.get(1)); - assertEquals(2, expandCalled); - List c = new ArrayList(tree.getChildren(rootIds.get(1))); - - assertEquals(c.get(4), lastExpanded); - - // Expanding an already expanded item should send no expand event - expandCalled = 0; - tree.expandItem(rootIds.get(0)); - assertEquals(0, expandCalled); - } - - /** - * Creates a tree with "rootItems" roots, each with "children" children, - * each with 1 child. - * - * @param rootItems - * @param children - * @param expand - * @return - */ - private Tree createTree(int rootItems, int children, boolean expand) { - Tree tree = new Tree(); - for (int i = 0; i < rootItems; i++) { - String rootId = "root " + i; - tree.addItem(rootId); - if (expand) { - tree.expandItemsRecursively(rootId); - } else { - tree.collapseItemsRecursively(rootId); - - } - for (int j = 0; j < children; j++) { - String childId = "child " + i + "/" + j; - tree.addItem(childId); - tree.setParent(childId, rootId); - tree.setChildrenAllowed(childId, false); - if (j == 4) { - tree.setChildrenAllowed(childId, true); - Object grandChildId = tree.addItem(); - tree.setParent(grandChildId, childId); - tree.setChildrenAllowed(grandChildId, false); - if (expand) { - tree.expandItemsRecursively(childId); - } else { - tree.collapseItemsRecursively(childId); - } - } - } - } - - return tree; - } - - public void testCollapseListener() { - Tree tree = createTree(7, 15, true); - tree.addListener((CollapseListener) this); - - List rootIds = new ArrayList(tree.rootItemIds()); - - assertEquals(7, rootIds.size()); - assertEquals(7 + 7 * 15 + 7, tree.size()); - - // Expanding should send one expand event for the root item id - tree.collapseItem(rootIds.get(0)); - assertEquals(1, collapseCalled); - assertEquals(rootIds.get(0), lastCollapsed); - - // Collapse sends one event for each collapsed node. - // In this case root + child 4 - collapseCalled = 0; - tree.collapseItemsRecursively(rootIds.get(1)); - assertEquals(2, collapseCalled); - List c = new ArrayList(tree.getChildren(rootIds.get(1))); - assertEquals(c.get(4), lastCollapsed); - - // Collapsing an already expanded item should send no expand event - collapseCalled = 0; - tree.collapseItem(rootIds.get(0)); - assertEquals(0, collapseCalled); - } - - @Override - public void nodeExpand(ExpandEvent event) { - lastExpanded = event.getItemId(); - expandCalled++; - - } - - @Override - public void nodeCollapse(CollapseEvent event) { - lastCollapsed = event.getItemId(); - collapseCalled++; - - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/tree/TreeListeners.java b/server/tests/src/com/vaadin/tests/server/component/tree/TreeListeners.java deleted file mode 100644 index 8d5b499264..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/tree/TreeListeners.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.vaadin.tests.server.component.tree; - -import com.vaadin.event.ItemClickEvent; -import com.vaadin.event.ItemClickEvent.ItemClickListener; -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; -import com.vaadin.ui.Tree; -import com.vaadin.ui.Tree.CollapseEvent; -import com.vaadin.ui.Tree.CollapseListener; -import com.vaadin.ui.Tree.ExpandEvent; -import com.vaadin.ui.Tree.ExpandListener; - -public class TreeListeners extends AbstractListenerMethodsTest { - public void testExpandListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(Tree.class, ExpandEvent.class, - ExpandListener.class); - } - - public void testItemClickListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(Tree.class, ItemClickEvent.class, - ItemClickListener.class); - } - - public void testCollapseListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(Tree.class, CollapseEvent.class, - CollapseListener.class); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/tree/TreeListenersTest.java b/server/tests/src/com/vaadin/tests/server/component/tree/TreeListenersTest.java new file mode 100644 index 0000000000..449f418596 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/tree/TreeListenersTest.java @@ -0,0 +1,27 @@ +package com.vaadin.tests.server.component.tree; + +import com.vaadin.event.ItemClickEvent; +import com.vaadin.event.ItemClickEvent.ItemClickListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; +import com.vaadin.ui.Tree; +import com.vaadin.ui.Tree.CollapseEvent; +import com.vaadin.ui.Tree.CollapseListener; +import com.vaadin.ui.Tree.ExpandEvent; +import com.vaadin.ui.Tree.ExpandListener; + +public class TreeListenersTest extends AbstractListenerMethodsTestBase { + public void testExpandListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Tree.class, ExpandEvent.class, + ExpandListener.class); + } + + public void testItemClickListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Tree.class, ItemClickEvent.class, + ItemClickListener.class); + } + + public void testCollapseListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Tree.class, CollapseEvent.class, + CollapseListener.class); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/treetable/EmptyTreeTable.java b/server/tests/src/com/vaadin/tests/server/component/treetable/EmptyTreeTable.java deleted file mode 100644 index 535ed8e860..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/treetable/EmptyTreeTable.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.vaadin.tests.server.component.treetable; - -import junit.framework.TestCase; - -import com.vaadin.ui.TreeTable; - -public class EmptyTreeTable extends TestCase { - public void testLastId() { - TreeTable treeTable = new TreeTable(); - - assertFalse(treeTable.isLastId(treeTable.getValue())); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/treetable/EmptyTreeTableTest.java b/server/tests/src/com/vaadin/tests/server/component/treetable/EmptyTreeTableTest.java new file mode 100644 index 0000000000..a886b74f57 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/treetable/EmptyTreeTableTest.java @@ -0,0 +1,13 @@ +package com.vaadin.tests.server.component.treetable; + +import junit.framework.TestCase; + +import com.vaadin.ui.TreeTable; + +public class EmptyTreeTableTest extends TestCase { + public void testLastId() { + TreeTable treeTable = new TreeTable(); + + assertFalse(treeTable.isLastId(treeTable.getValue())); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/treetable/TreeTableSetContainerNull.java b/server/tests/src/com/vaadin/tests/server/component/treetable/TreeTableSetContainerNull.java deleted file mode 100644 index a3b79a14f0..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/treetable/TreeTableSetContainerNull.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.vaadin.tests.server.component.treetable; - -import junit.framework.TestCase; - -import com.vaadin.ui.TreeTable; - -public class TreeTableSetContainerNull extends TestCase { - - public void testNullContainer() { - TreeTable treeTable = new TreeTable(); - - // should not cause an exception - treeTable.setContainerDataSource(null); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/treetable/TreeTableSetContainerNullTest.java b/server/tests/src/com/vaadin/tests/server/component/treetable/TreeTableSetContainerNullTest.java new file mode 100644 index 0000000000..4a34094da1 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/treetable/TreeTableSetContainerNullTest.java @@ -0,0 +1,15 @@ +package com.vaadin.tests.server.component.treetable; + +import junit.framework.TestCase; + +import com.vaadin.ui.TreeTable; + +public class TreeTableSetContainerNullTest extends TestCase { + + public void testNullContainer() { + TreeTable treeTable = new TreeTable(); + + // should not cause an exception + treeTable.setContainerDataSource(null); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/ui/CustomUIClassLoader.java b/server/tests/src/com/vaadin/tests/server/component/ui/CustomUIClassLoader.java deleted file mode 100644 index 1df1d36cab..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/ui/CustomUIClassLoader.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.vaadin.tests.server.component.ui; - -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import junit.framework.TestCase; - -import org.easymock.EasyMock; - -import com.vaadin.server.DefaultDeploymentConfiguration; -import com.vaadin.server.DefaultUIProvider; -import com.vaadin.server.DeploymentConfiguration; -import com.vaadin.server.UIClassSelectionEvent; -import com.vaadin.server.VaadinRequest; -import com.vaadin.server.VaadinService; -import com.vaadin.server.VaadinSession; -import com.vaadin.tests.util.AlwaysLockedVaadinSession; -import com.vaadin.ui.UI; - -public class CustomUIClassLoader extends TestCase { - - /** - * Stub root - */ - public static class MyUI extends UI { - @Override - protected void init(VaadinRequest request) { - // Nothing to see here - } - } - - /** - * Dummy ClassLoader that just saves the name of the requested class before - * delegating to the default implementation. - */ - public class LoggingClassLoader extends ClassLoader { - - private List requestedClasses = new ArrayList(); - - @Override - protected synchronized Class loadClass(String name, boolean resolve) - throws ClassNotFoundException { - requestedClasses.add(name); - return super.loadClass(name, resolve); - } - } - - /** - * Tests that a UI class can be loaded even if no classloader has been - * provided. - * - * @throws Exception - * if thrown - */ - public void testWithDefaultClassLoader() throws Exception { - VaadinSession application = createStubApplication(); - application.setConfiguration(createConfigurationMock()); - - DefaultUIProvider uiProvider = new DefaultUIProvider(); - Class uiClass = uiProvider - .getUIClass(new UIClassSelectionEvent( - createRequestMock(getClass().getClassLoader()))); - - assertEquals(MyUI.class, uiClass); - } - - private static DeploymentConfiguration createConfigurationMock() { - Properties properties = new Properties(); - properties.put(VaadinSession.UI_PARAMETER, MyUI.class.getName()); - return new DefaultDeploymentConfiguration(CustomUIClassLoader.class, - properties); - } - - private static VaadinRequest createRequestMock(ClassLoader classloader) { - // Mock a VaadinService to give the passed classloader - VaadinService configurationMock = EasyMock - .createMock(VaadinService.class); - EasyMock.expect(configurationMock.getDeploymentConfiguration()) - .andReturn(createConfigurationMock()); - EasyMock.expect(configurationMock.getClassLoader()).andReturn( - classloader); - - // Mock a VaadinRequest to give the mocked vaadin service - VaadinRequest requestMock = EasyMock.createMock(VaadinRequest.class); - EasyMock.expect(requestMock.getService()).andReturn(configurationMock); - EasyMock.expect(requestMock.getService()).andReturn(configurationMock); - EasyMock.expect(requestMock.getService()).andReturn(configurationMock); - - EasyMock.replay(configurationMock, requestMock); - return requestMock; - } - - /** - * Tests that the ClassLoader passed in the ApplicationStartEvent is used to - * load UI classes. - * - * @throws Exception - * if thrown - */ - public void testWithClassLoader() throws Exception { - LoggingClassLoader loggingClassLoader = new LoggingClassLoader(); - - DefaultUIProvider uiProvider = new DefaultUIProvider(); - Class uiClass = uiProvider - .getUIClass(new UIClassSelectionEvent( - createRequestMock(loggingClassLoader))); - - assertEquals(MyUI.class, uiClass); - assertEquals(1, loggingClassLoader.requestedClasses.size()); - assertEquals(MyUI.class.getName(), - loggingClassLoader.requestedClasses.get(0)); - - } - - private VaadinSession createStubApplication() { - return new AlwaysLockedVaadinSession(null) { - @Override - public DeploymentConfiguration getConfiguration() { - return createConfigurationMock(); - } - }; - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/ui/CustomUIClassLoaderTest.java b/server/tests/src/com/vaadin/tests/server/component/ui/CustomUIClassLoaderTest.java new file mode 100644 index 0000000000..be23a998a3 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/ui/CustomUIClassLoaderTest.java @@ -0,0 +1,124 @@ +package com.vaadin.tests.server.component.ui; + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import junit.framework.TestCase; + +import org.easymock.EasyMock; + +import com.vaadin.server.DefaultDeploymentConfiguration; +import com.vaadin.server.DefaultUIProvider; +import com.vaadin.server.DeploymentConfiguration; +import com.vaadin.server.UIClassSelectionEvent; +import com.vaadin.server.VaadinRequest; +import com.vaadin.server.VaadinService; +import com.vaadin.server.VaadinSession; +import com.vaadin.tests.util.AlwaysLockedVaadinSession; +import com.vaadin.ui.UI; + +public class CustomUIClassLoaderTest extends TestCase { + + /** + * Stub root + */ + public static class MyUI extends UI { + @Override + protected void init(VaadinRequest request) { + // Nothing to see here + } + } + + /** + * Dummy ClassLoader that just saves the name of the requested class before + * delegating to the default implementation. + */ + public class LoggingClassLoader extends ClassLoader { + + private List requestedClasses = new ArrayList(); + + @Override + protected synchronized Class loadClass(String name, boolean resolve) + throws ClassNotFoundException { + requestedClasses.add(name); + return super.loadClass(name, resolve); + } + } + + /** + * Tests that a UI class can be loaded even if no classloader has been + * provided. + * + * @throws Exception + * if thrown + */ + public void testWithDefaultClassLoader() throws Exception { + VaadinSession application = createStubApplication(); + application.setConfiguration(createConfigurationMock()); + + DefaultUIProvider uiProvider = new DefaultUIProvider(); + Class uiClass = uiProvider + .getUIClass(new UIClassSelectionEvent( + createRequestMock(getClass().getClassLoader()))); + + assertEquals(MyUI.class, uiClass); + } + + private static DeploymentConfiguration createConfigurationMock() { + Properties properties = new Properties(); + properties.put(VaadinSession.UI_PARAMETER, MyUI.class.getName()); + return new DefaultDeploymentConfiguration(CustomUIClassLoaderTest.class, + properties); + } + + private static VaadinRequest createRequestMock(ClassLoader classloader) { + // Mock a VaadinService to give the passed classloader + VaadinService configurationMock = EasyMock + .createMock(VaadinService.class); + EasyMock.expect(configurationMock.getDeploymentConfiguration()) + .andReturn(createConfigurationMock()); + EasyMock.expect(configurationMock.getClassLoader()).andReturn( + classloader); + + // Mock a VaadinRequest to give the mocked vaadin service + VaadinRequest requestMock = EasyMock.createMock(VaadinRequest.class); + EasyMock.expect(requestMock.getService()).andReturn(configurationMock); + EasyMock.expect(requestMock.getService()).andReturn(configurationMock); + EasyMock.expect(requestMock.getService()).andReturn(configurationMock); + + EasyMock.replay(configurationMock, requestMock); + return requestMock; + } + + /** + * Tests that the ClassLoader passed in the ApplicationStartEvent is used to + * load UI classes. + * + * @throws Exception + * if thrown + */ + public void testWithClassLoader() throws Exception { + LoggingClassLoader loggingClassLoader = new LoggingClassLoader(); + + DefaultUIProvider uiProvider = new DefaultUIProvider(); + Class uiClass = uiProvider + .getUIClass(new UIClassSelectionEvent( + createRequestMock(loggingClassLoader))); + + assertEquals(MyUI.class, uiClass); + assertEquals(1, loggingClassLoader.requestedClasses.size()); + assertEquals(MyUI.class.getName(), + loggingClassLoader.requestedClasses.get(0)); + + } + + private VaadinSession createStubApplication() { + return new AlwaysLockedVaadinSession(null) { + @Override + public DeploymentConfiguration getConfiguration() { + return createConfigurationMock(); + } + }; + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/ui/LegacyUIAddRemoveComponents.java b/server/tests/src/com/vaadin/tests/server/component/ui/LegacyUIAddRemoveComponents.java deleted file mode 100644 index 24fd3d85a8..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/ui/LegacyUIAddRemoveComponents.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.vaadin.tests.server.component.ui; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; - -import org.junit.Test; - -import com.vaadin.server.VaadinRequest; -import com.vaadin.ui.Component; -import com.vaadin.ui.Label; -import com.vaadin.ui.LegacyWindow; - -public class LegacyUIAddRemoveComponents { - - private static class TestUI extends LegacyWindow { - @Override - protected void init(VaadinRequest request) { - } - } - - @Test - public void addComponent() { - TestUI ui = new TestUI(); - Component c = new Label("abc"); - - ui.addComponent(c); - - assertSame(c.getParent(), ui.iterator().next()); - assertSame(c, ui.getContent().iterator().next()); - assertEquals(1, ui.getComponentCount()); - assertEquals(1, ui.getContent().getComponentCount()); - } - - @Test - public void removeComponent() { - TestUI ui = new TestUI(); - Component c = new Label("abc"); - - ui.addComponent(c); - - ui.removeComponent(c); - - assertEquals(ui.getContent(), ui.iterator().next()); - assertFalse(ui.getContent().iterator().hasNext()); - assertEquals(1, ui.getComponentCount()); - assertEquals(0, ui.getContent().getComponentCount()); - } - - @Test - public void replaceComponent() { - TestUI ui = new TestUI(); - Component c = new Label("abc"); - Component d = new Label("def"); - - ui.addComponent(c); - - ui.replaceComponent(c, d); - - assertSame(d.getParent(), ui.iterator().next()); - assertSame(d, ui.getContent().iterator().next()); - assertEquals(1, ui.getComponentCount()); - assertEquals(1, ui.getContent().getComponentCount()); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/ui/LegacyUIAddRemoveComponentsTest.java b/server/tests/src/com/vaadin/tests/server/component/ui/LegacyUIAddRemoveComponentsTest.java new file mode 100644 index 0000000000..2a88bb3208 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/ui/LegacyUIAddRemoveComponentsTest.java @@ -0,0 +1,65 @@ +package com.vaadin.tests.server.component.ui; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; + +import org.junit.Test; + +import com.vaadin.server.VaadinRequest; +import com.vaadin.ui.Component; +import com.vaadin.ui.Label; +import com.vaadin.ui.LegacyWindow; + +public class LegacyUIAddRemoveComponentsTest { + + private static class TestUI extends LegacyWindow { + @Override + protected void init(VaadinRequest request) { + } + } + + @Test + public void addComponent() { + TestUI ui = new TestUI(); + Component c = new Label("abc"); + + ui.addComponent(c); + + assertSame(c.getParent(), ui.iterator().next()); + assertSame(c, ui.getContent().iterator().next()); + assertEquals(1, ui.getComponentCount()); + assertEquals(1, ui.getContent().getComponentCount()); + } + + @Test + public void removeComponent() { + TestUI ui = new TestUI(); + Component c = new Label("abc"); + + ui.addComponent(c); + + ui.removeComponent(c); + + assertEquals(ui.getContent(), ui.iterator().next()); + assertFalse(ui.getContent().iterator().hasNext()); + assertEquals(1, ui.getComponentCount()); + assertEquals(0, ui.getContent().getComponentCount()); + } + + @Test + public void replaceComponent() { + TestUI ui = new TestUI(); + Component c = new Label("abc"); + Component d = new Label("def"); + + ui.addComponent(c); + + ui.replaceComponent(c, d); + + assertSame(d.getParent(), ui.iterator().next()); + assertSame(d, ui.getContent().iterator().next()); + assertEquals(1, ui.getComponentCount()); + assertEquals(1, ui.getContent().getComponentCount()); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/upload/UploadListeners.java b/server/tests/src/com/vaadin/tests/server/component/upload/UploadListeners.java deleted file mode 100644 index 265e5382d4..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/upload/UploadListeners.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.vaadin.tests.server.component.upload; - -import com.vaadin.server.StreamVariable.StreamingProgressEvent; -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; -import com.vaadin.ui.Upload; -import com.vaadin.ui.Upload.FailedEvent; -import com.vaadin.ui.Upload.FailedListener; -import com.vaadin.ui.Upload.FinishedEvent; -import com.vaadin.ui.Upload.FinishedListener; -import com.vaadin.ui.Upload.ProgressListener; -import com.vaadin.ui.Upload.StartedEvent; -import com.vaadin.ui.Upload.StartedListener; -import com.vaadin.ui.Upload.SucceededEvent; -import com.vaadin.ui.Upload.SucceededListener; - -public class UploadListeners extends AbstractListenerMethodsTest { - public void testProgressListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(Upload.class, StreamingProgressEvent.class, - ProgressListener.class); - } - - public void testSucceededListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(Upload.class, SucceededEvent.class, - SucceededListener.class); - } - - public void testStartedListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(Upload.class, StartedEvent.class, - StartedListener.class); - } - - public void testFailedListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(Upload.class, FailedEvent.class, - FailedListener.class); - } - - public void testFinishedListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(Upload.class, FinishedEvent.class, - FinishedListener.class); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/upload/UploadListenersTest.java b/server/tests/src/com/vaadin/tests/server/component/upload/UploadListenersTest.java new file mode 100644 index 0000000000..13d4c6bfe6 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/upload/UploadListenersTest.java @@ -0,0 +1,41 @@ +package com.vaadin.tests.server.component.upload; + +import com.vaadin.server.StreamVariable.StreamingProgressEvent; +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; +import com.vaadin.ui.Upload; +import com.vaadin.ui.Upload.FailedEvent; +import com.vaadin.ui.Upload.FailedListener; +import com.vaadin.ui.Upload.FinishedEvent; +import com.vaadin.ui.Upload.FinishedListener; +import com.vaadin.ui.Upload.ProgressListener; +import com.vaadin.ui.Upload.StartedEvent; +import com.vaadin.ui.Upload.StartedListener; +import com.vaadin.ui.Upload.SucceededEvent; +import com.vaadin.ui.Upload.SucceededListener; + +public class UploadListenersTest extends AbstractListenerMethodsTestBase { + public void testProgressListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Upload.class, StreamingProgressEvent.class, + ProgressListener.class); + } + + public void testSucceededListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Upload.class, SucceededEvent.class, + SucceededListener.class); + } + + public void testStartedListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Upload.class, StartedEvent.class, + StartedListener.class); + } + + public void testFailedListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Upload.class, FailedEvent.class, + FailedListener.class); + } + + public void testFinishedListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Upload.class, FinishedEvent.class, + FinishedListener.class); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/window/AddRemoveSubWindow.java b/server/tests/src/com/vaadin/tests/server/component/window/AddRemoveSubWindow.java deleted file mode 100644 index 774eafceaf..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/window/AddRemoveSubWindow.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.vaadin.tests.server.component.window; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -import com.vaadin.server.LegacyApplication; -import com.vaadin.server.VaadinSession; -import com.vaadin.tests.util.AlwaysLockedVaadinSession; -import com.vaadin.ui.LegacyWindow; -import com.vaadin.ui.UI; -import com.vaadin.ui.Window; - -public class AddRemoveSubWindow { - - public class TestApp extends LegacyApplication { - - @Override - public void init() { - LegacyWindow w = new LegacyWindow("Main window"); - setMainWindow(w); - } - } - - @Test - public void addSubWindow() { - VaadinSession.setCurrent(new AlwaysLockedVaadinSession(null)); - TestApp app = new TestApp(); - app.init(); - Window subWindow = new Window("Sub window"); - UI mainWindow = app.getMainWindow(); - - mainWindow.addWindow(subWindow); - // Added to main window so the parent of the sub window should be the - // main window - assertEquals(subWindow.getParent(), mainWindow); - - try { - mainWindow.addWindow(subWindow); - assertTrue("Window.addWindow did not throw the expected exception", - false); - } catch (IllegalArgumentException e) { - // Should throw an exception as it has already been added to the - // main window - } - - // Try to add the same sub window to another window - try { - LegacyWindow w = new LegacyWindow(); - w.addWindow(subWindow); - assertTrue("Window.addWindow did not throw the expected exception", - false); - } catch (IllegalArgumentException e) { - // Should throw an exception as it has already been added to the - // main window - } - - } - - @Test - public void removeSubWindow() { - TestApp app = new TestApp(); - app.init(); - Window subWindow = new Window("Sub window"); - UI mainWindow = app.getMainWindow(); - mainWindow.addWindow(subWindow); - - // Added to main window so the parent of the sub window should be the - // main window - assertEquals(subWindow.getParent(), mainWindow); - - // Parent should still be set - assertEquals(subWindow.getParent(), mainWindow); - - // Remove from the main window and assert it has been removed - boolean removed = mainWindow.removeWindow(subWindow); - assertTrue("Window was not removed correctly", removed); - assertNull(subWindow.getParent()); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/window/AddRemoveSubWindowTest.java b/server/tests/src/com/vaadin/tests/server/component/window/AddRemoveSubWindowTest.java new file mode 100644 index 0000000000..7fa8665c01 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/window/AddRemoveSubWindowTest.java @@ -0,0 +1,82 @@ +package com.vaadin.tests.server.component.window; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.vaadin.server.LegacyApplication; +import com.vaadin.server.VaadinSession; +import com.vaadin.tests.util.AlwaysLockedVaadinSession; +import com.vaadin.ui.LegacyWindow; +import com.vaadin.ui.UI; +import com.vaadin.ui.Window; + +public class AddRemoveSubWindowTest { + + public class TestApp extends LegacyApplication { + + @Override + public void init() { + LegacyWindow w = new LegacyWindow("Main window"); + setMainWindow(w); + } + } + + @Test + public void addSubWindow() { + VaadinSession.setCurrent(new AlwaysLockedVaadinSession(null)); + TestApp app = new TestApp(); + app.init(); + Window subWindow = new Window("Sub window"); + UI mainWindow = app.getMainWindow(); + + mainWindow.addWindow(subWindow); + // Added to main window so the parent of the sub window should be the + // main window + assertEquals(subWindow.getParent(), mainWindow); + + try { + mainWindow.addWindow(subWindow); + assertTrue("Window.addWindow did not throw the expected exception", + false); + } catch (IllegalArgumentException e) { + // Should throw an exception as it has already been added to the + // main window + } + + // Try to add the same sub window to another window + try { + LegacyWindow w = new LegacyWindow(); + w.addWindow(subWindow); + assertTrue("Window.addWindow did not throw the expected exception", + false); + } catch (IllegalArgumentException e) { + // Should throw an exception as it has already been added to the + // main window + } + + } + + @Test + public void removeSubWindow() { + TestApp app = new TestApp(); + app.init(); + Window subWindow = new Window("Sub window"); + UI mainWindow = app.getMainWindow(); + mainWindow.addWindow(subWindow); + + // Added to main window so the parent of the sub window should be the + // main window + assertEquals(subWindow.getParent(), mainWindow); + + // Parent should still be set + assertEquals(subWindow.getParent(), mainWindow); + + // Remove from the main window and assert it has been removed + boolean removed = mainWindow.removeWindow(subWindow); + assertTrue("Window was not removed correctly", removed); + assertNull(subWindow.getParent()); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/window/AttachDetachWindow.java b/server/tests/src/com/vaadin/tests/server/component/window/AttachDetachWindow.java deleted file mode 100644 index 5720744e2f..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/window/AttachDetachWindow.java +++ /dev/null @@ -1,314 +0,0 @@ -package com.vaadin.tests.server.component.window; - -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import org.junit.Assert; -import org.junit.Test; - -import com.vaadin.server.ClientConnector; -import com.vaadin.server.VaadinRequest; -import com.vaadin.server.VaadinSession; -import com.vaadin.tests.util.AlwaysLockedVaadinSession; -import com.vaadin.ui.HasComponents.ComponentAttachEvent; -import com.vaadin.ui.HasComponents.ComponentAttachListener; -import com.vaadin.ui.HasComponents.ComponentDetachEvent; -import com.vaadin.ui.HasComponents.ComponentDetachListener; -import com.vaadin.ui.Label; -import com.vaadin.ui.UI; -import com.vaadin.ui.VerticalLayout; -import com.vaadin.ui.Window; - -public class AttachDetachWindow { - - private VaadinSession testApp = new AlwaysLockedVaadinSession(null); - - private interface TestContainer { - public boolean attachCalled(); - - public boolean detachCalled(); - - public TestContent getTestContent(); - - public VaadinSession getSession(); - } - - private class TestWindow extends Window implements TestContainer { - boolean windowAttachCalled = false; - boolean windowDetachCalled = false; - private TestContent testContent = new TestContent(); - - TestWindow() { - setContent(testContent); - } - - @Override - public void attach() { - super.attach(); - windowAttachCalled = true; - } - - @Override - public void detach() { - super.detach(); - windowDetachCalled = true; - } - - @Override - public boolean attachCalled() { - return windowAttachCalled; - } - - @Override - public boolean detachCalled() { - return windowDetachCalled; - } - - @Override - public TestContent getTestContent() { - return testContent; - } - - @Override - public VaadinSession getSession() { - return super.getSession(); - } - } - - private class TestContent extends VerticalLayout { - boolean contentDetachCalled = false; - boolean childDetachCalled = false; - boolean contentAttachCalled = false; - boolean childAttachCalled = false; - - private Label child = new Label() { - @Override - public void attach() { - super.attach(); - childAttachCalled = true; - } - - @Override - public void detach() { - super.detach(); - childDetachCalled = true; - } - }; - - public TestContent() { - addComponent(child); - } - - @Override - public void attach() { - super.attach(); - contentAttachCalled = true; - } - - @Override - public void detach() { - super.detach(); - contentDetachCalled = true; - } - } - - private class TestUI extends UI implements TestContainer { - boolean rootAttachCalled = false; - boolean rootDetachCalled = false; - private TestContent testContent = new TestContent(); - - public TestUI() { - setContent(testContent); - } - - @Override - protected void init(VaadinRequest request) { - // Do nothing - } - - @Override - public boolean attachCalled() { - return rootAttachCalled; - } - - @Override - public boolean detachCalled() { - return rootDetachCalled; - } - - @Override - public TestContent getTestContent() { - return testContent; - } - - @Override - public void attach() { - super.attach(); - rootAttachCalled = true; - } - - @Override - public void detach() { - super.detach(); - rootDetachCalled = true; - } - } - - TestUI main = new TestUI(); - TestWindow sub = new TestWindow(); - - @Test - public void addSubWindowBeforeAttachingMainWindow() { - assertUnattached(main); - assertUnattached(sub); - - main.addWindow(sub); - assertUnattached(main); - assertUnattached(sub); - - // attaching main should recurse to sub - main.setSession(testApp); - assertAttached(main); - assertAttached(sub); - } - - @Test - public void addSubWindowAfterAttachingMainWindow() { - assertUnattached(main); - assertUnattached(sub); - - main.setSession(testApp); - assertAttached(main); - assertUnattached(sub); - - // main is already attached, so attach should be called for sub - main.addWindow(sub); - assertAttached(main); - assertAttached(sub); - } - - @Test - public void removeSubWindowBeforeDetachingMainWindow() { - main.setSession(testApp); - main.addWindow(sub); - - // sub should be detached when removing from attached main - main.removeWindow(sub); - assertAttached(main); - assertDetached(sub); - - // main detach should recurse to sub - main.setSession(null); - assertDetached(main); - assertDetached(sub); - } - - @Test - public void removeSubWindowAfterDetachingMainWindow() { - main.setSession(testApp); - main.addWindow(sub); - - // main detach should recurse to sub - main.setSession(null); - assertDetached(main); - assertDetached(sub); - - main.removeWindow(sub); - assertDetached(main); - assertDetached(sub); - } - - @Test - public void addWindow_attachEventIsFired() { - TestUI ui = new TestUI(); - final Window window = new Window(); - - final boolean[] eventFired = new boolean[1]; - ui.addComponentAttachListener(new ComponentAttachListener() { - - @Override - public void componentAttachedToContainer(ComponentAttachEvent event) { - eventFired[0] = event.getAttachedComponent().equals(window); - } - }); - ui.addWindow(window); - Assert.assertTrue("Attach event is not fired for added window", - eventFired[0]); - } - - @Test - public void removeWindow_detachEventIsFired() { - TestUI ui = new TestUI(); - final Window window = new Window(); - - final boolean[] eventFired = new boolean[1]; - ui.addComponentDetachListener(new ComponentDetachListener() { - - @Override - public void componentDetachedFromContainer( - ComponentDetachEvent event) { - eventFired[0] = event.getDetachedComponent().equals(window); - } - }); - ui.addWindow(window); - ui.removeWindow(window); - - Assert.assertTrue("Detach event is not fired for removed window", - eventFired[0]); - } - - /** - * Asserts that win and its children are attached to testApp and their - * attach() methods have been called. - */ - private void assertAttached(TestContainer win) { - TestContent testContent = win.getTestContent(); - - assertTrue("window attach not called", win.attachCalled()); - assertTrue("window content attach not called", - testContent.contentAttachCalled); - assertTrue("window child attach not called", - testContent.childAttachCalled); - - assertSame("window not attached", win.getSession(), testApp); - assertSame("window content not attached", testContent.getUI() - .getSession(), testApp); - assertSame("window children not attached", testContent.child.getUI() - .getSession(), testApp); - } - - /** - * Asserts that win and its children are not attached. - */ - private void assertUnattached(TestContainer win) { - assertSame("window not detached", win.getSession(), null); - assertSame("window content not detached", - getSession(win.getTestContent()), null); - assertSame("window children not detached", - getSession(win.getTestContent().child), null); - } - - private VaadinSession getSession(ClientConnector testContainer) { - UI ui = testContainer.getUI(); - if (ui != null) { - return ui.getSession(); - } else { - return null; - } - } - - /** - * Asserts that win and its children are unattached and their detach() - * methods have been been called. - * - * @param win - */ - private void assertDetached(TestContainer win) { - assertUnattached(win); - assertTrue("window detach not called", win.detachCalled()); - assertTrue("window content detach not called", - win.getTestContent().contentDetachCalled); - assertTrue("window child detach not called", - win.getTestContent().childDetachCalled); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/window/AttachDetachWindowTest.java b/server/tests/src/com/vaadin/tests/server/component/window/AttachDetachWindowTest.java new file mode 100644 index 0000000000..9f7a54df9c --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/window/AttachDetachWindowTest.java @@ -0,0 +1,314 @@ +package com.vaadin.tests.server.component.window; + +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import org.junit.Assert; +import org.junit.Test; + +import com.vaadin.server.ClientConnector; +import com.vaadin.server.VaadinRequest; +import com.vaadin.server.VaadinSession; +import com.vaadin.tests.util.AlwaysLockedVaadinSession; +import com.vaadin.ui.HasComponents.ComponentAttachEvent; +import com.vaadin.ui.HasComponents.ComponentAttachListener; +import com.vaadin.ui.HasComponents.ComponentDetachEvent; +import com.vaadin.ui.HasComponents.ComponentDetachListener; +import com.vaadin.ui.Label; +import com.vaadin.ui.UI; +import com.vaadin.ui.VerticalLayout; +import com.vaadin.ui.Window; + +public class AttachDetachWindowTest { + + private VaadinSession testApp = new AlwaysLockedVaadinSession(null); + + private interface TestContainer { + public boolean attachCalled(); + + public boolean detachCalled(); + + public TestContent getTestContent(); + + public VaadinSession getSession(); + } + + private class TestWindow extends Window implements TestContainer { + boolean windowAttachCalled = false; + boolean windowDetachCalled = false; + private TestContent testContent = new TestContent(); + + TestWindow() { + setContent(testContent); + } + + @Override + public void attach() { + super.attach(); + windowAttachCalled = true; + } + + @Override + public void detach() { + super.detach(); + windowDetachCalled = true; + } + + @Override + public boolean attachCalled() { + return windowAttachCalled; + } + + @Override + public boolean detachCalled() { + return windowDetachCalled; + } + + @Override + public TestContent getTestContent() { + return testContent; + } + + @Override + public VaadinSession getSession() { + return super.getSession(); + } + } + + private class TestContent extends VerticalLayout { + boolean contentDetachCalled = false; + boolean childDetachCalled = false; + boolean contentAttachCalled = false; + boolean childAttachCalled = false; + + private Label child = new Label() { + @Override + public void attach() { + super.attach(); + childAttachCalled = true; + } + + @Override + public void detach() { + super.detach(); + childDetachCalled = true; + } + }; + + public TestContent() { + addComponent(child); + } + + @Override + public void attach() { + super.attach(); + contentAttachCalled = true; + } + + @Override + public void detach() { + super.detach(); + contentDetachCalled = true; + } + } + + private class TestUI extends UI implements TestContainer { + boolean rootAttachCalled = false; + boolean rootDetachCalled = false; + private TestContent testContent = new TestContent(); + + public TestUI() { + setContent(testContent); + } + + @Override + protected void init(VaadinRequest request) { + // Do nothing + } + + @Override + public boolean attachCalled() { + return rootAttachCalled; + } + + @Override + public boolean detachCalled() { + return rootDetachCalled; + } + + @Override + public TestContent getTestContent() { + return testContent; + } + + @Override + public void attach() { + super.attach(); + rootAttachCalled = true; + } + + @Override + public void detach() { + super.detach(); + rootDetachCalled = true; + } + } + + TestUI main = new TestUI(); + TestWindow sub = new TestWindow(); + + @Test + public void addSubWindowBeforeAttachingMainWindow() { + assertUnattached(main); + assertUnattached(sub); + + main.addWindow(sub); + assertUnattached(main); + assertUnattached(sub); + + // attaching main should recurse to sub + main.setSession(testApp); + assertAttached(main); + assertAttached(sub); + } + + @Test + public void addSubWindowAfterAttachingMainWindow() { + assertUnattached(main); + assertUnattached(sub); + + main.setSession(testApp); + assertAttached(main); + assertUnattached(sub); + + // main is already attached, so attach should be called for sub + main.addWindow(sub); + assertAttached(main); + assertAttached(sub); + } + + @Test + public void removeSubWindowBeforeDetachingMainWindow() { + main.setSession(testApp); + main.addWindow(sub); + + // sub should be detached when removing from attached main + main.removeWindow(sub); + assertAttached(main); + assertDetached(sub); + + // main detach should recurse to sub + main.setSession(null); + assertDetached(main); + assertDetached(sub); + } + + @Test + public void removeSubWindowAfterDetachingMainWindow() { + main.setSession(testApp); + main.addWindow(sub); + + // main detach should recurse to sub + main.setSession(null); + assertDetached(main); + assertDetached(sub); + + main.removeWindow(sub); + assertDetached(main); + assertDetached(sub); + } + + @Test + public void addWindow_attachEventIsFired() { + TestUI ui = new TestUI(); + final Window window = new Window(); + + final boolean[] eventFired = new boolean[1]; + ui.addComponentAttachListener(new ComponentAttachListener() { + + @Override + public void componentAttachedToContainer(ComponentAttachEvent event) { + eventFired[0] = event.getAttachedComponent().equals(window); + } + }); + ui.addWindow(window); + Assert.assertTrue("Attach event is not fired for added window", + eventFired[0]); + } + + @Test + public void removeWindow_detachEventIsFired() { + TestUI ui = new TestUI(); + final Window window = new Window(); + + final boolean[] eventFired = new boolean[1]; + ui.addComponentDetachListener(new ComponentDetachListener() { + + @Override + public void componentDetachedFromContainer( + ComponentDetachEvent event) { + eventFired[0] = event.getDetachedComponent().equals(window); + } + }); + ui.addWindow(window); + ui.removeWindow(window); + + Assert.assertTrue("Detach event is not fired for removed window", + eventFired[0]); + } + + /** + * Asserts that win and its children are attached to testApp and their + * attach() methods have been called. + */ + private void assertAttached(TestContainer win) { + TestContent testContent = win.getTestContent(); + + assertTrue("window attach not called", win.attachCalled()); + assertTrue("window content attach not called", + testContent.contentAttachCalled); + assertTrue("window child attach not called", + testContent.childAttachCalled); + + assertSame("window not attached", win.getSession(), testApp); + assertSame("window content not attached", testContent.getUI() + .getSession(), testApp); + assertSame("window children not attached", testContent.child.getUI() + .getSession(), testApp); + } + + /** + * Asserts that win and its children are not attached. + */ + private void assertUnattached(TestContainer win) { + assertSame("window not detached", win.getSession(), null); + assertSame("window content not detached", + getSession(win.getTestContent()), null); + assertSame("window children not detached", + getSession(win.getTestContent().child), null); + } + + private VaadinSession getSession(ClientConnector testContainer) { + UI ui = testContainer.getUI(); + if (ui != null) { + return ui.getSession(); + } else { + return null; + } + } + + /** + * Asserts that win and its children are unattached and their detach() + * methods have been been called. + * + * @param win + */ + private void assertDetached(TestContainer win) { + assertUnattached(win); + assertTrue("window detach not called", win.detachCalled()); + assertTrue("window content detach not called", + win.getTestContent().contentDetachCalled); + assertTrue("window child detach not called", + win.getTestContent().childDetachCalled); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/window/WindowAttach.java b/server/tests/src/com/vaadin/tests/server/component/window/WindowAttach.java deleted file mode 100644 index 586300f650..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/window/WindowAttach.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.tests.server.component.window; - -import org.junit.Test; - -import com.vaadin.server.VaadinRequest; -import com.vaadin.ui.UI; -import com.vaadin.ui.VerticalLayout; -import com.vaadin.ui.Window; - -public class WindowAttach { - - private static class MyUI extends UI { - @Override - protected void init(VaadinRequest request) { - } - } - - @Test(expected = IllegalArgumentException.class) - public void testAttachUsingSetContent() { - UI ui = new MyUI(); - ui.setContent(new Window("foo")); - } - - @Test(expected = IllegalArgumentException.class) - public void testAddToLayout() { - VerticalLayout vl = new VerticalLayout(); - vl.addComponent(new Window("foo")); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/window/WindowAttachTest.java b/server/tests/src/com/vaadin/tests/server/component/window/WindowAttachTest.java new file mode 100644 index 0000000000..867342ab03 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/window/WindowAttachTest.java @@ -0,0 +1,44 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.tests.server.component.window; + +import org.junit.Test; + +import com.vaadin.server.VaadinRequest; +import com.vaadin.ui.UI; +import com.vaadin.ui.VerticalLayout; +import com.vaadin.ui.Window; + +public class WindowAttachTest { + + private static class MyUI extends UI { + @Override + protected void init(VaadinRequest request) { + } + } + + @Test(expected = IllegalArgumentException.class) + public void testAttachUsingSetContent() { + UI ui = new MyUI(); + ui.setContent(new Window("foo")); + } + + @Test(expected = IllegalArgumentException.class) + public void testAddToLayout() { + VerticalLayout vl = new VerticalLayout(); + vl.addComponent(new Window("foo")); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/component/window/WindowListeners.java b/server/tests/src/com/vaadin/tests/server/component/window/WindowListeners.java deleted file mode 100644 index c33871cbd8..0000000000 --- a/server/tests/src/com/vaadin/tests/server/component/window/WindowListeners.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.vaadin.tests.server.component.window; - -import com.vaadin.event.FieldEvents.BlurEvent; -import com.vaadin.event.FieldEvents.BlurListener; -import com.vaadin.event.FieldEvents.FocusEvent; -import com.vaadin.event.FieldEvents.FocusListener; -import com.vaadin.tests.server.component.AbstractListenerMethodsTest; -import com.vaadin.ui.Window; -import com.vaadin.ui.Window.CloseEvent; -import com.vaadin.ui.Window.CloseListener; -import com.vaadin.ui.Window.ResizeEvent; -import com.vaadin.ui.Window.ResizeListener; - -public class WindowListeners extends AbstractListenerMethodsTest { - public void testFocusListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(Window.class, FocusEvent.class, - FocusListener.class); - } - - public void testBlurListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(Window.class, BlurEvent.class, - BlurListener.class); - } - - public void testResizeListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(Window.class, ResizeEvent.class, - ResizeListener.class); - } - - public void testCloseListenerAddGetRemove() throws Exception { - testListenerAddGetRemove(Window.class, CloseEvent.class, - CloseListener.class); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/component/window/WindowListenersTest.java b/server/tests/src/com/vaadin/tests/server/component/window/WindowListenersTest.java new file mode 100644 index 0000000000..87a1af301c --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/component/window/WindowListenersTest.java @@ -0,0 +1,34 @@ +package com.vaadin.tests.server.component.window; + +import com.vaadin.event.FieldEvents.BlurEvent; +import com.vaadin.event.FieldEvents.BlurListener; +import com.vaadin.event.FieldEvents.FocusEvent; +import com.vaadin.event.FieldEvents.FocusListener; +import com.vaadin.tests.server.component.AbstractListenerMethodsTestBase; +import com.vaadin.ui.Window; +import com.vaadin.ui.Window.CloseEvent; +import com.vaadin.ui.Window.CloseListener; +import com.vaadin.ui.Window.ResizeEvent; +import com.vaadin.ui.Window.ResizeListener; + +public class WindowListenersTest extends AbstractListenerMethodsTestBase { + public void testFocusListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Window.class, FocusEvent.class, + FocusListener.class); + } + + public void testBlurListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Window.class, BlurEvent.class, + BlurListener.class); + } + + public void testResizeListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Window.class, ResizeEvent.class, + ResizeListener.class); + } + + public void testCloseListenerAddGetRemove() throws Exception { + testListenerAddGetRemove(Window.class, CloseEvent.class, + CloseListener.class); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/componentcontainer/AbstractIndexedLayoutTest.java b/server/tests/src/com/vaadin/tests/server/componentcontainer/AbstractIndexedLayoutTest.java deleted file mode 100644 index e3e743d02a..0000000000 --- a/server/tests/src/com/vaadin/tests/server/componentcontainer/AbstractIndexedLayoutTest.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.vaadin.tests.server.componentcontainer; - -import junit.framework.TestCase; - -import com.vaadin.ui.Component; -import com.vaadin.ui.Label; -import com.vaadin.ui.Layout; - -public abstract class AbstractIndexedLayoutTest extends TestCase { - - private Layout layout; - - protected abstract Layout createLayout(); - - @Override - protected void setUp() throws Exception { - layout = createLayout(); - } - - public Layout getLayout() { - return layout; - } - - public void testAddRemoveComponent() { - Label c1 = new Label(); - Label c2 = new Label(); - - layout.addComponent(c1); - - assertEquals(c1, getComponent(0)); - assertEquals(1, getComponentCount()); - layout.addComponent(c2); - assertEquals(c1, getComponent(0)); - assertEquals(c2, getComponent(1)); - assertEquals(2, getComponentCount()); - layout.removeComponent(c1); - assertEquals(c2, getComponent(0)); - assertEquals(1, getComponentCount()); - layout.removeComponent(c2); - assertEquals(0, getComponentCount()); - } - - protected abstract int getComponentCount(); - - protected abstract Component getComponent(int index); - - protected abstract int getComponentIndex(Component c); - - public void testGetComponentIndex() { - Label c1 = new Label(); - Label c2 = new Label(); - - layout.addComponent(c1); - assertEquals(0, getComponentIndex(c1)); - layout.addComponent(c2); - assertEquals(0, getComponentIndex(c1)); - assertEquals(1, getComponentIndex(c2)); - layout.removeComponent(c1); - assertEquals(0, getComponentIndex(c2)); - layout.removeComponent(c2); - assertEquals(-1, getComponentIndex(c2)); - assertEquals(-1, getComponentIndex(c1)); - } - - public void testGetComponent() { - Label c1 = new Label(); - Label c2 = new Label(); - - layout.addComponent(c1); - assertEquals(c1, getComponent(0)); - layout.addComponent(c2); - assertEquals(c1, getComponent(0)); - assertEquals(c2, getComponent(1)); - layout.removeComponent(c1); - assertEquals(c2, getComponent(0)); - layout.removeComponent(c2); - try { - getComponent(0); - fail(); - } catch (IndexOutOfBoundsException e) { - // Expected - } - } -} diff --git a/server/tests/src/com/vaadin/tests/server/componentcontainer/AbstractIndexedLayoutTestBase.java b/server/tests/src/com/vaadin/tests/server/componentcontainer/AbstractIndexedLayoutTestBase.java new file mode 100644 index 0000000000..f19821f92e --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/componentcontainer/AbstractIndexedLayoutTestBase.java @@ -0,0 +1,84 @@ +package com.vaadin.tests.server.componentcontainer; + +import junit.framework.TestCase; + +import com.vaadin.ui.Component; +import com.vaadin.ui.Label; +import com.vaadin.ui.Layout; + +public abstract class AbstractIndexedLayoutTestBase extends TestCase { + + private Layout layout; + + protected abstract Layout createLayout(); + + @Override + protected void setUp() throws Exception { + layout = createLayout(); + } + + public Layout getLayout() { + return layout; + } + + public void testAddRemoveComponent() { + Label c1 = new Label(); + Label c2 = new Label(); + + layout.addComponent(c1); + + assertEquals(c1, getComponent(0)); + assertEquals(1, getComponentCount()); + layout.addComponent(c2); + assertEquals(c1, getComponent(0)); + assertEquals(c2, getComponent(1)); + assertEquals(2, getComponentCount()); + layout.removeComponent(c1); + assertEquals(c2, getComponent(0)); + assertEquals(1, getComponentCount()); + layout.removeComponent(c2); + assertEquals(0, getComponentCount()); + } + + protected abstract int getComponentCount(); + + protected abstract Component getComponent(int index); + + protected abstract int getComponentIndex(Component c); + + public void testGetComponentIndex() { + Label c1 = new Label(); + Label c2 = new Label(); + + layout.addComponent(c1); + assertEquals(0, getComponentIndex(c1)); + layout.addComponent(c2); + assertEquals(0, getComponentIndex(c1)); + assertEquals(1, getComponentIndex(c2)); + layout.removeComponent(c1); + assertEquals(0, getComponentIndex(c2)); + layout.removeComponent(c2); + assertEquals(-1, getComponentIndex(c2)); + assertEquals(-1, getComponentIndex(c1)); + } + + public void testGetComponent() { + Label c1 = new Label(); + Label c2 = new Label(); + + layout.addComponent(c1); + assertEquals(c1, getComponent(0)); + layout.addComponent(c2); + assertEquals(c1, getComponent(0)); + assertEquals(c2, getComponent(1)); + layout.removeComponent(c1); + assertEquals(c2, getComponent(0)); + layout.removeComponent(c2); + try { + getComponent(0); + fail(); + } catch (IndexOutOfBoundsException e) { + // Expected + } + } +} diff --git a/server/tests/src/com/vaadin/tests/server/componentcontainer/CssLayoutTest.java b/server/tests/src/com/vaadin/tests/server/componentcontainer/CssLayoutTest.java index dc9667c38e..8dd36beda3 100644 --- a/server/tests/src/com/vaadin/tests/server/componentcontainer/CssLayoutTest.java +++ b/server/tests/src/com/vaadin/tests/server/componentcontainer/CssLayoutTest.java @@ -4,7 +4,7 @@ import com.vaadin.ui.Component; import com.vaadin.ui.CssLayout; import com.vaadin.ui.Layout; -public class CssLayoutTest extends AbstractIndexedLayoutTest { +public class CssLayoutTest extends AbstractIndexedLayoutTestBase { @Override protected Layout createLayout() { diff --git a/server/tests/src/com/vaadin/tests/server/componentcontainer/FormLayoutTest.java b/server/tests/src/com/vaadin/tests/server/componentcontainer/FormLayoutTest.java index 50de871106..c689e7fe06 100644 --- a/server/tests/src/com/vaadin/tests/server/componentcontainer/FormLayoutTest.java +++ b/server/tests/src/com/vaadin/tests/server/componentcontainer/FormLayoutTest.java @@ -10,7 +10,7 @@ import com.vaadin.ui.FormLayout; import com.vaadin.ui.Label; import com.vaadin.ui.Layout; -public class FormLayoutTest extends AbstractIndexedLayoutTest { +public class FormLayoutTest extends AbstractIndexedLayoutTestBase { @Override protected Layout createLayout() { diff --git a/server/tests/src/com/vaadin/tests/server/componentcontainer/VerticalLayoutTest.java b/server/tests/src/com/vaadin/tests/server/componentcontainer/VerticalLayoutTest.java index 0e3a1d5734..565cc8e8ab 100644 --- a/server/tests/src/com/vaadin/tests/server/componentcontainer/VerticalLayoutTest.java +++ b/server/tests/src/com/vaadin/tests/server/componentcontainer/VerticalLayoutTest.java @@ -4,7 +4,7 @@ import com.vaadin.ui.Component; import com.vaadin.ui.Layout; import com.vaadin.ui.VerticalLayout; -public class VerticalLayoutTest extends AbstractIndexedLayoutTest { +public class VerticalLayoutTest extends AbstractIndexedLayoutTestBase { @Override protected Layout createLayout() { diff --git a/server/tests/src/com/vaadin/tests/server/components/AbstractFieldValueChangeTestBase.java b/server/tests/src/com/vaadin/tests/server/components/AbstractFieldValueChangeTestBase.java new file mode 100644 index 0000000000..637947fc9b --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/components/AbstractFieldValueChangeTestBase.java @@ -0,0 +1,129 @@ +package com.vaadin.tests.server.components; + +import junit.framework.TestCase; + +import org.easymock.EasyMock; + +import com.vaadin.data.Property.ValueChangeEvent; +import com.vaadin.data.Property.ValueChangeListener; +import com.vaadin.data.Property.ValueChangeNotifier; +import com.vaadin.data.util.ObjectProperty; +import com.vaadin.ui.AbstractField; + +/** + * Base class for tests for checking that value change listeners for fields are + * not called exactly once when they should be, and not at other times. + * + * Does not check all cases (e.g. properties that do not implement + * {@link ValueChangeNotifier}). + * + * Subclasses should implement {@link #setValue()} and call + * super.setValue(AbstractField). Also, subclasses should typically + * override {@link #setValue(AbstractField)} to set the field value via + * changeVariables(). + */ +public abstract class AbstractFieldValueChangeTestBase extends TestCase { + + private AbstractField field; + private ValueChangeListener listener; + + protected void setUp(AbstractField field) throws Exception { + this.field = field; + listener = EasyMock.createStrictMock(ValueChangeListener.class); + + } + + protected ValueChangeListener getListener() { + return listener; + } + + /** + * Test that listeners are not called when they have been unregistered. + */ + public void testRemoveListener() { + getField().setPropertyDataSource(new ObjectProperty("")); + getField().setBuffered(false); + + // Expectations and start test + listener.valueChange(EasyMock.isA(ValueChangeEvent.class)); + EasyMock.replay(listener); + + // Add listener and set the value -> should end up in listener once + getField().addListener(listener); + setValue(getField()); + + // Ensure listener was called once + EasyMock.verify(listener); + + // Remove the listener and set the value -> should not end up in + // listener + getField().removeListener(listener); + setValue(getField()); + + // Ensure listener still has been called only once + EasyMock.verify(listener); + } + + /** + * Common unbuffered case: both writeThrough (auto-commit) and readThrough + * are on. Calling commit() should not cause notifications. + * + * Using the readThrough mode allows changes made to the property value to + * be seen in some cases also when there is no notification of value change + * from the property. + * + * Field value change notifications closely mirror value changes of the data + * source behind the field. + */ + public void testNonBuffered() { + getField().setPropertyDataSource(new ObjectProperty("")); + getField().setBuffered(false); + + expectValueChangeFromSetValueNotCommit(); + } + + /** + * Fully buffered use where the data source is neither read nor modified + * during editing, and is updated at commit(). + * + * Field value change notifications reflect the buffered value in the field, + * not the original data source value changes. + */ + public void testBuffered() { + getField().setPropertyDataSource(new ObjectProperty("")); + getField().setBuffered(true); + + expectValueChangeFromSetValueNotCommit(); + } + + protected void expectValueChangeFromSetValueNotCommit() { + // Expectations and start test + listener.valueChange(EasyMock.isA(ValueChangeEvent.class)); + EasyMock.replay(listener); + + // Add listener and set the value -> should end up in listener once + getField().addListener(listener); + setValue(getField()); + + // Ensure listener was called once + EasyMock.verify(listener); + + // commit + getField().commit(); + + // Ensure listener was not called again + EasyMock.verify(listener); + } + + protected AbstractField getField() { + return field; + } + + /** + * Override in subclasses to set value with changeVariables(). + */ + protected void setValue(AbstractField field) { + field.setValue((T) "newValue"); + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/components/AbstractTestFieldValueChange.java b/server/tests/src/com/vaadin/tests/server/components/AbstractTestFieldValueChange.java deleted file mode 100644 index c8d6ecce9c..0000000000 --- a/server/tests/src/com/vaadin/tests/server/components/AbstractTestFieldValueChange.java +++ /dev/null @@ -1,129 +0,0 @@ -package com.vaadin.tests.server.components; - -import junit.framework.TestCase; - -import org.easymock.EasyMock; - -import com.vaadin.data.Property.ValueChangeEvent; -import com.vaadin.data.Property.ValueChangeListener; -import com.vaadin.data.Property.ValueChangeNotifier; -import com.vaadin.data.util.ObjectProperty; -import com.vaadin.ui.AbstractField; - -/** - * Base class for tests for checking that value change listeners for fields are - * not called exactly once when they should be, and not at other times. - * - * Does not check all cases (e.g. properties that do not implement - * {@link ValueChangeNotifier}). - * - * Subclasses should implement {@link #setValue()} and call - * super.setValue(AbstractField). Also, subclasses should typically - * override {@link #setValue(AbstractField)} to set the field value via - * changeVariables(). - */ -public abstract class AbstractTestFieldValueChange extends TestCase { - - private AbstractField field; - private ValueChangeListener listener; - - protected void setUp(AbstractField field) throws Exception { - this.field = field; - listener = EasyMock.createStrictMock(ValueChangeListener.class); - - } - - protected ValueChangeListener getListener() { - return listener; - } - - /** - * Test that listeners are not called when they have been unregistered. - */ - public void testRemoveListener() { - getField().setPropertyDataSource(new ObjectProperty("")); - getField().setBuffered(false); - - // Expectations and start test - listener.valueChange(EasyMock.isA(ValueChangeEvent.class)); - EasyMock.replay(listener); - - // Add listener and set the value -> should end up in listener once - getField().addListener(listener); - setValue(getField()); - - // Ensure listener was called once - EasyMock.verify(listener); - - // Remove the listener and set the value -> should not end up in - // listener - getField().removeListener(listener); - setValue(getField()); - - // Ensure listener still has been called only once - EasyMock.verify(listener); - } - - /** - * Common unbuffered case: both writeThrough (auto-commit) and readThrough - * are on. Calling commit() should not cause notifications. - * - * Using the readThrough mode allows changes made to the property value to - * be seen in some cases also when there is no notification of value change - * from the property. - * - * Field value change notifications closely mirror value changes of the data - * source behind the field. - */ - public void testNonBuffered() { - getField().setPropertyDataSource(new ObjectProperty("")); - getField().setBuffered(false); - - expectValueChangeFromSetValueNotCommit(); - } - - /** - * Fully buffered use where the data source is neither read nor modified - * during editing, and is updated at commit(). - * - * Field value change notifications reflect the buffered value in the field, - * not the original data source value changes. - */ - public void testBuffered() { - getField().setPropertyDataSource(new ObjectProperty("")); - getField().setBuffered(true); - - expectValueChangeFromSetValueNotCommit(); - } - - protected void expectValueChangeFromSetValueNotCommit() { - // Expectations and start test - listener.valueChange(EasyMock.isA(ValueChangeEvent.class)); - EasyMock.replay(listener); - - // Add listener and set the value -> should end up in listener once - getField().addListener(listener); - setValue(getField()); - - // Ensure listener was called once - EasyMock.verify(listener); - - // commit - getField().commit(); - - // Ensure listener was not called again - EasyMock.verify(listener); - } - - protected AbstractField getField() { - return field; - } - - /** - * Override in subclasses to set value with changeVariables(). - */ - protected void setValue(AbstractField field) { - field.setValue((T) "newValue"); - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/components/ComboBoxValueChangeTest.java b/server/tests/src/com/vaadin/tests/server/components/ComboBoxValueChangeTest.java new file mode 100644 index 0000000000..f3cc337657 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/components/ComboBoxValueChangeTest.java @@ -0,0 +1,31 @@ +package com.vaadin.tests.server.components; + +import java.util.HashMap; +import java.util.Map; + +import com.vaadin.ui.AbstractField; +import com.vaadin.ui.ComboBox; + +/** + * Check that the value change listener for a combo box is triggered exactly + * once when setting the value, at the correct time. + * + * See Ticket 4394. + */ +public class ComboBoxValueChangeTest extends + AbstractFieldValueChangeTestBase { + @Override + protected void setUp() throws Exception { + ComboBox combo = new ComboBox(); + combo.addItem("myvalue"); + super.setUp(combo); + } + + @Override + protected void setValue(AbstractField field) { + Map variables = new HashMap(); + variables.put("selected", new String[] { "myvalue" }); + ((ComboBox) field).changeVariables(field, variables); + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/components/GridLayoutLastRowRemovalTest.java b/server/tests/src/com/vaadin/tests/server/components/GridLayoutLastRowRemovalTest.java new file mode 100644 index 0000000000..3467d1d80c --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/components/GridLayoutLastRowRemovalTest.java @@ -0,0 +1,40 @@ +package com.vaadin.tests.server.components; + +import junit.framework.TestCase; + +import com.vaadin.ui.GridLayout; +import com.vaadin.ui.Label; + +public class GridLayoutLastRowRemovalTest extends TestCase { + + public void testRemovingLastRow() { + GridLayout grid = new GridLayout(2, 1); + grid.addComponent(new Label("Col1")); + grid.addComponent(new Label("Col2")); + + try { + // Removing the last row in the grid + grid.removeRow(0); + } catch (IllegalArgumentException iae) { + // Removing the last row should not throw an + // IllegalArgumentException + fail("removeRow(0) threw an IllegalArgumentExcetion when removing the last row"); + } + + // The column amount should be preserved + assertEquals(2, grid.getColumns()); + + // There should be one row left + assertEquals(1, grid.getRows()); + + // There should be no component left in the grid layout + assertNull("A component should not be left in the layout", + grid.getComponent(0, 0)); + assertNull("A component should not be left in the layout", + grid.getComponent(1, 0)); + + // The cursor should be in the first cell + assertEquals(0, grid.getCursorX()); + assertEquals(0, grid.getCursorY()); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/components/TestComboBoxValueChange.java b/server/tests/src/com/vaadin/tests/server/components/TestComboBoxValueChange.java deleted file mode 100644 index 308889fa33..0000000000 --- a/server/tests/src/com/vaadin/tests/server/components/TestComboBoxValueChange.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.vaadin.tests.server.components; - -import java.util.HashMap; -import java.util.Map; - -import com.vaadin.ui.AbstractField; -import com.vaadin.ui.ComboBox; - -/** - * Check that the value change listener for a combo box is triggered exactly - * once when setting the value, at the correct time. - * - * See Ticket 4394. - */ -public class TestComboBoxValueChange extends - AbstractTestFieldValueChange { - @Override - protected void setUp() throws Exception { - ComboBox combo = new ComboBox(); - combo.addItem("myvalue"); - super.setUp(combo); - } - - @Override - protected void setValue(AbstractField field) { - Map variables = new HashMap(); - variables.put("selected", new String[] { "myvalue" }); - ((ComboBox) field).changeVariables(field, variables); - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/components/TestGridLayoutLastRowRemoval.java b/server/tests/src/com/vaadin/tests/server/components/TestGridLayoutLastRowRemoval.java deleted file mode 100644 index 92664917fd..0000000000 --- a/server/tests/src/com/vaadin/tests/server/components/TestGridLayoutLastRowRemoval.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.vaadin.tests.server.components; - -import junit.framework.TestCase; - -import com.vaadin.ui.GridLayout; -import com.vaadin.ui.Label; - -public class TestGridLayoutLastRowRemoval extends TestCase { - - public void testRemovingLastRow() { - GridLayout grid = new GridLayout(2, 1); - grid.addComponent(new Label("Col1")); - grid.addComponent(new Label("Col2")); - - try { - // Removing the last row in the grid - grid.removeRow(0); - } catch (IllegalArgumentException iae) { - // Removing the last row should not throw an - // IllegalArgumentException - fail("removeRow(0) threw an IllegalArgumentExcetion when removing the last row"); - } - - // The column amount should be preserved - assertEquals(2, grid.getColumns()); - - // There should be one row left - assertEquals(1, grid.getRows()); - - // There should be no component left in the grid layout - assertNull("A component should not be left in the layout", - grid.getComponent(0, 0)); - assertNull("A component should not be left in the layout", - grid.getComponent(1, 0)); - - // The cursor should be in the first cell - assertEquals(0, grid.getCursorX()); - assertEquals(0, grid.getCursorY()); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/components/TestTextFieldValueChange.java b/server/tests/src/com/vaadin/tests/server/components/TestTextFieldValueChange.java deleted file mode 100644 index 7c47b94df4..0000000000 --- a/server/tests/src/com/vaadin/tests/server/components/TestTextFieldValueChange.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.vaadin.tests.server.components; - -import java.util.HashMap; -import java.util.Map; - -import org.easymock.EasyMock; -import org.junit.Assert; - -import com.vaadin.data.Property.ValueChangeEvent; -import com.vaadin.data.util.ObjectProperty; -import com.vaadin.ui.AbstractField; -import com.vaadin.ui.TextField; - -/** - * Check that the value change listener for a text field is triggered exactly - * once when setting the value, at the correct time. - * - * See Ticket 4394. - */ -public class TestTextFieldValueChange extends - AbstractTestFieldValueChange { - - @Override - protected void setUp() throws Exception { - super.setUp(new TextField()); - } - - /** - * Case where the text field only uses its internal buffer, no external - * property data source. - */ - public void testNoDataSource() { - getField().setPropertyDataSource(null); - - expectValueChangeFromSetValueNotCommit(); - } - - @Override - protected void setValue(AbstractField field) { - Map variables = new HashMap(); - variables.put("text", "newValue"); - ((TextField) field).changeVariables(field, variables); - } - - /** - * Test that field propagates value change events originating from property, - * but don't fire value change events twice if value has only changed once. - * - * - * TODO make test field type agnostic (eg. combobox) - */ - public void testValueChangeEventPropagationWithReadThrough() { - ObjectProperty property = new ObjectProperty(""); - getField().setPropertyDataSource(property); - - // defaults, buffering off - getField().setBuffered(false); - - // Expectations and start test - getListener().valueChange(EasyMock.isA(ValueChangeEvent.class)); - EasyMock.replay(getListener()); - - // Add listener and set the value -> should end up in listener once - getField().addListener(getListener()); - - property.setValue("Foo"); - - // Ensure listener was called once - EasyMock.verify(getListener()); - - // get value should not fire value change again - Object value = getField().getValue(); - Assert.assertEquals("Foo", value); - - // Ensure listener still has been called only once - EasyMock.verify(getListener()); - } - - /** - * Value change events from property should not propagate if read through is - * false. Execpt when the property is being set. - * - * TODO make test field type agnostic (eg. combobox) - */ - public void testValueChangePropagationWithReadThroughOff() { - final String initialValue = "initial"; - ObjectProperty property = new ObjectProperty( - initialValue); - - // set buffering - getField().setBuffered(true); - - // Value change should only happen once, when setting the property, - // further changes via property should not cause value change listener - // in field to be notified - getListener().valueChange(EasyMock.isA(ValueChangeEvent.class)); - EasyMock.replay(getListener()); - - getField().addListener(getListener()); - getField().setPropertyDataSource(property); - - // Ensure listener was called once - EasyMock.verify(getListener()); - - // modify property value, should not fire value change in field as the - // read buffering is on (read through == false) - property.setValue("Foo"); - - // Ensure listener still has been called only once - EasyMock.verify(getListener()); - - // get value should not fire value change again - Object value = getField().getValue(); - - // field value should be different from the original value and current - // proeprty value - boolean isValueEqualToInitial = value.equals(initialValue); - Assert.assertTrue(isValueEqualToInitial); - - // Ensure listener still has been called only once - EasyMock.verify(getListener()); - - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/components/TestWindow.java b/server/tests/src/com/vaadin/tests/server/components/TestWindow.java deleted file mode 100644 index 6707965be6..0000000000 --- a/server/tests/src/com/vaadin/tests/server/components/TestWindow.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.vaadin.tests.server.components; - -import java.util.HashMap; -import java.util.Map; - -import junit.framework.TestCase; - -import org.easymock.EasyMock; - -import com.vaadin.ui.LegacyWindow; -import com.vaadin.ui.Window; -import com.vaadin.ui.Window.CloseEvent; -import com.vaadin.ui.Window.CloseListener; -import com.vaadin.ui.Window.ResizeEvent; -import com.vaadin.ui.Window.ResizeListener; - -public class TestWindow extends TestCase { - - private Window window; - - @Override - protected void setUp() throws Exception { - window = new Window(); - new LegacyWindow().addWindow(window); - } - - public void testCloseListener() { - CloseListener cl = EasyMock.createMock(Window.CloseListener.class); - - // Expectations - cl.windowClose(EasyMock.isA(CloseEvent.class)); - - // Start actual test - EasyMock.replay(cl); - - // Add listener and send a close event -> should end up in listener once - window.addListener(cl); - sendClose(window); - - // Ensure listener was called once - EasyMock.verify(cl); - - // Remove the listener and send close event -> should not end up in - // listener - window.removeListener(cl); - sendClose(window); - - // Ensure listener still has been called only once - EasyMock.verify(cl); - - } - - public void testResizeListener() { - ResizeListener rl = EasyMock.createMock(Window.ResizeListener.class); - - // Expectations - rl.windowResized(EasyMock.isA(ResizeEvent.class)); - - // Start actual test - EasyMock.replay(rl); - - // Add listener and send a resize event -> should end up in listener - // once - window.addListener(rl); - sendResize(window); - - // Ensure listener was called once - EasyMock.verify(rl); - - // Remove the listener and send close event -> should not end up in - // listener - window.removeListener(rl); - sendResize(window); - - // Ensure listener still has been called only once - EasyMock.verify(rl); - - } - - private void sendResize(Window window2) { - Map variables = new HashMap(); - variables.put("height", 1234); - window.changeVariables(window, variables); - - } - - private static void sendClose(Window window) { - Map variables = new HashMap(); - variables.put("close", true); - window.changeVariables(window, variables); - } -} diff --git a/server/tests/src/com/vaadin/tests/server/components/TextFieldValueChangeTest.java b/server/tests/src/com/vaadin/tests/server/components/TextFieldValueChangeTest.java new file mode 100644 index 0000000000..cfceb6f7d7 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/components/TextFieldValueChangeTest.java @@ -0,0 +1,125 @@ +package com.vaadin.tests.server.components; + +import java.util.HashMap; +import java.util.Map; + +import org.easymock.EasyMock; +import org.junit.Assert; + +import com.vaadin.data.Property.ValueChangeEvent; +import com.vaadin.data.util.ObjectProperty; +import com.vaadin.ui.AbstractField; +import com.vaadin.ui.TextField; + +/** + * Check that the value change listener for a text field is triggered exactly + * once when setting the value, at the correct time. + * + * See Ticket 4394. + */ +public class TextFieldValueChangeTest extends + AbstractFieldValueChangeTestBase { + + @Override + protected void setUp() throws Exception { + super.setUp(new TextField()); + } + + /** + * Case where the text field only uses its internal buffer, no external + * property data source. + */ + public void testNoDataSource() { + getField().setPropertyDataSource(null); + + expectValueChangeFromSetValueNotCommit(); + } + + @Override + protected void setValue(AbstractField field) { + Map variables = new HashMap(); + variables.put("text", "newValue"); + ((TextField) field).changeVariables(field, variables); + } + + /** + * Test that field propagates value change events originating from property, + * but don't fire value change events twice if value has only changed once. + * + * + * TODO make test field type agnostic (eg. combobox) + */ + public void testValueChangeEventPropagationWithReadThrough() { + ObjectProperty property = new ObjectProperty(""); + getField().setPropertyDataSource(property); + + // defaults, buffering off + getField().setBuffered(false); + + // Expectations and start test + getListener().valueChange(EasyMock.isA(ValueChangeEvent.class)); + EasyMock.replay(getListener()); + + // Add listener and set the value -> should end up in listener once + getField().addListener(getListener()); + + property.setValue("Foo"); + + // Ensure listener was called once + EasyMock.verify(getListener()); + + // get value should not fire value change again + Object value = getField().getValue(); + Assert.assertEquals("Foo", value); + + // Ensure listener still has been called only once + EasyMock.verify(getListener()); + } + + /** + * Value change events from property should not propagate if read through is + * false. Execpt when the property is being set. + * + * TODO make test field type agnostic (eg. combobox) + */ + public void testValueChangePropagationWithReadThroughOff() { + final String initialValue = "initial"; + ObjectProperty property = new ObjectProperty( + initialValue); + + // set buffering + getField().setBuffered(true); + + // Value change should only happen once, when setting the property, + // further changes via property should not cause value change listener + // in field to be notified + getListener().valueChange(EasyMock.isA(ValueChangeEvent.class)); + EasyMock.replay(getListener()); + + getField().addListener(getListener()); + getField().setPropertyDataSource(property); + + // Ensure listener was called once + EasyMock.verify(getListener()); + + // modify property value, should not fire value change in field as the + // read buffering is on (read through == false) + property.setValue("Foo"); + + // Ensure listener still has been called only once + EasyMock.verify(getListener()); + + // get value should not fire value change again + Object value = getField().getValue(); + + // field value should be different from the original value and current + // proeprty value + boolean isValueEqualToInitial = value.equals(initialValue); + Assert.assertTrue(isValueEqualToInitial); + + // Ensure listener still has been called only once + EasyMock.verify(getListener()); + + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/components/WindowTest.java b/server/tests/src/com/vaadin/tests/server/components/WindowTest.java new file mode 100644 index 0000000000..26fe238342 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/components/WindowTest.java @@ -0,0 +1,92 @@ +package com.vaadin.tests.server.components; + +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +import org.easymock.EasyMock; + +import com.vaadin.ui.LegacyWindow; +import com.vaadin.ui.Window; +import com.vaadin.ui.Window.CloseEvent; +import com.vaadin.ui.Window.CloseListener; +import com.vaadin.ui.Window.ResizeEvent; +import com.vaadin.ui.Window.ResizeListener; + +public class WindowTest extends TestCase { + + private Window window; + + @Override + protected void setUp() throws Exception { + window = new Window(); + new LegacyWindow().addWindow(window); + } + + public void testCloseListener() { + CloseListener cl = EasyMock.createMock(Window.CloseListener.class); + + // Expectations + cl.windowClose(EasyMock.isA(CloseEvent.class)); + + // Start actual test + EasyMock.replay(cl); + + // Add listener and send a close event -> should end up in listener once + window.addListener(cl); + sendClose(window); + + // Ensure listener was called once + EasyMock.verify(cl); + + // Remove the listener and send close event -> should not end up in + // listener + window.removeListener(cl); + sendClose(window); + + // Ensure listener still has been called only once + EasyMock.verify(cl); + + } + + public void testResizeListener() { + ResizeListener rl = EasyMock.createMock(Window.ResizeListener.class); + + // Expectations + rl.windowResized(EasyMock.isA(ResizeEvent.class)); + + // Start actual test + EasyMock.replay(rl); + + // Add listener and send a resize event -> should end up in listener + // once + window.addListener(rl); + sendResize(window); + + // Ensure listener was called once + EasyMock.verify(rl); + + // Remove the listener and send close event -> should not end up in + // listener + window.removeListener(rl); + sendResize(window); + + // Ensure listener still has been called only once + EasyMock.verify(rl); + + } + + private void sendResize(Window window2) { + Map variables = new HashMap(); + variables.put("height", 1234); + window.changeVariables(window, variables); + + } + + private static void sendClose(Window window) { + Map variables = new HashMap(); + variables.put("close", true); + window.changeVariables(window, variables); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/validation/BeanValidationTest.java b/server/tests/src/com/vaadin/tests/server/validation/BeanValidationTest.java new file mode 100644 index 0000000000..6b7582525e --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/validation/BeanValidationTest.java @@ -0,0 +1,125 @@ +package com.vaadin.tests.server.validation; + +import org.junit.Assert; +import org.junit.Test; + +import com.vaadin.data.Validator.InvalidValueException; +import com.vaadin.data.fieldgroup.BeanFieldGroup; +import com.vaadin.data.validator.BeanValidator; +import com.vaadin.tests.data.bean.BeanToValidate; +import com.vaadin.ui.Field; + +public class BeanValidationTest { + @Test(expected = InvalidValueException.class) + public void testBeanValidationNull() { + BeanValidator validator = new BeanValidator(BeanToValidate.class, + "firstname"); + validator.validate(null); + } + + @Test(expected = InvalidValueException.class) + public void testBeanValidationStringTooShort() { + BeanValidator validator = new BeanValidator(BeanToValidate.class, + "firstname"); + validator.validate("aa"); + } + + @Test + public void testBeanValidationStringOk() { + BeanValidator validator = new BeanValidator(BeanToValidate.class, + "firstname"); + validator.validate("aaa"); + } + + @Test(expected = InvalidValueException.class) + public void testBeanValidationIntegerTooSmall() { + BeanValidator validator = new BeanValidator(BeanToValidate.class, "age"); + validator.validate(17); + } + + @Test + public void testBeanValidationIntegerOk() { + BeanValidator validator = new BeanValidator(BeanToValidate.class, "age"); + validator.validate(18); + } + + @Test(expected = InvalidValueException.class) + public void testBeanValidationTooManyDigits() { + BeanValidator validator = new BeanValidator(BeanToValidate.class, + "decimals"); + validator.validate("1234.567"); + } + + @Test + public void testBeanValidationDigitsOk() { + BeanValidator validator = new BeanValidator(BeanToValidate.class, + "decimals"); + validator.validate("123.45"); + } + + @Test + public void testBeanValidationException_OneValidationError() { + InvalidValueException[] causes = null; + BeanValidator validator = new BeanValidator(BeanToValidate.class, + "lastname"); + try { + validator.validate(null); + } catch (InvalidValueException e) { + causes = e.getCauses(); + } + + Assert.assertEquals(1, causes.length); + } + + @Test + public void testBeanValidationsException_TwoValidationErrors() { + InvalidValueException[] causes = null; + BeanValidator validator = new BeanValidator(BeanToValidate.class, + "nickname"); + try { + validator.validate("A"); + } catch (InvalidValueException e) { + causes = e.getCauses(); + } + + Assert.assertEquals(2, causes.length); + } + + public void testBeanValidationNotAddedTwice() { + // See ticket #11045 + BeanFieldGroup fieldGroup = new BeanFieldGroup( + BeanToValidate.class); + + BeanToValidate beanToValidate = new BeanToValidate(); + beanToValidate.setFirstname("a"); + fieldGroup.setItemDataSource(beanToValidate); + + Field nameField = fieldGroup.buildAndBind("firstname"); + Assert.assertEquals(1, nameField.getValidators().size()); + + try { + nameField.validate(); + } catch (InvalidValueException e) { + // NOTE: causes are empty if only one validation fails + Assert.assertEquals(0, e.getCauses().length); + } + + // Create new, identical bean to cause duplicate validator unless #11045 + // is fixed + beanToValidate = new BeanToValidate(); + beanToValidate.setFirstname("a"); + fieldGroup.setItemDataSource(beanToValidate); + + Assert.assertEquals(1, nameField.getValidators().size()); + + try { + nameField.validate(); + } catch (InvalidValueException e) { + // NOTE: if more than one validation fails, we get the number of + // failed validations + Assert.assertEquals(0, e.getCauses().length); + } + + } + +} diff --git a/server/tests/src/com/vaadin/tests/server/validation/ReadOnlyValidationTest.java b/server/tests/src/com/vaadin/tests/server/validation/ReadOnlyValidationTest.java new file mode 100644 index 0000000000..661236e597 --- /dev/null +++ b/server/tests/src/com/vaadin/tests/server/validation/ReadOnlyValidationTest.java @@ -0,0 +1,17 @@ +package com.vaadin.tests.server.validation; + +import org.junit.Test; + +import com.vaadin.data.validator.IntegerValidator; +import com.vaadin.ui.TextField; + +public class ReadOnlyValidationTest { + + @Test + public void testIntegerValidation() { + TextField field = new TextField(); + field.addValidator(new IntegerValidator("Enter a Valid Number")); + field.setValue(String.valueOf(10)); + field.validate(); + } +} diff --git a/server/tests/src/com/vaadin/tests/server/validation/TestBeanValidation.java b/server/tests/src/com/vaadin/tests/server/validation/TestBeanValidation.java deleted file mode 100644 index 832ae14950..0000000000 --- a/server/tests/src/com/vaadin/tests/server/validation/TestBeanValidation.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.vaadin.tests.server.validation; - -import org.junit.Assert; -import org.junit.Test; - -import com.vaadin.data.Validator.InvalidValueException; -import com.vaadin.data.fieldgroup.BeanFieldGroup; -import com.vaadin.data.validator.BeanValidator; -import com.vaadin.tests.data.bean.BeanToValidate; -import com.vaadin.ui.Field; - -public class TestBeanValidation { - @Test(expected = InvalidValueException.class) - public void testBeanValidationNull() { - BeanValidator validator = new BeanValidator(BeanToValidate.class, - "firstname"); - validator.validate(null); - } - - @Test(expected = InvalidValueException.class) - public void testBeanValidationStringTooShort() { - BeanValidator validator = new BeanValidator(BeanToValidate.class, - "firstname"); - validator.validate("aa"); - } - - @Test - public void testBeanValidationStringOk() { - BeanValidator validator = new BeanValidator(BeanToValidate.class, - "firstname"); - validator.validate("aaa"); - } - - @Test(expected = InvalidValueException.class) - public void testBeanValidationIntegerTooSmall() { - BeanValidator validator = new BeanValidator(BeanToValidate.class, "age"); - validator.validate(17); - } - - @Test - public void testBeanValidationIntegerOk() { - BeanValidator validator = new BeanValidator(BeanToValidate.class, "age"); - validator.validate(18); - } - - @Test(expected = InvalidValueException.class) - public void testBeanValidationTooManyDigits() { - BeanValidator validator = new BeanValidator(BeanToValidate.class, - "decimals"); - validator.validate("1234.567"); - } - - @Test - public void testBeanValidationDigitsOk() { - BeanValidator validator = new BeanValidator(BeanToValidate.class, - "decimals"); - validator.validate("123.45"); - } - - @Test - public void testBeanValidationException_OneValidationError() { - InvalidValueException[] causes = null; - BeanValidator validator = new BeanValidator(BeanToValidate.class, - "lastname"); - try { - validator.validate(null); - } catch (InvalidValueException e) { - causes = e.getCauses(); - } - - Assert.assertEquals(1, causes.length); - } - - @Test - public void testBeanValidationsException_TwoValidationErrors() { - InvalidValueException[] causes = null; - BeanValidator validator = new BeanValidator(BeanToValidate.class, - "nickname"); - try { - validator.validate("A"); - } catch (InvalidValueException e) { - causes = e.getCauses(); - } - - Assert.assertEquals(2, causes.length); - } - - public void testBeanValidationNotAddedTwice() { - // See ticket #11045 - BeanFieldGroup fieldGroup = new BeanFieldGroup( - BeanToValidate.class); - - BeanToValidate beanToValidate = new BeanToValidate(); - beanToValidate.setFirstname("a"); - fieldGroup.setItemDataSource(beanToValidate); - - Field nameField = fieldGroup.buildAndBind("firstname"); - Assert.assertEquals(1, nameField.getValidators().size()); - - try { - nameField.validate(); - } catch (InvalidValueException e) { - // NOTE: causes are empty if only one validation fails - Assert.assertEquals(0, e.getCauses().length); - } - - // Create new, identical bean to cause duplicate validator unless #11045 - // is fixed - beanToValidate = new BeanToValidate(); - beanToValidate.setFirstname("a"); - fieldGroup.setItemDataSource(beanToValidate); - - Assert.assertEquals(1, nameField.getValidators().size()); - - try { - nameField.validate(); - } catch (InvalidValueException e) { - // NOTE: if more than one validation fails, we get the number of - // failed validations - Assert.assertEquals(0, e.getCauses().length); - } - - } - -} diff --git a/server/tests/src/com/vaadin/tests/server/validation/TestReadOnlyValidation.java b/server/tests/src/com/vaadin/tests/server/validation/TestReadOnlyValidation.java deleted file mode 100644 index e37b97e02c..0000000000 --- a/server/tests/src/com/vaadin/tests/server/validation/TestReadOnlyValidation.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.vaadin.tests.server.validation; - -import org.junit.Test; - -import com.vaadin.data.validator.IntegerValidator; -import com.vaadin.ui.TextField; - -public class TestReadOnlyValidation { - - @Test - public void testIntegerValidation() { - TextField field = new TextField(); - field.addValidator(new IntegerValidator("Enter a Valid Number")); - field.setValue(String.valueOf(10)); - field.validate(); - } -} diff --git a/server/tests/src/com/vaadin/ui/AbsFieldDataSourceLocaleChange.java b/server/tests/src/com/vaadin/ui/AbsFieldDataSourceLocaleChange.java deleted file mode 100644 index fa69fc46da..0000000000 --- a/server/tests/src/com/vaadin/ui/AbsFieldDataSourceLocaleChange.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.vaadin.ui; - -import java.text.NumberFormat; -import java.util.Locale; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.vaadin.data.util.converter.StringToIntegerConverter; -import com.vaadin.server.VaadinRequest; -import com.vaadin.server.VaadinSession; -import com.vaadin.tests.util.AlwaysLockedVaadinSession; - -public class AbsFieldDataSourceLocaleChange { - - private VaadinSession vaadinSession; - private UI ui; - - @Before - public void setup() { - vaadinSession = new AlwaysLockedVaadinSession(null); - VaadinSession.setCurrent(vaadinSession); - ui = new UI() { - - @Override - protected void init(VaadinRequest request) { - - } - }; - ui.setSession(vaadinSession); - UI.setCurrent(ui); - } - - @Test - public void localeChangesOnAttach() { - TextField tf = new TextField(); - - tf.setConverter(new StringToIntegerConverter() { - @Override - protected NumberFormat getFormat(Locale locale) { - if (locale == null) { - NumberFormat format = super.getFormat(locale); - format.setGroupingUsed(false); - format.setMinimumIntegerDigits(10); - return format; - } - return super.getFormat(locale); - } - }); - tf.setImmediate(true); - tf.setConvertedValue(10000); - Assert.assertEquals("0000010000", tf.getValue()); - - VerticalLayout vl = new VerticalLayout(); - ui.setContent(vl); - ui.setLocale(new Locale("en", "US")); - - vl.addComponent(tf); - Assert.assertEquals("10,000", tf.getValue()); - } -} diff --git a/server/tests/src/com/vaadin/ui/AbsFieldDataSourceLocaleChangeTest.java b/server/tests/src/com/vaadin/ui/AbsFieldDataSourceLocaleChangeTest.java new file mode 100644 index 0000000000..bb5babf360 --- /dev/null +++ b/server/tests/src/com/vaadin/ui/AbsFieldDataSourceLocaleChangeTest.java @@ -0,0 +1,62 @@ +package com.vaadin.ui; + +import java.text.NumberFormat; +import java.util.Locale; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.vaadin.data.util.converter.StringToIntegerConverter; +import com.vaadin.server.VaadinRequest; +import com.vaadin.server.VaadinSession; +import com.vaadin.tests.util.AlwaysLockedVaadinSession; + +public class AbsFieldDataSourceLocaleChangeTest { + + private VaadinSession vaadinSession; + private UI ui; + + @Before + public void setup() { + vaadinSession = new AlwaysLockedVaadinSession(null); + VaadinSession.setCurrent(vaadinSession); + ui = new UI() { + + @Override + protected void init(VaadinRequest request) { + + } + }; + ui.setSession(vaadinSession); + UI.setCurrent(ui); + } + + @Test + public void localeChangesOnAttach() { + TextField tf = new TextField(); + + tf.setConverter(new StringToIntegerConverter() { + @Override + protected NumberFormat getFormat(Locale locale) { + if (locale == null) { + NumberFormat format = super.getFormat(locale); + format.setGroupingUsed(false); + format.setMinimumIntegerDigits(10); + return format; + } + return super.getFormat(locale); + } + }); + tf.setImmediate(true); + tf.setConvertedValue(10000); + Assert.assertEquals("0000010000", tf.getValue()); + + VerticalLayout vl = new VerticalLayout(); + ui.setContent(vl); + ui.setLocale(new Locale("en", "US")); + + vl.addComponent(tf); + Assert.assertEquals("10,000", tf.getValue()); + } +} diff --git a/server/tests/src/com/vaadin/ui/AbsSelectTest.java b/server/tests/src/com/vaadin/ui/AbsSelectTest.java new file mode 100644 index 0000000000..0b807c5f21 --- /dev/null +++ b/server/tests/src/com/vaadin/ui/AbsSelectTest.java @@ -0,0 +1,147 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.ui; + +import java.util.ArrayList; +import java.util.HashSet; + +import org.junit.Assert; +import org.junit.Test; + +import com.vaadin.data.util.ObjectProperty; + +public class AbsSelectTest { + + @Test + public void addItemsStrings() { + NativeSelect ns = new NativeSelect(); + ns.addItems("Foo", "bar", "baz"); + Assert.assertEquals(3, ns.size()); + Assert.assertArrayEquals(new Object[] { "Foo", "bar", "baz" }, ns + .getItemIds().toArray()); + } + + @Test + public void addItemsObjects() { + Object o1 = new Object(); + Object o2 = new Object(); + Object o3 = new Object(); + + NativeSelect ns = new NativeSelect(); + ns.addItems(o1, o2, o3); + Assert.assertEquals(3, ns.size()); + Assert.assertArrayEquals(new Object[] { o1, o2, o3 }, ns.getItemIds() + .toArray()); + } + + @Test + public void addItemsStringList() { + ArrayList itemIds = new ArrayList(); + itemIds.add("foo"); + itemIds.add("bar"); + itemIds.add("baz"); + NativeSelect ns = new NativeSelect(); + ns.addItems(itemIds); + Assert.assertEquals(3, ns.size()); + Assert.assertArrayEquals(new Object[] { "foo", "bar", "baz" }, ns + .getItemIds().toArray()); + } + + @Test + public void addItemsObjectList() { + Object o1 = new Object(); + Object o2 = new Object(); + Object o3 = new Object(); + ArrayList itemIds = new ArrayList(); + itemIds.add(o1); + itemIds.add(o2); + itemIds.add(o3); + NativeSelect ns = new NativeSelect(); + ns.addItems(itemIds); + Assert.assertEquals(3, ns.size()); + Assert.assertArrayEquals(new Object[] { o1, o2, o3 }, ns.getItemIds() + .toArray()); + + } + + @Test + public void singleSelectInitiallyEmpty() { + AbstractSelect s = new ListSelect(); + Assert.assertTrue(s.isEmpty()); + } + + @Test + public void singleSelectEmptyAfterClearUsingPDS() { + AbstractSelect s = new ListSelect(); + s.addItem("foo"); + s.addItem("bar"); + s.setPropertyDataSource(new ObjectProperty("foo")); + + Assert.assertFalse(s.isEmpty()); + s.clear(); + Assert.assertTrue(s.isEmpty()); + } + + @Test + public void singleSelectEmptyAfterClear() { + AbstractSelect s = new ListSelect(); + s.addItem("foo"); + s.addItem("bar"); + s.setValue("bar"); + + Assert.assertFalse(s.isEmpty()); + s.clear(); + Assert.assertTrue(s.isEmpty()); + } + + @Test + public void multiSelectInitiallyEmpty() { + AbstractSelect s = new ListSelect(); + s.setMultiSelect(true); + Assert.assertTrue(s.isEmpty()); + } + + @Test + public void multiSelectEmptyAfterClearUsingPDS() { + AbstractSelect s = new ListSelect(); + s.setMultiSelect(true); + s.addItem("foo"); + s.addItem("bar"); + HashSet sel = new HashSet(); + sel.add("foo"); + sel.add("bar"); + s.setPropertyDataSource(new ObjectProperty(sel)); + + Assert.assertFalse(s.isEmpty()); + s.clear(); + Assert.assertTrue(s.isEmpty()); + } + + @Test + public void multiSelectEmptyAfterClear() { + AbstractSelect s = new ListSelect(); + s.setMultiSelect(true); + s.addItem("foo"); + s.addItem("bar"); + s.select("foo"); + s.select("bar"); + + Assert.assertFalse(s.isEmpty()); + s.clear(); + Assert.assertTrue(s.isEmpty()); + } + +} diff --git a/server/tests/src/com/vaadin/ui/AbstractSelectTest.java b/server/tests/src/com/vaadin/ui/AbstractSelectTest.java deleted file mode 100644 index bd399f088c..0000000000 --- a/server/tests/src/com/vaadin/ui/AbstractSelectTest.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.ui; - -import java.util.ArrayList; -import java.util.HashSet; - -import org.junit.Assert; -import org.junit.Test; - -import com.vaadin.data.util.ObjectProperty; - -public class AbstractSelectTest { - - @Test - public void addItemsStrings() { - NativeSelect ns = new NativeSelect(); - ns.addItems("Foo", "bar", "baz"); - Assert.assertEquals(3, ns.size()); - Assert.assertArrayEquals(new Object[] { "Foo", "bar", "baz" }, ns - .getItemIds().toArray()); - } - - @Test - public void addItemsObjects() { - Object o1 = new Object(); - Object o2 = new Object(); - Object o3 = new Object(); - - NativeSelect ns = new NativeSelect(); - ns.addItems(o1, o2, o3); - Assert.assertEquals(3, ns.size()); - Assert.assertArrayEquals(new Object[] { o1, o2, o3 }, ns.getItemIds() - .toArray()); - } - - @Test - public void addItemsStringList() { - ArrayList itemIds = new ArrayList(); - itemIds.add("foo"); - itemIds.add("bar"); - itemIds.add("baz"); - NativeSelect ns = new NativeSelect(); - ns.addItems(itemIds); - Assert.assertEquals(3, ns.size()); - Assert.assertArrayEquals(new Object[] { "foo", "bar", "baz" }, ns - .getItemIds().toArray()); - } - - @Test - public void addItemsObjectList() { - Object o1 = new Object(); - Object o2 = new Object(); - Object o3 = new Object(); - ArrayList itemIds = new ArrayList(); - itemIds.add(o1); - itemIds.add(o2); - itemIds.add(o3); - NativeSelect ns = new NativeSelect(); - ns.addItems(itemIds); - Assert.assertEquals(3, ns.size()); - Assert.assertArrayEquals(new Object[] { o1, o2, o3 }, ns.getItemIds() - .toArray()); - - } - - @Test - public void singleSelectInitiallyEmpty() { - AbstractSelect s = new ListSelect(); - Assert.assertTrue(s.isEmpty()); - } - - @Test - public void singleSelectEmptyAfterClearUsingPDS() { - AbstractSelect s = new ListSelect(); - s.addItem("foo"); - s.addItem("bar"); - s.setPropertyDataSource(new ObjectProperty("foo")); - - Assert.assertFalse(s.isEmpty()); - s.clear(); - Assert.assertTrue(s.isEmpty()); - } - - @Test - public void singleSelectEmptyAfterClear() { - AbstractSelect s = new ListSelect(); - s.addItem("foo"); - s.addItem("bar"); - s.setValue("bar"); - - Assert.assertFalse(s.isEmpty()); - s.clear(); - Assert.assertTrue(s.isEmpty()); - } - - @Test - public void multiSelectInitiallyEmpty() { - AbstractSelect s = new ListSelect(); - s.setMultiSelect(true); - Assert.assertTrue(s.isEmpty()); - } - - @Test - public void multiSelectEmptyAfterClearUsingPDS() { - AbstractSelect s = new ListSelect(); - s.setMultiSelect(true); - s.addItem("foo"); - s.addItem("bar"); - HashSet sel = new HashSet(); - sel.add("foo"); - sel.add("bar"); - s.setPropertyDataSource(new ObjectProperty(sel)); - - Assert.assertFalse(s.isEmpty()); - s.clear(); - Assert.assertTrue(s.isEmpty()); - } - - @Test - public void multiSelectEmptyAfterClear() { - AbstractSelect s = new ListSelect(); - s.setMultiSelect(true); - s.addItem("foo"); - s.addItem("bar"); - s.select("foo"); - s.select("bar"); - - Assert.assertFalse(s.isEmpty()); - s.clear(); - Assert.assertTrue(s.isEmpty()); - } - -} diff --git a/server/tests/src/com/vaadin/ui/LabelDataSource.java b/server/tests/src/com/vaadin/ui/LabelDataSource.java deleted file mode 100644 index b57e83df8e..0000000000 --- a/server/tests/src/com/vaadin/ui/LabelDataSource.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.ui; - -import java.util.Locale; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.vaadin.data.util.ObjectProperty; -import com.vaadin.server.VaadinRequest; -import com.vaadin.server.VaadinSession; -import com.vaadin.tests.util.AlwaysLockedVaadinSession; - -public class LabelDataSource { - - Label label; - private static final String STRING_DS_VALUE = "String DatA source"; - private static final int INTEGER_DS_VALUE = 1587; - private static final String INTEGER_STRING_VALUE_FI = "1 587"; - private static final String INTEGER_STRING_VALUE_EN_US = "1,587"; - private static final Object INTEGER_STRING_VALUE_DE = "1.587"; - ObjectProperty stringDataSource; - private ObjectProperty integerDataSource; - VaadinSession vaadinSession; - - @Before - public void setup() { - vaadinSession = new AlwaysLockedVaadinSession(null); - VaadinSession.setCurrent(vaadinSession); - - label = new Label(); - stringDataSource = new ObjectProperty(STRING_DS_VALUE); - integerDataSource = new ObjectProperty(INTEGER_DS_VALUE); - } - - @Test - public void stringDataSource() { - label.setPropertyDataSource(stringDataSource); - Assert.assertEquals(STRING_DS_VALUE, label.getState().text); - Assert.assertEquals(STRING_DS_VALUE, label.getValue()); - Assert.assertEquals(stringDataSource, label.getPropertyDataSource()); - label.setPropertyDataSource(null); - Assert.assertEquals(STRING_DS_VALUE, label.getState().text); - Assert.assertEquals(STRING_DS_VALUE, label.getValue()); - Assert.assertEquals(null, label.getPropertyDataSource()); - label.setValue("foo"); - Assert.assertEquals("foo", label.getState().text); - Assert.assertEquals("foo", label.getValue()); - Assert.assertNull(label.getPropertyDataSource()); - - } - - @Test - public void integerDataSourceFi() { - label.setLocale(new Locale("fi", "FI")); - label.setPropertyDataSource(integerDataSource); - Assert.assertEquals(INTEGER_STRING_VALUE_FI, label.getState().text); - Assert.assertEquals(INTEGER_STRING_VALUE_FI, label.getValue()); - Assert.assertEquals(integerDataSource, label.getPropertyDataSource()); - } - - @Test - public void integerDataSourceEn() { - label.setLocale(new Locale("en", "US")); - label.setPropertyDataSource(integerDataSource); - Assert.assertEquals(INTEGER_STRING_VALUE_EN_US, label.getState().text); - Assert.assertEquals(INTEGER_STRING_VALUE_EN_US, label.getValue()); - Assert.assertEquals(integerDataSource, label.getPropertyDataSource()); - } - - @Test - public void changeLocaleAfterDataSource() { - label.setLocale(new Locale("en", "US")); - label.setPropertyDataSource(integerDataSource); - label.setLocale(new Locale("fi", "FI")); - Assert.assertEquals(INTEGER_STRING_VALUE_FI, label.getState().text); - Assert.assertEquals(INTEGER_STRING_VALUE_FI, label.getValue()); - Assert.assertEquals(integerDataSource, label.getPropertyDataSource()); - } - - @Test - public void setRemoveDataSource() { - label.setValue("before"); - label.setPropertyDataSource(stringDataSource); - Assert.assertEquals(STRING_DS_VALUE, label.getValue()); - label.setPropertyDataSource(null); - Assert.assertEquals(STRING_DS_VALUE, label.getValue()); - label.setValue("after"); - Assert.assertEquals("after", label.getValue()); - } - - public class MockUI extends UI { - - public MockUI() { - setSession(vaadinSession); - } - - @Override - protected void init(VaadinRequest request) { - } - - } - - @Test - public void attachToSessionWithDifferentLocale() { - label.setValue("before"); - // label.setLocale(Locale.GERMANY); - label.setPropertyDataSource(integerDataSource); - UI ui = new MockUI(); - ui.setLocale(Locale.GERMANY); - ui.setContent(label); - Assert.assertEquals(INTEGER_STRING_VALUE_DE, label.getState().text); - } -} diff --git a/server/tests/src/com/vaadin/ui/LabelDataSourceTest.java b/server/tests/src/com/vaadin/ui/LabelDataSourceTest.java new file mode 100644 index 0000000000..8ec3ca1245 --- /dev/null +++ b/server/tests/src/com/vaadin/ui/LabelDataSourceTest.java @@ -0,0 +1,129 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.ui; + +import java.util.Locale; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.vaadin.data.util.ObjectProperty; +import com.vaadin.server.VaadinRequest; +import com.vaadin.server.VaadinSession; +import com.vaadin.tests.util.AlwaysLockedVaadinSession; + +public class LabelDataSourceTest { + + Label label; + private static final String STRING_DS_VALUE = "String DatA source"; + private static final int INTEGER_DS_VALUE = 1587; + private static final String INTEGER_STRING_VALUE_FI = "1 587"; + private static final String INTEGER_STRING_VALUE_EN_US = "1,587"; + private static final Object INTEGER_STRING_VALUE_DE = "1.587"; + ObjectProperty stringDataSource; + private ObjectProperty integerDataSource; + VaadinSession vaadinSession; + + @Before + public void setup() { + vaadinSession = new AlwaysLockedVaadinSession(null); + VaadinSession.setCurrent(vaadinSession); + + label = new Label(); + stringDataSource = new ObjectProperty(STRING_DS_VALUE); + integerDataSource = new ObjectProperty(INTEGER_DS_VALUE); + } + + @Test + public void stringDataSource() { + label.setPropertyDataSource(stringDataSource); + Assert.assertEquals(STRING_DS_VALUE, label.getState().text); + Assert.assertEquals(STRING_DS_VALUE, label.getValue()); + Assert.assertEquals(stringDataSource, label.getPropertyDataSource()); + label.setPropertyDataSource(null); + Assert.assertEquals(STRING_DS_VALUE, label.getState().text); + Assert.assertEquals(STRING_DS_VALUE, label.getValue()); + Assert.assertEquals(null, label.getPropertyDataSource()); + label.setValue("foo"); + Assert.assertEquals("foo", label.getState().text); + Assert.assertEquals("foo", label.getValue()); + Assert.assertNull(label.getPropertyDataSource()); + + } + + @Test + public void integerDataSourceFi() { + label.setLocale(new Locale("fi", "FI")); + label.setPropertyDataSource(integerDataSource); + Assert.assertEquals(INTEGER_STRING_VALUE_FI, label.getState().text); + Assert.assertEquals(INTEGER_STRING_VALUE_FI, label.getValue()); + Assert.assertEquals(integerDataSource, label.getPropertyDataSource()); + } + + @Test + public void integerDataSourceEn() { + label.setLocale(new Locale("en", "US")); + label.setPropertyDataSource(integerDataSource); + Assert.assertEquals(INTEGER_STRING_VALUE_EN_US, label.getState().text); + Assert.assertEquals(INTEGER_STRING_VALUE_EN_US, label.getValue()); + Assert.assertEquals(integerDataSource, label.getPropertyDataSource()); + } + + @Test + public void changeLocaleAfterDataSource() { + label.setLocale(new Locale("en", "US")); + label.setPropertyDataSource(integerDataSource); + label.setLocale(new Locale("fi", "FI")); + Assert.assertEquals(INTEGER_STRING_VALUE_FI, label.getState().text); + Assert.assertEquals(INTEGER_STRING_VALUE_FI, label.getValue()); + Assert.assertEquals(integerDataSource, label.getPropertyDataSource()); + } + + @Test + public void setRemoveDataSource() { + label.setValue("before"); + label.setPropertyDataSource(stringDataSource); + Assert.assertEquals(STRING_DS_VALUE, label.getValue()); + label.setPropertyDataSource(null); + Assert.assertEquals(STRING_DS_VALUE, label.getValue()); + label.setValue("after"); + Assert.assertEquals("after", label.getValue()); + } + + public class MockUI extends UI { + + public MockUI() { + setSession(vaadinSession); + } + + @Override + protected void init(VaadinRequest request) { + } + + } + + @Test + public void attachToSessionWithDifferentLocale() { + label.setValue("before"); + // label.setLocale(Locale.GERMANY); + label.setPropertyDataSource(integerDataSource); + UI ui = new MockUI(); + ui.setLocale(Locale.GERMANY); + ui.setContent(label); + Assert.assertEquals(INTEGER_STRING_VALUE_DE, label.getState().text); + } +} diff --git a/server/tests/src/com/vaadin/ui/UIThemeEscaping.java b/server/tests/src/com/vaadin/ui/UIThemeEscaping.java deleted file mode 100644 index 236f283823..0000000000 --- a/server/tests/src/com/vaadin/ui/UIThemeEscaping.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.ui; - -import com.vaadin.server.VaadinRequest; -import org.junit.Before; -import org.junit.Test; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class UIThemeEscaping { - - private UI ui; - - private void initUiWithTheme(String theme) { - VaadinRequest request = getRequestWithTheme(theme); - - ui.doInit(request, 1234, "foobar"); - } - - private VaadinRequest getRequestWithTheme(String theme) { - VaadinRequest request = mock(VaadinRequest.class); - - when(request.getParameter("theme")).thenReturn(theme); - - return request; - } - - @Before - public void setup() { - ui = new UI() { - @Override - protected void init(VaadinRequest request) { - // Nothing to do - } - }; - } - - @Test - public void dangerousCharactersAreRemoved() { - ui.setTheme("a<å(_\"$"); - - assertThat(ui.getTheme(), is("aå_$")); - } - - @Test - public void nullThemeIsSet() { - ui.setTheme("foobar"); - - ui.setTheme(null); - - assertThat(ui.getTheme(), is(nullValue())); - } - - @Test - public void themeIsSetOnInit() { - ui.setTheme("foobar"); - - initUiWithTheme("bar"); - - assertThat(ui.getTheme(), is("bar")); - } - - @Test - public void nullThemeIsSetOnInit() { - ui.setTheme("foobar"); - - initUiWithTheme(null); - - assertThat(ui.getTheme(), is(nullValue())); - } -} diff --git a/server/tests/src/com/vaadin/ui/UIThemeEscapingTest.java b/server/tests/src/com/vaadin/ui/UIThemeEscapingTest.java new file mode 100644 index 0000000000..7a0a5551e3 --- /dev/null +++ b/server/tests/src/com/vaadin/ui/UIThemeEscapingTest.java @@ -0,0 +1,89 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.ui; + +import com.vaadin.server.VaadinRequest; +import org.junit.Before; +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class UIThemeEscapingTest { + + private UI ui; + + private void initUiWithTheme(String theme) { + VaadinRequest request = getRequestWithTheme(theme); + + ui.doInit(request, 1234, "foobar"); + } + + private VaadinRequest getRequestWithTheme(String theme) { + VaadinRequest request = mock(VaadinRequest.class); + + when(request.getParameter("theme")).thenReturn(theme); + + return request; + } + + @Before + public void setup() { + ui = new UI() { + @Override + protected void init(VaadinRequest request) { + // Nothing to do + } + }; + } + + @Test + public void dangerousCharactersAreRemoved() { + ui.setTheme("a<å(_\"$"); + + assertThat(ui.getTheme(), is("aå_$")); + } + + @Test + public void nullThemeIsSet() { + ui.setTheme("foobar"); + + ui.setTheme(null); + + assertThat(ui.getTheme(), is(nullValue())); + } + + @Test + public void themeIsSetOnInit() { + ui.setTheme("foobar"); + + initUiWithTheme("bar"); + + assertThat(ui.getTheme(), is("bar")); + } + + @Test + public void nullThemeIsSetOnInit() { + ui.setTheme("foobar"); + + initUiWithTheme(null); + + assertThat(ui.getTheme(), is(nullValue())); + } +} diff --git a/server/tests/src/com/vaadin/util/CurrentInstanceTest.java b/server/tests/src/com/vaadin/util/CurrentInstanceTest.java new file mode 100644 index 0000000000..36055a036a --- /dev/null +++ b/server/tests/src/com/vaadin/util/CurrentInstanceTest.java @@ -0,0 +1,194 @@ +/* + * Copyright 2000-2014 Vaadin Ltd. + * + * 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.vaadin.util; + +import static org.junit.Assert.assertNull; + +import java.lang.reflect.Field; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.easymock.EasyMock; +import org.junit.Assert; +import org.junit.Test; + +import com.vaadin.server.VaadinRequest; +import com.vaadin.server.VaadinService; +import com.vaadin.server.VaadinSession; +import com.vaadin.ui.UI; + +public class CurrentInstanceTest { + + @Test + public void testInitiallyCleared() throws Exception { + assertCleared(); + } + + @Test + public void testClearedAfterRemove() throws Exception { + CurrentInstance.set(CurrentInstanceTest.class, this); + Assert.assertEquals(this, + CurrentInstance.get(CurrentInstanceTest.class)); + CurrentInstance.set(CurrentInstanceTest.class, null); + + assertCleared(); + } + + @Test + public void testClearedAfterRemoveInheritable() throws Exception { + CurrentInstance.setInheritable(CurrentInstanceTest.class, this); + Assert.assertEquals(this, + CurrentInstance.get(CurrentInstanceTest.class)); + CurrentInstance.setInheritable(CurrentInstanceTest.class, null); + + assertCleared(); + } + + @Test + public void testInheritableThreadLocal() throws Exception { + final AtomicBoolean threadFailed = new AtomicBoolean(true); + + CurrentInstance.setInheritable(CurrentInstanceTest.class, this); + Assert.assertEquals(this, + CurrentInstance.get(CurrentInstanceTest.class)); + Thread t = new Thread() { + @Override + public void run() { + Assert.assertEquals(CurrentInstanceTest.this, + CurrentInstance.get(CurrentInstanceTest.class)); + threadFailed.set(false); + } + }; + t.start(); + CurrentInstance.set(CurrentInstanceTest.class, null); + + assertCleared(); + while (t.isAlive()) { + Thread.sleep(1000); + } + Assert.assertFalse("Thread failed", threadFailed.get()); + + } + + @Test + public void testClearedAfterRemoveInSeparateThread() throws Exception { + final AtomicBoolean threadFailed = new AtomicBoolean(true); + + CurrentInstance.setInheritable(CurrentInstanceTest.class, this); + Assert.assertEquals(this, + CurrentInstance.get(CurrentInstanceTest.class)); + Thread t = new Thread() { + @Override + public void run() { + try { + Assert.assertEquals(CurrentInstanceTest.this, + CurrentInstance.get(CurrentInstanceTest.class)); + CurrentInstance.set(CurrentInstanceTest.class, null); + assertCleared(); + + threadFailed.set(false); + } catch (Exception e) { + e.printStackTrace(); + } + } + }; + t.start(); + + while (t.isAlive()) { + Thread.sleep(1000); + } + Assert.assertFalse("Thread failed", threadFailed.get()); + + // Clearing the threadlocal in the thread should not have cleared it + // here + Assert.assertEquals(this, + CurrentInstance.get(CurrentInstanceTest.class)); + + // Clearing the only remaining threadlocal should free all memory + CurrentInstance.set(CurrentInstanceTest.class, null); + assertCleared(); + } + + @Test + public void testClearedWithClearAll() throws Exception { + CurrentInstance.set(CurrentInstanceTest.class, this); + Assert.assertEquals(this, + CurrentInstance.get(CurrentInstanceTest.class)); + CurrentInstance.clearAll(); + + assertCleared(); + } + + private void assertCleared() throws SecurityException, + NoSuchFieldException, IllegalAccessException { + Assert.assertNull(getInternalCurrentInstanceVariable().get()); + } + + private InheritableThreadLocal, CurrentInstance>> getInternalCurrentInstanceVariable() + throws SecurityException, NoSuchFieldException, + IllegalAccessException { + Field f = CurrentInstance.class.getDeclaredField("instances"); + f.setAccessible(true); + return (InheritableThreadLocal, CurrentInstance>>) f + .get(null); + } + + public void testInheritedClearedAfterRemove() { + + } + + private static class UIStoredInCurrentInstance extends UI { + @Override + protected void init(VaadinRequest request) { + } + } + + private static class SessionStoredInCurrentInstance extends VaadinSession { + public SessionStoredInCurrentInstance(VaadinService service) { + super(service); + } + } + + @Test + public void testRestoringNullUIWorks() throws Exception { + // First make sure current instance is empty + CurrentInstance.clearAll(); + + // Then store a new UI in there + Map, CurrentInstance> old = CurrentInstance + .setCurrent(new UIStoredInCurrentInstance()); + + // Restore the old values and assert that the UI is null again + CurrentInstance.restoreInstances(old); + assertNull(CurrentInstance.get(UI.class)); + } + + @Test + public void testRestoringNullSessionWorks() throws Exception { + // First make sure current instance is empty + CurrentInstance.clearAll(); + + // Then store a new session in there + Map, CurrentInstance> old = CurrentInstance + .setCurrent(new SessionStoredInCurrentInstance(EasyMock + .createNiceMock(VaadinService.class))); + + // Restore the old values and assert that the session is null again + CurrentInstance.restoreInstances(old); + assertNull(CurrentInstance.get(VaadinSession.class)); + assertNull(CurrentInstance.get(VaadinService.class)); + } +} diff --git a/server/tests/src/com/vaadin/util/ReflectToolsGetFieldValueByType.java b/server/tests/src/com/vaadin/util/ReflectToolsGetFieldValueByType.java deleted file mode 100644 index 25f8ba7796..0000000000 --- a/server/tests/src/com/vaadin/util/ReflectToolsGetFieldValueByType.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.vaadin.util; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import org.junit.Test; - -public class ReflectToolsGetFieldValueByType { - @Test - public void getFieldValue() { - class MyClass { - public Integer getField() { - return 1; - } - - public void setField(Integer i) { - } - - } - class MySubClass extends MyClass { - public String field = "Hello"; - } - - MySubClass myInstance = new MySubClass(); - - java.lang.reflect.Field memberField; - Object fieldValue = new Boolean(false); - try { - memberField = myInstance.getClass().getField("field"); - // Should get a String value. Without the third parameter (calling - // ReflectTools.getJavaFieldValue(Object object, Field field)) would - // get an Integer value - fieldValue = ReflectTools.getJavaFieldValue(myInstance, - memberField, String.class); - } catch (Exception e) { - } - assertTrue(fieldValue instanceof String); - - } - - @Test - public void getFieldValueViaGetter() { - class MyClass { - public Integer field = 1; - } - class MySubClass extends MyClass { - public String field = "Hello"; - } - - MySubClass myInstance = new MySubClass(); - - java.lang.reflect.Field memberField; - try { - memberField = myInstance.getClass().getField("field"); - // Should throw an IllegalArgument exception as the mySubClass class - // doesn't have an Integer field. - ReflectTools.getJavaFieldValue(myInstance, memberField, - Integer.class); - fail("Previous method call should have thrown an exception"); - } catch (Exception e) { - } - } -} diff --git a/server/tests/src/com/vaadin/util/ReflectToolsGetFieldValueByTypeTest.java b/server/tests/src/com/vaadin/util/ReflectToolsGetFieldValueByTypeTest.java new file mode 100644 index 0000000000..67796314c0 --- /dev/null +++ b/server/tests/src/com/vaadin/util/ReflectToolsGetFieldValueByTypeTest.java @@ -0,0 +1,63 @@ +package com.vaadin.util; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.Test; + +public class ReflectToolsGetFieldValueByTypeTest { + @Test + public void getFieldValue() { + class MyClass { + public Integer getField() { + return 1; + } + + public void setField(Integer i) { + } + + } + class MySubClass extends MyClass { + public String field = "Hello"; + } + + MySubClass myInstance = new MySubClass(); + + java.lang.reflect.Field memberField; + Object fieldValue = new Boolean(false); + try { + memberField = myInstance.getClass().getField("field"); + // Should get a String value. Without the third parameter (calling + // ReflectTools.getJavaFieldValue(Object object, Field field)) would + // get an Integer value + fieldValue = ReflectTools.getJavaFieldValue(myInstance, + memberField, String.class); + } catch (Exception e) { + } + assertTrue(fieldValue instanceof String); + + } + + @Test + public void getFieldValueViaGetter() { + class MyClass { + public Integer field = 1; + } + class MySubClass extends MyClass { + public String field = "Hello"; + } + + MySubClass myInstance = new MySubClass(); + + java.lang.reflect.Field memberField; + try { + memberField = myInstance.getClass().getField("field"); + // Should throw an IllegalArgument exception as the mySubClass class + // doesn't have an Integer field. + ReflectTools.getJavaFieldValue(myInstance, memberField, + Integer.class); + fail("Previous method call should have thrown an exception"); + } catch (Exception e) { + } + } +} diff --git a/server/tests/src/com/vaadin/util/ReflectToolsGetPrimitiveFieldValue.java b/server/tests/src/com/vaadin/util/ReflectToolsGetPrimitiveFieldValue.java deleted file mode 100644 index 690f77d9a5..0000000000 --- a/server/tests/src/com/vaadin/util/ReflectToolsGetPrimitiveFieldValue.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.vaadin.util; - -import static org.junit.Assert.assertFalse; - -import org.junit.Test; - -public class ReflectToolsGetPrimitiveFieldValue { - @Test - public void getFieldValueViaGetter() { - class MyClass { - public int field = 1; - } - - MyClass myInstance = new MyClass(); - - java.lang.reflect.Field memberField; - Object fieldValue = new Boolean(false); - try { - memberField = myInstance.getClass().getField("field"); - fieldValue = ReflectTools - .getJavaFieldValue(myInstance, memberField); - } catch (Exception e) { - } - assertFalse(fieldValue instanceof Boolean); - } -} diff --git a/server/tests/src/com/vaadin/util/ReflectToolsGetPrimitiveFieldValueTest.java b/server/tests/src/com/vaadin/util/ReflectToolsGetPrimitiveFieldValueTest.java new file mode 100644 index 0000000000..40e8f05e1e --- /dev/null +++ b/server/tests/src/com/vaadin/util/ReflectToolsGetPrimitiveFieldValueTest.java @@ -0,0 +1,26 @@ +package com.vaadin.util; + +import static org.junit.Assert.assertFalse; + +import org.junit.Test; + +public class ReflectToolsGetPrimitiveFieldValueTest { + @Test + public void getFieldValueViaGetter() { + class MyClass { + public int field = 1; + } + + MyClass myInstance = new MyClass(); + + java.lang.reflect.Field memberField; + Object fieldValue = new Boolean(false); + try { + memberField = myInstance.getClass().getField("field"); + fieldValue = ReflectTools + .getJavaFieldValue(myInstance, memberField); + } catch (Exception e) { + } + assertFalse(fieldValue instanceof Boolean); + } +} diff --git a/server/tests/src/com/vaadin/util/TestCurrentInstance.java b/server/tests/src/com/vaadin/util/TestCurrentInstance.java deleted file mode 100644 index 666a0ef019..0000000000 --- a/server/tests/src/com/vaadin/util/TestCurrentInstance.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright 2000-2014 Vaadin Ltd. - * - * 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.vaadin.util; - -import static org.junit.Assert.assertNull; - -import java.lang.reflect.Field; -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.easymock.EasyMock; -import org.junit.Assert; -import org.junit.Test; - -import com.vaadin.server.VaadinRequest; -import com.vaadin.server.VaadinService; -import com.vaadin.server.VaadinSession; -import com.vaadin.ui.UI; - -public class TestCurrentInstance { - - @Test - public void testInitiallyCleared() throws Exception { - assertCleared(); - } - - @Test - public void testClearedAfterRemove() throws Exception { - CurrentInstance.set(TestCurrentInstance.class, this); - Assert.assertEquals(this, - CurrentInstance.get(TestCurrentInstance.class)); - CurrentInstance.set(TestCurrentInstance.class, null); - - assertCleared(); - } - - @Test - public void testClearedAfterRemoveInheritable() throws Exception { - CurrentInstance.setInheritable(TestCurrentInstance.class, this); - Assert.assertEquals(this, - CurrentInstance.get(TestCurrentInstance.class)); - CurrentInstance.setInheritable(TestCurrentInstance.class, null); - - assertCleared(); - } - - @Test - public void testInheritableThreadLocal() throws Exception { - final AtomicBoolean threadFailed = new AtomicBoolean(true); - - CurrentInstance.setInheritable(TestCurrentInstance.class, this); - Assert.assertEquals(this, - CurrentInstance.get(TestCurrentInstance.class)); - Thread t = new Thread() { - @Override - public void run() { - Assert.assertEquals(TestCurrentInstance.this, - CurrentInstance.get(TestCurrentInstance.class)); - threadFailed.set(false); - } - }; - t.start(); - CurrentInstance.set(TestCurrentInstance.class, null); - - assertCleared(); - while (t.isAlive()) { - Thread.sleep(1000); - } - Assert.assertFalse("Thread failed", threadFailed.get()); - - } - - @Test - public void testClearedAfterRemoveInSeparateThread() throws Exception { - final AtomicBoolean threadFailed = new AtomicBoolean(true); - - CurrentInstance.setInheritable(TestCurrentInstance.class, this); - Assert.assertEquals(this, - CurrentInstance.get(TestCurrentInstance.class)); - Thread t = new Thread() { - @Override - public void run() { - try { - Assert.assertEquals(TestCurrentInstance.this, - CurrentInstance.get(TestCurrentInstance.class)); - CurrentInstance.set(TestCurrentInstance.class, null); - assertCleared(); - - threadFailed.set(false); - } catch (Exception e) { - e.printStackTrace(); - } - } - }; - t.start(); - - while (t.isAlive()) { - Thread.sleep(1000); - } - Assert.assertFalse("Thread failed", threadFailed.get()); - - // Clearing the threadlocal in the thread should not have cleared it - // here - Assert.assertEquals(this, - CurrentInstance.get(TestCurrentInstance.class)); - - // Clearing the only remaining threadlocal should free all memory - CurrentInstance.set(TestCurrentInstance.class, null); - assertCleared(); - } - - @Test - public void testClearedWithClearAll() throws Exception { - CurrentInstance.set(TestCurrentInstance.class, this); - Assert.assertEquals(this, - CurrentInstance.get(TestCurrentInstance.class)); - CurrentInstance.clearAll(); - - assertCleared(); - } - - private void assertCleared() throws SecurityException, - NoSuchFieldException, IllegalAccessException { - Assert.assertNull(getInternalCurrentInstanceVariable().get()); - } - - private InheritableThreadLocal, CurrentInstance>> getInternalCurrentInstanceVariable() - throws SecurityException, NoSuchFieldException, - IllegalAccessException { - Field f = CurrentInstance.class.getDeclaredField("instances"); - f.setAccessible(true); - return (InheritableThreadLocal, CurrentInstance>>) f - .get(null); - } - - public void testInheritedClearedAfterRemove() { - - } - - private static class UIStoredInCurrentInstance extends UI { - @Override - protected void init(VaadinRequest request) { - } - } - - private static class SessionStoredInCurrentInstance extends VaadinSession { - public SessionStoredInCurrentInstance(VaadinService service) { - super(service); - } - } - - @Test - public void testRestoringNullUIWorks() throws Exception { - // First make sure current instance is empty - CurrentInstance.clearAll(); - - // Then store a new UI in there - Map, CurrentInstance> old = CurrentInstance - .setCurrent(new UIStoredInCurrentInstance()); - - // Restore the old values and assert that the UI is null again - CurrentInstance.restoreInstances(old); - assertNull(CurrentInstance.get(UI.class)); - } - - @Test - public void testRestoringNullSessionWorks() throws Exception { - // First make sure current instance is empty - CurrentInstance.clearAll(); - - // Then store a new session in there - Map, CurrentInstance> old = CurrentInstance - .setCurrent(new SessionStoredInCurrentInstance(EasyMock - .createNiceMock(VaadinService.class))); - - // Restore the old values and assert that the session is null again - CurrentInstance.restoreInstances(old); - assertNull(CurrentInstance.get(VaadinSession.class)); - assertNull(CurrentInstance.get(VaadinService.class)); - } -} -- cgit v1.2.3 From 57d1b87d7f3a1beb100cd7cd3cc50ef124224057 Mon Sep 17 00:00:00 2001 From: Mika Murtojärvi Date: Tue, 2 Sep 2014 12:08:01 +0000 Subject: Revert "Output legacy locators for TestBench Recorder (#14102)." This reverts commit f50b07abc784ae54af4ce7609d49013319eca57a. - the same issue is solved by https://dev.vaadin.com/review/#/c/4459/8 Change-Id: I6807fd48fd36791a9214d2223cabc6d4322bcba7 --- .../com/vaadin/client/ApplicationConnection.java | 186 ++++++++++----------- .../client/componentlocator/ComponentLocator.java | 22 +-- 2 files changed, 94 insertions(+), 114 deletions(-) (limited to 'client') diff --git a/client/src/com/vaadin/client/ApplicationConnection.java b/client/src/com/vaadin/client/ApplicationConnection.java index 947909c753..cd69f6c186 100644 --- a/client/src/com/vaadin/client/ApplicationConnection.java +++ b/client/src/com/vaadin/client/ApplicationConnection.java @@ -110,14 +110,14 @@ import com.vaadin.shared.ui.ui.UIState.PushConfigurationState; * This is the client side communication "engine", managing client-server * communication with its server side counterpart * com.vaadin.server.VaadinService. - * + * * Client-side connectors receive updates from the corresponding server-side * connector (typically component) as state updates or RPC calls. The connector * has the possibility to communicate back with its server side counter part * through RPC calls. - * + * * TODO document better - * + * * Entry point classes (widgetsets) define onModuleLoad(). */ public class ApplicationConnection implements HasHandlers { @@ -156,12 +156,12 @@ public class ApplicationConnection implements HasHandlers { * A string that, if found in a non-JSON response to a UIDL request, will * cause the browser to refresh the page. If followed by a colon, optional * whitespace, and a URI, causes the browser to synchronously load the URI. - * + * *

    * This allows, for instance, a servlet filter to redirect the application * to a custom login page when the session expires. For example: *

    - * + * *
          * if (sessionExpired) {
          *     response.setHeader("Content-Type", "text/html");
    @@ -344,7 +344,7 @@ public class ApplicationConnection implements HasHandlers {
         /**
          * Event triggered when a XHR request has finished with the status code of
          * the response.
    -     * 
    +     *
          * Useful for handlers observing network failures like online/off-line
          * monitors.
          */
    @@ -400,12 +400,12 @@ public class ApplicationConnection implements HasHandlers {
         /**
          * Event triggered when a application is stopped by calling
          * {@link ApplicationConnection#setApplicationRunning(false)}.
    -     * 
    +     *
          * To listen for the event add a {@link ApplicationStoppedHandler} by
          * invoking
          * {@link ApplicationConnection#addHandler(ApplicationConnection.ApplicationStoppedEvent.Type, ApplicationStoppedHandler)}
          * to the {@link ApplicationConnection}
    -     * 
    +     *
          * @since 7.1.8
          * @author Vaadin Ltd
          */
    @@ -432,7 +432,7 @@ public class ApplicationConnection implements HasHandlers {
             /**
              * Called when a communication error has occurred. Returning
              * true from this method suppresses error handling.
    -         * 
    +         *
              * @param details
              *            A string describing the error.
              * @param statusCode
    @@ -447,7 +447,7 @@ public class ApplicationConnection implements HasHandlers {
          * A listener for listening to application stopped events. The listener can
          * be added to a {@link ApplicationConnection} by invoking
          * {@link ApplicationConnection#addHandler(ApplicationStoppedEvent.Type, ApplicationStoppedHandler)}
    -     * 
    +     *
          * @since 7.1.8
          * @author Vaadin Ltd
          */
    @@ -457,7 +457,7 @@ public class ApplicationConnection implements HasHandlers {
              * Triggered when the {@link ApplicationConnection} marks a previously
              * running application as stopped by invoking
              * {@link ApplicationConnection#setApplicationRunning(false)}
    -         * 
    +         *
              * @param event
              *            the event triggered by the {@link ApplicationConnection}
              */
    @@ -560,7 +560,7 @@ public class ApplicationConnection implements HasHandlers {
          * called once this application has started (first response received) or
          * failed to start. This ensures that the applications are started in order,
          * to avoid session-id problems.
    -     * 
    +     *
          */
         public void start() {
             String jsonText = configuration.getUIDL();
    @@ -637,7 +637,7 @@ public class ApplicationConnection implements HasHandlers {
                 return componentLocator.@com.vaadin.client.componentlocator.ComponentLocator::getElementsByPathStartingAt(Ljava/lang/String;Lcom/google/gwt/dom/client/Element;)(id, element);
             });
             client.getPathForElement = $entry(function(element) {
    -            return componentLocator.@com.vaadin.client.componentlocator.ComponentLocator::getLegacyPathForElement(Lcom/google/gwt/dom/client/Element;)(element);
    +            return componentLocator.@com.vaadin.client.componentlocator.ComponentLocator::getPathForElement(Lcom/google/gwt/dom/client/Element;)(element);
             });
             client.initializing = false;
     
    @@ -670,7 +670,7 @@ public class ApplicationConnection implements HasHandlers {
          * 
  • vaadin.postRequestHooks is a map of functions which gets * called after each XHR made by vaadin application. Note, that it is * attaching js functions responsibility to create the variable like this: - * + * *
          * if(!vaadin.postRequestHooks) {vaadin.postRequestHooks = new Object();}
          * postRequestHooks.myHook = function(appId) {
    @@ -681,7 +681,7 @@ public class ApplicationConnection implements HasHandlers {
          * 
    First parameter passed to these functions is the identifier * of Vaadin application that made the request. * - * + * * TODO make this multi-app aware */ private native void initializeClientHooks() @@ -712,7 +712,7 @@ public class ApplicationConnection implements HasHandlers { /** * Runs possibly registered client side post request hooks. This is expected * to be run after each uidl request made by Vaadin application. - * + * * @param appId */ private static native void runPostRequestHooks(String appId) @@ -732,7 +732,7 @@ public class ApplicationConnection implements HasHandlers { /** * If on Liferay and logged in, ask the client side session management * JavaScript to extend the session duration. - * + * * Otherwise, Liferay client side JavaScript will explicitly expire the * session even though the server side considers the session to be active. * See ticket #8305 for more information. @@ -751,7 +751,7 @@ public class ApplicationConnection implements HasHandlers { /** * Indicates whether or not there are currently active UIDL requests. Used * internally to sequence requests properly, seldom needed in Widgets. - * + * * @return true if there are active requests */ public boolean hasActiveRequest() { @@ -771,7 +771,7 @@ public class ApplicationConnection implements HasHandlers { /** * Requests an analyze of layouts, to find inconsistencies. Exclusively used * for debugging during development. - * + * * @deprecated as of 7.1. Replaced by {@link UIConnector#analyzeLayouts()} */ @Deprecated @@ -783,7 +783,7 @@ public class ApplicationConnection implements HasHandlers { * Sends a request to the server to print details to console that will help * the developer to locate the corresponding server-side connector in the * source code. - * + * * @param serverConnector * @deprecated as of 7.1. Replaced by * {@link UIConnector#showServerDebugInfo(ServerConnector)} @@ -795,7 +795,7 @@ public class ApplicationConnection implements HasHandlers { /** * Makes an UIDL request to the server. - * + * * @param reqInvocations * Data containing RPC invocations and all related information. * @param extraParams @@ -835,7 +835,7 @@ public class ApplicationConnection implements HasHandlers { /** * Sends an asynchronous or synchronous UIDL request to the server using the * given URI. - * + * * @param uri * The URI to use for the request. May includes GET parameters * @param payload @@ -1004,7 +1004,7 @@ public class ApplicationConnection implements HasHandlers { /** * Handles received UIDL JSON text, parsing it, and passing it on to the * appropriate handlers, while logging timing information. - * + * * @param jsonText * @param statusCode */ @@ -1032,7 +1032,7 @@ public class ApplicationConnection implements HasHandlers { /** * Sends an asynchronous UIDL request to the server using the given URI. - * + * * @param uri * The URI to use for the request. May includes GET parameters * @param payload @@ -1167,7 +1167,7 @@ public class ApplicationConnection implements HasHandlers { /** * Checks whether or not the CSS is loaded. By default checks the size of * the loading indicator element. - * + * * @return */ protected boolean isCSSLoaded() { @@ -1177,12 +1177,12 @@ public class ApplicationConnection implements HasHandlers { /** * Shows the communication error notification. - * + * * @param details * Optional details for debugging. * @param statusCode * The status code returned for the request - * + * */ protected void showCommunicationError(String details, int statusCode) { VConsole.error("Communication error: " + details); @@ -1191,7 +1191,7 @@ public class ApplicationConnection implements HasHandlers { /** * Shows the authentication error notification. - * + * * @param details * Optional details for debugging. */ @@ -1202,7 +1202,7 @@ public class ApplicationConnection implements HasHandlers { /** * Shows the session expiration notification. - * + * * @param details * Optional details for debugging. */ @@ -1213,7 +1213,7 @@ public class ApplicationConnection implements HasHandlers { /** * Shows an error notification. - * + * * @param details * Optional details for debugging. * @param message @@ -1226,7 +1226,7 @@ public class ApplicationConnection implements HasHandlers { /** * Shows the error notification. - * + * * @param details * Optional details for debugging. */ @@ -1313,7 +1313,7 @@ public class ApplicationConnection implements HasHandlers { /** * This method is called after applying uidl change set to application. - * + * * It will clean current and queued variable change sets. And send next * change set if it exists. */ @@ -1332,7 +1332,7 @@ public class ApplicationConnection implements HasHandlers { /** * Cleans given queue of variable changes of such changes that came from * components that do not exist anymore. - * + * * @param variableBurst */ private void cleanVariableBurst( @@ -1381,7 +1381,7 @@ public class ApplicationConnection implements HasHandlers { *

    * Used by the native "client.isActive" function. *

    - * + * * @return true if deferred commands are (potentially) being executed, false * otherwise */ @@ -1396,7 +1396,7 @@ public class ApplicationConnection implements HasHandlers { /** * Returns the loading indicator used by this ApplicationConnection - * + * * @return The loading indicator for this ApplicationConnection */ public VLoadingIndicator getLoadingIndicator() { @@ -1405,7 +1405,7 @@ public class ApplicationConnection implements HasHandlers { /** * Determines whether or not the loading indicator is showing. - * + * * @return true if the loading indicator is visible * @deprecated As of 7.1. Use {@link #getLoadingIndicator()} and * {@link VLoadingIndicator#isVisible()}.isVisible() instead. @@ -1439,7 +1439,7 @@ public class ApplicationConnection implements HasHandlers { * server is received. *

    * The initial id when no request has yet been processed is -1. - * + * * @return and id identifying the response */ public int getLastResponseId() { @@ -1868,13 +1868,13 @@ public class ApplicationConnection implements HasHandlers { /** * Sends the state change events created while updating the state * information. - * + * * This must be called after hierarchy change listeners have been * called. At least caption updates for the parent are strange if * fired from state change listeners and thus calls the parent * BEFORE the parent is aware of the child (through a * ConnectorHierarchyChangedEvent) - * + * * @param pendingStateChangeEvents * The events to send */ @@ -2205,7 +2205,7 @@ public class ApplicationConnection implements HasHandlers { * Updates the connector hierarchy and returns a list of events that * should be fired after update of the hierarchy and the state is * done. - * + * * @param json * The JSON containing the hierarchy information * @return A collection of events that should be fired when update @@ -2605,9 +2605,9 @@ public class ApplicationConnection implements HasHandlers { /** * Adds an explicit RPC method invocation to the send queue. - * + * * @since 7.0 - * + * * @param invocation * RPC method invocation * @param delayed @@ -2647,7 +2647,7 @@ public class ApplicationConnection implements HasHandlers { /** * Removes any pending invocation of the given method from the queue - * + * * @param invocation * The invocation to remove */ @@ -2665,12 +2665,12 @@ public class ApplicationConnection implements HasHandlers { /** * This method sends currently queued variable changes to server. It is * called when immediate variable update must happen. - * + * * To ensure correct order for variable changes (due servers multithreading * or network), we always wait for active request to be handler before * sending a new one. If there is an active request, we will put varible * "burst" to queue that will be purged after current request is handled. - * + * */ public void sendPendingVariableChanges() { if (!deferedSendPending) { @@ -2711,11 +2711,11 @@ public class ApplicationConnection implements HasHandlers { /** * Build the variable burst and send it to server. - * + * * When sync is forced, we also force sending of all pending variable-bursts * at the same time. This is ok as we can assume that DOM will never be * updated after this. - * + * * @param pendingInvocations * List of RPC method invocations to send */ @@ -2802,7 +2802,7 @@ public class ApplicationConnection implements HasHandlers { * is true, the update is sent as soon as possible. If immediate is false, * the update will be sent along with the next immediate update. *

    - * + * * @param paintableId * the id of the paintable that owns the variable * @param variableName @@ -2824,7 +2824,7 @@ public class ApplicationConnection implements HasHandlers { * is true, the update is sent as soon as possible. If immediate is false, * the update will be sent along with the next immediate update. *

    - * + * * @param paintableId * the id of the paintable that owns the variable * @param variableName @@ -2847,7 +2847,7 @@ public class ApplicationConnection implements HasHandlers { * is true, the update is sent as soon as possible. If immediate is false, * the update will be sent along with the next immediate update. *

    - * + * * @param paintableId * the id of the paintable that owns the variable * @param variableName @@ -2870,7 +2870,7 @@ public class ApplicationConnection implements HasHandlers { * is true, the update is sent as soon as possible. If immediate is false, * the update will be sent along with the next immediate update. *

    - * + * * @param paintableId * the id of the paintable that owns the variable * @param variableName @@ -2893,7 +2893,7 @@ public class ApplicationConnection implements HasHandlers { * is true, the update is sent as soon as possible. If immediate is false, * the update will be sent along with the next immediate update. *

    - * + * * @param paintableId * the id of the paintable that owns the variable * @param variableName @@ -2916,7 +2916,7 @@ public class ApplicationConnection implements HasHandlers { * is true, the update is sent as soon as possible. If immediate is false, * the update will be sent along with the next immediate update. *

    - * + * * @param paintableId * the id of the paintable that owns the variable * @param variableName @@ -2939,7 +2939,7 @@ public class ApplicationConnection implements HasHandlers { * is true, the update is sent as soon as possible. If immediate is false, * the update will be sent along with the next immediate update. *

    - * + * * @param paintableId * the id of the paintable that owns the variable * @param variableName @@ -2962,7 +2962,7 @@ public class ApplicationConnection implements HasHandlers { * is true, the update is sent as soon as possible. If immediate is false, * the update will be sent along with the next immediate update. *

    - * + * * @param paintableId * the id of the paintable that owns the variable * @param variableName @@ -2979,13 +2979,13 @@ public class ApplicationConnection implements HasHandlers { /** * Sends a new value for the given paintables given variable to the server. - * + * * The update is actually queued to be sent at a suitable time. If immediate * is true, the update is sent as soon as possible. If immediate is false, * the update will be sent along with the next immediate update. - * + * * A null array is sent as an empty array. - * + * * @param paintableId * the id of the paintable that owns the variable * @param variableName @@ -3002,14 +3002,14 @@ public class ApplicationConnection implements HasHandlers { /** * Sends a new value for the given paintables given variable to the server. - * + * * The update is actually queued to be sent at a suitable time. If immediate * is true, the update is sent as soon as possible. If immediate is false, * the update will be sent along with the next immediate update.

    - * + * * A null array is sent as an empty array. - * - * + * + * * @param paintableId * the id of the paintable that owns the variable * @param variableName @@ -3026,7 +3026,7 @@ public class ApplicationConnection implements HasHandlers { /** * Does absolutely nothing. Replaced by {@link LayoutManager}. - * + * * @param container * @deprecated As of 7.0, serves no purpose */ @@ -3048,7 +3048,7 @@ public class ApplicationConnection implements HasHandlers { /** * Returns false - * + * * @param paintable * @return false, always * @deprecated As of 7.0, serves no purpose @@ -3060,7 +3060,7 @@ public class ApplicationConnection implements HasHandlers { /** * Returns false - * + * * @param paintable * @return false, always * @deprecated As of 7.0, serves no purpose @@ -3081,16 +3081,16 @@ public class ApplicationConnection implements HasHandlers { /** * Get either an existing ComponentConnector or create a new * ComponentConnector with the given type and id. - * + * * If a ComponentConnector with the given id already exists, returns it. * Otherwise creates and registers a new ComponentConnector of the given * type. - * + * * @param connectorId * Id of the paintable * @param connectorType * Type of the connector, as passed from the server side - * + * * @return Either an existing ComponentConnector or a new ComponentConnector * of the given type */ @@ -3103,15 +3103,15 @@ public class ApplicationConnection implements HasHandlers { /** * Creates a new ServerConnector with the given type and id. - * + * * Creates and registers a new ServerConnector of the given type. Should * never be called with the connector id of an existing connector. - * + * * @param connectorId * Id of the new connector * @param connectorType * Type of the connector, as passed from the server side - * + * * @return A new ServerConnector of the given type */ private ServerConnector createAndRegisterConnector(String connectorId, @@ -3131,7 +3131,7 @@ public class ApplicationConnection implements HasHandlers { /** * Gets a recource that has been pre-loaded via UIDL, such as custom * layouts. - * + * * @param name * identifier of the resource to get * @return the resource @@ -3142,7 +3142,7 @@ public class ApplicationConnection implements HasHandlers { /** * Singleton method to get instance of app's context menu. - * + * * @return VContextMenu object */ public VContextMenu getContextMenu() { @@ -3157,7 +3157,7 @@ public class ApplicationConnection implements HasHandlers { /** * Gets an {@link Icon} instance corresponding to a URI. - * + * * @since 7.2 * @param uri * @return Icon object @@ -3179,7 +3179,7 @@ public class ApplicationConnection implements HasHandlers { * Translates custom protocols in UIDL URI's to be recognizable by browser. * All uri's from UIDL should be routed via this method before giving them * to browser due URI's in UIDL may contain custom protocols like theme://. - * + * * @param uidlUri * Vaadin URI from uidl * @return translated URI ready for browser @@ -3251,7 +3251,7 @@ public class ApplicationConnection implements HasHandlers { /** * Gets the URI for the current theme. Can be used to reference theme * resources. - * + * * @return URI to the current theme */ public String getThemeUri() { @@ -3262,7 +3262,7 @@ public class ApplicationConnection implements HasHandlers { /** * Listens for Notification hide event, and redirects. Used for system * messages, such as session expired. - * + * */ private class NotificationRedirect implements VNotification.EventListener { String url; @@ -3291,7 +3291,7 @@ public class ApplicationConnection implements HasHandlers { /** * Gets the token (aka double submit cookie) that the server uses to protect * against Cross Site Request Forgery attacks. - * + * * @return the CSRF token string */ public String getCsrfToken() { @@ -3301,7 +3301,7 @@ public class ApplicationConnection implements HasHandlers { /** * Use to notify that the given component's caption has changed; layouts may * have to be recalculated. - * + * * @param component * the Paintable whose caption has changed * @deprecated As of 7.0.2, has not had any effect for a long time @@ -3313,7 +3313,7 @@ public class ApplicationConnection implements HasHandlers { /** * Gets the main view - * + * * @return the main view */ public UIConnector getUIConnector() { @@ -3322,7 +3322,7 @@ public class ApplicationConnection implements HasHandlers { /** * Gets the {@link ApplicationConfiguration} for the current application. - * + * * @see ApplicationConfiguration * @return the configuration for this application */ @@ -3335,7 +3335,7 @@ public class ApplicationConnection implements HasHandlers { * list of events which has server side listeners is updated automatically * before the component is updated so the value is correct if called from * updatedFromUIDL. - * + * * @param paintable * The connector to register event listeners for * @param eventIdentifier @@ -3355,7 +3355,7 @@ public class ApplicationConnection implements HasHandlers { /** * Adds the get parameters to the uri and returns the new uri that contains * the parameters. - * + * * @param uri * The uri to which the parameters should be added. * @param extraParams @@ -3408,7 +3408,7 @@ public class ApplicationConnection implements HasHandlers { /** * Get VTooltip instance related to application connection - * + * * @return VTooltip instance */ public VTooltip getVTooltip() { @@ -3420,7 +3420,7 @@ public class ApplicationConnection implements HasHandlers { * this method is now handled by the state change event handler in * AbstractComponentConnector. The only function this method has is to * return true if the UIDL is a "cached" update. - * + * * @param component * @param uidl * @param manageCaption @@ -3471,7 +3471,7 @@ public class ApplicationConnection implements HasHandlers { * Schedules a heartbeat request to occur after the configured heartbeat * interval elapses if the interval is a positive number. Otherwise, does * nothing. - * + * * @deprecated as of 7.2, use {@link Heartbeat#schedule()} instead */ @Deprecated @@ -3485,7 +3485,7 @@ public class ApplicationConnection implements HasHandlers { * Heartbeat requests are used to inform the server that the client-side is * still alive. If the client page is closed or the connection lost, the * server will eventually close the inactive UI. - * + * * @deprecated as of 7.2, use {@link Heartbeat#send()} instead */ @Deprecated @@ -3509,7 +3509,7 @@ public class ApplicationConnection implements HasHandlers { /** * This method can be used to postpone rendering of a response for a short * period of time (e.g. to avoid the rendering process during animation). - * + * * @param lock */ public void suspendReponseHandling(Object lock) { @@ -3518,7 +3518,7 @@ public class ApplicationConnection implements HasHandlers { /** * Resumes the rendering process once all locks have been removed. - * + * * @param lock */ public void resumeResponseHandling(Object lock) { @@ -3563,7 +3563,7 @@ public class ApplicationConnection implements HasHandlers { /** * Sets the delegate that is called whenever a communication error occurrs. - * + * * @param delegate * the delegate. */ @@ -3606,7 +3606,7 @@ public class ApplicationConnection implements HasHandlers { /** * Gets the active connector for focused element in browser. - * + * * @return Connector for focused element or null. */ private ComponentConnector getActiveConnector() { @@ -3620,7 +3620,7 @@ public class ApplicationConnection implements HasHandlers { /** * Sets the status for the push connection. - * + * * @param enabled * true to enable the push connection; * false to disable the push connection. @@ -3670,7 +3670,7 @@ public class ApplicationConnection implements HasHandlers { /** * Returns a human readable string representation of the method used to * communicate with the server. - * + * * @since 7.1 * @return A string representation of the current transport type */ diff --git a/client/src/com/vaadin/client/componentlocator/ComponentLocator.java b/client/src/com/vaadin/client/componentlocator/ComponentLocator.java index feb1c91767..0dfaf99cc1 100644 --- a/client/src/com/vaadin/client/componentlocator/ComponentLocator.java +++ b/client/src/com/vaadin/client/componentlocator/ComponentLocator.java @@ -36,7 +36,6 @@ import com.vaadin.client.ApplicationConnection; public class ComponentLocator { private final List locatorStrategies; - private final LocatorStrategy legacyLocatorStrategy; /** * Reference to ApplicationConnection instance. @@ -52,9 +51,8 @@ public class ComponentLocator { */ public ComponentLocator(ApplicationConnection client) { this.client = client; - legacyLocatorStrategy = new LegacyLocatorStrategy(client); locatorStrategies = Arrays.asList(new VaadinFinderLocatorStrategy( - client), legacyLocatorStrategy); + client), new LegacyLocatorStrategy(client)); } /** @@ -114,24 +112,6 @@ public class ComponentLocator { return null; } - /** - * Returns a String locator which uniquely identifies the target element. - * The returned locator is in a legacy format that is suitable for Vaadin - * TestBench Recorder. For non-legacy format, use - * {@link #getPathForElement(com.google.gwt.user.client.Element)} instead. - * - * - * @since 7.4 - * @param targetElement - * The element to generate a path for. - * @return A String locator that identifies the target element or null if a - * String locator could not be created. - */ - public String getLegacyPathForElement(Element targetElement) { - return legacyLocatorStrategy - .getPathForElement(DOM.asOld(targetElement)); - } - /** * Locates an element using a String locator (path) which identifies a DOM * element. The {@link #getPathForElement(Element)} method can be used for -- cgit v1.2.3 From 3a65f9869e2e9eccae4b28f0640920f7265cb035 Mon Sep 17 00:00:00 2001 From: Markus Koivisto Date: Thu, 8 Jan 2015 16:15:35 +0200 Subject: Removed apostrophe typo in VToolTip.Java (#15533) Changed "it's" to possesive "its". Change-Id: I4db55425a6f6778d0c1d0716ab833fa4fa8d31ac --- client/src/com/vaadin/client/VTooltip.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'client') diff --git a/client/src/com/vaadin/client/VTooltip.java b/client/src/com/vaadin/client/VTooltip.java index 47a1b71228..453563370c 100644 --- a/client/src/com/vaadin/client/VTooltip.java +++ b/client/src/com/vaadin/client/VTooltip.java @@ -134,11 +134,11 @@ public class VTooltip extends VOverlay { description.setInnerHTML(info.getTitle()); /* * Issue #11871: to correctly update the offsetWidth of description - * element we need to clear style width of it's parent DIV from old + * element we need to clear style width of its parent DIV from old * value (in some strange cases this width=[tooltip MAX_WIDTH] after * tooltip text has been already updated to new shortly value: * - *
    This is a short tooltip
    -- cgit v1.2.3 From 65904ffbdebc861a45c1b504d244d02a12f4561b Mon Sep 17 00:00:00 2001 From: Fabian Lange Date: Wed, 23 Jul 2014 22:40:35 +0200 Subject: Appending query param with vaadin version to js files (#12210) while #7868 is supposed to solve the overall issue, this solves a big part of the upgrade + cached files issues quickly. When I use vaadin themes, I have control over how they are included, so I can add a vaadin version number to it. For the default JS I cannot. Change-Id: Ica1cddee417946aa32116eb09882a3dc6c2924a6 --- WebContent/VAADIN/vaadinBootstrap.js | 16 ++++++++++++---- .../communication/AtmospherePushConnection.java | 21 ++++++++++++++------- client/src/com/vaadin/client/ui/ui/UIConnector.java | 7 ++++++- server/src/com/vaadin/server/BootstrapHandler.java | 9 +++++++-- 4 files changed, 39 insertions(+), 14 deletions(-) (limited to 'client') diff --git a/WebContent/VAADIN/vaadinBootstrap.js b/WebContent/VAADIN/vaadinBootstrap.js index ced077138f..53b213e110 100644 --- a/WebContent/VAADIN/vaadinBootstrap.js +++ b/WebContent/VAADIN/vaadinBootstrap.js @@ -18,13 +18,19 @@ log = console.log; } - var loadTheme = function(url) { + var loadTheme = function(url, version) { if(!themesLoaded[url]) { - log("loadTheme", url); + log("loadTheme", url, version); + + var href = url + '/styles.css'; + if (version) { + href += '?v=' + version; + } + var stylesheet = document.createElement('link'); stylesheet.setAttribute('rel', 'stylesheet'); stylesheet.setAttribute('type', 'text/css'); - stylesheet.setAttribute('href', url + "/styles.css"); + stylesheet.setAttribute('href', href); document.getElementsByTagName('head')[0].appendChild(stylesheet); themesLoaded[url] = true; } @@ -200,8 +206,10 @@ var bootstrapApp = function(mayDefer) { var vaadinDir = getConfig('vaadinDir'); + var versionInfo = getConfig('versionInfo'); + var themeUri = vaadinDir + 'themes/' + getConfig('theme'); - loadTheme(themeUri); + loadTheme(themeUri, versionInfo && versionInfo['vaadinVersion']); var widgetset = getConfig('widgetset'); var widgetsetUrl = getConfig('widgetsetUrl'); diff --git a/client/src/com/vaadin/client/communication/AtmospherePushConnection.java b/client/src/com/vaadin/client/communication/AtmospherePushConnection.java index a2c4dd8323..d10449ccaa 100644 --- a/client/src/com/vaadin/client/communication/AtmospherePushConnection.java +++ b/client/src/com/vaadin/client/communication/AtmospherePushConnection.java @@ -31,6 +31,7 @@ import com.vaadin.client.ResourceLoader.ResourceLoadEvent; import com.vaadin.client.ResourceLoader.ResourceLoadListener; import com.vaadin.client.VConsole; import com.vaadin.shared.ApplicationConstants; +import com.vaadin.shared.Version; import com.vaadin.shared.communication.PushConstants; import com.vaadin.shared.ui.ui.UIConstants; import com.vaadin.shared.ui.ui.UIState.PushConfigurationState; @@ -514,16 +515,10 @@ public class AtmospherePushConnection implements PushConnection { }-*/; private void runWhenAtmosphereLoaded(final Command command) { - if (isAtmosphereLoaded()) { command.execute(); } else { - final String pushJs; - if (ApplicationConfiguration.isProductionMode()) { - pushJs = ApplicationConstants.VAADIN_PUSH_JS; - } else { - pushJs = ApplicationConstants.VAADIN_PUSH_DEBUG_JS; - } + final String pushJs = getVersionedPushJs(); VConsole.log("Loading " + pushJs); ResourceLoader.get().loadScript( @@ -553,6 +548,18 @@ public class AtmospherePushConnection implements PushConnection { } } + private String getVersionedPushJs() { + String pushJs; + if (ApplicationConfiguration.isProductionMode()) { + pushJs = ApplicationConstants.VAADIN_PUSH_JS; + } else { + pushJs = ApplicationConstants.VAADIN_PUSH_DEBUG_JS; + } + // Parameter appended to bypass caches after version upgrade. + pushJs += "?v=" + Version.getFullVersion(); + return pushJs; + } + /* * (non-Javadoc) * diff --git a/client/src/com/vaadin/client/ui/ui/UIConnector.java b/client/src/com/vaadin/client/ui/ui/UIConnector.java index d6f14bf158..9e1da113bf 100644 --- a/client/src/com/vaadin/client/ui/ui/UIConnector.java +++ b/client/src/com/vaadin/client/ui/ui/UIConnector.java @@ -76,6 +76,7 @@ import com.vaadin.client.ui.window.WindowConnector; import com.vaadin.server.Page.Styles; import com.vaadin.shared.ApplicationConstants; import com.vaadin.shared.MouseEventDetails; +import com.vaadin.shared.Version; import com.vaadin.shared.communication.MethodInvocation; import com.vaadin.shared.ui.ComponentStateUtil; import com.vaadin.shared.ui.Connect; @@ -1014,9 +1015,13 @@ public class UIConnector extends AbstractSingleComponentContainerConnector * @return The URL the theme can be loaded from */ private String getThemeUrl(String theme) { - return getConnection().translateVaadinUri( + String themeUrl = getConnection().translateVaadinUri( ApplicationConstants.VAADIN_PROTOCOL_PREFIX + "themes/" + theme + "/styles" + ".css"); + // Parameter appended to bypass caches after version upgrade. + themeUrl += "?v=" + Version.getFullVersion(); + return themeUrl; + } /** diff --git a/server/src/com/vaadin/server/BootstrapHandler.java b/server/src/com/vaadin/server/BootstrapHandler.java index 30e43f48a8..c45e2b70e0 100644 --- a/server/src/com/vaadin/server/BootstrapHandler.java +++ b/server/src/com/vaadin/server/BootstrapHandler.java @@ -414,6 +414,9 @@ public abstract class BootstrapHandler extends SynchronizedRequestHandler { String vaadinLocation = vaadinService.getStaticFileLocation(request) + "/VAADIN/"; + // Parameter appended to JS to bypass caches after version upgrade. + String versionQueryParam = "?v=" + Version.getFullVersion(); + if (context.getPushMode().isEnabled()) { // Load client-side dependencies for push support String pushJS = vaadinLocation; @@ -424,12 +427,14 @@ public abstract class BootstrapHandler extends SynchronizedRequestHandler { pushJS += ApplicationConstants.VAADIN_PUSH_DEBUG_JS; } + pushJS += versionQueryParam; + fragmentNodes.add(new Element(Tag.valueOf("script"), "").attr( "type", "text/javascript").attr("src", pushJS)); } String bootstrapLocation = vaadinLocation - + ApplicationConstants.VAADIN_BOOTSTRAP_JS; + + ApplicationConstants.VAADIN_BOOTSTRAP_JS + versionQueryParam; fragmentNodes.add(new Element(Tag.valueOf("script"), "").attr("type", "text/javascript").attr("src", bootstrapLocation)); Element mainScriptTag = new Element(Tag.valueOf("script"), "").attr( @@ -613,7 +618,7 @@ public abstract class BootstrapHandler extends SynchronizedRequestHandler { } /** - * Don not override. + * Do not override. * * @param context * @return -- cgit v1.2.3