summaryrefslogtreecommitdiff
path: root/tests/tests/text/src/android/text/util/cts/LinkifyTest.java
blob: c30f9ca102750d29dc436a16af9c0e14a77b3ed5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * 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 android.text.util.cts;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import android.content.Context;
import android.platform.test.annotations.AsbSecurityTest;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.text.util.Linkify.MatchFilter;
import android.text.util.Linkify.TransformFilter;
import android.widget.TextView;

import androidx.test.InstrumentationRegistry;
import androidx.test.annotation.UiThreadTest;
import androidx.test.filters.MediumTest;
import androidx.test.runner.AndroidJUnit4;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatcher;

import java.util.Locale;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Test {@link Linkify}.
 */
@MediumTest
@RunWith(AndroidJUnit4.class)
public class LinkifyTest {
    private static final Pattern LINKIFY_TEST_PATTERN = Pattern.compile(
            "(test:)?[a-zA-Z0-9]+(\\.pattern)?");

    private MatchFilter mMatchFilterStartWithDot =
            (final CharSequence s, final int start, final int end) -> {
                if (start == 0) {
                    return true;
                }

                if (s.charAt(start - 1) == '.') {
                    return false;
                }

                return true;
            };

    private TransformFilter mTransformFilterUpperChar = (final Matcher match, String url) -> {
            StringBuilder buffer = new StringBuilder();
            String matchingRegion = match.group();

            for (int i = 0, size = matchingRegion.length(); i < size; i++) {
                char character = matchingRegion.charAt(i);

                if (character == '.' || Character.isLowerCase(character)
                        || Character.isDigit(character)) {
                    buffer.append(character);
                }
            }
            return buffer.toString();
        };

    private Context mContext;

    @Before
    public void setup() {
        mContext = InstrumentationRegistry.getTargetContext();
    }

    @Test
    public void testConstructor() {
        new Linkify();
    }

    @Test
    public void testAddLinksToSpannable() {
        // Verify URLs including the ones that have new gTLDs, and the
        // ones that look like gTLDs (and so are accepted by linkify)
        // and the ones that should not be linkified due to non-compliant
        // gTLDs
        final String longGTLD =
                "abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabc";
        SpannableString spannable = new SpannableString("name@gmail.com, "
                + "www.google.com, http://www.google.com/language_tools?hl=en, "
                + "a.bd, "   // a URL with accepted TLD so should be linkified
                + "d.e, f.1, g.12, "  // not valid, so should not be linkified
                + "http://h." + longGTLD + " "  // valid, should be linkified
                + "j." + longGTLD + "a"); // not a valid URL (gtld too long), no linkify

        assertTrue(Linkify.addLinks(spannable, Linkify.WEB_URLS));
        URLSpan[] spans = spannable.getSpans(0, spannable.length(), URLSpan.class);
        assertEquals(4, spans.length);
        assertEquals("http://www.google.com", spans[0].getURL());
        assertEquals("http://www.google.com/language_tools?hl=en", spans[1].getURL());
        assertEquals("http://a.bd", spans[2].getURL());
        assertEquals("http://h." + longGTLD, spans[3].getURL());

        assertTrue(Linkify.addLinks(spannable, Linkify.EMAIL_ADDRESSES));
        spans = spannable.getSpans(0, spannable.length(), URLSpan.class);
        assertEquals(1, spans.length);
        assertEquals("mailto:name@gmail.com", spans[0].getURL());

        assertFalse(Linkify.addLinks((Spannable) null, 0));
    }

    @Test(expected=NullPointerException.class)
    public void testAddLinksToSpannableNullWithWebUrls() {
        Linkify.addLinks((Spannable) null, Linkify.WEB_URLS);
    }

    @UiThreadTest
    @Test
    public void testAddLinksToTextView() {
        String text = "www.google.com, name@gmail.com";
        TextView tv = new TextView(mContext);
        tv.setText(text);

        assertTrue(Linkify.addLinks(tv, Linkify.WEB_URLS));
        URLSpan[] spans = ((Spannable) tv.getText()).getSpans(0, text.length(), URLSpan.class);
        assertEquals(1, spans.length);
        assertEquals("http://www.google.com", spans[0].getURL());

        SpannableString spannable = SpannableString.valueOf(text);
        tv.setText(spannable);
        assertTrue(Linkify.addLinks(tv, Linkify.EMAIL_ADDRESSES));
        spans = ((Spannable) tv.getText()).getSpans(0, text.length(), URLSpan.class);
        assertEquals(1, spans.length);
        assertEquals("mailto:name@gmail.com", spans[0].getURL());

        assertFalse(Linkify.addLinks((TextView) null, 0));
    }

    @UiThreadTest
    @Test(expected=NullPointerException.class)
    public void testAddLinksToTextViewNullWithWebUrls() {
        Linkify.addLinks((TextView) null, Linkify.WEB_URLS);
    }

    @UiThreadTest
    @Test
    public void testAddLinksToTextViewWithScheme() {
        String text = "Alan, Charlie";
        TextView tv = new TextView(mContext);
        tv.setText(text);

        Linkify.addLinks(tv, LINKIFY_TEST_PATTERN, "Test:");
        URLSpan[] spans = ((Spannable) tv.getText()).getSpans(0, text.length(), URLSpan.class);
        assertEquals(2, spans.length);
        assertEquals("test:Alan", spans[0].getURL());
        assertEquals("test:Charlie", spans[1].getURL());

        text = "google.pattern, test:AZ0101.pattern";
        tv.setText(text);
        Linkify.addLinks(tv, LINKIFY_TEST_PATTERN, "Test:");
        spans = ((Spannable) tv.getText()).getSpans(0, text.length(), URLSpan.class);
        assertEquals(2, spans.length);
        assertEquals("test:google.pattern", spans[0].getURL());
        assertEquals("test:AZ0101.pattern", spans[1].getURL());

        tv = new TextView(mContext);
        tv.setText(text);
        Linkify.addLinks(tv, LINKIFY_TEST_PATTERN, null);
        spans = ((Spannable) tv.getText()).getSpans(0, text.length(), URLSpan.class);
        assertEquals(2, spans.length);
        assertEquals("google.pattern", spans[0].getURL());
        assertEquals("test:AZ0101.pattern", spans[1].getURL());
    }

    @UiThreadTest
    @Test(expected=NullPointerException.class)
    public void testAddLinksToTextViewWithSchemeNullView() {
        Linkify.addLinks((TextView) null, LINKIFY_TEST_PATTERN, "Test:");
    }

    @UiThreadTest
    @Test(expected=NullPointerException.class)
    public void testAddLinksToTextViewWithSchemeNullPattern() {
        TextView tv = new TextView(mContext);
        tv.setText("Alan, Charlie");
        Linkify.addLinks(tv, null, "Test:");
    }

    @UiThreadTest
    @Test
    public void testAddLinksToTextViewWithSchemeAndFilter() {
        TextView tv = new TextView(mContext);

        String text = "FilterUpperCase.pattern, 12.345.pattern";
        tv.setText(text);
        Linkify.addLinks(tv, LINKIFY_TEST_PATTERN, "Test:",
                mMatchFilterStartWithDot, mTransformFilterUpperChar);
        URLSpan[] spans = ((Spannable) tv.getText()).getSpans(0, text.length(), URLSpan.class);
        assertEquals(2, spans.length);
        assertEquals("test:ilterpperase.pattern", spans[0].getURL());
        assertEquals("test:12", spans[1].getURL());

        tv.setText(text);
        Linkify.addLinks(tv, LINKIFY_TEST_PATTERN, null,
                mMatchFilterStartWithDot, mTransformFilterUpperChar);
        spans = ((Spannable) tv.getText()).getSpans(0, text.length(), URLSpan.class);
        assertEquals(2, spans.length);
        assertEquals("ilterpperase.pattern", spans[0].getURL());
        assertEquals("12", spans[1].getURL());

        tv.setText(text);
        Linkify.addLinks(tv, LINKIFY_TEST_PATTERN, "Test:", null, mTransformFilterUpperChar);
        spans = ((Spannable) tv.getText()).getSpans(0, text.length(), URLSpan.class);
        assertEquals(3, spans.length);
        assertEquals("test:ilterpperase.pattern", spans[0].getURL());
        assertEquals("test:12", spans[1].getURL());
        assertEquals("test:345.pattern", spans[2].getURL());

        tv.setText(text);
        Linkify.addLinks(tv, LINKIFY_TEST_PATTERN, "Test:", mMatchFilterStartWithDot, null);
        spans = ((Spannable) tv.getText()).getSpans(0, text.length(), URLSpan.class);
        assertEquals(2, spans.length);
        assertEquals("test:FilterUpperCase.pattern", spans[0].getURL());
        assertEquals("test:12", spans[1].getURL());
    }

    @UiThreadTest
    @Test(expected=NullPointerException.class)
    public void testAddLinksToTextViewWithSchemeAndFilterNullView() {
        Linkify.addLinks((TextView) null, LINKIFY_TEST_PATTERN, "Test:",
                mMatchFilterStartWithDot, mTransformFilterUpperChar);
    }

    @UiThreadTest
    @Test(expected=NullPointerException.class)
    public void testAddLinksToTextViewWithSchemeAndFilterNullPattern() {
        TextView tv = new TextView(mContext);
        tv.setText("FilterUpperCase.pattern, 12.345.pattern");
        Linkify.addLinks(tv, null, "Test:",
                mMatchFilterStartWithDot, mTransformFilterUpperChar);
    }

    @Test
    public void testAddLinksToSpannableWithScheme() {
        String text = "google.pattern, test:AZ0101.pattern";

        SpannableString spannable = new SpannableString(text);
        Linkify.addLinks(spannable, LINKIFY_TEST_PATTERN, "Test:");
        URLSpan[] spans = (spannable.getSpans(0, spannable.length(), URLSpan.class));
        assertEquals(2, spans.length);
        assertEquals("test:google.pattern", spans[0].getURL());
        assertEquals("test:AZ0101.pattern", spans[1].getURL());

        spannable = new SpannableString(text);
        Linkify.addLinks(spannable, LINKIFY_TEST_PATTERN, null);
        spans = (spannable.getSpans(0, spannable.length(), URLSpan.class));
        assertEquals(2, spans.length);
        assertEquals("google.pattern", spans[0].getURL());
        assertEquals("test:AZ0101.pattern", spans[1].getURL());
    }

    @UiThreadTest
    @Test(expected=NullPointerException.class)
    public void testAddLinksToSpannableWithSchemeNullSpannable() {
        Linkify.addLinks((Spannable)null, LINKIFY_TEST_PATTERN, "Test:");
    }

    @UiThreadTest
    @Test(expected=NullPointerException.class)
    public void testAddLinksToSpannableWithSchemeNullPattern() {
        String text = "google.pattern, test:AZ0101.pattern";
        SpannableString spannable = new SpannableString(text);

        Linkify.addLinks(spannable, null, "Test:");
    }

    @Test
    public void testAddLinksToSpannableWithSchemeAndFilter() {
        String text = "FilterUpperCase.pattern, 12.345.pattern";

        SpannableString spannable = new SpannableString(text);
        Linkify.addLinks(spannable, LINKIFY_TEST_PATTERN, "Test:",
                mMatchFilterStartWithDot, mTransformFilterUpperChar);
        URLSpan[] spans = (spannable.getSpans(0, spannable.length(), URLSpan.class));
        assertEquals(2, spans.length);
        assertEquals("test:ilterpperase.pattern", spans[0].getURL());
        assertEquals("test:12", spans[1].getURL());

        spannable = new SpannableString(text);
        Linkify.addLinks(spannable, LINKIFY_TEST_PATTERN, null, mMatchFilterStartWithDot,
                mTransformFilterUpperChar);
        spans = (spannable.getSpans(0, spannable.length(), URLSpan.class));
        assertEquals(2, spans.length);
        assertEquals("ilterpperase.pattern", spans[0].getURL());
        assertEquals("12", spans[1].getURL());

        spannable = new SpannableString(text);
        Linkify.addLinks(spannable, LINKIFY_TEST_PATTERN, "Test:", null, mTransformFilterUpperChar);
        spans = (spannable.getSpans(0, spannable.length(), URLSpan.class));
        assertEquals(3, spans.length);
        assertEquals("test:ilterpperase.pattern", spans[0].getURL());
        assertEquals("test:12", spans[1].getURL());
        assertEquals("test:345.pattern", spans[2].getURL());

        spannable = new SpannableString(text);
        Linkify.addLinks(spannable, LINKIFY_TEST_PATTERN, "Test:", mMatchFilterStartWithDot, null);
        spans = (spannable.getSpans(0, spannable.length(), URLSpan.class));
        assertEquals(2, spans.length);
        assertEquals("test:FilterUpperCase.pattern", spans[0].getURL());
        assertEquals("test:12", spans[1].getURL());
    }

    @UiThreadTest
    @Test(expected=NullPointerException.class)
    public void testAddLinksToSpannableWithSchemeAndFilterNullSpannable() {
        Linkify.addLinks((Spannable)null, LINKIFY_TEST_PATTERN, "Test:",
                mMatchFilterStartWithDot, mTransformFilterUpperChar);
    }

    @UiThreadTest
    @Test(expected=NullPointerException.class)
    public void testAddLinksToSpannableWithSchemeAndFilterNullPattern() {
        String text = "FilterUpperCase.pattern, 12.345.pattern";
        SpannableString spannable = new SpannableString(text);

        Linkify.addLinks(spannable, null, "Test:", mMatchFilterStartWithDot,
                mTransformFilterUpperChar);
    }

    @Test
    public void testAddLinksPhoneNumbers() {
        String numbersInvalid = "123456789 not a phone number";
        String numbersUKLocal = "tel:(0812)1234560 (0812)1234561";
        String numbersUSLocal = "tel:(812)1234562 (812)123.4563 "
                + " tel:(800)5551210 (800)555-1211 555-1212";
        String numbersIntl = "tel:+4408121234564 +44-0812-123-4565"
                + " tel:+18005551213 +1-800-555-1214";
        SpannableString spannable = new SpannableString(
                numbersInvalid
                + " " + numbersUKLocal
                + " " + numbersUSLocal
                + " " + numbersIntl);

        // phonenumber linkify depends on the device's SIM card country.
        final TelephonyManager tm =
                (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
        final String region = tm.getSimCountryIso().toUpperCase(Locale.US);

        assertTrue(Linkify.addLinks(spannable, Linkify.PHONE_NUMBERS));
        final URLSpan[] spans = spannable.getSpans(0, spannable.length(), URLSpan.class);
        if ("US".equals(region)) {
            // For the US, these specific phone numbers should be detected.
            assertEquals(9, spans.length);
            assertEquals("tel:8121234562", spans[0].getURL());
            assertEquals("tel:8121234563", spans[1].getURL());
            assertEquals("tel:8005551210", spans[2].getURL());
            assertEquals("tel:8005551211", spans[3].getURL());
            assertEquals("tel:5551212", spans[4].getURL());
            assertEquals("tel:+4408121234564", spans[5].getURL());
            assertEquals("tel:+4408121234565", spans[6].getURL());
            assertEquals("tel:+18005551213", spans[7].getURL());
            assertEquals("tel:+18005551214", spans[8].getURL());
        } else {
            // For other countries, the phone numbers that would be detected are based on the
            // country, so the exact list is unknown, but the various international phone numbers,
            // starting with '+', must always be detected, and must appear next to each other and
            // at the end of the list.
            assertTrue(spans.length >= 4);
            assertEquals("tel:+4408121234564", spans[spans.length - 4].getURL());
            assertEquals("tel:+4408121234565", spans[spans.length - 3].getURL());
            assertEquals("tel:+18005551213", spans[spans.length - 2].getURL());
            assertEquals("tel:+18005551214", spans[spans.length - 1].getURL());
        }

        assertFalse(Linkify.addLinks((Spannable) null, 0));
    }

    // Add links with scheme (array)

    @UiThreadTest
    @Test
    public void testAddLinks_withTextView_addsLinksWhenDefaultSchemeIsNull() {
        Pattern pattern = Pattern.compile("\\b((http|https)://)?android\\.com+\\b");
        TextView textView = new TextView(mContext);
        textView.setText("any https://android.com any android.com any");

        Linkify.addLinks(textView, pattern, null, null, null);

        URLSpan[] spans = textView.getUrls();
        assertEquals("android.com and https://android.com should be linkified", 2, spans.length);
        assertEquals("https://android.com", spans[0].getURL());
        assertEquals("android.com", spans[1].getURL());
    }

    @UiThreadTest
    @Test
    public void testAddLinks_withTextView_addsLinksWhenSchemesArrayIsNull() {
        Pattern pattern = Pattern.compile("\\b((http|https)://)?android\\.com+\\b");
        TextView textView = new TextView(mContext);
        textView.setText("any https://android.com any android.com any");

        Linkify.addLinks(textView, pattern, "http://", null, null);

        URLSpan[] spans = textView.getUrls();
        assertEquals("android.com and https://android.com should be linkified", 2, spans.length);
        // expected behavior, passing null schemes array means: prepend defaultScheme to all links.
        assertEquals("http://https://android.com", spans[0].getURL());
        assertEquals("http://android.com", spans[1].getURL());
    }

    @UiThreadTest
    @Test
    public void testAddLinks_withTextView_prependsDefaultSchemeToBeginingOfLink() {
        Pattern pattern = Pattern.compile("\\b((http|https)://)?android\\.com+\\b");
        TextView textView = new TextView(mContext);
        textView.setText("any android.com any");

        Linkify.addLinks(textView, pattern, "http://", new String[] { "http://", "https://"},
                null, null);

        URLSpan[] spans = textView.getUrls();
        assertEquals("android.com should be linkified", 1, spans.length);
        assertEquals("http://android.com", spans[0].getURL());
    }

    @UiThreadTest
    @Test
    public void testAddLinks_withTextView_doesNotPrependSchemeIfSchemeExists() {
        Pattern pattern = Pattern.compile("\\b((http|https)://)?android\\.com+\\b");
        TextView textView = new TextView(mContext);
        textView.setText("any https://android.com any");

        Linkify.addLinks(textView, pattern, "http://", new String[] { "http://", "https://"},
                null, null);

        URLSpan[] spans = textView.getUrls();
        assertEquals("android.com should be linkified", 1, spans.length);
        assertEquals("https://android.com", spans[0].getURL());
    }

    public class MyUrlSpan extends URLSpan {
        public MyUrlSpan(String url) {
            super(url);
        }
    }

    @Test
    public void testAddLinks_UrlSpanFactory_withSpannable() {
        final String text = "a https://android.com a +1 123 456 7878 a android@android.com a";
        final Spannable spannable = new SpannableString(text);
        final int mask = Linkify.WEB_URLS | Linkify.PHONE_NUMBERS | Linkify.EMAIL_ADDRESSES;
        final Function<String, URLSpan> spanFactory = (String string) -> new MyUrlSpan(string);

        Linkify.addLinks(spannable, mask, spanFactory);

        final MyUrlSpan[] myUrlSpans = spannable.getSpans(0, spannable.length(), MyUrlSpan.class);
        assertNotNull(myUrlSpans);
        assertEquals(3, myUrlSpans.length);
        assertEquals("https://android.com", myUrlSpans[0].getURL());
        assertEquals("tel:+11234567878", myUrlSpans[1].getURL());
        assertEquals("mailto:android@android.com", myUrlSpans[2].getURL());

        final URLSpan[] urlSpans = spannable.getSpans(0, spannable.length(), URLSpan.class);
        assertArrayEquals(myUrlSpans, urlSpans);
    }

    @Test
    public void testAddLinks_UrlSpanFactory_withSpannableAndFilter() {
        final String text = "google.pattern, test:AZ0101.pattern";
        final SpannableString spannable = new SpannableString(text);
        final Function<String, URLSpan> spanFactory = (String string) -> new MyUrlSpan(string);

        Linkify.addLinks(spannable, LINKIFY_TEST_PATTERN, "test:", null /*schemes*/,
                null /*matchFilter*/, null /*transformFilter*/, spanFactory);

        final MyUrlSpan[] myUrlSpans = spannable.getSpans(0, spannable.length(), MyUrlSpan.class);
        assertNotNull(myUrlSpans);
        assertEquals(2, myUrlSpans.length);
        assertEquals("test:google.pattern", myUrlSpans[0].getURL());
        assertEquals("test:AZ0101.pattern", myUrlSpans[1].getURL());

        final URLSpan[] urlSpans = spannable.getSpans(0, spannable.length(), URLSpan.class);
        assertArrayEquals(myUrlSpans, urlSpans);
    }

    // WEB_URLS Related Tests

    @Test
    public void testAddLinks_doesNotAddLinksForUrlWithoutProtocolAndWithoutKnownTld()
            {
        Spannable spannable = new SpannableString("hey man.its me");
        boolean linksAdded = Linkify.addLinks(spannable, Linkify.ALL);
        assertFalse("Should not add link with unknown TLD", linksAdded);
    }

    @Test
    public void testAddLinks_shouldNotAddEmailAddressAsUrl() {
        String url = "name@gmail.com";
        verifyAddLinksWithWebUrlFails("Should not recognize email address as URL", url);
    }

    @Test
    public void testAddLinks_acceptsUrlsWithCommasInRequestParameterValues() {
        String url = "https://android.com/path?ll=37.4221,-122.0836&z=17&pll=37.4221,-122.0836";
        verifyAddLinksWithWebUrlSucceeds("Should accept commas", url);
    }

    @Test
    public void testAddLinks_addsLinksForUrlWithProtocolWithoutTld() {
        String url = "http://android/#notld///a/n/d/r/o/i/d&p1=1&p2=2";
        verifyAddLinksWithWebUrlSucceeds("Should accept URL starting with protocol but does not" +
                " have TLD", url);
    }

    @Test
    public void testAddLinks_matchesProtocolCaseInsensitive() {
        String url = "hTtP://android.com";
        verifyAddLinksWithWebUrlSucceeds("Protocol matching should be case insensitive", url);
    }

    @Test
    public void testAddLinks_matchesValidUrlWithSchemeAndHostname() {
        String url = "http://www.android.com";
        verifyAddLinksWithWebUrlSucceeds("Should match valid URL with scheme and hostname", url);
    }

    @Test
    public void testAddLinks_matchesValidUrlWithSchemeHostnameAndNewTld() {
        String url = "http://www.android.me";
        verifyAddLinksWithWebUrlSucceeds("Should match valid URL with scheme hostname and new TLD",
                url);
    }

    @Test
    public void testAddLinks_matchesValidUrlWithHostnameAndNewTld() {
        String url = "android.camera";
        verifyAddLinksWithWebUrlSucceeds("Should match valid URL with hostname and new TLD", url);
    }

    @Test
    public void testAddLinks_matchesPunycodeUrl() {
        String url = "http://xn--fsqu00a.xn--unup4y";
        verifyAddLinksWithWebUrlSucceeds("Should match Punycode URL", url);
    }

    @Test
    public void testAddLinks_matchesPunycodeUrlWithoutProtocol() {
        String url = "xn--fsqu00a.xn--unup4y";
        verifyAddLinksWithWebUrlSucceeds("Should match Punycode URL without protocol", url);
    }

    @Test
    public void testAddLinks_doesNotMatchPunycodeTldThatStartsWithDash() {
        String url = "xn--fsqu00a.-xn--unup4y";
        verifyAddLinksWithWebUrlFails("Should not match Punycode TLD that starts with dash", url);
    }

    @Test
    public void testAddLinks_partiallyMatchesPunycodeTldThatEndsWithDash() {
        String url = "http://xn--fsqu00a.xn--unup4y-";
        verifyAddLinksWithWebUrlPartiallyMatches("Should partially match Punycode TLD that ends " +
                "with dash", "http://xn--fsqu00a.xn--unup4y", url);
    }

    @Test
    public void testAddLinks_matchesUrlWithUnicodeDomainName() {
        String url = "http://\uD604\uAE08\uC601\uC218\uC99D.kr";
        verifyAddLinksWithWebUrlSucceeds("Should match URL with Unicode domain name", url);
    }

    @Test
    public void testAddLinks_matchesUrlWithUnicodeDomainNameWithoutProtocol() {
        String url = "\uD604\uAE08\uC601\uC218\uC99D.kr";
        verifyAddLinksWithWebUrlSucceeds("Should match URL without protocol and with Unicode " +
                "domain name", url);
    }

    @Test
    public void testAddLinks_matchesUrlWithUnicodeDomainNameAndTld() {
        String url = "\uB3C4\uBA54\uC778.\uD55C\uAD6D";
        verifyAddLinksWithWebUrlSucceeds("Should match URL with Unicode domain name and TLD", url);
    }

    @Test
    public void testAddLinks_matchesUrlWithUnicodePath() {
        String url = "http://android.com/\u2019/a";
        verifyAddLinksWithWebUrlSucceeds("Should match URL with Unicode path", url);
    }

    @Test
    public void testAddLinks_matchesValidUrlWithPort() {
        String url = "http://www.example.com:8080";
        verifyAddLinksWithWebUrlSucceeds("Should match URL with port", url);
    }

    @Test
    public void testAddLinks_matchesUrlWithPortAndQuery() {
        String url = "http://www.example.com:8080/?foo=bar";
        verifyAddLinksWithWebUrlSucceeds("Should match URL with port and query", url);
    }

    @Test
    public void testAddLinks_matchesUrlWithTilde() {
        String url = "http://www.example.com:8080/~user/?foo=bar";
        verifyAddLinksWithWebUrlSucceeds("Should match URL with tilde", url);
    }

    @Test
    public void testAddLinks_matchesUrlStartingWithHttpAndDoesNotHaveTld() {
        String url = "http://android/#notld///a/n/d/r/o/i/d&p1=1&p2=2";
        verifyAddLinksWithWebUrlSucceeds("Should match URL without a TLD and starting with http",
                url);
    }

    @Test
    public void testAddLinks_doesNotMatchUrlsWithoutProtocolAndWithUnknownTld() {
        String url = "thank.you";
        verifyAddLinksWithWebUrlFails("Should not match URL that does not start with a protocol " +
                "and does not contain a known TLD", url);
    }

    @Test
    public void testAddLinks_matchesValidUrlWithEmoji() {
        String url = "Thank\u263A.com";
        verifyAddLinksWithWebUrlSucceeds("Should match URL with emoji", url);
    }

    @Test
    public void testAddLinks_doesNotMatchUrlsWithEmojiWithoutProtocolAndWithoutKnownTld()
            {
        String url = "Thank\u263A.you";
        verifyAddLinksWithWebUrlFails("Should not match URLs containing emoji and with unknown " +
                "TLD", url);
    }

    @Test
    public void testAddLinks_matchesDomainNameWithSurrogatePairs() {
        String url = "android\uD83C\uDF38.com";
        verifyAddLinksWithWebUrlSucceeds("Should match domain name with Unicode surrogate pairs",
                url);
    }

    @Test
    public void testAddLinks_matchesTldWithSurrogatePairs() {
        String url = "http://android.\uD83C\uDF38com";
        verifyAddLinksWithWebUrlSucceeds("Should match TLD with Unicode surrogate pairs", url);
    }

    @Test
    public void testAddLinks_doesNotMatchUrlWithExcludedSurrogate() {
        String url = "android\uD83F\uDFFE.com";
        verifyAddLinksWithWebUrlFails("Should not match URL with excluded Unicode surrogate" +
                " pair",  url);
    }

    @Test
    public void testAddLinks_matchesPathWithSurrogatePairs() {
        String url = "http://android.com/path-with-\uD83C\uDF38?v=\uD83C\uDF38f";
        verifyAddLinksWithWebUrlSucceeds("Should match path and query with Unicode surrogate pairs",
                url);
    }

    @Test
    public void testAddLinks__doesNotMatchUnicodeSpaces() {
        String part1 = "http://and";
        String part2 = "roid.com";
        String[] emptySpaces = new String[]{
                "\u00A0", // no-break space
                "\u2000", // en quad
                "\u2001", // em quad
                "\u2002", // en space
                "\u2003", // em space
                "\u2004", // three-per-em space
                "\u2005", // four-per-em space
                "\u2006", // six-per-em space
                "\u2007", // figure space
                "\u2008", // punctuation space
                "\u2009", // thin space
                "\u200A", // hair space
                "\u2028", // line separator
                "\u2029", // paragraph separator
                "\u202F", // narrow no-break space
                "\u3000"  // ideographic space
        };

        for (String emptySpace : emptySpaces) {
            String url = part1 + emptySpace + part2;
            verifyAddLinksWithWebUrlPartiallyMatches("Should not include empty space with code: " +
                    emptySpace.codePointAt(0), part1, url);
        }
    }

    @Test
    public void testAddLinks_matchesDomainNameWithDash() {
        String url = "http://a-nd.r-oid.com";
        verifyAddLinksWithWebUrlSucceeds("Should match domain name with '-'", url);

        url = "a-nd.r-oid.com";
        verifyAddLinksWithWebUrlSucceeds("Should match domain name with '-'", url);
    }

    @Test
    public void testAddLinks_matchesDomainNameWithUnderscore() {
        String url = "http://a_nd.r_oid.com";
        verifyAddLinksWithWebUrlSucceeds("Should match domain name with '_'", url);

        url = "a_nd.r_oid.com";
        verifyAddLinksWithWebUrlSucceeds("Should match domain name with '_'", url);
    }

    @Test
    public void testAddLinks_matchesPathAndQueryWithDollarSign() {
        String url = "http://android.com/path$?v=$val";
        verifyAddLinksWithWebUrlSucceeds("Should match path and query with '$'", url);

        url = "android.com/path$?v=$val";
        verifyAddLinksWithWebUrlSucceeds("Should match path and query with '$'", url);
    }

    @Test
    public void testAddLinks_matchesEmptyPathWithQueryParams() {
        String url = "http://android.com?q=v";
        verifyAddLinksWithWebUrlSucceeds("Should match empty path with query params", url);

        url = "android.com?q=v";
        verifyAddLinksWithWebUrlSucceeds("Should match empty path with query params", url);

        url = "http://android.com/?q=v";
        verifyAddLinksWithWebUrlSucceeds("Should match empty path with query params", url);

        url = "android.com/?q=v";
        verifyAddLinksWithWebUrlSucceeds("Should match empty path with query params", url);
    }

    // EMAIL_ADDRESSES Related Tests

    @Test
    public void testAddLinks_email_matchesShortValidEmail() {
        String email = "a@a.co";
        verifyAddLinksWithEmailSucceeds("Should match email: " + email, email);

        email = "ab@a.co";
        verifyAddLinksWithEmailSucceeds("Should match email: " + email, email);
    }

    @Test
    public void testAddLinks_email_matchesRegularEmail() {
        String email = "email@android.com";
        verifyAddLinksWithEmailSucceeds("Should match email: " + email, email);
    }

    @Test
    public void testAddLinks_email_matchesEmailWithMultipleSubdomains() {
        String email = "email@e.somelongdomainnameforandroid.abc.uk";
        verifyAddLinksWithEmailSucceeds("Should match email: " + email, email);
    }

    @Test
    public void testAddLinks_email_matchesLocalPartWithDot() {
        String email = "e.mail@android.com";
        verifyAddLinksWithEmailSucceeds("Should match email: " + email, email);
    }

    @Test
    public void testAddLinks_email_matchesLocalPartWithPlus() {
        String email = "e+mail@android.com";
        verifyAddLinksWithEmailSucceeds("Should match email: " + email, email);
    }

    @Test
    public void testAddLinks_email_matchesLocalPartWithUnderscore() {
        String email = "e_mail@android.com";
        verifyAddLinksWithEmailSucceeds("Should match email: " + email, email);
    }

    @Test
    public void testAddLinks_email_matchesLocalPartWithDash() {
        String email = "e-mail@android.com";
        verifyAddLinksWithEmailSucceeds("Should match email: " + email, email);
    }

    @Test
    public void testAddLinks_email_matchesLocalPartWithApostrophe() {
        String email = "e'mail@android.com";
        verifyAddLinksWithEmailSucceeds("Should match email: " + email, email);
    }

    @Test
    public void testAddLinks_email_matchesLocalPartWithDigits() {
        String email = "123@android.com";
        verifyAddLinksWithEmailSucceeds("Should match email: " + email, email);
    }

    @Test
    public void testAddLinks_email_matchesUnicodeLocalPart() {
        String email = "\uD604\uAE08\uC601\uC218\uC99D@android.kr";
        verifyAddLinksWithEmailSucceeds("Should match email: " + email, email);
    }

    @Test
    public void testAddLinks_email_matchesLocalPartWithEmoji() {
        String email = "smiley\u263A@android.com";
        verifyAddLinksWithEmailSucceeds("Should match email: " + email, email);
    }

    @Test
    public void testAddLinks_email_matchesLocalPartWithSurrogatePairs()
            {
        String email = "a\uD83C\uDF38a@android.com";
        verifyAddLinksWithEmailSucceeds("Should match email: " + email, email);
    }

    @Test
    public void testAddLinks_email_matchesDomainWithDash() {
        String email = "email@an-droid.com";
        verifyAddLinksWithEmailSucceeds("Should match email: " + email, email);
    }

    @Test
    public void testAddLinks_email_matchesUnicodeDomain() {
        String email = "email@\uD604\uAE08\uC601\uC218\uC99D.kr";
        verifyAddLinksWithEmailSucceeds("Should match email: " + email, email);
    }

    @Test
    public void testAddLinks_email_matchesUnicodeLocalPartAndDomain()
            {
        String email = "\uD604\uAE08\uC601\uC218\uC99D@\uD604\uAE08\uC601\uC218\uC99D.kr";
        verifyAddLinksWithEmailSucceeds("Should match email: " + email, email);
    }

    @Test
    public void testAddLinks_email_matchesDomainWithEmoji() {
        String email = "smiley@\u263Aandroid.com";
        verifyAddLinksWithEmailSucceeds("Should match email: " + email, email);
    }

    @Test
    public void testAddLinks_email_matchesDomainWithSurrogatePairs()
            {
        String email = "email@\uD83C\uDF38android.com";
        verifyAddLinksWithEmailSucceeds("Should match email: " + email, email);
    }

    @Test
    public void testAddLinks_email_matchesLocalPartAndDomainWithSurrogatePairs()
            {
        String email = "a\uD83C\uDF38a@\uD83C\uDF38android.com";
        verifyAddLinksWithEmailSucceeds("Should match email: " + email, email);
    }

    @Test
    public void testAddLinks_partiallyMatchesEmailEndingWithDot() {
        String email = "email@android.co.uk.";
        verifyAddLinksWithEmailPartiallyMatches("Should partially match email ending with dot",
                "mailto:email@android.co.uk", email);
    }

    @Test
    public void testAddLinks_email_partiallyMatchesLocalPartStartingWithDot()
            {
        String email = ".email@android.com";
        verifyAddLinksWithEmailPartiallyMatches("Should partially match email starting " +
                "with dot", "mailto:email@android.com", email);
    }

    @Test
    public void testAddLinks_email_doesNotMatchStringWithoutAtSign() {
        String email = "android.com";
        verifyAddLinksWithEmailFails("Should not match email: " + email, email);
    }

    @Test
    public void testAddLinks_email_doesNotMatchPlainString() {
        String email = "email";
        verifyAddLinksWithEmailFails("Should not match email: " + email, email);
    }

    @Test
    public void testAddLinks_email_doesNotMatchEmailWithoutTld() {
        String email = "email@android";
        verifyAddLinksWithEmailFails("Should not match email: " + email, email);
    }

    @Test
    public void testAddLinks_email_doesNotMatchLocalPartEndingWithDot()
            {
        String email = "email.@android.com";
        verifyAddLinksWithEmailFails("Should not match email: " + email, email);
    }

    @Test
    public void testAddLinks_email_doesNotMatchDomainStartingWithDash()
            {
        String email = "email@-android.com";
        verifyAddLinksWithEmailFails("Should not match email: " + email, email);
    }

    @Test
    public void testAddLinks_email_doesNotMatchDomainWithConsecutiveDots()
            {
        String email = "email@android..com";
        verifyAddLinksWithEmailFails("Should not match email: " + email, email);
    }

    @Test
    public void testAddLinks_email_doesNotMatchEmailWithIp() {
        String email = "email@127.0.0.1";
        verifyAddLinksWithEmailFails("Should not match email: " + email, email);
    }

    @Test
    public void testAddLinks_email_doesNotMatchEmailWithInvalidTld()
            {
        String email = "email@android.c";
        verifyAddLinksWithEmailFails("Should not match email: " + email, email);
    }

    @Test
    public void testAddLinks_email_matchesLocalPartUpTo64Chars() {
        String localPart = "";
        for (int i = 0; i < 64; i++) {
            localPart += "a";
        }
        String email = localPart + "@android.com";
        verifyAddLinksWithEmailSucceeds("Should match email local part of length: " +
                localPart.length(), email);

        email = localPart + "a@android.com";
        verifyAddLinksWithEmailFails("Should not match email local part of length:" +
                localPart.length(), email);
    }

    @Test
    public void testAddLinks_email_matchesSubdomainUpTo63Chars() {
        String subdomain = "";
        for (int i = 0; i < 63; i++) {
            subdomain += "a";
        }
        String email = "email@" + subdomain + ".com";

        verifyAddLinksWithEmailSucceeds("Should match email subdomain of length: " +
                subdomain.length(), email);

        subdomain += "a";
        email = "email@" + subdomain + ".com";

        verifyAddLinksWithEmailFails("Should not match email subdomain of length:" +
                subdomain.length(), email);
    }

    @Test
    public void testAddLinks_email_matchesDomainUpTo255Chars() {
        String domain = "";
        while (domain.length() <= 250) {
            domain += "d.";
        }
        domain += "com";
        assertEquals(255, domain.length());
        String email = "a@" + domain;
        verifyAddLinksWithEmailSucceeds("Should match email domain of length: " +
                domain.length(), email);

        email = email + "m";
        verifyAddLinksWithEmailFails("Should not match email domain of length:" +
                domain.length(), email);
    }

    @Test
    @AsbSecurityTest(cveBugId = 116321860)
    public void testAddLinks_unsupportedCharacters() {
        String url = "moc.diordna.com";
        verifyAddLinksWithWebUrlSucceeds(url + " should be linkified", url);

        verifyAddLinksWithWebUrlFails("u202C character should not be linkified", "\u202C" + url);
        verifyAddLinksWithWebUrlFails("u202D character should not be linkified", url + "\u202D");
        verifyAddLinksWithWebUrlFails(
                "u202E character should not be linkified", url + "moc\u202E.diordna.com");
    }

    // Utility functions
    private static void verifyAddLinksWithWebUrlSucceeds(String msg, String url) {
        verifyAddLinksSucceeds(msg, url, Linkify.WEB_URLS);
    }

    private static void verifyAddLinksWithWebUrlFails(String msg, String url) {
        verifyAddLinksFails(msg, url, Linkify.WEB_URLS);
    }

    private static void verifyAddLinksWithWebUrlPartiallyMatches(String msg, String expected,
            String url) {
        verifyAddLinksPartiallyMatches(msg, expected, url, Linkify.WEB_URLS);
    }

    private static void verifyAddLinksWithEmailSucceeds(String msg, String url) {
        verifyAddLinksSucceeds(msg, url, Linkify.EMAIL_ADDRESSES);
    }

    private static void verifyAddLinksWithEmailFails(String msg, String url) {
        verifyAddLinksFails(msg, url, Linkify.EMAIL_ADDRESSES);
    }

    private static void verifyAddLinksWithEmailPartiallyMatches(String msg, String expected,
            String url) {
        verifyAddLinksPartiallyMatches(msg, expected, url, Linkify.EMAIL_ADDRESSES);
    }

    private static void verifyAddLinksSucceeds(String msg, String string, int type) {
        String str = "start " + string + " end";
        Spannable spannable = new SpannableString(str);

        boolean linksAdded = Linkify.addLinks(spannable, type);
        URLSpan[] spans = spannable.getSpans(0, str.length(), URLSpan.class);

        assertTrue(msg, linksAdded);
        assertEquals("Span should start from the beginning of: " + string,
                "start ".length(), spannable.getSpanStart(spans[0]));
        assertEquals("Span should end at the end of: " + string,
                str.length() - " end".length(), spannable.getSpanEnd(spans[0]));
    }

    private static void verifyAddLinksFails(String msg, String string, int type) {
        Spannable spannable = new SpannableString("start " + string + " end");
        boolean linksAdded = Linkify.addLinks(spannable, type);
        assertFalse(msg, linksAdded);
    }

    private static void verifyAddLinksPartiallyMatches(String msg, String expected,
            String string, int type) {
        Spannable spannable = new SpannableString("start " + string + " end");
        boolean linksAdded = Linkify.addLinks(spannable, type);
        URLSpan[] spans = spannable.getSpans(0, spannable.length(), URLSpan.class);
        assertTrue(msg, linksAdded);
        assertEquals(msg, expected, spans[0].getURL().toString());
    }

    /** Helper to match a CharSequence based on String equivalence. */
    class EqStringMatcher implements ArgumentMatcher<CharSequence> {
        private final String mReference;

        EqStringMatcher(CharSequence reference) {
            mReference = reference.toString();
        }

        @Override
        public boolean matches(CharSequence arg) {
            return mReference.equals(arg.toString());
        }
    }
}