001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.console.test;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020
021import java.util.*;
022import java.util.regex.*;
023import java.util.stream.*;
024
025import org.apache.juneau.marshall.collections.*;
026import org.apache.juneau.console.*;
027
028/**
029 * Test helper that extracts the {@code #juneau-page} contract and {@code <template>} ids from a
030 * rendered console page, validates them against {@link PageContractSchema}, and offers fluent
031 * assertions so adopters assert on the contract instead of on rendered chrome HTML.
032 *
033 * <p>
034 * Failures throw {@link AssertionError}, so the class works under any test framework.
035 *
036 * <p>
037 * {@link #assertPage(String)} also fails immediately if the contract still carries the pre-rename top-level
038 * <c>version</c> key (now <c>contractVersion</c>), even when {@link #isValid()} is never called.
039 *
040 * <h2 class='section'>Example:</h2>
041 * <p class='bjava'>
042 *    String <jv>html</jv> = <jv>client</jv>.get(<js>"/slo"</js>).run().getContent().asString();
043 *    PageContractAssert.<jsm>assertPage</jsm>(<jv>html</jv>)
044 *       .isValid()
045 *       .hasContractVersion(<js>"1"</js>)
046 *       .hasActiveNav(<js>"slo"</js>)
047 *       .hasNavPath(<js>"home"</js>, <js>"about"</js>)
048 *       .hasNavHref(<js>"slo"</js>, <js>"/slo"</js>)
049 *       .hasFooterText(<js>"Sandbox Support Console"</js>)
050 *       .hasHeaderSlot(<js>"banner"</js>)
051 *       .hasCard(<js>"releases"</js>, <js>"datatables"</js>)
052 *       .hasCardKey(<js>"releases"</js>, <js>"/table/dataUrl"</js>, <js>"/rest/releases/data"</js>)
053 *       .templateContains(<js>"jc-seg-1"</js>, <js>"id=\"ssc-table-slot\""</js>);
054 *
055 *    PageContractAssert.<jsm>assertPage</jsm>(<jv>html</jv>)
056 *       .subscribes(<js>"tasks"</js>, <js>"selection:changes"</js>, <js>"params"</js>)
057 *       .declaresTopic(<js>"ops.jobs"</js>)
058 *       .hasBridge(<js>"ops"</js>)
059 *       .hasNoWiringErrors();
060 * </p>
061 *
062 * @since 10.0.0
063 */
064@SuppressWarnings({
065   "java:S1192", // Duplicated literals read more clearly inline than as constants.
066   "java:S1168", // Null means "not found" for the private lookup helpers; callers test for it.
067   "java:S3776" // Contract walkers branch once per structural case; splitting them obscures the traversal.
068})
069public final class PageContractAssert {
070
071   private static final Pattern ISLAND = Pattern.compile(
072      "<script type=\"application/json\" id=\"juneau-page\">(.*?)</script>", Pattern.DOTALL);
073   private static final Pattern TEMPLATE_OPEN = Pattern.compile("<template data-(card|slot)=\"([^\"]+)\">");
074
075   private final String json;
076   private final JsonMap contract;
077   private final Map<String,String> templates;
078
079   private PageContractAssert(String html) {
080      var m = ISLAND.matcher(html);
081      if (! m.find())
082         throw new AssertionError("no <script type=\"application/json\" id=\"juneau-page\"> in page");
083      json = m.group(1);
084      try {
085         contract = JsonMap.ofString(json);
086      } catch (Exception e) {
087         throw new AssertionError("unparseable page contract: " + e.getMessage(), e);
088      }
089      if (contract.containsKey("version"))
090         throw new AssertionError("page contract key 'version' was renamed to 'contractVersion'; regenerate the page with a current Juneau");
091      templates = scanTemplates(html);
092   }
093
094   /**
095    * Parses the contract and templates out of a rendered page.
096    *
097    * @param html The full rendered page.
098    * @return A new assertion object.
099    * @throws AssertionError If the page has no parseable contract island.
100    */
101   public static PageContractAssert assertPage(String html) {
102      return new PageContractAssert(html);
103   }
104
105   /**
106    * Asserts the contract passes the schema and rules R-1..R-4.
107    *
108    * @return This object.
109    */
110   public PageContractAssert isValid() {
111      var errors = PageContractSchema.get().validate(json, templates.keySet());
112      if (! errors.isEmpty())
113         throw new AssertionError("page contract is invalid:\n" + String.join("\n", errors));
114      return this;
115   }
116
117   /** @param v The expected contract version. @return This object. */
118   public PageContractAssert hasContractVersion(String v) {
119      return eq("contractVersion", v, contract.getString("contractVersion"));
120   }
121
122   /** @param v The expected page title. @return This object. */
123   public PageContractAssert hasTitle(String v) {
124      return eq("title", v, contract.getString("title"));
125   }
126
127   /** @param name The expected theme name. @return This object. */
128   public PageContractAssert hasTheme(String name) {
129      var t = contract.getMap("theme");
130      return eq("theme.name", name, t == null ? null : t.getString("name"));
131   }
132
133   /** @param idPath The expected active path, root first. @return This object. */
134   public PageContractAssert hasActiveNav(String... idPath) {
135      var actual = strings(contract.getList("activeNav"));
136      if (! actual.equals(List.of(idPath)))
137         throw new AssertionError("activeNav: expected " + List.of(idPath) + " but was " + actual);
138      return this;
139   }
140
141   /** Asserts {@code activeNav} is empty (the JS prefix fallback applies). @return This object. */
142   public PageContractAssert hasNoActiveNav() {
143      var actual = strings(contract.getList("activeNav"));
144      if (! actual.isEmpty())
145         throw new AssertionError("activeNav: expected [] but was " + actual);
146      return this;
147   }
148
149   /** @param idPath A root-first id path that must exist in {@code nav}. @return This object. */
150   public PageContractAssert hasNavPath(String... idPath) {
151      if (idPath.length == 0)
152         throw new AssertionError("hasNavPath() requires at least one path segment");
153      node(List.of(idPath));
154      return this;
155   }
156
157   /**
158    * @param id A node id, or a {@code /}-separated id path such as {@code "home/about"}.
159    * @param href The expected href.
160    * @return This object.
161    */
162   public PageContractAssert hasNavHref(String id, String href) {
163      var n = node(List.of(id.split("/")));
164      if (neq(href, n.getString("href")))
165         throw new AssertionError("nav '" + id + "' href: expected '" + href + "' but was '" + n.getString("href") + "'");
166      return this;
167   }
168
169   /**
170    * @param idPath A {@code /}-separated id path.
171    * @param childIds The expected child ids, in order.
172    * @return This object.
173    */
174   public PageContractAssert hasNavChildren(String idPath, String... childIds) {
175      var n = node(List.of(idPath.split("/")));
176      var kids = n.getList("children");
177      var actual = kids == null ? List.<String>of() : kids.stream().map(k -> ((JsonMap)k).getString("id")).toList();
178      if (! actual.equals(List.of(childIds)))
179         throw new AssertionError("nav '" + idPath + "' children: expected " + List.of(childIds) + " but was " + actual);
180      return this;
181   }
182
183   /** @param v The expected {@code header.title}. @return This object. */
184   public PageContractAssert hasHeaderTitle(String v) {
185      var h = contract.getMap("header");
186      return eq("header.title", v, h == null ? null : h.getString("title"));
187   }
188
189   /** @param name A header slot name ({@code brand}, {@code actions}, {@code replace}, {@code banner}). @return This object. */
190   public PageContractAssert hasHeaderSlot(String name) {
191      return slot("header", name);
192   }
193
194   /** @param v The expected {@code footer.text}. @return This object. */
195   public PageContractAssert hasFooterText(String v) {
196      var f = contract.getMap("footer");
197      return eq("footer.text", v, f == null ? null : f.getString("text"));
198   }
199
200   /** @param name A footer slot name ({@code content}). @return This object. */
201   public PageContractAssert hasFooterSlot(String name) {
202      return slot("footer", name);
203   }
204
205   /**
206    * @param id The card id.
207    * @param type The expected card type.
208    * @return This object.
209    */
210   public PageContractAssert hasCard(String id, String type) {
211      var c = card(id);
212      if (neq(type, c.getString("type")))
213         throw new AssertionError("card '" + id + "' type: expected '" + type + "' but was '" + c.getString("type") + "'");
214      return this;
215   }
216
217   /** @param ids The expected card ids, in contract order. @return This object. */
218   public PageContractAssert hasCardOrder(String... ids) {
219      var actual = cardIds();
220      if (! actual.equals(List.of(ids)))
221         throw new AssertionError("card order: expected " + List.of(ids) + " but was " + actual);
222      return this;
223   }
224
225   /** @param cardId The card id. @param topic A topic the card must subscribe to. @return This object. */
226   public PageContractAssert subscribes(String cardId, String topic) {
227      subscription(cardId, topic, null);
228      return this;
229   }
230
231   /**
232    * @param cardId The card id.
233    * @param topic A topic the card must subscribe to.
234    * @param role The role it must be wired to.
235    * @return This object.
236    */
237   public PageContractAssert subscribes(String cardId, String topic, String role) {
238      subscription(cardId, topic, role);
239      return this;
240   }
241
242   /** @param cardId The card id. @param topic A custom topic the card must declare in {@code publishes}. @return This object. */
243   public PageContractAssert publishes(String cardId, String topic) {
244      var topics = topicsOf(card(cardId).getList("publishes"));
245      if (! topics.contains(topic))
246         throw new AssertionError("card '" + cardId + "' does not publish '" + topic + "'; publishes: " + topics);
247      return this;
248   }
249
250   /** @param topic A top-level {@code topics} entry that must exist. @return This object. */
251   public PageContractAssert declaresTopic(String topic) {
252      var topics = topicsOf(contract.getList("topics"));
253      if (! topics.contains(topic))
254         throw new AssertionError("no topics entry '" + topic + "'; topics: " + topics);
255      return this;
256   }
257
258   /** @param id A top-level {@code bridges} id that must exist. @return This object. */
259   public PageContractAssert hasBridge(String id) {
260      var ids = new ArrayList<String>();
261      var l = contract.getList("bridges");
262      if (l != null)
263         for (var o : l)
264            ids.add(((JsonMap)o).getString("id"));
265      if (! ids.contains(id))
266         throw new AssertionError("no bridge '" + id + "'; bridges: " + ids);
267      return this;
268   }
269
270   /**
271    * Runs R-10 and R-11 against the standard card-type registry. Pair it with {@code BusPolicy.check(contract())}
272    * (juneau-console-bus) for the server-grant side (E-55). A page with custom card types needs the
273    * {@link #hasNoWiringErrors(CardTypeRegistry)} overload with the registry that knows them.
274    *
275    * @return This object.
276    */
277   public PageContractAssert hasNoWiringErrors() {
278      return hasNoWiringErrors(CardTypeRegistry.standard());
279   }
280
281   /** @param registry The registry that knows the page's card types. @return This object. */
282   public PageContractAssert hasNoWiringErrors(CardTypeRegistry registry) {
283      var problems = BusWiringValidator.validate(contract, registry);
284      if (! problems.isEmpty())
285         throw new AssertionError("page wiring has errors:\n"
286            + problems.stream().map(p -> p.code() + " " + p.message()).collect(Collectors.joining("\n")));
287      return this;
288   }
289
290   private JsonMap subscription(String cardId, String topic, String role) {
291      var l = card(cardId).getList("subscribes");
292      var roles = new ArrayList<String>();
293      if (l != null)
294         for (var o : l) {
295            var m = (JsonMap)o;
296            if (! topic.equals(m.getString("topic")))
297               continue;
298            if (role == null || role.equals(m.getString("as")))
299               return m;
300            roles.add(m.getString("as"));
301         }
302      if (! roles.isEmpty())
303         throw new AssertionError("card '" + cardId + "' subscribes to '" + topic + "' as " + roles + ", not '" + role + "'");
304      throw new AssertionError("card '" + cardId + "' does not subscribe to '" + topic + "'; subscribes: " + topicsOf(l));
305   }
306
307   private static List<String> topicsOf(List<?> l) {
308      var out = new ArrayList<String>();
309      if (l != null)
310         for (var o : l)
311            out.add(((JsonMap)o).getString("topic"));
312      return out;
313   }
314
315   /**
316    * @param id The card id.
317    * @param src The expected {@code src} value.
318    * @return This object.
319    */
320   public PageContractAssert hasCardSrc(String id, String src) {
321      return eq("card '" + id + "' src", src, card(id).getString("src"));
322   }
323
324   /**
325    * @param id The card id.
326    * @param jsonPointer A {@code /}-separated path into the card's JSON, for example {@code "/table/dataUrl"}.
327    * @param expected The expected value at that path.
328    * @return This object.
329    */
330   public PageContractAssert hasCardKey(String id, String jsonPointer, Object expected) {
331      var actual = resolvePointer(card(id), jsonPointer);
332      if (neq(expected, actual))
333         throw new AssertionError("card '" + id + "' " + jsonPointer + ": expected '" + expected + "' but was '" + actual + "'");
334      return this;
335   }
336
337   /**
338    * @param templateId A {@code data-card} or {@code data-slot} template id.
339    * @param fragment Markup that must appear in the template.
340    * @return This object.
341    */
342   public PageContractAssert templateContains(String templateId, String fragment) {
343      if (! template(templateId).contains(fragment))
344         throw new AssertionError("template '" + templateId + "' does not contain '" + fragment + "'");
345      return this;
346   }
347
348   /**
349    * Asserts this page and another render the same contract and the same template markup.
350    *
351    * <p>
352    * Use it to prove two ways of producing a page (for example a hand-written template and its builder twin) agree.
353    * The contracts are compared as key-sorted JSON; list order is kept, because card, nav and option order is part of
354    * the page.  Templates are compared by id on their {@linkplain String#strip() stripped} markup, so the whitespace a
355    * template author's layout puts around a card body does not count.
356    *
357    * <p>
358    * The failure message names the first difference, for example
359    * {@code page contracts differ at $.cards[0].bare: this=true other=false}.
360    *
361    * @param other The page this one must equal.
362    * @return This object.
363    */
364   public PageContractAssert isTwinOf(PageContractAssert other) {
365      assertTwins(contract, templates, other.contract, other.templates);
366      return this;
367   }
368
369   /**
370    * Asserts two contract and template pairs are twins, as {@link #isTwinOf(PageContractAssert)} does.
371    *
372    * <p>
373    * Exposed so a test that must first adjust either side (for example remove a card known to differ) can still use the
374    * shared comparison.
375    *
376    * @param contract The first contract.
377    * @param templates The first page's templates, by id.
378    * @param otherContract The second contract.
379    * @param otherTemplates The second page's templates, by id.
380    * @throws AssertionError If the contracts or templates differ.
381    */
382   public static void assertTwins(Map<?,?> contract, Map<String,String> templates, Map<?,?> otherContract, Map<String,String> otherTemplates) {
383      var diff = firstDiff("$", canonical(contract), canonical(otherContract));
384      if (diff != null)
385         throw new AssertionError("page contracts differ at " + diff);
386      var a = stripped(templates);
387      var b = stripped(otherTemplates);
388      var ids = new TreeSet<>(a.keySet());
389      ids.addAll(b.keySet());
390      for (var id : ids)
391         if (neq(a.get(id), b.get(id)))
392            throw new AssertionError("page template '" + id + "' differs: this=" + a.get(id) + " other=" + b.get(id));
393   }
394
395   private static Map<String,String> stripped(Map<String,String> templates) {
396      var out = new TreeMap<String,String>();
397      templates.forEach((k, v) -> out.put(k, v.strip()));
398      return out;
399   }
400
401   // Recursively key-sorts every Map; List order is kept.
402   private static Object canonical(Object v) {
403      if (v instanceof Map<?,?> m) {
404         var out = new TreeMap<String,Object>();
405         m.forEach((k, x) -> out.put(String.valueOf(k), canonical(x)));
406         return out;
407      }
408      if (v instanceof List<?> l)
409         return l.stream().map(PageContractAssert::canonical).toList();
410      return v;
411   }
412
413   // The first place two canonical trees differ, or null.
414   private static String firstDiff(String path, Object a, Object b) {
415      if (! neq(a, b))
416         return null;
417      if (a instanceof Map<?,?> x && b instanceof Map<?,?> y) {
418         var keys = new TreeSet<Object>(x.keySet());
419         keys.addAll(y.keySet());
420         for (var k : keys) {
421            var d = firstDiff(path + "." + k, x.get(k), y.get(k));
422            if (d != null)
423               return d;
424         }
425      }
426      if (a instanceof List<?> x && b instanceof List<?> y && x.size() == y.size())
427         for (var i = 0; i < x.size(); i++) {
428            var d = firstDiff(path + "[" + i + "]", x.get(i), y.get(i));
429            if (d != null)
430               return d;
431         }
432      return path + ": this=" + a + " other=" + b;
433   }
434
435   /**
436    * Escape hatch for asserts this class does not offer.
437    *
438    * @return The parsed contract.
439    */
440   public JsonMap contract() {
441      return contract;
442   }
443
444   /**
445    * @return Every {@code <template data-card|data-slot>} id mapped to its inner markup, in document order.
446    */
447   public Map<String,String> templates() {
448      return u(templates);
449   }
450
451   /**
452    * @param templateId A {@code data-card} or {@code data-slot} template id.
453    * @return The template's inner markup.
454    */
455   public String template(String templateId) {
456      var t = templates.get(templateId);
457      if (t == null)
458         throw new AssertionError("no <template data-card|data-slot=\"" + templateId + "\">; templates: " + templates.keySet());
459      return t;
460   }
461
462   private PageContractAssert eq(String what, String expected, String actual) {
463      if (neq(expected, actual))
464         throw new AssertionError(what + ": expected '" + expected + "' but was '" + actual + "'");
465      return this;
466   }
467
468   private PageContractAssert slot(String scope, String name) {
469      var sec = contract.getMap(scope);
470      var slots = sec == null ? null : sec.getMap("slots");
471      if (slots == null || ! slots.containsKey(name))
472         throw new AssertionError(scope + ".slots has no '" + name + "'");
473      return this;
474   }
475
476   private JsonMap node(List<String> path) {
477      var level = contract.getList("nav");
478      JsonMap found = null;
479      for (var id : path) {
480         found = null;
481         if (level != null)
482            for (var o : level)
483               if (id.equals(((JsonMap)o).getString("id")))
484                  found = (JsonMap)o;
485         if (found == null)
486            throw new AssertionError("nav path " + path + " not found (failed at '" + id + "')");
487         level = found.getList("children");
488      }
489      return found;
490   }
491
492   /**
493    * @param id The card id.
494    * @return The card's parsed JSON.
495    */
496   public JsonMap card(String id) {
497      for (var o : contract.getList("cards"))
498         if (id.equals(((JsonMap)o).getString("id")))
499            return (JsonMap)o;
500      for (var o : contract.getList("cards")) {
501         var found = findNested((JsonMap)o, id);
502         if (found != null)
503            return found;
504      }
505      throw new AssertionError("no card '" + id + "'; cards: " + cardIds());
506   }
507
508   /**
509    * Asserts that a card sits inside another card (a switcher view or section).
510    *
511    * @param parentId The enclosing card id.
512    * @param id The nested card id.
513    * @param type The expected nested card type.
514    * @return This object.
515    */
516   public PageContractAssert hasNestedCard(String parentId, String id, String type) {
517      var parent = card(parentId);
518      var found = findNested(parent, id);
519      if (found == null)
520         throw new AssertionError("card '" + parentId + "' does not hold a nested card '" + id + "'");
521      if (neq(type, found.getString("type")))
522         throw new AssertionError("nested card '" + id + "' type: expected '" + type + "' but was '" + found.getString("type") + "'");
523      return this;
524   }
525
526   // Depth-first through views[*].card, views[*].sections[*].card and views[*].cards[*].
527   private static JsonMap findNested(JsonMap card, String id) {
528      if (! (card.get("views") instanceof List<?> views))
529         return null;
530      for (var v : views) {
531         if (! (v instanceof Map<?,?> vm))
532            continue;
533         var candidates = new ArrayList<Object>();
534         candidates.add(vm.get("card"));
535         if (vm.get("cards") instanceof List<?> stacked)
536            candidates.addAll(stacked);
537         if (vm.get("sections") instanceof List<?> secs)
538            for (var s : secs)
539               if (s instanceof Map<?,?> sm)
540                  candidates.add(sm.get("card"));
541         for (var c : candidates) {
542            if (! (c instanceof Map<?,?> cm))
543               continue;
544            var j = cm instanceof JsonMap jm ? jm : new JsonMap(toStringKeys(cm));
545            if (id.equals(j.getString("id")))
546               return j;
547            var deeper = findNested(j, id);
548            if (deeper != null)
549               return deeper;
550         }
551      }
552      return null;
553   }
554
555   private static Map<String,Object> toStringKeys(Map<?,?> m) {
556      var out = new LinkedHashMap<String,Object>();
557      m.forEach((k, v) -> out.put(String.valueOf(k), v));
558      return out;
559   }
560
561   private List<String> cardIds() {
562      return contract.getList("cards").stream().map(o -> ((JsonMap)o).getString("id")).toList();
563   }
564
565   private static Object resolvePointer(Object node, String pointer) {
566      if (pointer.isEmpty())
567         return node;
568      if (! pointer.startsWith("/"))
569         throw new AssertionError("json pointer '" + pointer + "' must start with '/'");
570      var cur = node;
571      for (var raw : pointer.substring(1).split("/", -1)) {
572         var seg = raw.replace("~1", "/").replace("~0", "~");
573         if (cur instanceof Map<?,?> m) {
574            cur = m.get(seg);
575         } else if (cur instanceof List<?> l) {
576            var idx = Integer.parseInt(seg);
577            cur = idx >= 0 && idx < l.size() ? l.get(idx) : null;
578         } else {
579            throw new AssertionError("json pointer '" + pointer + "' hit a leaf before '" + seg + "'; node was: " + cur);
580         }
581      }
582      return cur;
583   }
584
585   private static List<String> strings(List<?> l) {
586      return l == null ? List.of() : l.stream().map(String::valueOf).toList();
587   }
588
589   // Depth-aware: page markup may itself contain <template> elements.
590   private static Map<String,String> scanTemplates(String html) {
591      var out = new LinkedHashMap<String,String>();
592      var m = TEMPLATE_OPEN.matcher(html);
593      var from = 0;
594      while (m.find(from)) {
595         var start = m.end();
596         var depth = 1;
597         var i = start;
598         while (depth > 0) {
599            var open = html.indexOf("<template", i);
600            var close = html.indexOf("</template>", i);
601            if (close < 0)
602               throw new AssertionError("unterminated <template data-" + m.group(1) + "=\"" + m.group(2) + "\">");
603            if (open >= 0 && open < close) {
604               depth++;
605               i = open + 9;
606            } else {
607               depth--;
608               i = close + 11;
609            }
610         }
611         out.put(m.group(2), html.substring(start, i - 11));
612         from = i;
613      }
614      return out;
615   }
616}