KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > commons > lang > StringUtilsTest


1 /*
2  * Copyright 2002-2005 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.commons.lang;
17
18 import java.lang.reflect.Constructor JavaDoc;
19 import java.lang.reflect.Modifier JavaDoc;
20 import java.util.Arrays JavaDoc;
21 import java.util.Iterator JavaDoc;
22
23 import junit.framework.Test;
24 import junit.framework.TestCase;
25 import junit.framework.TestSuite;
26 import junit.textui.TestRunner;
27
28 /**
29  * Unit tests {@link org.apache.commons.lang.StringUtils}.
30  *
31  * @author <a HREF="mailto:dlr@collab.net">Daniel Rall</a>
32  * @author <a HREF="mailto:bayard@generationjava.com">Henri Yandell</a>
33  * @author Stephen Colebourne
34  * @author <a HREF="mailto:ridesmet@users.sourceforge.net">Ringo De Smet</a>
35  * @author <a HREF="mailto:fredrik@westermarck.com>Fredrik Westermarck</a>
36  * @author Holger Krauth
37  * @author <a HREF="hps@intermeta.de">Henning P. Schmiedehausen</a>
38  * @author Phil Steitz
39  * @author Gary D. Gregory
40  * @author Al Chou
41  * @version $Id: StringUtilsTest.java 161244 2005-04-14 06:16:36Z ggregory $
42  */

43 public class StringUtilsTest extends TestCase {
44     
45     static final String JavaDoc WHITESPACE;
46     static final String JavaDoc NON_WHITESPACE;
47     static final String JavaDoc TRIMMABLE;
48     static final String JavaDoc NON_TRIMMABLE;
49     static {
50         String JavaDoc ws = "";
51         String JavaDoc nws = "";
52         String JavaDoc tr = "";
53         String JavaDoc ntr = "";
54         for (int i = 0; i < Character.MAX_VALUE; i++) {
55             if (Character.isWhitespace((char) i)) {
56                 ws += String.valueOf((char) i);
57                 if (i > 32) {
58                     ntr += String.valueOf((char) i);
59                 }
60             } else if (i < 40) {
61                 nws += String.valueOf((char) i);
62             }
63         }
64         for (int i = 0; i <= 32; i++) {
65             tr += String.valueOf((char) i);
66         }
67         WHITESPACE = ws;
68         NON_WHITESPACE = nws;
69         TRIMMABLE = tr;
70         NON_TRIMMABLE = ntr;
71     }
72
73     private static final String JavaDoc[] ARRAY_LIST = { "foo", "bar", "baz" };
74     private static final String JavaDoc[] EMPTY_ARRAY_LIST = {};
75     private static final String JavaDoc[] NULL_ARRAY_LIST = {null};
76     private static final String JavaDoc[] MIXED_ARRAY_LIST = {null, "", "foo"};
77     private static final Object JavaDoc[] MIXED_TYPE_LIST = {new String JavaDoc("foo"), new Long JavaDoc(2)};
78
79     private static final String JavaDoc SEPARATOR = ",";
80     private static final char SEPARATOR_CHAR = ';';
81
82     private static final String JavaDoc TEXT_LIST = "foo,bar,baz";
83     private static final String JavaDoc TEXT_LIST_CHAR = "foo;bar;baz";
84     private static final String JavaDoc TEXT_LIST_NOSEP = "foobarbaz";
85
86     private static final String JavaDoc FOO_UNCAP = "foo";
87     private static final String JavaDoc FOO_CAP = "Foo";
88
89     private static final String JavaDoc SENTENCE_UNCAP = "foo bar baz";
90     private static final String JavaDoc SENTENCE_CAP = "Foo Bar Baz";
91
92     public StringUtilsTest(String JavaDoc name) {
93         super(name);
94     }
95
96     public static void main(String JavaDoc[] args) {
97         TestRunner.run(suite());
98     }
99
100     public static Test suite() {
101         TestSuite suite = new TestSuite(StringUtilsTest.class);
102         suite.setName("StringUtilsTest Tests");
103         return suite;
104     }
105
106     protected void setUp() throws Exception JavaDoc {
107         super.setUp();
108     }
109
110     protected void tearDown() throws Exception JavaDoc {
111         super.tearDown();
112     }
113
114     //-----------------------------------------------------------------------
115
public void testConstructor() {
116         assertNotNull(new StringUtils());
117         Constructor JavaDoc[] cons = StringUtils.class.getDeclaredConstructors();
118         assertEquals(1, cons.length);
119         assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
120         assertEquals(true, Modifier.isPublic(StringUtils.class.getModifiers()));
121         assertEquals(false, Modifier.isFinal(StringUtils.class.getModifiers()));
122     }
123     
124     //-----------------------------------------------------------------------
125
public void testCaseFunctions() {
126         assertEquals(null, StringUtils.upperCase(null));
127         assertEquals(null, StringUtils.lowerCase(null));
128         assertEquals(null, StringUtils.capitalize(null));
129         assertEquals(null, StringUtils.uncapitalize(null));
130
131         assertEquals("capitalize(String) failed",
132                      FOO_CAP, StringUtils.capitalize(FOO_UNCAP) );
133         assertEquals("capitalize(empty-string) failed",
134                      "", StringUtils.capitalize("") );
135         assertEquals("capitalize(single-char-string) failed",
136                      "X", StringUtils.capitalize("x") );
137         assertEquals("uncapitalize(String) failed",
138                      FOO_UNCAP, StringUtils.uncapitalize(FOO_CAP) );
139         assertEquals("uncapitalize(empty-string) failed",
140                      "", StringUtils.uncapitalize("") );
141         assertEquals("uncapitalize(single-char-string) failed",
142                      "x", StringUtils.uncapitalize("X") );
143                      
144         // reflection type of tests: Sentences.
145
assertEquals("uncapitalize(capitalize(String)) failed",
146                      SENTENCE_UNCAP, StringUtils.uncapitalize(StringUtils.capitalize(SENTENCE_UNCAP)) );
147         assertEquals("capitalize(uncapitalize(String)) failed",
148                      SENTENCE_CAP, StringUtils.capitalize(StringUtils.uncapitalize(SENTENCE_CAP)) );
149
150         // reflection type of tests: One word.
151
assertEquals("uncapitalize(capitalize(String)) failed",
152                     FOO_UNCAP, StringUtils.uncapitalize(StringUtils.capitalize(FOO_UNCAP)) );
153         assertEquals("capitalize(uncapitalize(String)) failed",
154                     FOO_CAP, StringUtils.capitalize(StringUtils.uncapitalize(FOO_CAP)) );
155
156         assertEquals("upperCase(String) failed",
157                      "FOO TEST THING", StringUtils.upperCase("fOo test THING") );
158         assertEquals("upperCase(empty-string) failed",
159                      "", StringUtils.upperCase("") );
160         assertEquals("lowerCase(String) failed",
161                      "foo test thing", StringUtils.lowerCase("fOo test THING") );
162         assertEquals("lowerCase(empty-string) failed",
163                      "", StringUtils.lowerCase("") );
164     }
165
166     public void testSwapCase_String() {
167         assertEquals(null, StringUtils.swapCase(null));
168         assertEquals("", StringUtils.swapCase(""));
169         assertEquals(" ", StringUtils.swapCase(" "));
170         
171         assertEquals("i", WordUtils.swapCase("I") );
172         assertEquals("I", WordUtils.swapCase("i") );
173         assertEquals("I AM HERE 123", StringUtils.swapCase("i am here 123") );
174         assertEquals("i aM hERE 123", StringUtils.swapCase("I Am Here 123") );
175         assertEquals("I AM here 123", StringUtils.swapCase("i am HERE 123") );
176         assertEquals("i am here 123", StringUtils.swapCase("I AM HERE 123") );
177     }
178
179     //-----------------------------------------------------------------------
180
public void testJoin_Objectarray() {
181         assertEquals(null, StringUtils.join(null));
182         assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST));
183         assertEquals("", StringUtils.join(NULL_ARRAY_LIST));
184         assertEquals("abc", StringUtils.join(new String JavaDoc[] {"a", "b", "c"}));
185         assertEquals("a", StringUtils.join(new String JavaDoc[] {null, "a", ""}));
186         assertEquals("foo", StringUtils.join(MIXED_ARRAY_LIST));
187         assertEquals("foo2", StringUtils.join(MIXED_TYPE_LIST));
188     }
189         
190     public void testJoin_ArrayChar() {
191         assertEquals(null, StringUtils.join((Object JavaDoc[]) null, ','));
192         assertEquals(TEXT_LIST_CHAR, StringUtils.join(ARRAY_LIST, SEPARATOR_CHAR));
193         assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST, SEPARATOR_CHAR));
194         assertEquals(";;foo", StringUtils.join(MIXED_ARRAY_LIST, SEPARATOR_CHAR));
195         assertEquals("foo;2", StringUtils.join(MIXED_TYPE_LIST, SEPARATOR_CHAR));
196     }
197     
198     public void testJoin_ArrayString() {
199         assertEquals(null, StringUtils.join((Object JavaDoc[]) null, null));
200         assertEquals(TEXT_LIST_NOSEP, StringUtils.join(ARRAY_LIST, null));
201         assertEquals(TEXT_LIST_NOSEP, StringUtils.join(ARRAY_LIST, ""));
202         
203         assertEquals("", StringUtils.join(NULL_ARRAY_LIST, null));
204         
205         assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST, null));
206         assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST, ""));
207         assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST, SEPARATOR));
208
209         assertEquals(TEXT_LIST, StringUtils.join(ARRAY_LIST, SEPARATOR));
210         assertEquals(",,foo", StringUtils.join(MIXED_ARRAY_LIST, SEPARATOR));
211         assertEquals("foo,2", StringUtils.join(MIXED_TYPE_LIST, SEPARATOR));
212     }
213     
214     public void testJoin_IteratorChar() {
215         assertEquals(null, StringUtils.join((Iterator JavaDoc) null, ','));
216         assertEquals(TEXT_LIST_CHAR, StringUtils.join(Arrays.asList(ARRAY_LIST).iterator(), SEPARATOR_CHAR));
217         assertEquals("", StringUtils.join(Arrays.asList(NULL_ARRAY_LIST).iterator(), SEPARATOR_CHAR));
218         assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST).iterator(), SEPARATOR_CHAR));
219     }
220     
221     public void testJoin_IteratorString() {
222         assertEquals(null, StringUtils.join((Iterator JavaDoc) null, null));
223         assertEquals(TEXT_LIST_NOSEP, StringUtils.join(Arrays.asList(ARRAY_LIST).iterator(), null));
224         assertEquals(TEXT_LIST_NOSEP, StringUtils.join(Arrays.asList(ARRAY_LIST).iterator(), ""));
225         
226         assertEquals("", StringUtils.join(Arrays.asList(NULL_ARRAY_LIST).iterator(), null));
227         
228         assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST).iterator(), null));
229         assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST).iterator(), ""));
230         assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST).iterator(), SEPARATOR));
231         
232         assertEquals(TEXT_LIST, StringUtils.join(Arrays.asList(ARRAY_LIST).iterator(), SEPARATOR));
233     }
234     
235     public void testConcatenate_Objectarray() {
236         assertEquals(null, StringUtils.concatenate(null));
237         assertEquals("", StringUtils.concatenate(EMPTY_ARRAY_LIST));
238         assertEquals("", StringUtils.concatenate(NULL_ARRAY_LIST));
239         assertEquals("foo", StringUtils.concatenate(MIXED_ARRAY_LIST));
240         assertEquals("foo2", StringUtils.concatenate(MIXED_TYPE_LIST));
241     }
242         
243     public void testSplit_String() {
244         assertEquals(null, StringUtils.split(null));
245         assertEquals(0, StringUtils.split("").length);
246         
247         String JavaDoc str = "a b .c";
248         String JavaDoc[] res = StringUtils.split(str);
249         assertEquals(3, res.length);
250         assertEquals("a", res[0]);
251         assertEquals("b", res[1]);
252         assertEquals(".c", res[2]);
253         
254         str = " a ";
255         res = StringUtils.split(str);
256         assertEquals(1, res.length);
257         assertEquals("a", res[0]);
258         
259         str = "a" + WHITESPACE + "b" + NON_WHITESPACE + "c";
260         res = StringUtils.split(str);
261         assertEquals(2, res.length);
262         assertEquals("a", res[0]);
263         assertEquals("b" + NON_WHITESPACE + "c", res[1]);
264     }
265     
266     public void testSplit_StringChar() {
267         assertEquals(null, StringUtils.split(null, '.'));
268         assertEquals(0, StringUtils.split("", '.').length);
269
270         String JavaDoc str = "a.b.. c";
271         String JavaDoc[] res = StringUtils.split(str, '.');
272         assertEquals(3, res.length);
273         assertEquals("a", res[0]);
274         assertEquals("b", res[1]);
275         assertEquals(" c", res[2]);
276             
277         str = ".a.";
278         res = StringUtils.split(str, '.');
279         assertEquals(1, res.length);
280         assertEquals("a", res[0]);
281         
282         str = "a b c";
283         res = StringUtils.split(str,' ');
284         assertEquals(3, res.length);
285         assertEquals("a", res[0]);
286         assertEquals("b", res[1]);
287         assertEquals("c", res[2]);
288     }
289     
290     public void testSplit_StringString_StringStringInt() {
291         assertEquals(null, StringUtils.split(null, "."));
292         assertEquals(null, StringUtils.split(null, ".", 3));
293         
294         assertEquals(0, StringUtils.split("", ".").length);
295         assertEquals(0, StringUtils.split("", ".", 3).length);
296         
297         innerTestSplit('.', ".", ' ');
298         innerTestSplit('.', ".", ',');
299         innerTestSplit('.', ".,", 'x');
300         for (int i = 0; i < WHITESPACE.length(); i++) {
301             for (int j = 0; j < NON_WHITESPACE.length(); j++) {
302                 innerTestSplit(WHITESPACE.charAt(i), null, NON_WHITESPACE.charAt(j));
303                 innerTestSplit(WHITESPACE.charAt(i), String.valueOf(WHITESPACE.charAt(i)), NON_WHITESPACE.charAt(j));
304             }
305         }
306         
307         String JavaDoc[] results = null;
308         String JavaDoc[] expectedResults = {"ab", "de fg"};
309         results = StringUtils.split("ab de fg", null, 2);
310         assertEquals(expectedResults.length, results.length);
311         for (int i = 0; i < expectedResults.length; i++) {
312             assertEquals(expectedResults[i], results[i]);
313         }
314         
315         String JavaDoc[] expectedResults2 = {"ab", "cd:ef"};
316         results = StringUtils.split("ab:cd:ef",":", 2);
317         assertEquals(expectedResults2.length, results.length);
318         for (int i = 0; i < expectedResults2.length; i++) {
319             assertEquals(expectedResults2[i], results[i]);
320         }
321     }
322     
323     private void innerTestSplit(char separator, String JavaDoc sepStr, char noMatch) {
324         String JavaDoc msg = "Failed on separator hex(" + Integer.toHexString(separator) +
325             "), noMatch hex(" + Integer.toHexString(noMatch) + "), sepStr(" + sepStr + ")";
326         
327         final String JavaDoc str = "a" + separator + "b" + separator + separator + noMatch + "c";
328         String JavaDoc[] res;
329         // (str, sepStr)
330
res = StringUtils.split(str, sepStr);
331         assertEquals(msg, 3, res.length);
332         assertEquals(msg, "a", res[0]);
333         assertEquals(msg, "b", res[1]);
334         assertEquals(msg, noMatch + "c", res[2]);
335         
336         final String JavaDoc str2 = separator + "a" + separator;
337         res = StringUtils.split(str2, sepStr);
338         assertEquals(msg, 1, res.length);
339         assertEquals(msg, "a", res[0]);
340
341         res = StringUtils.split(str, sepStr, -1);
342         assertEquals(msg, 3, res.length);
343         assertEquals(msg, "a", res[0]);
344         assertEquals(msg, "b", res[1]);
345         assertEquals(msg, noMatch + "c", res[2]);
346         
347         res = StringUtils.split(str, sepStr, 0);
348         assertEquals(msg, 3, res.length);
349         assertEquals(msg, "a", res[0]);
350         assertEquals(msg, "b", res[1]);
351         assertEquals(msg, noMatch + "c", res[2]);
352         
353         res = StringUtils.split(str, sepStr, 1);
354         assertEquals(msg, 1, res.length);
355         assertEquals(msg, str, res[0]);
356         
357         res = StringUtils.split(str, sepStr, 2);
358         assertEquals(msg, 2, res.length);
359         assertEquals(msg, "a", res[0]);
360         assertEquals(msg, str.substring(2), res[1]);
361     }
362
363     public void testSplitByWholeString_StringStringBoolean() {
364         assertEquals( null, StringUtils.splitByWholeSeparator( null, "." ) ) ;
365
366         assertEquals( 0, StringUtils.splitByWholeSeparator( "", "." ).length ) ;
367
368         String JavaDoc stringToSplitOnNulls = "ab de fg" ;
369         String JavaDoc[] splitOnNullExpectedResults = { "ab", "de", "fg" } ;
370
371         String JavaDoc[] splitOnNullResults = StringUtils.splitByWholeSeparator( "ab de fg", null ) ;
372         assertEquals( splitOnNullExpectedResults.length, splitOnNullResults.length ) ;
373         for ( int i = 0 ; i < splitOnNullExpectedResults.length ; i+= 1 ) {
374             assertEquals( splitOnNullExpectedResults[i], splitOnNullResults[i] ) ;
375         }
376
377         String JavaDoc stringToSplitOnCharactersAndString = "abstemiouslyaeiouyabstemiously" ;
378
379         String JavaDoc[] splitOnStringExpectedResults = { "abstemiously", "abstemiously" } ;
380         String JavaDoc[] splitOnStringResults = StringUtils.splitByWholeSeparator( stringToSplitOnCharactersAndString, "aeiouy" ) ;
381         assertEquals( splitOnStringExpectedResults.length, splitOnStringResults.length ) ;
382         for ( int i = 0 ; i < splitOnStringExpectedResults.length ; i+= 1 ) {
383             assertEquals( splitOnStringExpectedResults[i], splitOnStringResults[i] ) ;
384         }
385     }
386
387     public void testSplitByWholeString_StringStringBooleanInt() {
388         assertEquals( null, StringUtils.splitByWholeSeparator( null, ".", 3 ) ) ;
389
390         assertEquals( 0, StringUtils.splitByWholeSeparator( "", ".", 3 ).length ) ;
391
392         String JavaDoc stringToSplitOnNulls = "ab de fg" ;
393         String JavaDoc[] splitOnNullExpectedResults = { "ab", "de fg" } ;
394         //String[] splitOnNullExpectedResults = { "ab", "de" } ;
395

396         String JavaDoc[] splitOnNullResults = StringUtils.splitByWholeSeparator( stringToSplitOnNulls, null, 2 ) ;
397         assertEquals( splitOnNullExpectedResults.length, splitOnNullResults.length ) ;
398         for ( int i = 0 ; i < splitOnNullExpectedResults.length ; i+= 1 ) {
399             assertEquals( splitOnNullExpectedResults[i], splitOnNullResults[i] ) ;
400         }
401
402         String JavaDoc stringToSplitOnCharactersAndString = "abstemiouslyaeiouyabstemiouslyaeiouyabstemiously" ;
403
404         String JavaDoc[] splitOnStringExpectedResults = { "abstemiously", "abstemiouslyaeiouyabstemiously" } ;
405         //String[] splitOnStringExpectedResults = { "abstemiously", "abstemiously" } ;
406
String JavaDoc[] splitOnStringResults = StringUtils.splitByWholeSeparator( stringToSplitOnCharactersAndString, "aeiouy", 2 ) ;
407         assertEquals( splitOnStringExpectedResults.length, splitOnStringResults.length ) ;
408         for ( int i = 0 ; i < splitOnStringExpectedResults.length ; i++ ) {
409             assertEquals( splitOnStringExpectedResults[i], splitOnStringResults[i] ) ;
410         }
411     }
412
413     
414     public void testSplitPreserveAllTokens_String() {
415         assertEquals(null, StringUtils.splitPreserveAllTokens(null));
416         assertEquals(0, StringUtils.splitPreserveAllTokens("").length);
417         
418         String JavaDoc str = "a b .c";
419         String JavaDoc[] res = StringUtils.splitPreserveAllTokens(str);
420         assertEquals(3, res.length);
421         assertEquals("a", res[0]);
422         assertEquals("b", res[1]);
423         assertEquals(".c", res[2]);
424         
425         str = " a b .c";
426         res = StringUtils.splitPreserveAllTokens(str);
427         assertEquals(4, res.length);
428         assertEquals("", res[0]);
429         assertEquals("a", res[1]);
430         assertEquals("b", res[2]);
431         assertEquals(".c", res[3]);
432         
433         str = "a b .c";
434         res = StringUtils.splitPreserveAllTokens(str);
435         assertEquals(5, res.length);
436         assertEquals("a", res[0]);
437         assertEquals("", res[1]);
438         assertEquals("b", res[2]);
439         assertEquals("", res[3]);
440         assertEquals(".c", res[4]);
441         
442         str = " a ";
443         res = StringUtils.splitPreserveAllTokens(str);
444         assertEquals(4, res.length);
445         assertEquals("", res[0]);
446         assertEquals("a", res[1]);
447         assertEquals("", res[2]);
448         assertEquals("", res[3]);
449
450         str = " a b";
451         res = StringUtils.splitPreserveAllTokens(str);
452         assertEquals(4, res.length);
453         assertEquals("", res[0]);
454         assertEquals("a", res[1]);
455         assertEquals("", res[2]);
456         assertEquals("b", res[3]);
457
458         str = "a" + WHITESPACE + "b" + NON_WHITESPACE + "c";
459         res = StringUtils.splitPreserveAllTokens(str);
460         assertEquals(WHITESPACE.length() + 1, res.length);
461         assertEquals("a", res[0]);
462         for(int i = 1; i < WHITESPACE.length()-1; i++)
463         {
464           assertEquals("", res[i]);
465         }
466         assertEquals("b" + NON_WHITESPACE + "c", res[WHITESPACE.length()]);
467     }
468     
469     public void testSplitPreserveAllTokens_StringChar() {
470         assertEquals(null, StringUtils.splitPreserveAllTokens(null, '.'));
471         assertEquals(0, StringUtils.splitPreserveAllTokens("", '.').length);
472
473         String JavaDoc str = "a.b. c";
474         String JavaDoc[] res = StringUtils.splitPreserveAllTokens(str, '.');
475         assertEquals(3, res.length);
476         assertEquals("a", res[0]);
477         assertEquals("b", res[1]);
478         assertEquals(" c", res[2]);
479             
480         str = "a.b.. c";
481         res = StringUtils.splitPreserveAllTokens(str, '.');
482         assertEquals(4, res.length);
483         assertEquals("a", res[0]);
484         assertEquals("b", res[1]);
485         assertEquals("", res[2]);
486         assertEquals(" c", res[3]);
487
488         str = ".a.";
489         res = StringUtils.splitPreserveAllTokens(str, '.');
490         assertEquals(3, res.length);
491         assertEquals("", res[0]);
492         assertEquals("a", res[1]);
493         assertEquals("", res[2]);
494        
495         str = ".a..";
496         res = StringUtils.splitPreserveAllTokens(str, '.');
497         assertEquals(4, res.length);
498         assertEquals("", res[0]);
499         assertEquals("a", res[1]);
500         assertEquals("", res[2]);
501         assertEquals("", res[3]);
502         
503         str = "..a.";
504         res = StringUtils.splitPreserveAllTokens(str, '.');
505         assertEquals(4, res.length);
506         assertEquals("", res[0]);
507         assertEquals("", res[1]);
508         assertEquals("a", res[2]);
509         assertEquals("", res[3]);
510         
511         str = "..a";
512         res = StringUtils.splitPreserveAllTokens(str, '.');
513         assertEquals(3, res.length);
514         assertEquals("", res[0]);
515         assertEquals("", res[1]);
516         assertEquals("a", res[2]);
517         
518         str = "a b c";
519         res = StringUtils.splitPreserveAllTokens(str,' ');
520         assertEquals(3, res.length);
521         assertEquals("a", res[0]);
522         assertEquals("b", res[1]);
523         assertEquals("c", res[2]);
524
525         str = "a b c";
526         res = StringUtils.splitPreserveAllTokens(str,' ');
527         assertEquals(5, res.length);
528         assertEquals("a", res[0]);
529         assertEquals("", res[1]);
530         assertEquals("b", res[2]);
531         assertEquals("", res[3]);
532         assertEquals("c", res[4]);
533         
534         str = " a b c";
535         res = StringUtils.splitPreserveAllTokens(str,' ');
536         assertEquals(4, res.length);
537         assertEquals("", res[0]);
538         assertEquals("a", res[1]);
539         assertEquals("b", res[2]);
540         assertEquals("c", res[3]);
541
542         str = " a b c";
543         res = StringUtils.splitPreserveAllTokens(str,' ');
544         assertEquals(5, res.length);
545         assertEquals("", res[0]);
546         assertEquals("", res[1]);
547         assertEquals("a", res[2]);
548         assertEquals("b", res[3]);
549         assertEquals("c", res[4]);
550
551     }
552     
553     public void testSplitPreserveAllTokens_StringString_StringStringInt() {
554         assertEquals(null, StringUtils.splitPreserveAllTokens(null, "."));
555         assertEquals(null, StringUtils.splitPreserveAllTokens(null, ".", 3));
556         
557         assertEquals(0, StringUtils.splitPreserveAllTokens("", ".").length);
558         assertEquals(0, StringUtils.splitPreserveAllTokens("", ".", 3).length);
559         
560         innerTestSplitPreserveAllTokens('.', ".", ' ');
561         innerTestSplitPreserveAllTokens('.', ".", ',');
562         innerTestSplitPreserveAllTokens('.', ".,", 'x');
563         for (int i = 0; i < WHITESPACE.length(); i++) {
564             for (int j = 0; j < NON_WHITESPACE.length(); j++) {
565                 innerTestSplitPreserveAllTokens(WHITESPACE.charAt(i), null, NON_WHITESPACE.charAt(j));
566                 innerTestSplitPreserveAllTokens(WHITESPACE.charAt(i), String.valueOf(WHITESPACE.charAt(i)), NON_WHITESPACE.charAt(j));
567             }
568         }
569
570         {
571           String JavaDoc[] results = null;
572           String JavaDoc[] expectedResults = {"ab", "de fg"};
573           results = StringUtils.splitPreserveAllTokens("ab de fg", null, 2);
574           assertEquals(expectedResults.length, results.length);
575           for (int i = 0; i < expectedResults.length; i++) {
576               assertEquals(expectedResults[i], results[i]);
577           }
578         }
579
580         {
581           String JavaDoc[] results = null;
582           String JavaDoc[] expectedResults = {"ab", " de fg"};
583           results = StringUtils.splitPreserveAllTokens("ab de fg", null, 2);
584           System.out.println("");
585           assertEquals(expectedResults.length, results.length);
586           for (int i = 0; i < expectedResults.length; i++) {
587               assertEquals(expectedResults[i], results[i]);
588           }
589         }
590         
591         {
592           String JavaDoc[] results = null;
593           String JavaDoc[] expectedResults = {"ab", "::de:fg"};
594           results = StringUtils.splitPreserveAllTokens("ab:::de:fg", ":", 2);
595           assertEquals(expectedResults.length, results.length);
596           for (int i = 0; i < expectedResults.length; i++) {
597               assertEquals(expectedResults[i], results[i]);
598           }
599         }
600         
601         {
602           String JavaDoc[] results = null;
603           String JavaDoc[] expectedResults = {"ab", "", " de fg"};
604           results = StringUtils.splitPreserveAllTokens("ab de fg", null, 3);
605           assertEquals(expectedResults.length, results.length);
606           for (int i = 0; i < expectedResults.length; i++) {
607               assertEquals(expectedResults[i], results[i]);
608           }
609         }
610         
611         {
612           String JavaDoc[] results = null;
613           String JavaDoc[] expectedResults = {"ab", "", "", "de fg"};
614           results = StringUtils.splitPreserveAllTokens("ab de fg", null, 4);
615           assertEquals(expectedResults.length, results.length);
616           for (int i = 0; i < expectedResults.length; i++) {
617               assertEquals(expectedResults[i], results[i]);
618           }
619         }
620
621         {
622           String JavaDoc[] expectedResults = {"ab", "cd:ef"};
623           String JavaDoc[] results = null;
624           results = StringUtils.splitPreserveAllTokens("ab:cd:ef",":", 2);
625           assertEquals(expectedResults.length, results.length);
626           for (int i = 0; i < expectedResults.length; i++) {
627               assertEquals(expectedResults[i], results[i]);
628           }
629         }
630
631         {
632           String JavaDoc[] results = null;
633           String JavaDoc[] expectedResults = {"ab", ":cd:ef"};
634           results = StringUtils.splitPreserveAllTokens("ab::cd:ef",":", 2);
635           assertEquals(expectedResults.length, results.length);
636           for (int i = 0; i < expectedResults.length; i++) {
637               assertEquals(expectedResults[i], results[i]);
638           }
639         }
640
641         {
642           String JavaDoc[] results = null;
643           String JavaDoc[] expectedResults = {"ab", "", ":cd:ef"};
644           results = StringUtils.splitPreserveAllTokens("ab:::cd:ef",":", 3);
645           assertEquals(expectedResults.length, results.length);
646           for (int i = 0; i < expectedResults.length; i++) {
647               assertEquals(expectedResults[i], results[i]);
648           }
649         }
650
651         {
652           String JavaDoc[] results = null;
653           String JavaDoc[] expectedResults = {"ab", "", "", "cd:ef"};
654           results = StringUtils.splitPreserveAllTokens("ab:::cd:ef",":", 4);
655           assertEquals(expectedResults.length, results.length);
656           for (int i = 0; i < expectedResults.length; i++) {
657               assertEquals(expectedResults[i], results[i]);
658           }
659         }
660
661         {
662           String JavaDoc[] results = null;
663           String JavaDoc[] expectedResults = {"", "ab", "", "", "cd:ef"};
664           results = StringUtils.splitPreserveAllTokens(":ab:::cd:ef",":", 5);
665           assertEquals(expectedResults.length, results.length);
666           for (int i = 0; i < expectedResults.length; i++) {
667               assertEquals(expectedResults[i], results[i]);
668           }
669         }
670         
671         {
672           String JavaDoc[] results = null;
673           String JavaDoc[] expectedResults = {"", "", "ab", "", "", "cd:ef"};
674           results = StringUtils.splitPreserveAllTokens("::ab:::cd:ef",":", 6);
675           assertEquals(expectedResults.length, results.length);
676           for (int i = 0; i < expectedResults.length; i++) {
677               assertEquals(expectedResults[i], results[i]);
678           }
679         }
680     }
681     
682     private void innerTestSplitPreserveAllTokens(char separator, String JavaDoc sepStr, char noMatch) {
683         String JavaDoc msg = "Failed on separator hex(" + Integer.toHexString(separator) +
684             "), noMatch hex(" + Integer.toHexString(noMatch) + "), sepStr(" + sepStr + ")";
685         
686         final String JavaDoc str = "a" + separator + "b" + separator + separator + noMatch + "c";
687         String JavaDoc[] res;
688         // (str, sepStr)
689
res = StringUtils.splitPreserveAllTokens(str, sepStr);
690         assertEquals(msg, 4, res.length);
691         assertEquals(msg, "a", res[0]);
692         assertEquals(msg, "b", res[1]);
693         assertEquals(msg, "", res[2]);
694         assertEquals(msg, noMatch + "c", res[3]);
695         
696         final String JavaDoc str2 = separator + "a" + separator;
697         res = StringUtils.splitPreserveAllTokens(str2, sepStr);
698         assertEquals(msg, 3, res.length);
699         assertEquals(msg, "", res[0]);
700         assertEquals(msg, "a", res[1]);
701         assertEquals(msg, "", res[2]);
702
703         res = StringUtils.splitPreserveAllTokens(str, sepStr, -1);
704         assertEquals(msg, 4, res.length);
705         assertEquals(msg, "a", res[0]);
706         assertEquals(msg, "b", res[1]);
707         assertEquals(msg, "", res[2]);
708         assertEquals(msg, noMatch + "c", res[3]);
709         
710         res = StringUtils.splitPreserveAllTokens(str, sepStr, 0);
711         assertEquals(msg, 4, res.length);
712         assertEquals(msg, "a", res[0]);
713         assertEquals(msg, "b", res[1]);
714         assertEquals(msg, "", res[2]);
715         assertEquals(msg, noMatch + "c", res[3]);
716         
717         res = StringUtils.splitPreserveAllTokens(str, sepStr, 1);
718         assertEquals(msg, 1, res.length);
719         assertEquals(msg, str, res[0]);
720         
721         res = StringUtils.splitPreserveAllTokens(str, sepStr, 2);
722         assertEquals(msg, 2, res.length);
723         assertEquals(msg, "a", res[0]);
724         assertEquals(msg, str.substring(2), res[1]);
725     }
726     
727     public void testDeleteSpace_String() {
728         assertEquals(null, StringUtils.deleteSpaces(null));
729         assertEquals("", StringUtils.deleteSpaces(""));
730         assertEquals("", StringUtils.deleteSpaces(" \t\t\n\n "));
731         assertEquals("test", StringUtils.deleteSpaces("t \t\ne\rs\n\n \tt"));
732     }
733     
734     public void testDeleteWhitespace_String() {
735         assertEquals(null, StringUtils.deleteWhitespace(null));
736         assertEquals("", StringUtils.deleteWhitespace(""));
737         assertEquals("", StringUtils.deleteWhitespace(" \u000C \t\t\u001F\n\n \u000B "));
738         assertEquals("", StringUtils.deleteWhitespace(StringUtilsTest.WHITESPACE));
739         assertEquals(StringUtilsTest.NON_WHITESPACE, StringUtils.deleteWhitespace(StringUtilsTest.NON_WHITESPACE));
740         // Note: u-2007 and u-000A both cause problems in the source code
741
// it should ignore 2007 but delete 000A
742
assertEquals("\u00A0\u202F", StringUtils.deleteWhitespace(" \u00A0 \t\t\n\n \u202F "));
743         assertEquals("\u00A0\u202F", StringUtils.deleteWhitespace("\u00A0\u202F"));
744         assertEquals("test", StringUtils.deleteWhitespace("\u000Bt \t\n\u0009e\rs\n\n \tt"));
745     }
746
747     public void testReplace_StringStringString() {
748         assertEquals(null, StringUtils.replace(null, null, null));
749         assertEquals(null, StringUtils.replace(null, null, "any"));
750         assertEquals(null, StringUtils.replace(null, "any", null));
751         assertEquals(null, StringUtils.replace(null, "any", "any"));
752
753         assertEquals("", StringUtils.replace("", null, null));
754         assertEquals("", StringUtils.replace("", null, "any"));
755         assertEquals("", StringUtils.replace("", "any", null));
756         assertEquals("", StringUtils.replace("", "any", "any"));
757
758         assertEquals("FOO", StringUtils.replace("FOO", "", "any"));
759         assertEquals("FOO", StringUtils.replace("FOO", null, "any"));
760         assertEquals("FOO", StringUtils.replace("FOO", "F", null));
761         assertEquals("FOO", StringUtils.replace("FOO", null, null));
762
763         assertEquals("", StringUtils.replace("foofoofoo", "foo", ""));
764         assertEquals("barbarbar", StringUtils.replace("foofoofoo", "foo", "bar"));
765         assertEquals("farfarfar", StringUtils.replace("foofoofoo", "oo", "ar"));
766        }
767     
768     public void testReplace_StringStringStringInt() {
769         assertEquals(null, StringUtils.replace(null, null, null, 2));
770         assertEquals(null, StringUtils.replace(null, null, "any", 2));
771         assertEquals(null, StringUtils.replace(null, "any", null, 2));
772         assertEquals(null, StringUtils.replace(null, "any", "any", 2));
773
774         assertEquals("f", StringUtils.replace("oofoo", "o", "", -1));
775         assertEquals("oofoo", StringUtils.replace("oofoo", "o", "", 0));
776         assertEquals("ofoo", StringUtils.replace("oofoo", "o", "", 1));
777         assertEquals("foo", StringUtils.replace("oofoo", "o", "", 2));
778         assertEquals("fo", StringUtils.replace("oofoo", "o", "", 3));
779         assertEquals("f", StringUtils.replace("oofoo", "o", "", 4));
780     }
781     
782     public void testReplaceOnce_StringStringString() {
783         assertEquals(null, StringUtils.replaceOnce(null, null, null));
784         assertEquals(null, StringUtils.replaceOnce(null, null, "any"));
785         assertEquals(null, StringUtils.replaceOnce(null, "any", null));
786         assertEquals(null, StringUtils.replaceOnce(null, "any", "any"));
787
788         assertEquals("", StringUtils.replaceOnce("", null, null));
789         assertEquals("", StringUtils.replaceOnce("", null, "any"));
790         assertEquals("", StringUtils.replaceOnce("", "any", null));
791         assertEquals("", StringUtils.replaceOnce("", "any", "any"));
792
793         assertEquals("FOO", StringUtils.replaceOnce("FOO", "", "any"));
794         assertEquals("FOO", StringUtils.replaceOnce("FOO", null, "any"));
795         assertEquals("FOO", StringUtils.replaceOnce("FOO", "F", null));
796         assertEquals("FOO", StringUtils.replaceOnce("FOO", null, null));
797
798         assertEquals("foofoo", StringUtils.replaceOnce("foofoofoo", "foo", ""));
799     }
800
801     public void testReplaceChars_StringCharChar() {
802         assertEquals(null, StringUtils.replaceChars(null, 'b', 'z'));
803         assertEquals("", StringUtils.replaceChars("", 'b', 'z'));
804         assertEquals("azcza", StringUtils.replaceChars("abcba", 'b', 'z'));
805         assertEquals("abcba", StringUtils.replaceChars("abcba", 'x', 'z'));
806     }
807     
808     public void testReplaceChars_StringStringString() {
809         assertEquals(null, StringUtils.replaceChars(null, null, null));
810         assertEquals(null, StringUtils.replaceChars(null, "", null));
811         assertEquals(null, StringUtils.replaceChars(null, "a", null));
812         assertEquals(null, StringUtils.replaceChars(null, null, ""));
813         assertEquals(null, StringUtils.replaceChars(null, null, "x"));
814         
815         assertEquals("", StringUtils.replaceChars("", null, null));
816         assertEquals("", StringUtils.replaceChars("", "", null));
817         assertEquals("", StringUtils.replaceChars("", "a", null));
818         assertEquals("", StringUtils.replaceChars("", null, ""));
819         assertEquals("", StringUtils.replaceChars("", null, "x"));
820
821         assertEquals("abc", StringUtils.replaceChars("abc", null, null));
822         assertEquals("abc", StringUtils.replaceChars("abc", null, ""));
823         assertEquals("abc", StringUtils.replaceChars("abc", null, "x"));
824         
825         assertEquals("abc", StringUtils.replaceChars("abc", "", null));
826         assertEquals("abc", StringUtils.replaceChars("abc", "", ""));
827         assertEquals("abc", StringUtils.replaceChars("abc", "", "x"));
828         
829         assertEquals("ac", StringUtils.replaceChars("abc", "b", null));
830         assertEquals("ac", StringUtils.replaceChars("abc", "b", ""));
831         assertEquals("axc", StringUtils.replaceChars("abc", "b", "x"));
832         
833         assertEquals("ayzya", StringUtils.replaceChars("abcba", "bc", "yz"));
834         assertEquals("ayya", StringUtils.replaceChars("abcba", "bc", "y"));
835         assertEquals("ayzya", StringUtils.replaceChars("abcba", "bc", "yzx"));
836         
837         assertEquals("abcba", StringUtils.replaceChars("abcba", "z", "w"));
838         assertSame("abcba", StringUtils.replaceChars("abcba", "z", "w"));
839         
840         // Javadoc examples:
841
assertEquals("jelly", StringUtils.replaceChars("hello", "ho", "jy"));
842         assertEquals("ayzya", StringUtils.replaceChars("abcba", "bc", "yz"));
843         assertEquals("ayya", StringUtils.replaceChars("abcba", "bc", "y"));
844         assertEquals("ayzya", StringUtils.replaceChars("abcba", "bc", "yzx"));
845         
846         // From http://issues.apache.org/bugzilla/show_bug.cgi?id=25454
847
assertEquals("bcc", StringUtils.replaceChars("abc", "ab", "bc"));
848         assertEquals("q651.506bera", StringUtils.replaceChars("d216.102oren",
849             "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789",
850             "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM567891234"));
851     }
852     
853     public void testOverlayString_StringStringIntInt() {
854         assertEquals("overlayString(String, String, int, int) failed",
855                      "foo foor baz", StringUtils.overlayString(SENTENCE_UNCAP, FOO_UNCAP, 4, 6) );
856         assertEquals("abef", StringUtils.overlayString("abcdef", "", 2, 4));
857         assertEquals("abzzzzef", StringUtils.overlayString("abcdef", "zzzz", 2, 4));
858         assertEquals("abcdzzzzcdef", StringUtils.overlayString("abcdef", "zzzz", 4, 2));
859         try {
860             StringUtils.overlayString(null, "zzzz", 2, 4);
861             fail();
862         } catch (NullPointerException JavaDoc ex) {}
863         try {
864             StringUtils.overlayString("abcdef", null, 2, 4);
865             fail();
866         } catch (NullPointerException JavaDoc ex) {}
867         try {
868             StringUtils.overlayString("abcdef", "zzzz", -1, 4);
869             fail();
870         } catch (IndexOutOfBoundsException JavaDoc ex) {}
871         try {
872             StringUtils.overlayString("abcdef", "zzzz", 2, 8);
873             fail();
874         } catch (IndexOutOfBoundsException JavaDoc ex) {}
875     }
876
877     public void testOverlay_StringStringIntInt() {
878         assertEquals(null, StringUtils.overlay(null, null, 2, 4));
879         assertEquals(null, StringUtils.overlay(null, null, -2, -4));
880         
881         assertEquals("", StringUtils.overlay("", null, 0, 0));
882         assertEquals("", StringUtils.overlay("", "", 0, 0));
883         assertEquals("zzzz", StringUtils.overlay("", "zzzz", 0, 0));
884         assertEquals("zzzz", StringUtils.overlay("", "zzzz", 2, 4));
885         assertEquals("zzzz", StringUtils.overlay("", "zzzz", -2, -4));
886         
887         assertEquals("abef", StringUtils.overlay("abcdef", null, 2, 4));
888         assertEquals("abef", StringUtils.overlay("abcdef", null, 4, 2));
889         assertEquals("abef", StringUtils.overlay("abcdef", "", 2, 4));
890         assertEquals("abef", StringUtils.overlay("abcdef", "", 4, 2));
891         assertEquals("abzzzzef", StringUtils.overlay("abcdef", "zzzz", 2, 4));
892         assertEquals("abzzzzef", StringUtils.overlay("abcdef", "zzzz", 4, 2));
893         
894         assertEquals("zzzzef", StringUtils.overlay("abcdef", "zzzz", -1, 4));
895         assertEquals("zzzzef", StringUtils.overlay("abcdef", "zzzz", 4, -1));
896         assertEquals("zzzzabcdef", StringUtils.overlay("abcdef", "zzzz", -2, -1));
897         assertEquals("zzzzabcdef", StringUtils.overlay("abcdef", "zzzz", -1, -2));
898         assertEquals("abcdzzzz", StringUtils.overlay("abcdef", "zzzz", 4, 10));
899         assertEquals("abcdzzzz", StringUtils.overlay("abcdef", "zzzz", 10, 4));
900         assertEquals("abcdefzzzz", StringUtils.overlay("abcdef", "zzzz", 8, 10));
901         assertEquals("abcdefzzzz", StringUtils.overlay("abcdef", "zzzz", 10, 8));
902     }
903
904     public void testRepeat_StringInt() {
905         assertEquals(null, StringUtils.repeat(null, 2));
906         assertEquals("", StringUtils.repeat("ab", 0));
907         assertEquals("", StringUtils.repeat("", 3));
908         assertEquals("aaa", StringUtils.repeat("a", 3));
909         assertEquals("ababab", StringUtils.repeat("ab", 3));
910         assertEquals("abcabcabc", StringUtils.repeat("abc", 3));
911         String JavaDoc str = StringUtils.repeat("a", 10000); // bigger than pad limit
912
assertEquals(10000, str.length());
913         assertEquals(true, StringUtils.containsOnly(str, new char[] {'a'}));
914     }
915
916     public void testDeprecatedChompFunctions() {
917         assertEquals("chompLast(String) failed",
918                      FOO_UNCAP, StringUtils.chompLast(FOO_UNCAP + "\n") );
919
920         assertEquals("getChomp(String, String) failed",
921                      "\n" + FOO_UNCAP, StringUtils.getChomp(FOO_UNCAP + "\n" + FOO_UNCAP, "\n") );
922
923         assertEquals("prechomp(String, String) failed",
924                      FOO_UNCAP, StringUtils.prechomp(FOO_UNCAP + "\n" + FOO_UNCAP, "\n") );
925
926         assertEquals("getPrechomp(String, String) failed",
927                      FOO_UNCAP + "\n", StringUtils.getPrechomp(FOO_UNCAP + "\n" + FOO_UNCAP, "\n") );
928
929         assertEquals("chopNewline(String, String) failed",
930                      FOO_UNCAP, StringUtils.chopNewline(FOO_UNCAP + "\r\n") );
931     }
932
933     public void testChop() {
934
935         String JavaDoc[][] chopCases = {
936             { FOO_UNCAP + "\r\n", FOO_UNCAP } ,
937             { FOO_UNCAP + "\n" , FOO_UNCAP } ,
938             { FOO_UNCAP + "\r", FOO_UNCAP },
939             { FOO_UNCAP + " \r", FOO_UNCAP + " " },
940             { "foo", "fo"},
941             { "foo\nfoo", "foo\nfo" },
942             { "\n", "" },
943             { "\r", "" },
944             { "\r\n", "" },
945             { null, null },
946             { "", "" },
947             { "a", "" },
948         };
949         for (int i = 0; i < chopCases.length; i++) {
950             String JavaDoc original = chopCases[i][0];
951             String JavaDoc expectedResult = chopCases[i][1];
952             assertEquals("chop(String) failed",
953                     expectedResult, StringUtils.chop(original));
954         }
955     }
956
957     public void testChomp() {
958
959         String JavaDoc[][] chompCases = {
960             { FOO_UNCAP + "\r\n", FOO_UNCAP },
961             { FOO_UNCAP + "\n" , FOO_UNCAP },
962             { FOO_UNCAP + "\r", FOO_UNCAP },
963             { FOO_UNCAP + " \r", FOO_UNCAP + " " },
964             { FOO_UNCAP, FOO_UNCAP },
965             { FOO_UNCAP + "\n\n", FOO_UNCAP + "\n"},
966             { FOO_UNCAP + "\r\n\r\n", FOO_UNCAP + "\r\n" },
967             { "foo\nfoo", "foo\nfoo" },
968             { "foo\n\rfoo", "foo\n\rfoo" },
969             { "\n", "" },
970             { "\r", "" },
971             { "a", "a" },
972             { "\r\n", "" },
973             { "", "" },
974             { null, null },
975             { FOO_UNCAP + "\n\r", FOO_UNCAP + "\n"}
976         };
977         for (int i = 0; i < chompCases.length; i++) {
978             String JavaDoc original = chompCases[i][0];
979             String JavaDoc expectedResult = chompCases[i][1];
980             assertEquals("chomp(String) failed",
981                     expectedResult, StringUtils.chomp(original));
982         }
983
984         assertEquals("chomp(String, String) failed",
985                 "foo", StringUtils.chomp("foobar", "bar"));
986         assertEquals("chomp(String, String) failed",
987                 "foobar", StringUtils.chomp("foobar", "baz"));
988         assertEquals("chomp(String, String) failed",
989                 "foo", StringUtils.chomp("foo", "foooo"));
990         assertEquals("chomp(String, String) failed",
991                 "foobar", StringUtils.chomp("foobar", ""));
992         assertEquals("chomp(String, String) failed",
993                 "foobar", StringUtils.chomp("foobar", null));
994         assertEquals("chomp(String, String) failed",
995                 "", StringUtils.chomp("", "foo"));
996         assertEquals("chomp(String, String) failed",
997                 "", StringUtils.chomp("", null));
998         assertEquals("chomp(String, String) failed",
999                 "", StringUtils.chomp("", ""));
1000        assertEquals("chomp(String, String) failed",
1001                null, StringUtils.chomp(null, "foo"));
1002        assertEquals("chomp(String, String) failed",
1003                null, StringUtils.chomp(null, null));
1004        assertEquals("chomp(String, String) failed",
1005                null, StringUtils.chomp(null, ""));
1006        assertEquals("chomp(String, String) failed",
1007                "", StringUtils.chomp("foo", "foo"));
1008        assertEquals("chomp(String, String) failed",
1009                " ", StringUtils.chomp(" foo", "foo"));
1010        assertEquals("chomp(String, String) failed",
1011                "foo ", StringUtils.chomp("foo ", "foo"));
1012    }
1013
1014    public void testChopNewLine() {
1015
1016        String JavaDoc[][] newLineCases = {
1017            { FOO_UNCAP + "\r\n", FOO_UNCAP } ,
1018            { FOO_UNCAP + "\n" , FOO_UNCAP } ,
1019            { FOO_UNCAP + "\r", FOO_UNCAP + "\r" },
1020            { FOO_UNCAP, FOO_UNCAP },
1021            { FOO_UNCAP + "\n" + FOO_UNCAP , FOO_UNCAP + "\n" + FOO_UNCAP },
1022            { FOO_UNCAP + "\n\n", FOO_UNCAP + "\n"},
1023            { "\n", "" },
1024            { "", "" },
1025            { "\r\n", "" }
1026      };
1027
1028      for (int i = 0; i < newLineCases.length; i++) {
1029          String JavaDoc original = newLineCases[i][0];
1030          String JavaDoc expectedResult = newLineCases[i][1];
1031          assertEquals("chopNewline(String) failed",
1032                  expectedResult, StringUtils.chopNewline(original));
1033      }
1034    }
1035
1036    //-----------------------------------------------------------------------
1037
public void testRightPad_StringInt() {
1038        assertEquals(null, StringUtils.rightPad(null, 5));
1039        assertEquals(" ", StringUtils.rightPad("", 5));
1040        assertEquals("abc ", StringUtils.rightPad("abc", 5));
1041        assertEquals("abc", StringUtils.rightPad("abc", 2));
1042        assertEquals("abc", StringUtils.rightPad("abc", -1));
1043    }
1044
1045    public void testRightPad_StringIntChar() {
1046        assertEquals(null, StringUtils.rightPad(null, 5, ' '));
1047        assertEquals(" ", StringUtils.rightPad("", 5, ' '));
1048        assertEquals("abc ", StringUtils.rightPad("abc", 5, ' '));
1049        assertEquals("abc", StringUtils.rightPad("abc", 2, ' '));
1050        assertEquals("abc", StringUtils.rightPad("abc", -1, ' '));
1051        assertEquals("abcxx", StringUtils.rightPad("abc", 5, 'x'));
1052        String JavaDoc str = StringUtils.rightPad("aaa", 10000, 'a'); // bigger than pad length
1053
assertEquals(10000, str.length());
1054        assertEquals(true, StringUtils.containsOnly(str, new char[] {'a'}));
1055    }
1056
1057    public void testRightPad_StringIntString() {
1058        assertEquals(null, StringUtils.rightPad(null, 5, "-+"));
1059        assertEquals(" ", StringUtils.rightPad("", 5, " "));
1060        assertEquals(null, StringUtils.rightPad(null, 8, null));
1061        assertEquals("abc-+-+", StringUtils.rightPad("abc", 7, "-+"));
1062        assertEquals("abc-+~", StringUtils.rightPad("abc", 6, "-+~"));
1063        assertEquals("abc-+", StringUtils.rightPad("abc", 5, "-+~"));
1064        assertEquals("abc", StringUtils.rightPad("abc", 2, " "));
1065        assertEquals("abc", StringUtils.rightPad("abc", -1, " "));
1066        assertEquals("abc ", StringUtils.rightPad("abc", 5, null));
1067        assertEquals("abc ", StringUtils.rightPad("abc", 5, ""));
1068    }
1069        
1070    //-----------------------------------------------------------------------
1071
public void testLeftPad_StringInt() {
1072        assertEquals(null, StringUtils.leftPad(null, 5));
1073        assertEquals(" ", StringUtils.leftPad("", 5));
1074        assertEquals(" abc", StringUtils.leftPad("abc", 5));
1075        assertEquals("abc", StringUtils.leftPad("abc", 2));
1076    }
1077        
1078    public void testLeftPad_StringIntChar() {
1079        assertEquals(null, StringUtils.leftPad(null, 5, ' '));
1080        assertEquals(" ", StringUtils.leftPad("", 5, ' '));
1081        assertEquals(" abc", StringUtils.leftPad("abc", 5, ' '));
1082        assertEquals("xxabc", StringUtils.leftPad("abc", 5, 'x'));
1083        assertEquals("abc", StringUtils.leftPad("abc", 2, ' '));
1084        String JavaDoc str = StringUtils.leftPad("aaa", 10000, 'a'); // bigger than pad length
1085
assertEquals(10000, str.length());
1086        assertEquals(true, StringUtils.containsOnly(str, new char[] {'a'}));
1087    }
1088        
1089    public void testLeftPad_StringIntString() {
1090        assertEquals(null, StringUtils.leftPad(null, 5, "-+"));
1091        assertEquals(null, StringUtils.leftPad(null, 5, null));
1092        assertEquals(" ", StringUtils.leftPad("", 5, " "));
1093        assertEquals("-+-+abc", StringUtils.leftPad("abc", 7, "-+"));
1094        assertEquals("-+~abc", StringUtils.leftPad("abc", 6, "-+~"));
1095        assertEquals("-+abc", StringUtils.leftPad("abc", 5, "-+~"));
1096        assertEquals("abc", StringUtils.leftPad("abc", 2, " "));
1097        assertEquals("abc", StringUtils.leftPad("abc", -1, " "));
1098        assertEquals(" abc", StringUtils.leftPad("abc", 5, null));
1099        assertEquals(" abc", StringUtils.leftPad("abc", 5, ""));
1100    }
1101
1102    //-----------------------------------------------------------------------
1103
public void testCenter_StringInt() {
1104        assertEquals(null, StringUtils.center(null, -1));
1105        assertEquals(null, StringUtils.center(null, 4));
1106        assertEquals(" ", StringUtils.center("", 4));
1107        assertEquals("ab", StringUtils.center("ab", 0));
1108        assertEquals("ab", StringUtils.center("ab", -1));
1109        assertEquals("ab", StringUtils.center("ab", 1));
1110        assertEquals(" ", StringUtils.center("", 4));
1111        assertEquals(" ab ", StringUtils.center("ab", 4));
1112        assertEquals("abcd", StringUtils.center("abcd", 2));
1113        assertEquals(" a ", StringUtils.center("a", 4));
1114        assertEquals(" a ", StringUtils.center("a", 5));
1115    }
1116    
1117    public void testCenter_StringIntChar() {
1118        assertEquals(null, StringUtils.center(null, -1, ' '));
1119        assertEquals(null, StringUtils.center(null, 4, ' '));
1120        assertEquals(" ", StringUtils.center("", 4, ' '));
1121        assertEquals("ab", StringUtils.center("ab", 0, ' '));
1122        assertEquals("ab", StringUtils.center("ab", -1, ' '));
1123        assertEquals("ab", StringUtils.center("ab", 1, ' '));
1124        assertEquals(" ", StringUtils.center("", 4, ' '));
1125        assertEquals(" ab ", StringUtils.center("ab", 4, ' '));
1126        assertEquals("abcd", StringUtils.center("abcd", 2, ' '));
1127        assertEquals(" a ", StringUtils.center("a", 4, ' '));
1128        assertEquals(" a ", StringUtils.center("a", 5, ' '));
1129        assertEquals("xxaxx", StringUtils.center("a", 5, 'x'));
1130    }
1131    
1132    public void testCenter_StringIntString() {
1133        assertEquals(null, StringUtils.center(null, 4, null));
1134        assertEquals(null, StringUtils.center(null, -1, " "));
1135        assertEquals(null, StringUtils.center(null, 4, " "));
1136        assertEquals(" ", StringUtils.center("", 4, " "));
1137        assertEquals("ab", StringUtils.center("ab", 0, " "));
1138        assertEquals("ab", StringUtils.center("ab", -1, " "));
1139        assertEquals("ab", StringUtils.center("ab", 1, " "));
1140        assertEquals(" ", StringUtils.center("", 4, " "));
1141        assertEquals(" ab ", StringUtils.center("ab", 4, " "));
1142        assertEquals("abcd", StringUtils.center("abcd", 2, " "));
1143        assertEquals(" a ", StringUtils.center("a", 4, " "));
1144        assertEquals("yayz", StringUtils.center("a", 4, "yz"));
1145        assertEquals("yzyayzy", StringUtils.center("a", 7, "yz"));
1146        assertEquals(" abc ", StringUtils.center("abc", 7, null));
1147        assertEquals(" abc ", StringUtils.center("abc", 7, ""));
1148    }
1149
1150    //-----------------------------------------------------------------------
1151
public void testReverse_String() {
1152        assertEquals(null, StringUtils.reverse(null) );
1153        assertEquals("", StringUtils.reverse("") );
1154        assertEquals("sdrawkcab", StringUtils.reverse("backwards") );
1155    }
1156        
1157    public void testReverseDelimited_StringChar() {
1158        assertEquals(null, StringUtils.reverseDelimited(null, '.') );
1159        assertEquals("", StringUtils.reverseDelimited("", '.') );
1160        assertEquals("c.b.a", StringUtils.reverseDelimited("a.b.c", '.') );
1161        assertEquals("a b c", StringUtils.reverseDelimited("a b c", '.') );
1162        assertEquals("", StringUtils.reverseDelimited("", '.') );
1163    }
1164
1165    public void testReverseDelimitedString_StringString() {
1166        assertEquals(null, StringUtils.reverseDelimitedString(null, null) );
1167        assertEquals("", StringUtils.reverseDelimitedString("", null) );
1168        assertEquals("", StringUtils.reverseDelimitedString("", ".") );
1169        assertEquals("a.b.c", StringUtils.reverseDelimitedString("a.b.c", null) );
1170        assertEquals("c b a", StringUtils.reverseDelimitedString("a b c", null) );
1171        assertEquals("c.b.a", StringUtils.reverseDelimitedString("a.b.c", ".") );
1172    }
1173
1174    //-----------------------------------------------------------------------
1175
public void testDefault_String() {
1176        assertEquals("", StringUtils.defaultString(null));
1177        assertEquals("", StringUtils.defaultString(""));
1178        assertEquals("abc", StringUtils.defaultString("abc"));
1179    }
1180
1181    public void testDefault_StringString() {
1182        assertEquals("NULL", StringUtils.defaultString(null, "NULL"));
1183        assertEquals("", StringUtils.defaultString("", "NULL"));
1184        assertEquals("abc", StringUtils.defaultString("abc", "NULL"));
1185    }
1186
1187    public void testDefaultIfEmpty_StringString() {
1188        assertEquals("NULL", StringUtils.defaultIfEmpty(null, "NULL"));
1189        assertEquals("NULL", StringUtils.defaultIfEmpty("", "NULL"));
1190        assertEquals("abc", StringUtils.defaultIfEmpty("abc", "NULL"));
1191    }
1192
1193    //-----------------------------------------------------------------------
1194
public void testEscapeFunctions_String() {
1195        assertEquals("", StringUtils.escape("") );
1196        assertEquals("abc", StringUtils.escape("abc") );
1197        assertEquals("\\t", StringUtils.escape("\t") );
1198        assertEquals("\\\\", StringUtils.escape("\\") );
1199        assertEquals("\\\\\\b\\t\\r", StringUtils.escape("\\\b\t\r") );
1200        assertEquals("\\u1234", StringUtils.escape("\u1234") );
1201        assertEquals("\\u0234", StringUtils.escape("\u0234") );
1202        assertEquals("\\u00FD", StringUtils.escape("\u00fd") );
1203    }
1204
1205    //-----------------------------------------------------------------------
1206
public void testAbbreviate_StringInt() {
1207        assertEquals(null, StringUtils.abbreviate(null, 10));
1208        assertEquals("", StringUtils.abbreviate("", 10));
1209        assertEquals("short", StringUtils.abbreviate("short", 10));
1210        assertEquals("Now is ...", StringUtils.abbreviate("Now is the time for all good men to come to the aid of their party.", 10));
1211
1212        String JavaDoc raspberry = "raspberry peach";
1213        assertEquals("raspberry p...", StringUtils.abbreviate(raspberry, 14));
1214        assertEquals("raspberry peach", StringUtils.abbreviate("raspberry peach", 15));
1215        assertEquals("raspberry peach", StringUtils.abbreviate("raspberry peach", 16));
1216        assertEquals("abc...", StringUtils.abbreviate("abcdefg", 6));
1217        assertEquals("abcdefg", StringUtils.abbreviate("abcdefg", 7));
1218        assertEquals("abcdefg", StringUtils.abbreviate("abcdefg", 8));
1219        assertEquals("a...", StringUtils.abbreviate("abcdefg", 4));
1220        assertEquals("", StringUtils.abbreviate("", 4));
1221        
1222        try {
1223            String JavaDoc res = StringUtils.abbreviate("abc", 3);
1224            fail("StringUtils.abbreviate expecting IllegalArgumentException");
1225        } catch (IllegalArgumentException JavaDoc ex) {
1226                // empty
1227
}
1228    }
1229    
1230    public void testAbbreviate_StringIntInt() {
1231        assertEquals(null, StringUtils.abbreviate(null, 10, 12));
1232        assertEquals("", StringUtils.abbreviate("", 0, 10));
1233        assertEquals("", StringUtils.abbreviate("", 2, 10));
1234        
1235        try {
1236            String JavaDoc res = StringUtils.abbreviate("abcdefghij", 0, 3);
1237            fail("StringUtils.abbreviate expecting IllegalArgumentException");
1238        } catch (IllegalArgumentException JavaDoc ex) {
1239                // empty
1240
}
1241        try {
1242            String JavaDoc res = StringUtils.abbreviate("abcdefghij", 5, 6);
1243            fail("StringUtils.abbreviate expecting IllegalArgumentException");
1244        } catch (IllegalArgumentException JavaDoc ex) {
1245                // empty
1246
}
1247        
1248
1249        String JavaDoc raspberry = "raspberry peach";
1250        assertEquals("raspberry peach", StringUtils.abbreviate(raspberry, 11, 15));
1251
1252        assertEquals(null, StringUtils.abbreviate(null, 7, 14));
1253        assertAbbreviateWithOffset("abcdefg...", -1, 10);
1254        assertAbbreviateWithOffset("abcdefg...", 0, 10);
1255        assertAbbreviateWithOffset("abcdefg...", 1, 10);
1256        assertAbbreviateWithOffset("abcdefg...", 2, 10);
1257        assertAbbreviateWithOffset("abcdefg...", 3, 10);
1258        assertAbbreviateWithOffset("abcdefg...", 4, 10);
1259        assertAbbreviateWithOffset("...fghi...", 5, 10);
1260        assertAbbreviateWithOffset("...ghij...", 6, 10);
1261        assertAbbreviateWithOffset("...hijk...", 7, 10);
1262        assertAbbreviateWithOffset("...ijklmno", 8, 10);
1263        assertAbbreviateWithOffset("...ijklmno", 9, 10);
1264        assertAbbreviateWithOffset("...ijklmno", 10, 10);
1265        assertAbbreviateWithOffset("...ijklmno", 10, 10);
1266        assertAbbreviateWithOffset("...ijklmno", 11, 10);
1267        assertAbbreviateWithOffset("...ijklmno", 12, 10);
1268        assertAbbreviateWithOffset("...ijklmno", 13, 10);
1269        assertAbbreviateWithOffset("...ijklmno", 14, 10);
1270        assertAbbreviateWithOffset("...ijklmno", 15, 10);
1271        assertAbbreviateWithOffset("...ijklmno", 16, 10);
1272        assertAbbreviateWithOffset("...ijklmno", Integer.MAX_VALUE, 10);
1273    }
1274
1275    private void assertAbbreviateWithOffset(String JavaDoc expected, int offset, int maxWidth) {
1276        String JavaDoc abcdefghijklmno = "abcdefghijklmno";
1277        String JavaDoc message = "abbreviate(String,int,int) failed";
1278        String JavaDoc actual = StringUtils.abbreviate(abcdefghijklmno, offset, maxWidth);
1279        if (offset >= 0 && offset < abcdefghijklmno.length()) {
1280            assertTrue(message + " -- should contain offset character",
1281                    actual.indexOf((char)('a'+offset)) != -1);
1282        }
1283        assertTrue(message + " -- should not be greater than maxWidth",
1284                actual.length() <= maxWidth);
1285        assertEquals(message, expected, actual);
1286    }
1287
1288    //-----------------------------------------------------------------------
1289
public void testDifference_StringString() {
1290        assertEquals(null, StringUtils.difference(null, null));
1291        assertEquals("", StringUtils.difference("", ""));
1292        assertEquals("abc", StringUtils.difference("", "abc"));
1293        assertEquals("", StringUtils.difference("abc", ""));
1294        assertEquals("i am a robot", StringUtils.difference(null, "i am a robot"));
1295        assertEquals("i am a machine", StringUtils.difference("i am a machine", null));
1296        assertEquals("robot", StringUtils.difference("i am a machine", "i am a robot"));
1297        assertEquals("", StringUtils.difference("abc", "abc"));
1298        assertEquals("you are a robot", StringUtils.difference("i am a robot", "you are a robot"));
1299    }
1300
1301    public void testDifferenceAt_StringString() {
1302        assertEquals(-1, StringUtils.indexOfDifference(null, null));
1303        assertEquals(0, StringUtils.indexOfDifference(null, "i am a robot"));
1304        assertEquals(-1, StringUtils.indexOfDifference("", ""));
1305        assertEquals(0, StringUtils.indexOfDifference("", "abc"));
1306        assertEquals(0, StringUtils.indexOfDifference("abc", ""));
1307        assertEquals(0, StringUtils.indexOfDifference("i am a machine", null));
1308        assertEquals(7, StringUtils.indexOfDifference("i am a machine", "i am a robot"));
1309        assertEquals(-1, StringUtils.indexOfDifference("foo", "foo"));
1310        assertEquals(0, StringUtils.indexOfDifference("i am a robot", "you are a robot"));
1311    }
1312
1313    //-----------------------------------------------------------------------
1314
public void testGetLevenshteinDistance_StringString() {
1315        assertEquals(0, StringUtils.getLevenshteinDistance("", "") );
1316        assertEquals(1, StringUtils.getLevenshteinDistance("", "a") );
1317        assertEquals(7, StringUtils.getLevenshteinDistance("aaapppp", "") );
1318        assertEquals(1, StringUtils.getLevenshteinDistance("frog", "fog") );
1319        assertEquals(3, StringUtils.getLevenshteinDistance("fly", "ant") );
1320        assertEquals(7, StringUtils.getLevenshteinDistance("elephant", "hippo") );
1321        assertEquals(7, StringUtils.getLevenshteinDistance("hippo", "elephant") );
1322        assertEquals(8, StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") );
1323        assertEquals(8, StringUtils.getLevenshteinDistance("zzzzzzzz", "hippo") );
1324        assertEquals(1, StringUtils.getLevenshteinDistance("hello", "hallo") );
1325        try {
1326            int d = StringUtils.getLevenshteinDistance("a", null);
1327            fail("expecting IllegalArgumentException");
1328        } catch (IllegalArgumentException JavaDoc ex) {
1329            // empty
1330
}
1331        try {
1332            int d = StringUtils.getLevenshteinDistance(null, "a");
1333            fail("expecting IllegalArgumentException");
1334        } catch (IllegalArgumentException JavaDoc ex) {
1335            // empty
1336
}
1337    }
1338
1339    /**
1340     * A sanity check for {@link StringUtils.EMPTY}.
1341     */

1342    public void testEMPTY() {
1343        assertNotNull(StringUtils.EMPTY);
1344        assertEquals("", StringUtils.EMPTY);
1345    }
1346    
1347    public void testRemoveStart() {
1348        // StringUtils.removeStart("", *) = ""
1349
assertNull(StringUtils.removeStart(null, null));
1350        assertNull(StringUtils.removeStart(null, ""));
1351        assertNull(StringUtils.removeStart(null, "a"));
1352        
1353        // StringUtils.removeStart(*, null) = *
1354
assertEquals(StringUtils.removeStart("", null), "");
1355        assertEquals(StringUtils.removeStart("", ""), "");
1356        assertEquals(StringUtils.removeStart("", "a"), "");
1357        
1358        // All others:
1359
assertEquals(StringUtils.removeStart("www.domain.com", "www."), "domain.com");
1360        assertEquals(StringUtils.removeStart("domain.com", "www."), "domain.com");
1361        assertEquals(StringUtils.removeStart("domain.com", ""), "domain.com");
1362        assertEquals(StringUtils.removeStart("domain.com", null), "domain.com");
1363    }
1364
1365    public void testRemoveEnd() {
1366        // StringUtils.removeEnd("", *) = ""
1367
assertNull(StringUtils.removeEnd(null, null));
1368        assertNull(StringUtils.removeEnd(null, ""));
1369        assertNull(StringUtils.removeEnd(null, "a"));
1370        
1371        // StringUtils.removeEnd(*, null) = *
1372
assertEquals(StringUtils.removeEnd("", null), "");
1373        assertEquals(StringUtils.removeEnd("", ""), "");
1374        assertEquals(StringUtils.removeEnd("", "a"), "");
1375        
1376        // All others:
1377
assertEquals(StringUtils.removeEnd("www.domain.com", ".com"), "www.domain");
1378        assertEquals(StringUtils.removeEnd("www.domain", ".com"), "www.domain");
1379        assertEquals(StringUtils.removeEnd("domain.com", ""), "domain.com");
1380        assertEquals(StringUtils.removeEnd("domain.com", null), "domain.com");
1381    }
1382
1383    public void testRemove_String() {
1384        // StringUtils.remove(null, *) = null
1385
assertEquals(null, StringUtils.remove(null, null));
1386        assertEquals(null, StringUtils.remove(null, ""));
1387        assertEquals(null, StringUtils.remove(null, "a"));
1388        
1389        // StringUtils.remove("", *) = ""
1390
assertEquals("", StringUtils.remove("", null));
1391        assertEquals("", StringUtils.remove("", ""));
1392        assertEquals("", StringUtils.remove("", "a"));
1393        
1394        // StringUtils.remove(*, null) = *
1395
assertEquals(null, StringUtils.remove(null, null));
1396        assertEquals("", StringUtils.remove("", null));
1397        assertEquals("a", StringUtils.remove("a", null));
1398        
1399        // StringUtils.remove(*, "") = *
1400
assertEquals(null, StringUtils.remove(null, ""));
1401        assertEquals("", StringUtils.remove("", ""));
1402        assertEquals("a", StringUtils.remove("a", ""));
1403        
1404        // StringUtils.remove("queued", "ue") = "qd"
1405
assertEquals("qd", StringUtils.remove("queued", "ue"));
1406        
1407        // StringUtils.remove("queued", "zz") = "queued"
1408
assertEquals("queued", StringUtils.remove("queued", "zz"));
1409    }
1410
1411    public void testRemove_char() {
1412        // StringUtils.remove(null, *) = null
1413
assertEquals(null, StringUtils.remove(null, 'a'));
1414        assertEquals(null, StringUtils.remove(null, 'a'));
1415        assertEquals(null, StringUtils.remove(null, 'a'));
1416        
1417        // StringUtils.remove("", *) = ""
1418
assertEquals("", StringUtils.remove("", 'a'));
1419        assertEquals("", StringUtils.remove("", 'a'));
1420        assertEquals("", StringUtils.remove("", 'a'));
1421        
1422        // StringUtils.remove("queued", 'u') = "qeed"
1423
assertEquals("qeed", StringUtils.remove("queued", 'u'));
1424        
1425        // StringUtils.remove("queued", 'z') = "queued"
1426
assertEquals("queued", StringUtils.remove("queued", 'z'));
1427    }
1428
1429}
1430
Popular Tags