You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DeclarativeTestBaseBase.java 9.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. package com.vaadin.tests.design;
  2. import static java.nio.charset.StandardCharsets.UTF_8;
  3. import static org.junit.Assert.assertNull;
  4. import java.io.ByteArrayInputStream;
  5. import java.io.ByteArrayOutputStream;
  6. import java.util.ArrayList;
  7. import java.util.Arrays;
  8. import java.util.Collection;
  9. import java.util.Collections;
  10. import java.util.HashSet;
  11. import java.util.List;
  12. import java.util.logging.Handler;
  13. import java.util.logging.LogRecord;
  14. import java.util.logging.Logger;
  15. import org.jsoup.Jsoup;
  16. import org.jsoup.nodes.Attribute;
  17. import org.jsoup.nodes.Element;
  18. import org.jsoup.nodes.Node;
  19. import org.jsoup.nodes.TextNode;
  20. import org.junit.Assert;
  21. import com.vaadin.ui.AbstractComponent;
  22. import com.vaadin.ui.Component;
  23. import com.vaadin.ui.declarative.Design;
  24. import com.vaadin.ui.declarative.DesignContext;
  25. import com.vaadin.ui.declarative.ShouldWriteDataDelegate;
  26. public abstract class DeclarativeTestBaseBase<T extends Component> {
  27. private static final String[] booleanAttributes = { "allowfullscreen",
  28. "async", "autofocus", "checked", "compact", "declare", "default",
  29. "defer", "disabled", "formnovalidate", "hidden", "inert", "ismap",
  30. "itemscope", "multiple", "muted", "nohref", "noresize", "noshade",
  31. "novalidate", "nowrap", "open", "readonly", "required", "reversed",
  32. "seamless", "selected", "sortable", "truespeed", "typemustmatch" };
  33. private static final class AlwaysWriteDelegate
  34. implements ShouldWriteDataDelegate {
  35. private static final long serialVersionUID = -6345914431997793599L;
  36. @Override
  37. public boolean shouldWriteData(Component component) {
  38. return true;
  39. }
  40. }
  41. public static final ShouldWriteDataDelegate ALWAYS_WRITE_DATA = new AlwaysWriteDelegate();
  42. public interface EqualsAsserter<TT> {
  43. public void assertObjectEquals(TT o1, TT o2);
  44. }
  45. protected T read(String design) {
  46. return (T) Design
  47. .read(new ByteArrayInputStream(design.getBytes(UTF_8)));
  48. }
  49. protected DesignContext readAndReturnContext(String design) {
  50. return Design.read(new ByteArrayInputStream(design.getBytes(UTF_8)),
  51. null);
  52. }
  53. protected String write(T object, boolean writeData) {
  54. DesignContext dc = new DesignContext();
  55. if (writeData) {
  56. dc.setShouldWriteDataDelegate(
  57. DeclarativeTestBaseBase.ALWAYS_WRITE_DATA);
  58. }
  59. return write(object, dc);
  60. }
  61. protected String write(T object, DesignContext context) {
  62. try {
  63. ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  64. context.setRootComponent(object);
  65. Design.write(context, outputStream);
  66. return outputStream.toString(UTF_8.name());
  67. } catch (Exception e) {
  68. throw new RuntimeException(e);
  69. }
  70. }
  71. protected void assertEquals(Object o1, Object o2) {
  72. assertEquals("", o1, o2);
  73. }
  74. protected void assertEquals(String message, Object o1, Object o2) {
  75. if (o1 == null) {
  76. assertNull(message, o2);
  77. return;
  78. }
  79. if (o2 == null) {
  80. assertNull(message, o1);
  81. return;
  82. }
  83. if (!(o1 instanceof Collection && o2 instanceof Collection)) {
  84. Assert.assertEquals(o1.getClass(), o2.getClass());
  85. }
  86. if (o1 instanceof Object[]) {
  87. Object[] a1 = ((Object[]) o1);
  88. Object[] a2 = ((Object[]) o2);
  89. Assert.assertEquals(message + ": array length", a1.length,
  90. a2.length);
  91. for (int i = 0; i < a1.length; i++) {
  92. assertEquals(message + ": element " + i, a1[i], a2[i]);
  93. }
  94. return;
  95. }
  96. List<EqualsAsserter<Object>> comparators = getComparators(o1);
  97. if (!comparators.isEmpty()) {
  98. for (EqualsAsserter<Object> ec : comparators) {
  99. ec.assertObjectEquals(o1, o2);
  100. }
  101. } else {
  102. Assert.assertEquals(message, o1, o2);
  103. }
  104. }
  105. private List<EqualsAsserter<Object>> getComparators(Object o1) {
  106. List<EqualsAsserter<Object>> result = new ArrayList<>();
  107. getComparators(o1.getClass(), result);
  108. return result;
  109. }
  110. private void getComparators(Class<?> c,
  111. List<EqualsAsserter<Object>> result) {
  112. if (c == null || !isVaadin(c)) {
  113. return;
  114. }
  115. EqualsAsserter<Object> comparator = (EqualsAsserter<Object>) getComparator(
  116. c);
  117. if (c.getSuperclass() != Object.class) {
  118. getComparators(c.getSuperclass(), result);
  119. }
  120. for (Class<?> i : c.getInterfaces()) {
  121. getComparators(i, result);
  122. }
  123. if (!result.contains(comparator)) {
  124. result.add(comparator);
  125. }
  126. }
  127. protected abstract <TT> EqualsAsserter<TT> getComparator(Class<TT> c);
  128. private boolean isVaadin(Class<?> c) {
  129. return c.getPackage() != null
  130. && c.getPackage().getName().startsWith("com.vaadin");
  131. }
  132. public static class TestLogHandler {
  133. final List<String> messages = new ArrayList<>();
  134. Handler handler = new Handler() {
  135. @Override
  136. public void publish(LogRecord record) {
  137. messages.add(record.getMessage());
  138. }
  139. @Override
  140. public void flush() {
  141. }
  142. @Override
  143. public void close() throws SecurityException {
  144. }
  145. };
  146. public TestLogHandler() {
  147. Logger.getLogger(AbstractComponent.class.getName()).getParent()
  148. .addHandler(handler);
  149. }
  150. public String getMessages() {
  151. if (messages.isEmpty()) {
  152. return "";
  153. }
  154. String r = "";
  155. for (String message : messages) {
  156. r += message + "\n";
  157. }
  158. return r;
  159. }
  160. }
  161. public T testRead(String design, T expected) {
  162. TestLogHandler l = new TestLogHandler();
  163. T read = read(design);
  164. assertEquals(expected, read);
  165. Assert.assertEquals("", l.getMessages());
  166. return read;
  167. }
  168. public DesignContext readComponentAndCompare(String design, T expected) {
  169. TestLogHandler l = new TestLogHandler();
  170. DesignContext context = readAndReturnContext(design);
  171. assertEquals(expected, context.getRootComponent());
  172. Assert.assertEquals("", l.getMessages());
  173. return context;
  174. }
  175. public void testWrite(String expected, T component) {
  176. TestLogHandler l = new TestLogHandler();
  177. testWrite(expected, component, false);
  178. Assert.assertEquals("", l.getMessages());
  179. }
  180. public void testWrite(String expectedDesign, T component,
  181. boolean writeData) {
  182. String written = write(component, writeData);
  183. Element producedElem = Jsoup.parse(written).body().child(0);
  184. Element comparableElem = Jsoup.parse(expectedDesign).body().child(0);
  185. String produced = elementToHtml(producedElem);
  186. String comparable = elementToHtml(comparableElem);
  187. Assert.assertEquals(comparable, produced);
  188. }
  189. public void testWrite(T component, String expected, DesignContext context) {
  190. String written = write(component, context);
  191. Element producedElem = Jsoup.parse(written).body().child(0);
  192. Element comparableElem = Jsoup.parse(expected).body().child(0);
  193. String produced = elementToHtml(producedElem);
  194. String comparable = elementToHtml(comparableElem);
  195. Assert.assertEquals(comparable, produced);
  196. }
  197. protected Element createElement(Component c) {
  198. return new DesignContext().createElement(c);
  199. }
  200. private String elementToHtml(Element producedElem) {
  201. StringBuilder stringBuilder = new StringBuilder();
  202. elementToHtml(producedElem, stringBuilder);
  203. return stringBuilder.toString();
  204. }
  205. /**
  206. * Produce predictable html (attributes in alphabetical order), always
  207. * include close tags
  208. */
  209. private String elementToHtml(Element producedElem, StringBuilder sb) {
  210. HashSet<String> booleanAttributes = new HashSet<>();
  211. List<String> names = new ArrayList<>();
  212. for (Attribute a : producedElem.attributes().asList()) {
  213. names.add(a.getKey());
  214. if (isBooleanAttribute(a.getKey())) {
  215. booleanAttributes.add(a.getKey());
  216. }
  217. }
  218. Collections.sort(names);
  219. sb.append('<').append(producedElem.tagName());
  220. for (String attrName : names) {
  221. sb.append(' ').append(attrName);
  222. if (!booleanAttributes.contains(attrName)) {
  223. sb.append('=').append("\'").append(producedElem.attr(attrName))
  224. .append("\'");
  225. }
  226. }
  227. sb.append('>');
  228. for (Node child : producedElem.childNodes()) {
  229. if (child instanceof Element) {
  230. elementToHtml((Element) child, sb);
  231. } else if (child instanceof TextNode) {
  232. String text = ((TextNode) child).text();
  233. sb.append(text.trim());
  234. }
  235. }
  236. sb.append("</").append(producedElem.tagName()).append('>');
  237. return sb.toString();
  238. }
  239. /**
  240. * Checks if this attribute name is defined as a boolean attribute in HTML5
  241. */
  242. protected static boolean isBooleanAttribute(final String key) {
  243. return Arrays.binarySearch(booleanAttributes, key) >= 0;
  244. }
  245. protected String stripOptionTags(String design) {
  246. return design.replaceAll("[ \n]*<option(.*)</option>[ \n]*", "");
  247. }
  248. }