1 /*
2  * SafeHtmlUtilTests.java
3  *
4  * Copyright (C) 2021 by RStudio, PBC
5  *
6  * Unless you have received this program directly from RStudio pursuant
7  * to the terms of a commercial license agreement with RStudio, then
8  * this program is licensed to you under the terms of version 3 of the
9  * GNU Affero General Public License. This program is distributed WITHOUT
10  * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
11  * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
12  * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
13  *
14  */
15 package org.rstudio.core.client;
16 
17 import com.google.gwt.junit.client.GWTTestCase;
18 import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
19 
20 public class SafeHtmlUtilTests extends GWTTestCase
21 {
22 
23    /**
24     * Are multiple needles discovered in the haystack?
25     */
testHighlightSearchMatch()26    public void testHighlightSearchMatch()
27    {
28       String haystack = "Sphinx of black quartz, judge my vow.";
29       String[] needles = { "black", "judge" };
30 
31       SafeHtmlBuilder sb = new SafeHtmlBuilder();
32 
33       SafeHtmlUtil.highlightSearchMatch(sb, haystack, needles, "match");
34 
35       assertEquals(
36             "Sphinx of <span class=\"match\">black</span> quartz, " +
37             "<span class=\"match\">judge</span> my vow.",
38             sb.toSafeHtml().asString());
39    }
40 
41    /**
42     * Is the haystack undisturbed when it contains no needles?
43     */
testNoSearchMatch()44    public void testNoSearchMatch()
45    {
46       String haystack = "Sphinx of black quartz, judge my vow.";
47       String[] needles = { "watermelon" };
48 
49       SafeHtmlBuilder sb = new SafeHtmlBuilder();
50 
51       SafeHtmlUtil.highlightSearchMatch(sb, haystack, needles, "match");
52 
53       assertEquals(haystack, sb.toSafeHtml().asString());
54    }
55 
56    /**
57     * Are overlapping search matches only emitted once?
58     */
testOverlappingMatch()59    public void testOverlappingMatch()
60    {
61       String haystack = "A closed mouth gathers no foot.";
62       String[] needles = { "gather", "gat", "her" };
63 
64       SafeHtmlBuilder sb = new SafeHtmlBuilder();
65 
66       SafeHtmlUtil.highlightSearchMatch(sb, haystack, needles, "match");
67 
68       assertEquals(
69             "A closed mouth <span class=\"match\">gather</span>s no foot.",
70             sb.toSafeHtml().asString());
71 
72    }
73 
74    @Override
getModuleName()75    public String getModuleName()
76    {
77       return "org.rstudio.studio.RStudioTests";
78    }
79 }
80