1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 package org.apache.commons.lang3; 18 19 import static org.junit.jupiter.api.Assertions.assertArrayEquals; 20 import static org.junit.jupiter.api.Assertions.assertEquals; 21 import static org.junit.jupiter.api.Assertions.assertFalse; 22 import static org.junit.jupiter.api.Assertions.assertNotEquals; 23 import static org.junit.jupiter.api.Assertions.assertNotNull; 24 import static org.junit.jupiter.api.Assertions.assertNull; 25 import static org.junit.jupiter.api.Assertions.assertSame; 26 import static org.junit.jupiter.api.Assertions.assertThrows; 27 import static org.junit.jupiter.api.Assertions.assertTrue; 28 29 import java.io.UnsupportedEncodingException; 30 import java.lang.reflect.Constructor; 31 import java.lang.reflect.Method; 32 import java.lang.reflect.Modifier; 33 import java.nio.CharBuffer; 34 import java.nio.charset.Charset; 35 import java.nio.charset.StandardCharsets; 36 import java.util.Arrays; 37 import java.util.Collections; 38 import java.util.Iterator; 39 import java.util.List; 40 import java.util.Locale; 41 import java.util.Objects; 42 import java.util.function.Supplier; 43 import java.util.regex.PatternSyntaxException; 44 45 import org.apache.commons.lang3.mutable.MutableInt; 46 import org.apache.commons.lang3.text.WordUtils; 47 import org.junit.jupiter.api.Disabled; 48 import org.junit.jupiter.api.Test; 49 import org.junit.jupiter.params.ParameterizedTest; 50 import org.junit.jupiter.params.provider.ValueSource; 51 52 /** 53 * Unit tests for methods of {@link org.apache.commons.lang3.StringUtils} 54 * which been moved to their own test classes. 55 */ 56 @SuppressWarnings("deprecation") // deliberate use of deprecated code 57 public class StringUtilsTest extends AbstractLangTest { 58 59 static final String WHITESPACE; 60 static final String NON_WHITESPACE; 61 static final String HARD_SPACE; 62 static final String TRIMMABLE; 63 static final String NON_TRIMMABLE; 64 65 static { 66 final StringBuilder ws = new StringBuilder(); 67 final StringBuilder nws = new StringBuilder(); 68 final String hs = String.valueOf((char) 160); 69 final StringBuilder tr = new StringBuilder(); 70 final StringBuilder ntr = new StringBuilder(); 71 for (int i = 0; i < Character.MAX_VALUE; i++) { 72 if (Character.isWhitespace((char) i)) { 73 ws.append(String.valueOf((char) i)); 74 if (i > 32) { 75 ntr.append(String.valueOf((char) i)); 76 } 77 } else if (i < 40) { 78 nws.append(String.valueOf((char) i)); 79 } 80 } 81 for (int i = 0; i <= 32; i++) { 82 tr.append(String.valueOf((char) i)); 83 } 84 WHITESPACE = ws.toString(); 85 NON_WHITESPACE = nws.toString(); 86 HARD_SPACE = hs; 87 TRIMMABLE = tr.toString(); 88 NON_TRIMMABLE = ntr.toString(); 89 } 90 91 private static final String[] ARRAY_LIST = {"foo", "bar", "baz"}; 92 private static final String[] EMPTY_ARRAY_LIST = {}; 93 private static final String[] NULL_ARRAY_LIST = {null}; 94 private static final Object[] NULL_TO_STRING_LIST = { 95 new Object() { 96 @Override 97 public String toString() { 98 return null; 99 } 100 } 101 }; 102 private static final String[] MIXED_ARRAY_LIST = {null, "", "foo"}; 103 private static final Object[] MIXED_TYPE_LIST = {"foo", Long.valueOf(2L)}; 104 private static final long[] LONG_PRIM_LIST = {1, 2}; 105 private static final int[] INT_PRIM_LIST = {1, 2}; 106 private static final byte[] BYTE_PRIM_LIST = {1, 2}; 107 private static final short[] SHORT_PRIM_LIST = {1, 2}; 108 private static final char[] CHAR_PRIM_LIST = {'1', '2'}; 109 private static final float[] FLOAT_PRIM_LIST = {1, 2}; 110 private static final double[] DOUBLE_PRIM_LIST = {1, 2}; 111 private static final List<String> MIXED_STRING_LIST = Arrays.asList(null, "", "foo"); 112 private static final List<Object> MIXED_TYPE_OBJECT_LIST = Arrays.<Object>asList("foo", Long.valueOf(2L)); 113 private static final List<String> STRING_LIST = Arrays.asList("foo", "bar", "baz"); 114 private static final List<String> EMPTY_STRING_LIST = Collections.emptyList(); 115 private static final List<String> NULL_STRING_LIST = Collections.singletonList(null); 116 117 private static final String SEPARATOR = ","; 118 private static final char SEPARATOR_CHAR = ';'; 119 private static final char COMMA_SEPARATOR_CHAR = ','; 120 121 private static final String TEXT_LIST = "foo,bar,baz"; 122 private static final String TEXT_LIST_CHAR = "foo;bar;baz"; 123 private static final String TEXT_LIST_NOSEP = "foobarbaz"; 124 125 private static final String FOO_UNCAP = "foo"; 126 private static final String FOO_CAP = "Foo"; 127 128 private static final String SENTENCE_UNCAP = "foo bar baz"; 129 private static final String SENTENCE_CAP = "Foo Bar Baz"; 130 131 private static final boolean[] EMPTY = {}; 132 private static final boolean[] ARRAY_FALSE_FALSE = {false, false}; 133 private static final boolean[] ARRAY_FALSE_TRUE = {false, true}; 134 private static final boolean[] ARRAY_FALSE_TRUE_FALSE = {false, true, false}; 135 assertAbbreviateWithAbbrevMarkerAndOffset(final String expected, final String abbrevMarker, final int offset, final int maxWidth)136 private void assertAbbreviateWithAbbrevMarkerAndOffset(final String expected, final String abbrevMarker, final int offset, final int maxWidth) { 137 final String abcdefghijklmno = "abcdefghijklmno"; 138 final String message = "abbreviate(String,String,int,int) failed"; 139 final String actual = StringUtils.abbreviate(abcdefghijklmno, abbrevMarker, offset, maxWidth); 140 if (offset >= 0 && offset < abcdefghijklmno.length()) { 141 assertTrue(actual.indexOf((char) ('a' + offset)) != -1, 142 message + " -- should contain offset character"); 143 } 144 assertTrue(actual.length() <= maxWidth, 145 message + " -- should not be greater than maxWidth"); 146 assertEquals(expected, actual, message); 147 } 148 assertAbbreviateWithOffset(final String expected, final int offset, final int maxWidth)149 private void assertAbbreviateWithOffset(final String expected, final int offset, final int maxWidth) { 150 final String abcdefghijklmno = "abcdefghijklmno"; 151 final String message = "abbreviate(String,int,int) failed"; 152 final String actual = StringUtils.abbreviate(abcdefghijklmno, offset, maxWidth); 153 if (offset >= 0 && offset < abcdefghijklmno.length()) { 154 assertTrue(actual.indexOf((char) ('a' + offset)) != -1, 155 message + " -- should contain offset character"); 156 } 157 assertTrue(actual.length() <= maxWidth, 158 message + " -- should not be greater than maxWidth"); 159 assertEquals(expected, actual, message); 160 } 161 innerTestSplit(final char separator, final String sepStr, final char noMatch)162 private void innerTestSplit(final char separator, final String sepStr, final char noMatch) { 163 final String msg = "Failed on separator hex(" + Integer.toHexString(separator) + 164 "), noMatch hex(" + Integer.toHexString(noMatch) + "), sepStr(" + sepStr + ")"; 165 166 final String str = "a" + separator + "b" + separator + separator + noMatch + "c"; 167 String[] res; 168 // (str, sepStr) 169 res = StringUtils.split(str, sepStr); 170 assertEquals(3, res.length, msg); 171 assertEquals("a", res[0]); 172 assertEquals("b", res[1]); 173 assertEquals(noMatch + "c", res[2]); 174 175 final String str2 = separator + "a" + separator; 176 res = StringUtils.split(str2, sepStr); 177 assertEquals(1, res.length, msg); 178 assertEquals("a", res[0], msg); 179 180 res = StringUtils.split(str, sepStr, -1); 181 assertEquals(3, res.length, msg); 182 assertEquals("a", res[0], msg); 183 assertEquals("b", res[1], msg); 184 assertEquals(noMatch + "c", res[2], msg); 185 186 res = StringUtils.split(str, sepStr, 0); 187 assertEquals(3, res.length, msg); 188 assertEquals("a", res[0], msg); 189 assertEquals("b", res[1], msg); 190 assertEquals(noMatch + "c", res[2], msg); 191 192 res = StringUtils.split(str, sepStr, 1); 193 assertEquals(1, res.length, msg); 194 assertEquals(str, res[0], msg); 195 196 res = StringUtils.split(str, sepStr, 2); 197 assertEquals(2, res.length, msg); 198 assertEquals("a", res[0], msg); 199 assertEquals(str.substring(2), res[1], msg); 200 } 201 innerTestSplitPreserveAllTokens(final char separator, final String sepStr, final char noMatch)202 private void innerTestSplitPreserveAllTokens(final char separator, final String sepStr, final char noMatch) { 203 final String msg = "Failed on separator hex(" + Integer.toHexString(separator) + 204 "), noMatch hex(" + Integer.toHexString(noMatch) + "), sepStr(" + sepStr + ")"; 205 206 final String str = "a" + separator + "b" + separator + separator + noMatch + "c"; 207 String[] res; 208 // (str, sepStr) 209 res = StringUtils.splitPreserveAllTokens(str, sepStr); 210 assertEquals(4, res.length, msg); 211 assertEquals("a", res[0], msg); 212 assertEquals("b", res[1], msg); 213 assertEquals("", res[2], msg); 214 assertEquals(noMatch + "c", res[3], msg); 215 216 final String str2 = separator + "a" + separator; 217 res = StringUtils.splitPreserveAllTokens(str2, sepStr); 218 assertEquals(3, res.length, msg); 219 assertEquals("", res[0], msg); 220 assertEquals("a", res[1], msg); 221 assertEquals("", res[2], msg); 222 223 res = StringUtils.splitPreserveAllTokens(str, sepStr, -1); 224 assertEquals(4, res.length, msg); 225 assertEquals("a", res[0], msg); 226 assertEquals("b", res[1], msg); 227 assertEquals("", res[2], msg); 228 assertEquals(noMatch + "c", res[3], msg); 229 230 res = StringUtils.splitPreserveAllTokens(str, sepStr, 0); 231 assertEquals(4, res.length, msg); 232 assertEquals("a", res[0], msg); 233 assertEquals("b", res[1], msg); 234 assertEquals("", res[2], msg); 235 assertEquals(noMatch + "c", res[3], msg); 236 237 res = StringUtils.splitPreserveAllTokens(str, sepStr, 1); 238 assertEquals(1, res.length, msg); 239 assertEquals(str, res[0], msg); 240 241 res = StringUtils.splitPreserveAllTokens(str, sepStr, 2); 242 assertEquals(2, res.length, msg); 243 assertEquals("a", res[0], msg); 244 assertEquals(str.substring(2), res[1], msg); 245 } 246 247 //Fixed LANG-1463 248 @Test testAbbreviateMarkerWithEmptyString()249 public void testAbbreviateMarkerWithEmptyString() { 250 final String greaterThanMaxTest = "much too long text"; 251 assertEquals("much too long", StringUtils.abbreviate(greaterThanMaxTest, "", 13)); 252 } 253 254 @Test testAbbreviate_StringInt()255 public void testAbbreviate_StringInt() { 256 assertNull(StringUtils.abbreviate(null, 10)); 257 assertEquals("", StringUtils.abbreviate("", 10)); 258 assertEquals("short", StringUtils.abbreviate("short", 10)); 259 assertEquals("Now is ...", StringUtils.abbreviate("Now is the time for all good men to come to the aid of their party.", 10)); 260 261 final String raspberry = "raspberry peach"; 262 assertEquals("raspberry p...", StringUtils.abbreviate(raspberry, 14)); 263 assertEquals("raspberry peach", StringUtils.abbreviate("raspberry peach", 15)); 264 assertEquals("raspberry peach", StringUtils.abbreviate("raspberry peach", 16)); 265 assertEquals("abc...", StringUtils.abbreviate("abcdefg", 6)); 266 assertEquals("abcdefg", StringUtils.abbreviate("abcdefg", 7)); 267 assertEquals("abcdefg", StringUtils.abbreviate("abcdefg", 8)); 268 assertEquals("a...", StringUtils.abbreviate("abcdefg", 4)); 269 assertEquals("", StringUtils.abbreviate("", 4)); 270 271 assertThrows( 272 IllegalArgumentException.class, 273 () -> StringUtils.abbreviate("abc", 3), 274 "StringUtils.abbreviate expecting IllegalArgumentException"); 275 } 276 277 @Test testAbbreviate_StringIntInt()278 public void testAbbreviate_StringIntInt() { 279 assertNull(StringUtils.abbreviate(null, 10, 12)); 280 assertEquals("", StringUtils.abbreviate("", 0, 10)); 281 assertEquals("", StringUtils.abbreviate("", 2, 10)); 282 283 assertThrows( 284 IllegalArgumentException.class, 285 () -> StringUtils.abbreviate("abcdefghij", 0, 3), 286 "StringUtils.abbreviate expecting IllegalArgumentException"); 287 assertThrows( 288 IllegalArgumentException.class, 289 () -> StringUtils.abbreviate("abcdefghij", 5, 6), 290 "StringUtils.abbreviate expecting IllegalArgumentException"); 291 292 final String raspberry = "raspberry peach"; 293 assertEquals("raspberry peach", StringUtils.abbreviate(raspberry, 11, 15)); 294 295 assertNull(StringUtils.abbreviate(null, 7, 14)); 296 assertAbbreviateWithOffset("abcdefg...", -1, 10); 297 assertAbbreviateWithOffset("abcdefg...", 0, 10); 298 assertAbbreviateWithOffset("abcdefg...", 1, 10); 299 assertAbbreviateWithOffset("abcdefg...", 2, 10); 300 assertAbbreviateWithOffset("abcdefg...", 3, 10); 301 assertAbbreviateWithOffset("abcdefg...", 4, 10); 302 assertAbbreviateWithOffset("...fghi...", 5, 10); 303 assertAbbreviateWithOffset("...ghij...", 6, 10); 304 assertAbbreviateWithOffset("...hijk...", 7, 10); 305 assertAbbreviateWithOffset("...ijklmno", 8, 10); 306 assertAbbreviateWithOffset("...ijklmno", 9, 10); 307 assertAbbreviateWithOffset("...ijklmno", 10, 10); 308 assertAbbreviateWithOffset("...ijklmno", 11, 10); 309 assertAbbreviateWithOffset("...ijklmno", 12, 10); 310 assertAbbreviateWithOffset("...ijklmno", 13, 10); 311 assertAbbreviateWithOffset("...ijklmno", 14, 10); 312 assertAbbreviateWithOffset("...ijklmno", 15, 10); 313 assertAbbreviateWithOffset("...ijklmno", 16, 10); 314 assertAbbreviateWithOffset("...ijklmno", Integer.MAX_VALUE, 10); 315 } 316 317 @Test testAbbreviate_StringStringInt()318 public void testAbbreviate_StringStringInt() { 319 assertNull(StringUtils.abbreviate(null, null, 10)); 320 assertNull(StringUtils.abbreviate(null, "...", 10)); 321 assertEquals("paranaguacu", StringUtils.abbreviate("paranaguacu", null, 10)); 322 assertEquals("", StringUtils.abbreviate("", "...", 2)); 323 assertEquals("wai**", StringUtils.abbreviate("waiheke", "**", 5)); 324 assertEquals("And af,,,,", StringUtils.abbreviate("And after a long time, he finally met his son.", ",,,,", 10)); 325 326 final String raspberry = "raspberry peach"; 327 assertEquals("raspberry pe..", StringUtils.abbreviate(raspberry, "..", 14)); 328 assertEquals("raspberry peach", StringUtils.abbreviate("raspberry peach", "---*---", 15)); 329 assertEquals("raspberry peach", StringUtils.abbreviate("raspberry peach", ".", 16)); 330 assertEquals("abc()(", StringUtils.abbreviate("abcdefg", "()(", 6)); 331 assertEquals("abcdefg", StringUtils.abbreviate("abcdefg", ";", 7)); 332 assertEquals("abcdefg", StringUtils.abbreviate("abcdefg", "_-", 8)); 333 assertEquals("abc.", StringUtils.abbreviate("abcdefg", ".", 4)); 334 assertEquals("", StringUtils.abbreviate("", 4)); 335 336 assertThrows( 337 IllegalArgumentException.class, 338 () -> StringUtils.abbreviate("abcdefghij", "...", 3), 339 "StringUtils.abbreviate expecting IllegalArgumentException"); 340 } 341 342 @Test testAbbreviate_StringStringIntInt()343 public void testAbbreviate_StringStringIntInt() { 344 assertNull(StringUtils.abbreviate(null, null, 10, 12)); 345 assertNull(StringUtils.abbreviate(null, "...", 10, 12)); 346 assertEquals("", StringUtils.abbreviate("", null, 0, 10)); 347 assertEquals("", StringUtils.abbreviate("", "...", 2, 10)); 348 349 assertThrows( 350 IllegalArgumentException.class, 351 () -> StringUtils.abbreviate("abcdefghij", "::", 0, 2), 352 "StringUtils.abbreviate expecting IllegalArgumentException"); 353 assertThrows( 354 IllegalArgumentException.class, 355 () -> StringUtils.abbreviate("abcdefghij", "!!!", 5, 6), 356 "StringUtils.abbreviate expecting IllegalArgumentException"); 357 358 final String raspberry = "raspberry peach"; 359 assertEquals("raspberry peach", StringUtils.abbreviate(raspberry, "--", 12, 15)); 360 361 assertNull(StringUtils.abbreviate(null, ";", 7, 14)); 362 assertAbbreviateWithAbbrevMarkerAndOffset("abcdefgh;;", ";;", -1, 10); 363 assertAbbreviateWithAbbrevMarkerAndOffset("abcdefghi.", ".", 0, 10); 364 assertAbbreviateWithAbbrevMarkerAndOffset("abcdefgh++", "++", 1, 10); 365 assertAbbreviateWithAbbrevMarkerAndOffset("abcdefghi*", "*", 2, 10); 366 assertAbbreviateWithAbbrevMarkerAndOffset("abcdef{{{{", "{{{{", 4, 10); 367 assertAbbreviateWithAbbrevMarkerAndOffset("abcdef____", "____", 5, 10); 368 assertAbbreviateWithAbbrevMarkerAndOffset("==fghijk==", "==", 5, 10); 369 assertAbbreviateWithAbbrevMarkerAndOffset("___ghij___", "___", 6, 10); 370 assertAbbreviateWithAbbrevMarkerAndOffset("/ghijklmno", "/", 7, 10); 371 assertAbbreviateWithAbbrevMarkerAndOffset("/ghijklmno", "/", 8, 10); 372 assertAbbreviateWithAbbrevMarkerAndOffset("/ghijklmno", "/", 9, 10); 373 assertAbbreviateWithAbbrevMarkerAndOffset("///ijklmno", "///", 10, 10); 374 assertAbbreviateWithAbbrevMarkerAndOffset("//hijklmno", "//", 10, 10); 375 assertAbbreviateWithAbbrevMarkerAndOffset("//hijklmno", "//", 11, 10); 376 assertAbbreviateWithAbbrevMarkerAndOffset("...ijklmno", "...", 12, 10); 377 assertAbbreviateWithAbbrevMarkerAndOffset("/ghijklmno", "/", 13, 10); 378 assertAbbreviateWithAbbrevMarkerAndOffset("/ghijklmno", "/", 14, 10); 379 assertAbbreviateWithAbbrevMarkerAndOffset("999ijklmno", "999", 15, 10); 380 assertAbbreviateWithAbbrevMarkerAndOffset("_ghijklmno", "_", 16, 10); 381 assertAbbreviateWithAbbrevMarkerAndOffset("+ghijklmno", "+", Integer.MAX_VALUE, 10); 382 } 383 384 @Test testAbbreviateMiddle()385 public void testAbbreviateMiddle() { 386 // javadoc examples 387 assertNull(StringUtils.abbreviateMiddle(null, null, 0)); 388 assertEquals("abc", StringUtils.abbreviateMiddle("abc", null, 0)); 389 assertEquals("abc", StringUtils.abbreviateMiddle("abc", ".", 0)); 390 assertEquals("abc", StringUtils.abbreviateMiddle("abc", ".", 3)); 391 assertEquals("ab.f", StringUtils.abbreviateMiddle("abcdef", ".", 4)); 392 393 // JIRA issue (LANG-405) example (slightly different than actual expected result) 394 assertEquals( 395 "A very long text with un...f the text is complete.", 396 StringUtils.abbreviateMiddle( 397 "A very long text with unimportant stuff in the middle but interesting start and " + 398 "end to see if the text is complete.", "...", 50)); 399 400 // Test a much longer text :) 401 final String longText = "Start text" + StringUtils.repeat("x", 10000) + "Close text"; 402 assertEquals( 403 "Start text->Close text", 404 StringUtils.abbreviateMiddle(longText, "->", 22)); 405 406 // Test negative length 407 assertEquals("abc", StringUtils.abbreviateMiddle("abc", ".", -1)); 408 409 // Test boundaries 410 // Fails to change anything as method ensures first and last char are kept 411 assertEquals("abc", StringUtils.abbreviateMiddle("abc", ".", 1)); 412 assertEquals("abc", StringUtils.abbreviateMiddle("abc", ".", 2)); 413 414 // Test length of n=1 415 assertEquals("a", StringUtils.abbreviateMiddle("a", ".", 1)); 416 417 // Test smallest length that can lead to success 418 assertEquals("a.d", StringUtils.abbreviateMiddle("abcd", ".", 3)); 419 420 // More from LANG-405 421 assertEquals("a..f", StringUtils.abbreviateMiddle("abcdef", "..", 4)); 422 assertEquals("ab.ef", StringUtils.abbreviateMiddle("abcdef", ".", 5)); 423 } 424 425 /** 426 * Tests {@code appendIfMissing}. 427 */ 428 @Test testAppendIfMissing()429 public void testAppendIfMissing() { 430 assertNull(StringUtils.appendIfMissing(null, null), "appendIfMissing(null,null)"); 431 assertEquals("abc", StringUtils.appendIfMissing("abc", null), "appendIfMissing(abc,null)"); 432 assertEquals("xyz", StringUtils.appendIfMissing("", "xyz"), "appendIfMissing(\"\",xyz)"); 433 assertEquals("abcxyz", StringUtils.appendIfMissing("abc", "xyz"), "appendIfMissing(abc,xyz)"); 434 assertEquals("abcxyz", StringUtils.appendIfMissing("abcxyz", "xyz"), "appendIfMissing(abcxyz,xyz)"); 435 assertEquals("aXYZxyz", StringUtils.appendIfMissing("aXYZ", "xyz"), "appendIfMissing(aXYZ,xyz)"); 436 437 assertNull(StringUtils.appendIfMissing(null, null, (CharSequence[]) null), "appendIfMissing(null,null,null)"); 438 assertEquals("abc", StringUtils.appendIfMissing("abc", null, (CharSequence[]) null), "appendIfMissing(abc,null,null)"); 439 assertEquals("xyz", StringUtils.appendIfMissing("", "xyz", (CharSequence[]) null), "appendIfMissing(\"\",xyz,null))"); 440 assertEquals("abcxyz", StringUtils.appendIfMissing("abc", "xyz", null), "appendIfMissing(abc,xyz,{null})"); 441 assertEquals("abc", StringUtils.appendIfMissing("abc", "xyz", ""), "appendIfMissing(abc,xyz,\"\")"); 442 assertEquals("abcxyz", StringUtils.appendIfMissing("abc", "xyz", "mno"), "appendIfMissing(abc,xyz,mno)"); 443 assertEquals("abcxyz", StringUtils.appendIfMissing("abcxyz", "xyz", "mno"), "appendIfMissing(abcxyz,xyz,mno)"); 444 assertEquals("abcmno", StringUtils.appendIfMissing("abcmno", "xyz", "mno"), "appendIfMissing(abcmno,xyz,mno)"); 445 assertEquals("abcXYZxyz", StringUtils.appendIfMissing("abcXYZ", "xyz", "mno"), "appendIfMissing(abcXYZ,xyz,mno)"); 446 assertEquals("abcMNOxyz", StringUtils.appendIfMissing("abcMNO", "xyz", "mno"), "appendIfMissing(abcMNO,xyz,mno)"); 447 } 448 449 /** 450 * Tests {@code appendIfMissingIgnoreCase}. 451 */ 452 @Test testAppendIfMissingIgnoreCase()453 public void testAppendIfMissingIgnoreCase() { 454 assertNull(StringUtils.appendIfMissingIgnoreCase(null, null), "appendIfMissingIgnoreCase(null,null)"); 455 assertEquals("abc", StringUtils.appendIfMissingIgnoreCase("abc", null), "appendIfMissingIgnoreCase(abc,null)"); 456 assertEquals("xyz", StringUtils.appendIfMissingIgnoreCase("", "xyz"), "appendIfMissingIgnoreCase(\"\",xyz)"); 457 assertEquals("abcxyz", StringUtils.appendIfMissingIgnoreCase("abc", "xyz"), "appendIfMissingIgnoreCase(abc,xyz)"); 458 assertEquals("abcxyz", StringUtils.appendIfMissingIgnoreCase("abcxyz", "xyz"), "appendIfMissingIgnoreCase(abcxyz,xyz)"); 459 assertEquals("abcXYZ", StringUtils.appendIfMissingIgnoreCase("abcXYZ", "xyz"), "appendIfMissingIgnoreCase(abcXYZ,xyz)"); 460 461 assertNull(StringUtils.appendIfMissingIgnoreCase(null, null, (CharSequence[]) null), "appendIfMissingIgnoreCase(null,null,null)"); 462 assertEquals("abc", StringUtils.appendIfMissingIgnoreCase("abc", null, (CharSequence[]) null), "appendIfMissingIgnoreCase(abc,null,null)"); 463 assertEquals("xyz", StringUtils.appendIfMissingIgnoreCase("", "xyz", (CharSequence[]) null), "appendIfMissingIgnoreCase(\"\",xyz,null)"); 464 assertEquals("abcxyz", StringUtils.appendIfMissingIgnoreCase("abc", "xyz", null), "appendIfMissingIgnoreCase(abc,xyz,{null})"); 465 assertEquals("abc", StringUtils.appendIfMissingIgnoreCase("abc", "xyz", ""), "appendIfMissingIgnoreCase(abc,xyz,\"\")"); 466 assertEquals("abcxyz", StringUtils.appendIfMissingIgnoreCase("abc", "xyz", "mno"), "appendIfMissingIgnoreCase(abc,xyz,mno)"); 467 assertEquals("abcxyz", StringUtils.appendIfMissingIgnoreCase("abcxyz", "xyz", "mno"), "appendIfMissingIgnoreCase(abcxyz,xyz,mno)"); 468 assertEquals("abcmno", StringUtils.appendIfMissingIgnoreCase("abcmno", "xyz", "mno"), "appendIfMissingIgnoreCase(abcmno,xyz,mno)"); 469 assertEquals("abcXYZ", StringUtils.appendIfMissingIgnoreCase("abcXYZ", "xyz", "mno"), "appendIfMissingIgnoreCase(abcXYZ,xyz,mno)"); 470 assertEquals("abcMNO", StringUtils.appendIfMissingIgnoreCase("abcMNO", "xyz", "mno"), "appendIfMissingIgnoreCase(abcMNO,xyz,mno)"); 471 } 472 473 @Test testCapitalize()474 public void testCapitalize() { 475 assertNull(StringUtils.capitalize(null)); 476 477 assertEquals("", StringUtils.capitalize(""), "capitalize(empty-string) failed"); 478 assertEquals("X", StringUtils.capitalize("x"), "capitalize(single-char-string) failed"); 479 assertEquals(FOO_CAP, StringUtils.capitalize(FOO_CAP), "capitalize(String) failed"); 480 assertEquals(FOO_CAP, StringUtils.capitalize(FOO_UNCAP), "capitalize(string) failed"); 481 482 assertEquals("\u01C8", StringUtils.capitalize("\u01C9"), "capitalize(String) is not using TitleCase"); 483 484 // Javadoc examples 485 assertNull(StringUtils.capitalize(null)); 486 assertEquals("", StringUtils.capitalize("")); 487 assertEquals("Cat", StringUtils.capitalize("cat")); 488 assertEquals("CAt", StringUtils.capitalize("cAt")); 489 assertEquals("'cat'", StringUtils.capitalize("'cat'")); 490 } 491 492 @Test testCenter_StringInt()493 public void testCenter_StringInt() { 494 assertNull(StringUtils.center(null, -1)); 495 assertNull(StringUtils.center(null, 4)); 496 assertEquals(" ", StringUtils.center("", 4)); 497 assertEquals("ab", StringUtils.center("ab", 0)); 498 assertEquals("ab", StringUtils.center("ab", -1)); 499 assertEquals("ab", StringUtils.center("ab", 1)); 500 assertEquals(" ", StringUtils.center("", 4)); 501 assertEquals(" ab ", StringUtils.center("ab", 4)); 502 assertEquals("abcd", StringUtils.center("abcd", 2)); 503 assertEquals(" a ", StringUtils.center("a", 4)); 504 assertEquals(" a ", StringUtils.center("a", 5)); 505 } 506 507 @Test testCenter_StringIntChar()508 public void testCenter_StringIntChar() { 509 assertNull(StringUtils.center(null, -1, ' ')); 510 assertNull(StringUtils.center(null, 4, ' ')); 511 assertEquals(" ", StringUtils.center("", 4, ' ')); 512 assertEquals("ab", StringUtils.center("ab", 0, ' ')); 513 assertEquals("ab", StringUtils.center("ab", -1, ' ')); 514 assertEquals("ab", StringUtils.center("ab", 1, ' ')); 515 assertEquals(" ", StringUtils.center("", 4, ' ')); 516 assertEquals(" ab ", StringUtils.center("ab", 4, ' ')); 517 assertEquals("abcd", StringUtils.center("abcd", 2, ' ')); 518 assertEquals(" a ", StringUtils.center("a", 4, ' ')); 519 assertEquals(" a ", StringUtils.center("a", 5, ' ')); 520 assertEquals("xxaxx", StringUtils.center("a", 5, 'x')); 521 } 522 523 @Test testCenter_StringIntString()524 public void testCenter_StringIntString() { 525 assertNull(StringUtils.center(null, 4, null)); 526 assertNull(StringUtils.center(null, -1, " ")); 527 assertNull(StringUtils.center(null, 4, " ")); 528 assertEquals(" ", StringUtils.center("", 4, " ")); 529 assertEquals("ab", StringUtils.center("ab", 0, " ")); 530 assertEquals("ab", StringUtils.center("ab", -1, " ")); 531 assertEquals("ab", StringUtils.center("ab", 1, " ")); 532 assertEquals(" ", StringUtils.center("", 4, " ")); 533 assertEquals(" ab ", StringUtils.center("ab", 4, " ")); 534 assertEquals("abcd", StringUtils.center("abcd", 2, " ")); 535 assertEquals(" a ", StringUtils.center("a", 4, " ")); 536 assertEquals("yayz", StringUtils.center("a", 4, "yz")); 537 assertEquals("yzyayzy", StringUtils.center("a", 7, "yz")); 538 assertEquals(" abc ", StringUtils.center("abc", 7, null)); 539 assertEquals(" abc ", StringUtils.center("abc", 7, "")); 540 } 541 542 @Test testChomp()543 public void testChomp() { 544 545 final String[][] chompCases = { 546 {FOO_UNCAP + "\r\n", FOO_UNCAP}, 547 {FOO_UNCAP + "\n", FOO_UNCAP}, 548 {FOO_UNCAP + "\r", FOO_UNCAP}, 549 {FOO_UNCAP + " \r", FOO_UNCAP + " "}, 550 {FOO_UNCAP, FOO_UNCAP}, 551 {FOO_UNCAP + "\n\n", FOO_UNCAP + "\n"}, 552 {FOO_UNCAP + "\r\n\r\n", FOO_UNCAP + "\r\n"}, 553 {"foo\nfoo", "foo\nfoo"}, 554 {"foo\n\rfoo", "foo\n\rfoo"}, 555 {"\n", ""}, 556 {"\r", ""}, 557 {"a", "a"}, 558 {"\r\n", ""}, 559 {"", ""}, 560 {null, null}, 561 {FOO_UNCAP + "\n\r", FOO_UNCAP + "\n"} 562 }; 563 for (final String[] chompCase : chompCases) { 564 final String original = chompCase[0]; 565 final String expectedResult = chompCase[1]; 566 assertEquals(expectedResult, StringUtils.chomp(original), "chomp(String) failed"); 567 } 568 569 assertEquals("foo", StringUtils.chomp("foobar", "bar"), "chomp(String, String) failed"); 570 assertEquals("foobar", StringUtils.chomp("foobar", "baz"), "chomp(String, String) failed"); 571 assertEquals("foo", StringUtils.chomp("foo", "foooo"), "chomp(String, String) failed"); 572 assertEquals("foobar", StringUtils.chomp("foobar", ""), "chomp(String, String) failed"); 573 assertEquals("foobar", StringUtils.chomp("foobar", null), "chomp(String, String) failed"); 574 assertEquals("", StringUtils.chomp("", "foo"), "chomp(String, String) failed"); 575 assertEquals("", StringUtils.chomp("", null), "chomp(String, String) failed"); 576 assertEquals("", StringUtils.chomp("", ""), "chomp(String, String) failed"); 577 assertNull(StringUtils.chomp(null, "foo"), "chomp(String, String) failed"); 578 assertNull(StringUtils.chomp(null, null), "chomp(String, String) failed"); 579 assertNull(StringUtils.chomp(null, ""), "chomp(String, String) failed"); 580 assertEquals("", StringUtils.chomp("foo", "foo"), "chomp(String, String) failed"); 581 assertEquals(" ", StringUtils.chomp(" foo", "foo"), "chomp(String, String) failed"); 582 assertEquals("foo ", StringUtils.chomp("foo ", "foo"), "chomp(String, String) failed"); 583 } 584 585 @Test testChop()586 public void testChop() { 587 588 final String[][] chopCases = { 589 {FOO_UNCAP + "\r\n", FOO_UNCAP}, 590 {FOO_UNCAP + "\n", FOO_UNCAP}, 591 {FOO_UNCAP + "\r", FOO_UNCAP}, 592 {FOO_UNCAP + " \r", FOO_UNCAP + " "}, 593 {"foo", "fo"}, 594 {"foo\nfoo", "foo\nfo"}, 595 {"\n", ""}, 596 {"\r", ""}, 597 {"\r\n", ""}, 598 {null, null}, 599 {"", ""}, 600 {"a", ""}, 601 }; 602 for (final String[] chopCase : chopCases) { 603 final String original = chopCase[0]; 604 final String expectedResult = chopCase[1]; 605 assertEquals(expectedResult, StringUtils.chop(original), "chop(String) failed"); 606 } 607 } 608 609 @Test testConstructor()610 public void testConstructor() { 611 assertNotNull(new StringUtils()); 612 final Constructor<?>[] cons = StringUtils.class.getDeclaredConstructors(); 613 assertEquals(1, cons.length); 614 assertTrue(Modifier.isPublic(cons[0].getModifiers())); 615 assertTrue(Modifier.isPublic(StringUtils.class.getModifiers())); 616 assertFalse(Modifier.isFinal(StringUtils.class.getModifiers())); 617 } 618 619 @Test testDefault_String()620 public void testDefault_String() { 621 assertEquals("", StringUtils.defaultString(null)); 622 assertEquals("", StringUtils.defaultString("")); 623 assertEquals("abc", StringUtils.defaultString("abc")); 624 } 625 626 @Test testDefault_StringString()627 public void testDefault_StringString() { 628 assertEquals("NULL", StringUtils.defaultString(null, "NULL")); 629 assertEquals("", StringUtils.defaultString("", "NULL")); 630 assertEquals("abc", StringUtils.defaultString("abc", "NULL")); 631 } 632 633 @Test testDefaultIfBlank_CharBuffers()634 public void testDefaultIfBlank_CharBuffers() { 635 assertEquals("NULL", StringUtils.defaultIfBlank(CharBuffer.wrap(""), CharBuffer.wrap("NULL")).toString()); 636 assertEquals("NULL", StringUtils.defaultIfBlank(CharBuffer.wrap(" "), CharBuffer.wrap("NULL")).toString()); 637 assertEquals("abc", StringUtils.defaultIfBlank(CharBuffer.wrap("abc"), CharBuffer.wrap("NULL")).toString()); 638 assertNull(StringUtils.defaultIfBlank(CharBuffer.wrap(""), (CharBuffer) null)); 639 // Tests compatibility for the API return type 640 final CharBuffer s = StringUtils.defaultIfBlank(CharBuffer.wrap("abc"), CharBuffer.wrap("NULL")); 641 assertEquals("abc", s.toString()); 642 } 643 644 @Test testDefaultIfBlank_StringBuffers()645 public void testDefaultIfBlank_StringBuffers() { 646 assertEquals("NULL", StringUtils.defaultIfBlank(new StringBuffer(""), new StringBuffer("NULL")).toString()); 647 assertEquals("NULL", StringUtils.defaultIfBlank(new StringBuffer(" "), new StringBuffer("NULL")).toString()); 648 assertEquals("abc", StringUtils.defaultIfBlank(new StringBuffer("abc"), new StringBuffer("NULL")).toString()); 649 assertNull(StringUtils.defaultIfBlank(new StringBuffer(""), (StringBuffer) null)); 650 // Tests compatibility for the API return type 651 final StringBuffer s = StringUtils.defaultIfBlank(new StringBuffer("abc"), new StringBuffer("NULL")); 652 assertEquals("abc", s.toString()); 653 } 654 655 @Test testDefaultIfBlank_StringBuilders()656 public void testDefaultIfBlank_StringBuilders() { 657 assertEquals("NULL", StringUtils.defaultIfBlank(new StringBuilder(""), new StringBuilder("NULL")).toString()); 658 assertEquals("NULL", StringUtils.defaultIfBlank(new StringBuilder(" "), new StringBuilder("NULL")).toString()); 659 assertEquals("abc", StringUtils.defaultIfBlank(new StringBuilder("abc"), new StringBuilder("NULL")).toString()); 660 assertNull(StringUtils.defaultIfBlank(new StringBuilder(""), (StringBuilder) null)); 661 // Tests compatibility for the API return type 662 final StringBuilder s = StringUtils.defaultIfBlank(new StringBuilder("abc"), new StringBuilder("NULL")); 663 assertEquals("abc", s.toString()); 664 } 665 666 @Test testDefaultIfBlank_StringString()667 public void testDefaultIfBlank_StringString() { 668 assertEquals("NULL", StringUtils.defaultIfBlank(null, "NULL")); 669 assertEquals("NULL", StringUtils.defaultIfBlank("", "NULL")); 670 assertEquals("NULL", StringUtils.defaultIfBlank(" ", "NULL")); 671 assertEquals("abc", StringUtils.defaultIfBlank("abc", "NULL")); 672 assertNull(StringUtils.defaultIfBlank("", (String) null)); 673 // Tests compatibility for the API return type 674 final String s = StringUtils.defaultIfBlank("abc", "NULL"); 675 assertEquals("abc", s); 676 } 677 678 679 @Test testGetIfBlank_StringStringSupplier()680 public void testGetIfBlank_StringStringSupplier() { 681 assertEquals("NULL", StringUtils.getIfBlank(null, () -> "NULL")); 682 assertEquals("NULL", StringUtils.getIfBlank("", () -> "NULL")); 683 assertEquals("NULL", StringUtils.getIfBlank(" ", () -> "NULL")); 684 assertEquals("abc", StringUtils.getIfBlank("abc", () -> "NULL")); 685 assertNull(StringUtils.getIfBlank("", () -> null)); 686 assertNull(StringUtils.defaultIfBlank("", (String) null)); 687 // Tests compatibility for the API return type 688 final String s = StringUtils.getIfBlank("abc", () -> "NULL"); 689 assertEquals("abc", s); 690 //Checking that default value supplied only on demand 691 final MutableInt numberOfCalls = new MutableInt(0); 692 final Supplier<String> countingDefaultSupplier = () -> { 693 numberOfCalls.increment(); 694 return "NULL"; 695 }; 696 StringUtils.getIfBlank("abc", countingDefaultSupplier); 697 assertEquals(0, numberOfCalls.getValue()); 698 StringUtils.getIfBlank("", countingDefaultSupplier); 699 assertEquals(1, numberOfCalls.getValue()); 700 StringUtils.getIfBlank(" ", countingDefaultSupplier); 701 assertEquals(2, numberOfCalls.getValue()); 702 StringUtils.getIfBlank(null, countingDefaultSupplier); 703 assertEquals(3, numberOfCalls.getValue()); 704 } 705 706 @Test testDefaultIfEmpty_CharBuffers()707 public void testDefaultIfEmpty_CharBuffers() { 708 assertEquals("NULL", StringUtils.defaultIfEmpty(CharBuffer.wrap(""), CharBuffer.wrap("NULL")).toString()); 709 assertEquals("abc", StringUtils.defaultIfEmpty(CharBuffer.wrap("abc"), CharBuffer.wrap("NULL")).toString()); 710 assertNull(StringUtils.defaultIfEmpty(CharBuffer.wrap(""), (CharBuffer) null)); 711 // Tests compatibility for the API return type 712 final CharBuffer s = StringUtils.defaultIfEmpty(CharBuffer.wrap("abc"), CharBuffer.wrap("NULL")); 713 assertEquals("abc", s.toString()); 714 } 715 716 717 @Test testDefaultIfEmpty_StringBuffers()718 public void testDefaultIfEmpty_StringBuffers() { 719 assertEquals("NULL", StringUtils.defaultIfEmpty(new StringBuffer(""), new StringBuffer("NULL")).toString()); 720 assertEquals("abc", StringUtils.defaultIfEmpty(new StringBuffer("abc"), new StringBuffer("NULL")).toString()); 721 assertNull(StringUtils.defaultIfEmpty(new StringBuffer(""), (StringBuffer) null)); 722 // Tests compatibility for the API return type 723 final StringBuffer s = StringUtils.defaultIfEmpty(new StringBuffer("abc"), new StringBuffer("NULL")); 724 assertEquals("abc", s.toString()); 725 } 726 727 @Test testDefaultIfEmpty_StringBuilders()728 public void testDefaultIfEmpty_StringBuilders() { 729 assertEquals("NULL", StringUtils.defaultIfEmpty(new StringBuilder(""), new StringBuilder("NULL")).toString()); 730 assertEquals("abc", StringUtils.defaultIfEmpty(new StringBuilder("abc"), new StringBuilder("NULL")).toString()); 731 assertNull(StringUtils.defaultIfEmpty(new StringBuilder(""), (StringBuilder) null)); 732 // Tests compatibility for the API return type 733 final StringBuilder s = StringUtils.defaultIfEmpty(new StringBuilder("abc"), new StringBuilder("NULL")); 734 assertEquals("abc", s.toString()); 735 } 736 737 @Test testDefaultIfEmpty_StringString()738 public void testDefaultIfEmpty_StringString() { 739 assertEquals("NULL", StringUtils.defaultIfEmpty(null, "NULL")); 740 assertEquals("NULL", StringUtils.defaultIfEmpty("", "NULL")); 741 assertEquals("abc", StringUtils.defaultIfEmpty("abc", "NULL")); 742 assertNull(StringUtils.getIfEmpty("", null)); 743 // Tests compatibility for the API return type 744 final String s = StringUtils.defaultIfEmpty("abc", "NULL"); 745 assertEquals("abc", s); 746 } 747 748 @Test testGetIfEmpty_StringStringSupplier()749 public void testGetIfEmpty_StringStringSupplier() { 750 assertEquals("NULL", StringUtils.getIfEmpty((String) null, () -> "NULL")); 751 assertEquals("NULL", StringUtils.getIfEmpty("", () -> "NULL")); 752 assertEquals("abc", StringUtils.getIfEmpty("abc", () -> "NULL")); 753 assertNull(StringUtils.getIfEmpty("", () -> null)); 754 assertNull(StringUtils.defaultIfEmpty("", (String) null)); 755 // Tests compatibility for the API return type 756 final String s = StringUtils.getIfEmpty("abc", () -> "NULL"); 757 assertEquals("abc", s); 758 //Checking that default value supplied only on demand 759 final MutableInt numberOfCalls = new MutableInt(0); 760 final Supplier<String> countingDefaultSupplier = () -> { 761 numberOfCalls.increment(); 762 return "NULL"; 763 }; 764 StringUtils.getIfEmpty("abc", countingDefaultSupplier); 765 assertEquals(0, numberOfCalls.getValue()); 766 StringUtils.getIfEmpty("", countingDefaultSupplier); 767 assertEquals(1, numberOfCalls.getValue()); 768 StringUtils.getIfEmpty(null, countingDefaultSupplier); 769 assertEquals(2, numberOfCalls.getValue()); 770 } 771 772 773 @Test testDeleteWhitespace_String()774 public void testDeleteWhitespace_String() { 775 assertNull(StringUtils.deleteWhitespace(null)); 776 assertEquals("", StringUtils.deleteWhitespace("")); 777 assertEquals("", StringUtils.deleteWhitespace(" \u000C \t\t\u001F\n\n \u000B ")); 778 assertEquals("", StringUtils.deleteWhitespace(StringUtilsTest.WHITESPACE)); 779 assertEquals(StringUtilsTest.NON_WHITESPACE, StringUtils.deleteWhitespace(StringUtilsTest.NON_WHITESPACE)); 780 // Note: u-2007 and u-000A both cause problems in the source code 781 // it should ignore 2007 but delete 000A 782 assertEquals("\u00A0\u202F", StringUtils.deleteWhitespace(" \u00A0 \t\t\n\n \u202F ")); 783 assertEquals("\u00A0\u202F", StringUtils.deleteWhitespace("\u00A0\u202F")); 784 assertEquals("test", StringUtils.deleteWhitespace("\u000Bt \t\n\u0009e\rs\n\n \tt")); 785 } 786 787 @Test testDifference_StringString()788 public void testDifference_StringString() { 789 assertNull(StringUtils.difference(null, null)); 790 assertEquals("", StringUtils.difference("", "")); 791 assertEquals("abc", StringUtils.difference("", "abc")); 792 assertEquals("", StringUtils.difference("abc", "")); 793 assertEquals("i am a robot", StringUtils.difference(null, "i am a robot")); 794 assertEquals("i am a machine", StringUtils.difference("i am a machine", null)); 795 assertEquals("robot", StringUtils.difference("i am a machine", "i am a robot")); 796 assertEquals("", StringUtils.difference("abc", "abc")); 797 assertEquals("you are a robot", StringUtils.difference("i am a robot", "you are a robot")); 798 } 799 800 @Test testDifferenceAt_StringArray()801 public void testDifferenceAt_StringArray() { 802 assertEquals(-1, StringUtils.indexOfDifference((String[]) null)); 803 assertEquals(-1, StringUtils.indexOfDifference()); 804 assertEquals(-1, StringUtils.indexOfDifference("abc")); 805 assertEquals(-1, StringUtils.indexOfDifference(null, null)); 806 assertEquals(-1, StringUtils.indexOfDifference("", "")); 807 assertEquals(0, StringUtils.indexOfDifference("", null)); 808 assertEquals(0, StringUtils.indexOfDifference("abc", null, null)); 809 assertEquals(0, StringUtils.indexOfDifference(null, null, "abc")); 810 assertEquals(0, StringUtils.indexOfDifference("", "abc")); 811 assertEquals(0, StringUtils.indexOfDifference("abc", "")); 812 assertEquals(-1, StringUtils.indexOfDifference("abc", "abc")); 813 assertEquals(1, StringUtils.indexOfDifference("abc", "a")); 814 assertEquals(2, StringUtils.indexOfDifference("ab", "abxyz")); 815 assertEquals(2, StringUtils.indexOfDifference("abcde", "abxyz")); 816 assertEquals(0, StringUtils.indexOfDifference("abcde", "xyz")); 817 assertEquals(0, StringUtils.indexOfDifference("xyz", "abcde")); 818 assertEquals(7, StringUtils.indexOfDifference("i am a machine", "i am a robot")); 819 } 820 821 @Test testDifferenceAt_StringString()822 public void testDifferenceAt_StringString() { 823 assertEquals(-1, StringUtils.indexOfDifference(null, null)); 824 assertEquals(0, StringUtils.indexOfDifference(null, "i am a robot")); 825 assertEquals(-1, StringUtils.indexOfDifference("", "")); 826 assertEquals(0, StringUtils.indexOfDifference("", "abc")); 827 assertEquals(0, StringUtils.indexOfDifference("abc", "")); 828 assertEquals(0, StringUtils.indexOfDifference("i am a machine", null)); 829 assertEquals(7, StringUtils.indexOfDifference("i am a machine", "i am a robot")); 830 assertEquals(-1, StringUtils.indexOfDifference("foo", "foo")); 831 assertEquals(0, StringUtils.indexOfDifference("i am a robot", "you are a robot")); 832 } 833 834 /** 835 * A sanity check for {@link StringUtils#EMPTY}. 836 */ 837 @Test testEMPTY()838 public void testEMPTY() { 839 assertNotNull(StringUtils.EMPTY); 840 assertEquals("", StringUtils.EMPTY); 841 assertEquals(0, StringUtils.EMPTY.length()); 842 } 843 844 @Test testEscapeSurrogatePairs()845 public void testEscapeSurrogatePairs() { 846 assertEquals("\uD83D\uDE30", StringEscapeUtils.escapeCsv("\uD83D\uDE30")); 847 // Examples from https://en.wikipedia.org/wiki/UTF-16 848 assertEquals("\uD800\uDC00", StringEscapeUtils.escapeCsv("\uD800\uDC00")); 849 assertEquals("\uD834\uDD1E", StringEscapeUtils.escapeCsv("\uD834\uDD1E")); 850 assertEquals("\uDBFF\uDFFD", StringEscapeUtils.escapeCsv("\uDBFF\uDFFD")); 851 assertEquals("\uDBFF\uDFFD", StringEscapeUtils.escapeHtml3("\uDBFF\uDFFD")); 852 assertEquals("\uDBFF\uDFFD", StringEscapeUtils.escapeHtml4("\uDBFF\uDFFD")); 853 assertEquals("\uDBFF\uDFFD", StringEscapeUtils.escapeXml("\uDBFF\uDFFD")); 854 } 855 856 /** 857 * Tests LANG-858. 858 */ 859 @Test testEscapeSurrogatePairsLang858()860 public void testEscapeSurrogatePairsLang858() { 861 assertEquals("\\uDBFF\\uDFFD", StringEscapeUtils.escapeJava("\uDBFF\uDFFD")); //fail LANG-858 862 assertEquals("\\uDBFF\\uDFFD", StringEscapeUtils.escapeEcmaScript("\uDBFF\uDFFD")); //fail LANG-858 863 } 864 865 @Test testGetBytes_Charset()866 public void testGetBytes_Charset() { 867 assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, StringUtils.getBytes(null, (Charset) null)); 868 assertArrayEquals(StringUtils.EMPTY.getBytes(), StringUtils.getBytes(StringUtils.EMPTY, (Charset) null)); 869 assertArrayEquals(StringUtils.EMPTY.getBytes(StandardCharsets.US_ASCII), 870 StringUtils.getBytes(StringUtils.EMPTY, StandardCharsets.US_ASCII)); 871 } 872 873 @Test testGetBytes_String()874 public void testGetBytes_String() throws UnsupportedEncodingException { 875 assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, StringUtils.getBytes(null, (String) null)); 876 assertArrayEquals(StringUtils.EMPTY.getBytes(), StringUtils.getBytes(StringUtils.EMPTY, (String) null)); 877 assertArrayEquals(StringUtils.EMPTY.getBytes(StandardCharsets.US_ASCII.name()), 878 StringUtils.getBytes(StringUtils.EMPTY, StandardCharsets.US_ASCII.name())); 879 } 880 881 @Test testGetCommonPrefix_StringArray()882 public void testGetCommonPrefix_StringArray() { 883 assertEquals("", StringUtils.getCommonPrefix((String[]) null)); 884 assertEquals("", StringUtils.getCommonPrefix()); 885 assertEquals("abc", StringUtils.getCommonPrefix("abc")); 886 assertEquals("", StringUtils.getCommonPrefix(null, null)); 887 assertEquals("", StringUtils.getCommonPrefix("", "")); 888 assertEquals("", StringUtils.getCommonPrefix("", null)); 889 assertEquals("", StringUtils.getCommonPrefix("abc", null, null)); 890 assertEquals("", StringUtils.getCommonPrefix(null, null, "abc")); 891 assertEquals("", StringUtils.getCommonPrefix("", "abc")); 892 assertEquals("", StringUtils.getCommonPrefix("abc", "")); 893 assertEquals("abc", StringUtils.getCommonPrefix("abc", "abc")); 894 assertEquals("a", StringUtils.getCommonPrefix("abc", "a")); 895 assertEquals("ab", StringUtils.getCommonPrefix("ab", "abxyz")); 896 assertEquals("ab", StringUtils.getCommonPrefix("abcde", "abxyz")); 897 assertEquals("", StringUtils.getCommonPrefix("abcde", "xyz")); 898 assertEquals("", StringUtils.getCommonPrefix("xyz", "abcde")); 899 assertEquals("i am a ", StringUtils.getCommonPrefix("i am a machine", "i am a robot")); 900 } 901 902 @Test testGetDigits()903 public void testGetDigits() { 904 assertNull(StringUtils.getDigits(null)); 905 assertEquals("", StringUtils.getDigits("")); 906 assertEquals("", StringUtils.getDigits("abc")); 907 assertEquals("1000", StringUtils.getDigits("1000$")); 908 assertEquals("12345", StringUtils.getDigits("123password45")); 909 assertEquals("5417543010", StringUtils.getDigits("(541) 754-3010")); 910 assertEquals("\u0967\u0968\u0969", StringUtils.getDigits("\u0967\u0968\u0969")); 911 } 912 913 @Test testGetFuzzyDistance()914 public void testGetFuzzyDistance() { 915 assertEquals(0, StringUtils.getFuzzyDistance("", "", Locale.ENGLISH)); 916 assertEquals(0, StringUtils.getFuzzyDistance("Workshop", "b", Locale.ENGLISH)); 917 assertEquals(1, StringUtils.getFuzzyDistance("Room", "o", Locale.ENGLISH)); 918 assertEquals(1, StringUtils.getFuzzyDistance("Workshop", "w", Locale.ENGLISH)); 919 assertEquals(2, StringUtils.getFuzzyDistance("Workshop", "ws", Locale.ENGLISH)); 920 assertEquals(4, StringUtils.getFuzzyDistance("Workshop", "wo", Locale.ENGLISH)); 921 assertEquals(3, StringUtils.getFuzzyDistance("Apache Software Foundation", "asf", Locale.ENGLISH)); 922 } 923 924 @Test testGetFuzzyDistance_NullNullNull()925 public void testGetFuzzyDistance_NullNullNull() { 926 assertThrows(IllegalArgumentException.class, () -> StringUtils.getFuzzyDistance(null, null, null)); 927 } 928 929 @Test testGetFuzzyDistance_NullStringLocale()930 public void testGetFuzzyDistance_NullStringLocale() { 931 assertThrows(IllegalArgumentException.class, () -> StringUtils.getFuzzyDistance(null, "clear", Locale.ENGLISH)); 932 } 933 934 @Test testGetFuzzyDistance_StringNullLoclae()935 public void testGetFuzzyDistance_StringNullLoclae() { 936 assertThrows(IllegalArgumentException.class, () -> StringUtils.getFuzzyDistance(" ", null, Locale.ENGLISH)); 937 } 938 939 @Test testGetFuzzyDistance_StringStringNull()940 public void testGetFuzzyDistance_StringStringNull() { 941 assertThrows(IllegalArgumentException.class, () -> StringUtils.getFuzzyDistance(" ", "clear", null)); 942 } 943 944 @Test testGetJaroWinklerDistance_NullNull()945 public void testGetJaroWinklerDistance_NullNull() { 946 assertThrows(IllegalArgumentException.class, () -> StringUtils.getJaroWinklerDistance(null, null)); 947 } 948 949 @Test testGetJaroWinklerDistance_NullString()950 public void testGetJaroWinklerDistance_NullString() { 951 assertThrows(IllegalArgumentException.class, () -> StringUtils.getJaroWinklerDistance(null, "clear")); 952 } 953 954 @Test testGetJaroWinklerDistance_StringNull()955 public void testGetJaroWinklerDistance_StringNull() { 956 assertThrows(IllegalArgumentException.class, () -> StringUtils.getJaroWinklerDistance(" ", null)); 957 } 958 959 @Test testGetJaroWinklerDistance_StringString()960 public void testGetJaroWinklerDistance_StringString() { 961 assertEquals(0.93d, StringUtils.getJaroWinklerDistance("frog", "fog")); 962 assertEquals(0.0d, StringUtils.getJaroWinklerDistance("fly", "ant")); 963 assertEquals(0.44d, StringUtils.getJaroWinklerDistance("elephant", "hippo")); 964 assertEquals(0.84d, StringUtils.getJaroWinklerDistance("dwayne", "duane")); 965 assertEquals(0.93d, StringUtils.getJaroWinklerDistance("ABC Corporation", "ABC Corp")); 966 assertEquals(0.95d, StringUtils.getJaroWinklerDistance("D N H Enterprises Inc", "D & H Enterprises, Inc.")); 967 assertEquals(0.92d, StringUtils.getJaroWinklerDistance("My Gym Children's Fitness Center", "My Gym. Childrens Fitness")); 968 assertEquals(0.88d, StringUtils.getJaroWinklerDistance("PENNSYLVANIA", "PENNCISYLVNIA")); 969 assertEquals(0.63d, StringUtils.getJaroWinklerDistance("Haus Ingeborg", "Ingeborg Esser")); 970 } 971 972 @Test testGetLevenshteinDistance_NullString()973 public void testGetLevenshteinDistance_NullString() { 974 assertThrows(IllegalArgumentException.class, () -> StringUtils.getLevenshteinDistance("a", null)); 975 } 976 977 @Test testGetLevenshteinDistance_NullStringInt()978 public void testGetLevenshteinDistance_NullStringInt() { 979 assertThrows(IllegalArgumentException.class, () -> StringUtils.getLevenshteinDistance(null, "a", 0)); 980 } 981 982 @Test testGetLevenshteinDistance_StringNull()983 public void testGetLevenshteinDistance_StringNull() { 984 assertThrows(IllegalArgumentException.class, () -> StringUtils.getLevenshteinDistance(null, "a")); 985 } 986 987 @Test testGetLevenshteinDistance_StringNullInt()988 public void testGetLevenshteinDistance_StringNullInt() { 989 assertThrows(IllegalArgumentException.class, () -> StringUtils.getLevenshteinDistance("a", null, 0)); 990 } 991 992 @Test testGetLevenshteinDistance_StringString()993 public void testGetLevenshteinDistance_StringString() { 994 assertEquals(0, StringUtils.getLevenshteinDistance("", "")); 995 assertEquals(1, StringUtils.getLevenshteinDistance("", "a")); 996 assertEquals(7, StringUtils.getLevenshteinDistance("aaapppp", "")); 997 assertEquals(1, StringUtils.getLevenshteinDistance("frog", "fog")); 998 assertEquals(3, StringUtils.getLevenshteinDistance("fly", "ant")); 999 assertEquals(7, StringUtils.getLevenshteinDistance("elephant", "hippo")); 1000 assertEquals(7, StringUtils.getLevenshteinDistance("hippo", "elephant")); 1001 assertEquals(8, StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz")); 1002 assertEquals(8, StringUtils.getLevenshteinDistance("zzzzzzzz", "hippo")); 1003 assertEquals(1, StringUtils.getLevenshteinDistance("hello", "hallo")); 1004 } 1005 1006 @Test testGetLevenshteinDistance_StringStringInt()1007 public void testGetLevenshteinDistance_StringStringInt() { 1008 // empty strings 1009 assertEquals(0, StringUtils.getLevenshteinDistance("", "", 0)); 1010 assertEquals(7, StringUtils.getLevenshteinDistance("aaapppp", "", 8)); 1011 assertEquals(7, StringUtils.getLevenshteinDistance("aaapppp", "", 7)); 1012 assertEquals(-1, StringUtils.getLevenshteinDistance("aaapppp", "", 6)); 1013 1014 // unequal strings, zero threshold 1015 assertEquals(-1, StringUtils.getLevenshteinDistance("b", "a", 0)); 1016 assertEquals(-1, StringUtils.getLevenshteinDistance("a", "b", 0)); 1017 1018 // equal strings 1019 assertEquals(0, StringUtils.getLevenshteinDistance("aa", "aa", 0)); 1020 assertEquals(0, StringUtils.getLevenshteinDistance("aa", "aa", 2)); 1021 1022 // same length 1023 assertEquals(-1, StringUtils.getLevenshteinDistance("aaa", "bbb", 2)); 1024 assertEquals(3, StringUtils.getLevenshteinDistance("aaa", "bbb", 3)); 1025 1026 // big stripe 1027 assertEquals(6, StringUtils.getLevenshteinDistance("aaaaaa", "b", 10)); 1028 1029 // distance less than threshold 1030 assertEquals(7, StringUtils.getLevenshteinDistance("aaapppp", "b", 8)); 1031 assertEquals(3, StringUtils.getLevenshteinDistance("a", "bbb", 4)); 1032 1033 // distance equal to threshold 1034 assertEquals(7, StringUtils.getLevenshteinDistance("aaapppp", "b", 7)); 1035 assertEquals(3, StringUtils.getLevenshteinDistance("a", "bbb", 3)); 1036 1037 // distance greater than threshold 1038 assertEquals(-1, StringUtils.getLevenshteinDistance("a", "bbb", 2)); 1039 assertEquals(-1, StringUtils.getLevenshteinDistance("bbb", "a", 2)); 1040 assertEquals(-1, StringUtils.getLevenshteinDistance("aaapppp", "b", 6)); 1041 1042 // stripe runs off array, strings not similar 1043 assertEquals(-1, StringUtils.getLevenshteinDistance("a", "bbb", 1)); 1044 assertEquals(-1, StringUtils.getLevenshteinDistance("bbb", "a", 1)); 1045 1046 // stripe runs off array, strings are similar 1047 assertEquals(-1, StringUtils.getLevenshteinDistance("12345", "1234567", 1)); 1048 assertEquals(-1, StringUtils.getLevenshteinDistance("1234567", "12345", 1)); 1049 1050 // old getLevenshteinDistance test cases 1051 assertEquals(1, StringUtils.getLevenshteinDistance("frog", "fog", 1)); 1052 assertEquals(3, StringUtils.getLevenshteinDistance("fly", "ant", 3)); 1053 assertEquals(7, StringUtils.getLevenshteinDistance("elephant", "hippo", 7)); 1054 assertEquals(-1, StringUtils.getLevenshteinDistance("elephant", "hippo", 6)); 1055 assertEquals(7, StringUtils.getLevenshteinDistance("hippo", "elephant", 7)); 1056 assertEquals(-1, StringUtils.getLevenshteinDistance("hippo", "elephant", 6)); 1057 assertEquals(8, StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz", 8)); 1058 assertEquals(8, StringUtils.getLevenshteinDistance("zzzzzzzz", "hippo", 8)); 1059 assertEquals(1, StringUtils.getLevenshteinDistance("hello", "hallo", 1)); 1060 1061 assertEquals(1, StringUtils.getLevenshteinDistance("frog", "fog", Integer.MAX_VALUE)); 1062 assertEquals(3, StringUtils.getLevenshteinDistance("fly", "ant", Integer.MAX_VALUE)); 1063 assertEquals(7, StringUtils.getLevenshteinDistance("elephant", "hippo", Integer.MAX_VALUE)); 1064 assertEquals(7, StringUtils.getLevenshteinDistance("hippo", "elephant", Integer.MAX_VALUE)); 1065 assertEquals(8, StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz", Integer.MAX_VALUE)); 1066 assertEquals(8, StringUtils.getLevenshteinDistance("zzzzzzzz", "hippo", Integer.MAX_VALUE)); 1067 assertEquals(1, StringUtils.getLevenshteinDistance("hello", "hallo", Integer.MAX_VALUE)); 1068 } 1069 1070 @Test testGetLevenshteinDistance_StringStringNegativeInt()1071 public void testGetLevenshteinDistance_StringStringNegativeInt() { 1072 assertThrows(IllegalArgumentException.class, () -> StringUtils.getLevenshteinDistance("a", "a", -1)); 1073 } 1074 1075 /** 1076 * Test for {@link StringUtils#isAllLowerCase(CharSequence)}. 1077 */ 1078 @Test testIsAllLowerCase()1079 public void testIsAllLowerCase() { 1080 assertFalse(StringUtils.isAllLowerCase(null)); 1081 assertFalse(StringUtils.isAllLowerCase(StringUtils.EMPTY)); 1082 assertFalse(StringUtils.isAllLowerCase(" ")); 1083 assertTrue(StringUtils.isAllLowerCase("abc")); 1084 assertFalse(StringUtils.isAllLowerCase("abc ")); 1085 assertFalse(StringUtils.isAllLowerCase("abc\n")); 1086 assertFalse(StringUtils.isAllLowerCase("abC")); 1087 assertFalse(StringUtils.isAllLowerCase("ab c")); 1088 assertFalse(StringUtils.isAllLowerCase("ab1c")); 1089 assertFalse(StringUtils.isAllLowerCase("ab/c")); 1090 } 1091 1092 /** 1093 * Test for {@link StringUtils#isAllUpperCase(CharSequence)}. 1094 */ 1095 @Test testIsAllUpperCase()1096 public void testIsAllUpperCase() { 1097 assertFalse(StringUtils.isAllUpperCase(null)); 1098 assertFalse(StringUtils.isAllUpperCase(StringUtils.EMPTY)); 1099 assertFalse(StringUtils.isAllUpperCase(" ")); 1100 assertTrue(StringUtils.isAllUpperCase("ABC")); 1101 assertFalse(StringUtils.isAllUpperCase("ABC ")); 1102 assertFalse(StringUtils.isAllUpperCase("ABC\n")); 1103 assertFalse(StringUtils.isAllUpperCase("aBC")); 1104 assertFalse(StringUtils.isAllUpperCase("A C")); 1105 assertFalse(StringUtils.isAllUpperCase("A1C")); 1106 assertFalse(StringUtils.isAllUpperCase("A/C")); 1107 } 1108 1109 /** 1110 * Test for {@link StringUtils#isMixedCase(CharSequence)}. 1111 */ 1112 @Test testIsMixedCase()1113 public void testIsMixedCase() { 1114 assertFalse(StringUtils.isMixedCase(null)); 1115 assertFalse(StringUtils.isMixedCase(StringUtils.EMPTY)); 1116 assertFalse(StringUtils.isMixedCase(" ")); 1117 assertFalse(StringUtils.isMixedCase("A")); 1118 assertFalse(StringUtils.isMixedCase("a")); 1119 assertFalse(StringUtils.isMixedCase("/")); 1120 assertFalse(StringUtils.isMixedCase("A/")); 1121 assertFalse(StringUtils.isMixedCase("/b")); 1122 assertFalse(StringUtils.isMixedCase("abc")); 1123 assertFalse(StringUtils.isMixedCase("ABC")); 1124 assertTrue(StringUtils.isMixedCase("aBc")); 1125 assertTrue(StringUtils.isMixedCase("aBc ")); 1126 assertTrue(StringUtils.isMixedCase("A c")); 1127 assertTrue(StringUtils.isMixedCase("aBc\n")); 1128 assertTrue(StringUtils.isMixedCase("A1c")); 1129 assertTrue(StringUtils.isMixedCase("a/C")); 1130 } 1131 1132 @Test testJoin_ArrayCharSeparator()1133 public void testJoin_ArrayCharSeparator() { 1134 assertNull(StringUtils.join((Object[]) null, ',')); 1135 assertEquals(TEXT_LIST_CHAR, StringUtils.join(ARRAY_LIST, SEPARATOR_CHAR)); 1136 assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST, SEPARATOR_CHAR)); 1137 assertEquals(";;foo", StringUtils.join(MIXED_ARRAY_LIST, SEPARATOR_CHAR)); 1138 assertEquals("foo;2", StringUtils.join(MIXED_TYPE_LIST, SEPARATOR_CHAR)); 1139 1140 assertNull(StringUtils.join((Object[]) null, ',', 0, 1)); 1141 assertEquals("/", StringUtils.join(MIXED_ARRAY_LIST, '/', 0, MIXED_ARRAY_LIST.length - 1)); 1142 assertEquals("foo", StringUtils.join(MIXED_TYPE_LIST, '/', 0, 1)); 1143 assertEquals("null", StringUtils.join(NULL_TO_STRING_LIST, '/', 0, 1)); 1144 assertEquals("foo/2", StringUtils.join(MIXED_TYPE_LIST, '/', 0, 2)); 1145 assertEquals("2", StringUtils.join(MIXED_TYPE_LIST, '/', 1, 2)); 1146 assertEquals("", StringUtils.join(MIXED_TYPE_LIST, '/', 2, 1)); 1147 } 1148 1149 @Test testJoin_ArrayOfBytes()1150 public void testJoin_ArrayOfBytes() { 1151 assertNull(StringUtils.join((byte[]) null, ',')); 1152 assertEquals("1;2", StringUtils.join(BYTE_PRIM_LIST, SEPARATOR_CHAR)); 1153 assertEquals("2", StringUtils.join(BYTE_PRIM_LIST, SEPARATOR_CHAR, 1, 2)); 1154 assertNull(StringUtils.join((byte[]) null, SEPARATOR_CHAR, 0, 1)); 1155 assertEquals(StringUtils.EMPTY, StringUtils.join(BYTE_PRIM_LIST, SEPARATOR_CHAR, 0, 0)); 1156 assertEquals(StringUtils.EMPTY, StringUtils.join(BYTE_PRIM_LIST, SEPARATOR_CHAR, 1, 0)); 1157 } 1158 1159 1160 @Test testJoin_ArrayOfBooleans()1161 public void testJoin_ArrayOfBooleans() { 1162 assertNull(StringUtils.join((boolean[]) null, COMMA_SEPARATOR_CHAR)); 1163 assertEquals("false;false", StringUtils.join(ARRAY_FALSE_FALSE, SEPARATOR_CHAR)); 1164 assertEquals("", StringUtils.join(EMPTY, SEPARATOR_CHAR)); 1165 assertEquals("false,true,false", StringUtils.join(ARRAY_FALSE_TRUE_FALSE, COMMA_SEPARATOR_CHAR)); 1166 assertEquals("true", StringUtils.join(ARRAY_FALSE_TRUE, SEPARATOR_CHAR, 1, 2)); 1167 assertNull(StringUtils.join((boolean[]) null, SEPARATOR_CHAR, 0, 1)); 1168 assertEquals(StringUtils.EMPTY, StringUtils.join(ARRAY_FALSE_FALSE, SEPARATOR_CHAR, 0, 0)); 1169 assertEquals(StringUtils.EMPTY, StringUtils.join(ARRAY_FALSE_TRUE_FALSE, SEPARATOR_CHAR, 1, 0)); 1170 } 1171 1172 @Test testJoin_ArrayOfChars()1173 public void testJoin_ArrayOfChars() { 1174 assertNull(StringUtils.join((char[]) null, ',')); 1175 assertEquals("1;2", StringUtils.join(CHAR_PRIM_LIST, SEPARATOR_CHAR)); 1176 assertEquals("2", StringUtils.join(CHAR_PRIM_LIST, SEPARATOR_CHAR, 1, 2)); 1177 assertNull(StringUtils.join((char[]) null, SEPARATOR_CHAR, 0, 1)); 1178 assertEquals(StringUtils.EMPTY, StringUtils.join(CHAR_PRIM_LIST, SEPARATOR_CHAR, 0, 0)); 1179 assertEquals(StringUtils.EMPTY, StringUtils.join(CHAR_PRIM_LIST, SEPARATOR_CHAR, 1, 0)); 1180 } 1181 1182 @Test testJoin_ArrayOfDoubles()1183 public void testJoin_ArrayOfDoubles() { 1184 assertNull(StringUtils.join((double[]) null, ',')); 1185 assertEquals("1.0;2.0", StringUtils.join(DOUBLE_PRIM_LIST, SEPARATOR_CHAR)); 1186 assertEquals("2.0", StringUtils.join(DOUBLE_PRIM_LIST, SEPARATOR_CHAR, 1, 2)); 1187 assertNull(StringUtils.join((double[]) null, SEPARATOR_CHAR, 0, 1)); 1188 assertEquals(StringUtils.EMPTY, StringUtils.join(DOUBLE_PRIM_LIST, SEPARATOR_CHAR, 0, 0)); 1189 assertEquals(StringUtils.EMPTY, StringUtils.join(DOUBLE_PRIM_LIST, SEPARATOR_CHAR, 1, 0)); 1190 } 1191 1192 @Test testJoin_ArrayOfFloats()1193 public void testJoin_ArrayOfFloats() { 1194 assertNull(StringUtils.join((float[]) null, ',')); 1195 assertEquals("1.0;2.0", StringUtils.join(FLOAT_PRIM_LIST, SEPARATOR_CHAR)); 1196 assertEquals("2.0", StringUtils.join(FLOAT_PRIM_LIST, SEPARATOR_CHAR, 1, 2)); 1197 assertNull(StringUtils.join((float[]) null, SEPARATOR_CHAR, 0, 1)); 1198 assertEquals(StringUtils.EMPTY, StringUtils.join(FLOAT_PRIM_LIST, SEPARATOR_CHAR, 0, 0)); 1199 assertEquals(StringUtils.EMPTY, StringUtils.join(FLOAT_PRIM_LIST, SEPARATOR_CHAR, 1, 0)); 1200 } 1201 1202 @Test testJoin_ArrayOfInts()1203 public void testJoin_ArrayOfInts() { 1204 assertNull(StringUtils.join((int[]) null, ',')); 1205 assertEquals("1;2", StringUtils.join(INT_PRIM_LIST, SEPARATOR_CHAR)); 1206 assertEquals("2", StringUtils.join(INT_PRIM_LIST, SEPARATOR_CHAR, 1, 2)); 1207 assertNull(StringUtils.join((int[]) null, SEPARATOR_CHAR, 0, 1)); 1208 assertEquals(StringUtils.EMPTY, StringUtils.join(INT_PRIM_LIST, SEPARATOR_CHAR, 0, 0)); 1209 assertEquals(StringUtils.EMPTY, StringUtils.join(INT_PRIM_LIST, SEPARATOR_CHAR, 1, 0)); 1210 } 1211 1212 @Test testJoin_ArrayOfLongs()1213 public void testJoin_ArrayOfLongs() { 1214 assertNull(StringUtils.join((long[]) null, ',')); 1215 assertEquals("1;2", StringUtils.join(LONG_PRIM_LIST, SEPARATOR_CHAR)); 1216 assertEquals("2", StringUtils.join(LONG_PRIM_LIST, SEPARATOR_CHAR, 1, 2)); 1217 assertNull(StringUtils.join((long[]) null, SEPARATOR_CHAR, 0, 1)); 1218 assertEquals(StringUtils.EMPTY, StringUtils.join(LONG_PRIM_LIST, SEPARATOR_CHAR, 0, 0)); 1219 assertEquals(StringUtils.EMPTY, StringUtils.join(LONG_PRIM_LIST, SEPARATOR_CHAR, 1, 0)); 1220 } 1221 1222 @Test testJoin_ArrayOfShorts()1223 public void testJoin_ArrayOfShorts() { 1224 assertNull(StringUtils.join((short[]) null, ',')); 1225 assertEquals("1;2", StringUtils.join(SHORT_PRIM_LIST, SEPARATOR_CHAR)); 1226 assertEquals("2", StringUtils.join(SHORT_PRIM_LIST, SEPARATOR_CHAR, 1, 2)); 1227 assertNull(StringUtils.join((short[]) null, SEPARATOR_CHAR, 0, 1)); 1228 assertEquals(StringUtils.EMPTY, StringUtils.join(SHORT_PRIM_LIST, SEPARATOR_CHAR, 0, 0)); 1229 assertEquals(StringUtils.EMPTY, StringUtils.join(SHORT_PRIM_LIST, SEPARATOR_CHAR, 1, 0)); 1230 } 1231 1232 @Test testJoin_ArrayString_EmptyDelimiter()1233 public void testJoin_ArrayString_EmptyDelimiter() { 1234 assertNull(StringUtils.join((Object[]) null, null)); 1235 assertEquals(TEXT_LIST_NOSEP, StringUtils.join(ARRAY_LIST, null)); 1236 assertEquals(TEXT_LIST_NOSEP, StringUtils.join(ARRAY_LIST, "")); 1237 1238 assertEquals("", StringUtils.join(NULL_ARRAY_LIST, null)); 1239 1240 assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST, null)); 1241 assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST, "")); 1242 1243 assertEquals("", StringUtils.join(MIXED_ARRAY_LIST, "", 0, MIXED_ARRAY_LIST.length - 1)); 1244 } 1245 1246 @ParameterizedTest 1247 @ValueSource(strings = {",", ";", Supplementary.CharU20000, Supplementary.CharU20001}) testJoin_ArrayString_NonEmptyDelimiter(final String delimiter)1248 public void testJoin_ArrayString_NonEmptyDelimiter(final String delimiter) { 1249 assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST, delimiter)); 1250 1251 assertEquals(String.join(delimiter, ARRAY_LIST), StringUtils.join(ARRAY_LIST, delimiter)); 1252 assertEquals(delimiter + delimiter + "foo", StringUtils.join(MIXED_ARRAY_LIST, delimiter)); 1253 assertEquals(String.join(delimiter, "foo", "2"), StringUtils.join(MIXED_TYPE_LIST, delimiter)); 1254 1255 assertEquals(delimiter, StringUtils.join(MIXED_ARRAY_LIST, delimiter, 0, MIXED_ARRAY_LIST.length - 1)); 1256 assertEquals("foo", StringUtils.join(MIXED_TYPE_LIST, delimiter, 0, 1)); 1257 assertEquals(String.join(delimiter, "foo", "2"), StringUtils.join(MIXED_TYPE_LIST, delimiter, 0, 2)); 1258 assertEquals("2", StringUtils.join(MIXED_TYPE_LIST, delimiter, 1, 2)); 1259 assertEquals("", StringUtils.join(MIXED_TYPE_LIST, delimiter, 2, 1)); 1260 } 1261 1262 @Test testJoin_IterableChar()1263 public void testJoin_IterableChar() { 1264 assertNull(StringUtils.join((Iterable<?>) null, ',')); 1265 assertEquals(TEXT_LIST_CHAR, StringUtils.join(Arrays.asList(ARRAY_LIST), SEPARATOR_CHAR)); 1266 assertEquals("", StringUtils.join(Arrays.asList(NULL_ARRAY_LIST), SEPARATOR_CHAR)); 1267 assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST), SEPARATOR_CHAR)); 1268 assertEquals("foo", StringUtils.join(Collections.singleton("foo"), 'x')); 1269 } 1270 1271 @Test testJoin_IterableString()1272 public void testJoin_IterableString() { 1273 assertNull(StringUtils.join((Iterable<?>) null, null)); 1274 assertEquals(TEXT_LIST_NOSEP, StringUtils.join(Arrays.asList(ARRAY_LIST), null)); 1275 assertEquals(TEXT_LIST_NOSEP, StringUtils.join(Arrays.asList(ARRAY_LIST), "")); 1276 assertEquals("foo", StringUtils.join(Collections.singleton("foo"), "x")); 1277 assertEquals("foo", StringUtils.join(Collections.singleton("foo"), null)); 1278 1279 assertEquals("", StringUtils.join(Arrays.asList(NULL_ARRAY_LIST), null)); 1280 1281 assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST), null)); 1282 assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST), "")); 1283 assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST), SEPARATOR)); 1284 1285 assertEquals(TEXT_LIST, StringUtils.join(Arrays.asList(ARRAY_LIST), SEPARATOR)); 1286 } 1287 1288 @Test testJoin_IteratorChar()1289 public void testJoin_IteratorChar() { 1290 assertNull(StringUtils.join((Iterator<?>) null, ',')); 1291 assertEquals(TEXT_LIST_CHAR, StringUtils.join(Arrays.asList(ARRAY_LIST).iterator(), SEPARATOR_CHAR)); 1292 assertEquals("", StringUtils.join(Arrays.asList(NULL_ARRAY_LIST).iterator(), SEPARATOR_CHAR)); 1293 assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST).iterator(), SEPARATOR_CHAR)); 1294 assertEquals("foo", StringUtils.join(Collections.singleton("foo").iterator(), 'x')); 1295 assertEquals("null", StringUtils.join(Arrays.asList(NULL_TO_STRING_LIST).iterator(), SEPARATOR_CHAR)); 1296 } 1297 1298 @Test testJoin_IteratorString()1299 public void testJoin_IteratorString() { 1300 assertNull(StringUtils.join((Iterator<?>) null, null)); 1301 assertEquals(TEXT_LIST_NOSEP, StringUtils.join(Arrays.asList(ARRAY_LIST).iterator(), null)); 1302 assertEquals(TEXT_LIST_NOSEP, StringUtils.join(Arrays.asList(ARRAY_LIST).iterator(), "")); 1303 assertEquals("foo", StringUtils.join(Collections.singleton("foo").iterator(), "x")); 1304 assertEquals("foo", StringUtils.join(Collections.singleton("foo").iterator(), null)); 1305 1306 assertEquals("", StringUtils.join(Arrays.asList(NULL_ARRAY_LIST).iterator(), null)); 1307 1308 assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST).iterator(), null)); 1309 assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST).iterator(), "")); 1310 assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST).iterator(), SEPARATOR)); 1311 1312 assertEquals(TEXT_LIST, StringUtils.join(Arrays.asList(ARRAY_LIST).iterator(), SEPARATOR)); 1313 1314 assertEquals("null", StringUtils.join(Arrays.asList(NULL_TO_STRING_LIST).iterator(), SEPARATOR)); 1315 } 1316 1317 @Test testJoin_List_EmptyDelimiter()1318 public void testJoin_List_EmptyDelimiter() { 1319 assertNull(StringUtils.join((List<String>) null, null)); 1320 assertEquals(TEXT_LIST_NOSEP, StringUtils.join(STRING_LIST, null)); 1321 assertEquals(TEXT_LIST_NOSEP, StringUtils.join(STRING_LIST, "")); 1322 1323 assertEquals("", StringUtils.join(NULL_STRING_LIST, null)); 1324 1325 assertEquals("", StringUtils.join(EMPTY_STRING_LIST, null)); 1326 assertEquals("", StringUtils.join(EMPTY_STRING_LIST, "")); 1327 1328 assertEquals("", StringUtils.join(MIXED_STRING_LIST, "", 0, MIXED_STRING_LIST.size()- 1)); 1329 } 1330 1331 @Test testJoin_List_CharDelimiter()1332 public void testJoin_List_CharDelimiter() { 1333 assertEquals("/", StringUtils.join(MIXED_STRING_LIST, '/', 0, MIXED_STRING_LIST.size() - 1)); 1334 assertEquals("foo", StringUtils.join(MIXED_TYPE_OBJECT_LIST, '/', 0, 1)); 1335 assertEquals("foo/2", StringUtils.join(MIXED_TYPE_OBJECT_LIST, '/', 0, 2)); 1336 assertEquals("2", StringUtils.join(MIXED_TYPE_OBJECT_LIST, '/', 1, 2)); 1337 assertEquals("", StringUtils.join(MIXED_TYPE_OBJECT_LIST, '/', 2, 1)); 1338 assertNull(null, StringUtils.join((List<?>) null, '/', 0, 1)); 1339 } 1340 1341 @ParameterizedTest 1342 @ValueSource(strings = {",", ";", Supplementary.CharU20000, Supplementary.CharU20001}) testJoin_List_NonEmptyDelimiter(final String delimiter)1343 public void testJoin_List_NonEmptyDelimiter(final String delimiter) { 1344 assertEquals("", StringUtils.join(EMPTY_STRING_LIST, delimiter)); 1345 1346 assertEquals(String.join(delimiter, STRING_LIST), StringUtils.join(STRING_LIST, delimiter)); 1347 assertEquals(delimiter + delimiter + "foo", StringUtils.join(MIXED_STRING_LIST, delimiter)); 1348 assertEquals(String.join(delimiter, "foo", "2"), StringUtils.join(MIXED_TYPE_OBJECT_LIST, delimiter)); 1349 1350 assertEquals(delimiter, StringUtils.join(MIXED_STRING_LIST, delimiter, 0, MIXED_STRING_LIST.size() - 1)); 1351 assertEquals("foo", StringUtils.join(MIXED_TYPE_OBJECT_LIST, delimiter, 0, 1)); 1352 assertEquals(String.join(delimiter, "foo", "2"), StringUtils.join(MIXED_TYPE_OBJECT_LIST, delimiter, 0, 2)); 1353 assertEquals("2", StringUtils.join(MIXED_TYPE_OBJECT_LIST, delimiter, 1, 2)); 1354 assertEquals("", StringUtils.join(MIXED_TYPE_OBJECT_LIST, delimiter, 2, 1)); 1355 assertNull(null, StringUtils.join((List<?>) null, delimiter, 0, 1)); 1356 } 1357 1358 @Test testJoin_Objectarray()1359 public void testJoin_Objectarray() { 1360 // assertNull(StringUtils.join(null)); // generates warning 1361 assertNull(StringUtils.join((Object[]) null)); // equivalent explicit cast 1362 // test additional varargs calls 1363 assertEquals("", StringUtils.join()); // empty array 1364 assertEquals("", StringUtils.join((Object) null)); // => new Object[]{null} 1365 1366 assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST)); 1367 assertEquals("", StringUtils.join(NULL_ARRAY_LIST)); 1368 assertEquals("null", StringUtils.join(NULL_TO_STRING_LIST)); 1369 assertEquals("abc", StringUtils.join("a", "b", "c")); 1370 assertEquals("a", StringUtils.join(null, "a", "")); 1371 assertEquals("foo", StringUtils.join(MIXED_ARRAY_LIST)); 1372 assertEquals("foo2", StringUtils.join(MIXED_TYPE_LIST)); 1373 } 1374 1375 @Disabled 1376 @Test testLang1593()1377 public void testLang1593() { 1378 final int[] arr = {1, 2, 3, 4, 5, 6, 7}; 1379 final String expected = StringUtils.join(arr, '-'); 1380 final String actual = StringUtils.join(arr, "-"); 1381 assertEquals(expected, actual); 1382 } 1383 1384 @Test testJoin_Objects()1385 public void testJoin_Objects() { 1386 assertEquals("abc", StringUtils.join("a", "b", "c")); 1387 assertEquals("a", StringUtils.join(null, "", "a")); 1388 assertNull(StringUtils.join((Object[]) null)); 1389 } 1390 1391 @ParameterizedTest 1392 @ValueSource(strings = {",", ";", Supplementary.CharU20000, Supplementary.CharU20001}) testJoinWith(final String delimiter)1393 public void testJoinWith(final String delimiter) { 1394 assertEquals("", StringUtils.joinWith(delimiter)); // empty array 1395 assertEquals("", StringUtils.joinWith(delimiter, (Object[]) NULL_ARRAY_LIST)); 1396 assertEquals("null", StringUtils.joinWith(delimiter, NULL_TO_STRING_LIST)); // toString method prints 'null' 1397 1398 assertEquals(String.join(delimiter, "a", "b", "c"), StringUtils.joinWith(delimiter, "a", "b", "c")); 1399 assertEquals(String.join(delimiter, "", "a", ""), StringUtils.joinWith(delimiter, null, "a", "")); 1400 assertEquals(String.join(delimiter, "", "a", ""), StringUtils.joinWith(delimiter, "", "a", "")); 1401 1402 assertEquals("ab", StringUtils.joinWith(null, "a", "b")); 1403 } 1404 1405 @Test testJoinWithThrowsException()1406 public void testJoinWithThrowsException() { 1407 assertThrows(IllegalArgumentException.class, () -> StringUtils.joinWith(",", (Object[]) null)); 1408 } 1409 1410 @Test testLang623()1411 public void testLang623() { 1412 assertEquals("t", StringUtils.replaceChars("\u00DE", '\u00DE', 't')); 1413 assertEquals("t", StringUtils.replaceChars("\u00FE", '\u00FE', 't')); 1414 } 1415 1416 @Test testLANG666()1417 public void testLANG666() { 1418 assertEquals("12", StringUtils.stripEnd("120.00", ".0")); 1419 assertEquals("121", StringUtils.stripEnd("121.00", ".0")); 1420 } 1421 1422 @Test testLeftPad_StringInt()1423 public void testLeftPad_StringInt() { 1424 assertNull(StringUtils.leftPad(null, 5)); 1425 assertEquals(" ", StringUtils.leftPad("", 5)); 1426 assertEquals(" abc", StringUtils.leftPad("abc", 5)); 1427 assertEquals("abc", StringUtils.leftPad("abc", 2)); 1428 } 1429 1430 @Test testLeftPad_StringIntChar()1431 public void testLeftPad_StringIntChar() { 1432 assertNull(StringUtils.leftPad(null, 5, ' ')); 1433 assertEquals(" ", StringUtils.leftPad("", 5, ' ')); 1434 assertEquals(" abc", StringUtils.leftPad("abc", 5, ' ')); 1435 assertEquals("xxabc", StringUtils.leftPad("abc", 5, 'x')); 1436 assertEquals("\uffff\uffffabc", StringUtils.leftPad("abc", 5, '\uffff')); 1437 assertEquals("abc", StringUtils.leftPad("abc", 2, ' ')); 1438 final String str = StringUtils.leftPad("aaa", 10000, 'a'); // bigger than pad length 1439 assertEquals(10000, str.length()); 1440 assertTrue(StringUtils.containsOnly(str, 'a')); 1441 } 1442 1443 @Test testLeftPad_StringIntString()1444 public void testLeftPad_StringIntString() { 1445 assertNull(StringUtils.leftPad(null, 5, "-+")); 1446 assertNull(StringUtils.leftPad(null, 5, null)); 1447 assertEquals(" ", StringUtils.leftPad("", 5, " ")); 1448 assertEquals("-+-+abc", StringUtils.leftPad("abc", 7, "-+")); 1449 assertEquals("-+~abc", StringUtils.leftPad("abc", 6, "-+~")); 1450 assertEquals("-+abc", StringUtils.leftPad("abc", 5, "-+~")); 1451 assertEquals("abc", StringUtils.leftPad("abc", 2, " ")); 1452 assertEquals("abc", StringUtils.leftPad("abc", -1, " ")); 1453 assertEquals(" abc", StringUtils.leftPad("abc", 5, null)); 1454 assertEquals(" abc", StringUtils.leftPad("abc", 5, "")); 1455 } 1456 1457 @Test testLength_CharBuffer()1458 public void testLength_CharBuffer() { 1459 assertEquals(0, StringUtils.length(CharBuffer.wrap(""))); 1460 assertEquals(1, StringUtils.length(CharBuffer.wrap("A"))); 1461 assertEquals(1, StringUtils.length(CharBuffer.wrap(" "))); 1462 assertEquals(8, StringUtils.length(CharBuffer.wrap("ABCDEFGH"))); 1463 } 1464 1465 @Test testLengthString()1466 public void testLengthString() { 1467 assertEquals(0, StringUtils.length(null)); 1468 assertEquals(0, StringUtils.length("")); 1469 assertEquals(0, StringUtils.length(StringUtils.EMPTY)); 1470 assertEquals(1, StringUtils.length("A")); 1471 assertEquals(1, StringUtils.length(" ")); 1472 assertEquals(8, StringUtils.length("ABCDEFGH")); 1473 } 1474 1475 @Test testLengthStringBuffer()1476 public void testLengthStringBuffer() { 1477 assertEquals(0, StringUtils.length(new StringBuffer(""))); 1478 assertEquals(0, StringUtils.length(new StringBuffer(StringUtils.EMPTY))); 1479 assertEquals(1, StringUtils.length(new StringBuffer("A"))); 1480 assertEquals(1, StringUtils.length(new StringBuffer(" "))); 1481 assertEquals(8, StringUtils.length(new StringBuffer("ABCDEFGH"))); 1482 } 1483 1484 @Test testLengthStringBuilder()1485 public void testLengthStringBuilder() { 1486 assertEquals(0, StringUtils.length(new StringBuilder(""))); 1487 assertEquals(0, StringUtils.length(new StringBuilder(StringUtils.EMPTY))); 1488 assertEquals(1, StringUtils.length(new StringBuilder("A"))); 1489 assertEquals(1, StringUtils.length(new StringBuilder(" "))); 1490 assertEquals(8, StringUtils.length(new StringBuilder("ABCDEFGH"))); 1491 } 1492 1493 @Test testLowerCase()1494 public void testLowerCase() { 1495 assertNull(StringUtils.lowerCase(null)); 1496 assertNull(StringUtils.lowerCase(null, Locale.ENGLISH)); 1497 assertEquals("foo test thing", StringUtils.lowerCase("fOo test THING"), "lowerCase(String) failed"); 1498 assertEquals("", StringUtils.lowerCase(""), "lowerCase(empty-string) failed"); 1499 assertEquals("foo test thing", StringUtils.lowerCase("fOo test THING", Locale.ENGLISH), 1500 "lowerCase(String, Locale) failed"); 1501 assertEquals("", StringUtils.lowerCase("", Locale.ENGLISH), "lowerCase(empty-string, Locale) failed"); 1502 } 1503 1504 @Test testNormalizeSpace()1505 public void testNormalizeSpace() { 1506 // Java says a non-breaking whitespace is not a whitespace. 1507 assertFalse(Character.isWhitespace('\u00A0')); 1508 // 1509 assertNull(StringUtils.normalizeSpace(null)); 1510 assertEquals("", StringUtils.normalizeSpace("")); 1511 assertEquals("", StringUtils.normalizeSpace(" ")); 1512 assertEquals("", StringUtils.normalizeSpace("\t")); 1513 assertEquals("", StringUtils.normalizeSpace("\n")); 1514 assertEquals("", StringUtils.normalizeSpace("\u0009")); 1515 assertEquals("", StringUtils.normalizeSpace("\u000B")); 1516 assertEquals("", StringUtils.normalizeSpace("\u000C")); 1517 assertEquals("", StringUtils.normalizeSpace("\u001C")); 1518 assertEquals("", StringUtils.normalizeSpace("\u001D")); 1519 assertEquals("", StringUtils.normalizeSpace("\u001E")); 1520 assertEquals("", StringUtils.normalizeSpace("\u001F")); 1521 assertEquals("", StringUtils.normalizeSpace("\f")); 1522 assertEquals("", StringUtils.normalizeSpace("\r")); 1523 assertEquals("a", StringUtils.normalizeSpace(" a ")); 1524 assertEquals("a b c", StringUtils.normalizeSpace(" a b c ")); 1525 assertEquals("a b c", StringUtils.normalizeSpace("a\t\f\r b\u000B c\n")); 1526 assertEquals("a b c", StringUtils.normalizeSpace("a\t\f\r " + HARD_SPACE + HARD_SPACE + "b\u000B c\n")); 1527 assertEquals("b", StringUtils.normalizeSpace("\u0000b")); 1528 assertEquals("b", StringUtils.normalizeSpace("b\u0000")); 1529 } 1530 1531 @Test testOverlay_StringStringIntInt()1532 public void testOverlay_StringStringIntInt() { 1533 assertNull(StringUtils.overlay(null, null, 2, 4)); 1534 assertNull(StringUtils.overlay(null, null, -2, -4)); 1535 1536 assertEquals("", StringUtils.overlay("", null, 0, 0)); 1537 assertEquals("", StringUtils.overlay("", "", 0, 0)); 1538 assertEquals("zzzz", StringUtils.overlay("", "zzzz", 0, 0)); 1539 assertEquals("zzzz", StringUtils.overlay("", "zzzz", 2, 4)); 1540 assertEquals("zzzz", StringUtils.overlay("", "zzzz", -2, -4)); 1541 1542 assertEquals("abef", StringUtils.overlay("abcdef", null, 2, 4)); 1543 assertEquals("abef", StringUtils.overlay("abcdef", null, 4, 2)); 1544 assertEquals("abef", StringUtils.overlay("abcdef", "", 2, 4)); 1545 assertEquals("abef", StringUtils.overlay("abcdef", "", 4, 2)); 1546 assertEquals("abzzzzef", StringUtils.overlay("abcdef", "zzzz", 2, 4)); 1547 assertEquals("abzzzzef", StringUtils.overlay("abcdef", "zzzz", 4, 2)); 1548 1549 assertEquals("zzzzef", StringUtils.overlay("abcdef", "zzzz", -1, 4)); 1550 assertEquals("zzzzef", StringUtils.overlay("abcdef", "zzzz", 4, -1)); 1551 assertEquals("zzzzabcdef", StringUtils.overlay("abcdef", "zzzz", -2, -1)); 1552 assertEquals("zzzzabcdef", StringUtils.overlay("abcdef", "zzzz", -1, -2)); 1553 assertEquals("abcdzzzz", StringUtils.overlay("abcdef", "zzzz", 4, 10)); 1554 assertEquals("abcdzzzz", StringUtils.overlay("abcdef", "zzzz", 10, 4)); 1555 assertEquals("abcdefzzzz", StringUtils.overlay("abcdef", "zzzz", 8, 10)); 1556 assertEquals("abcdefzzzz", StringUtils.overlay("abcdef", "zzzz", 10, 8)); 1557 } 1558 1559 /** 1560 * Tests {@code prependIfMissing}. 1561 */ 1562 @Test testPrependIfMissing()1563 public void testPrependIfMissing() { 1564 assertNull(StringUtils.prependIfMissing(null, null), "prependIfMissing(null,null)"); 1565 assertEquals("abc", StringUtils.prependIfMissing("abc", null), "prependIfMissing(abc,null)"); 1566 assertEquals("xyz", StringUtils.prependIfMissing("", "xyz"), "prependIfMissing(\"\",xyz)"); 1567 assertEquals("xyzabc", StringUtils.prependIfMissing("abc", "xyz"), "prependIfMissing(abc,xyz)"); 1568 assertEquals("xyzabc", StringUtils.prependIfMissing("xyzabc", "xyz"), "prependIfMissing(xyzabc,xyz)"); 1569 assertEquals("xyzXYZabc", StringUtils.prependIfMissing("XYZabc", "xyz"), "prependIfMissing(XYZabc,xyz)"); 1570 1571 assertNull(StringUtils.prependIfMissing(null, null, (CharSequence[]) null), "prependIfMissing(null,null null)"); 1572 assertEquals("abc", StringUtils.prependIfMissing("abc", null, (CharSequence[]) null), "prependIfMissing(abc,null,null)"); 1573 assertEquals("xyz", StringUtils.prependIfMissing("", "xyz", (CharSequence[]) null), "prependIfMissing(\"\",xyz,null)"); 1574 assertEquals("xyzabc", StringUtils.prependIfMissing("abc", "xyz", null), "prependIfMissing(abc,xyz,{null})"); 1575 assertEquals("abc", StringUtils.prependIfMissing("abc", "xyz", ""), "prependIfMissing(abc,xyz,\"\")"); 1576 assertEquals("xyzabc", StringUtils.prependIfMissing("abc", "xyz", "mno"), "prependIfMissing(abc,xyz,mno)"); 1577 assertEquals("xyzabc", StringUtils.prependIfMissing("xyzabc", "xyz", "mno"), "prependIfMissing(xyzabc,xyz,mno)"); 1578 assertEquals("mnoabc", StringUtils.prependIfMissing("mnoabc", "xyz", "mno"), "prependIfMissing(mnoabc,xyz,mno)"); 1579 assertEquals("xyzXYZabc", StringUtils.prependIfMissing("XYZabc", "xyz", "mno"), "prependIfMissing(XYZabc,xyz,mno)"); 1580 assertEquals("xyzMNOabc", StringUtils.prependIfMissing("MNOabc", "xyz", "mno"), "prependIfMissing(MNOabc,xyz,mno)"); 1581 } 1582 1583 /** 1584 * Tests {@code prependIfMissingIgnoreCase}. 1585 */ 1586 @Test testPrependIfMissingIgnoreCase()1587 public void testPrependIfMissingIgnoreCase() { 1588 assertNull(StringUtils.prependIfMissingIgnoreCase(null, null), "prependIfMissingIgnoreCase(null,null)"); 1589 assertEquals("abc", StringUtils.prependIfMissingIgnoreCase("abc", null), "prependIfMissingIgnoreCase(abc,null)"); 1590 assertEquals("xyz", StringUtils.prependIfMissingIgnoreCase("", "xyz"), "prependIfMissingIgnoreCase(\"\",xyz)"); 1591 assertEquals("xyzabc", StringUtils.prependIfMissingIgnoreCase("abc", "xyz"), "prependIfMissingIgnoreCase(abc,xyz)"); 1592 assertEquals("xyzabc", StringUtils.prependIfMissingIgnoreCase("xyzabc", "xyz"), "prependIfMissingIgnoreCase(xyzabc,xyz)"); 1593 assertEquals("XYZabc", StringUtils.prependIfMissingIgnoreCase("XYZabc", "xyz"), "prependIfMissingIgnoreCase(XYZabc,xyz)"); 1594 1595 assertNull(StringUtils.prependIfMissingIgnoreCase(null, null, (CharSequence[]) null), "prependIfMissingIgnoreCase(null,null null)"); 1596 assertEquals("abc", StringUtils.prependIfMissingIgnoreCase("abc", null, (CharSequence[]) null), "prependIfMissingIgnoreCase(abc,null,null)"); 1597 assertEquals("xyz", StringUtils.prependIfMissingIgnoreCase("", "xyz", (CharSequence[]) null), "prependIfMissingIgnoreCase(\"\",xyz,null)"); 1598 assertEquals("xyzabc", StringUtils.prependIfMissingIgnoreCase("abc", "xyz", null), "prependIfMissingIgnoreCase(abc,xyz,{null})"); 1599 assertEquals("abc", StringUtils.prependIfMissingIgnoreCase("abc", "xyz", ""), "prependIfMissingIgnoreCase(abc,xyz,\"\")"); 1600 assertEquals("xyzabc", StringUtils.prependIfMissingIgnoreCase("abc", "xyz", "mno"), "prependIfMissingIgnoreCase(abc,xyz,mno)"); 1601 assertEquals("xyzabc", StringUtils.prependIfMissingIgnoreCase("xyzabc", "xyz", "mno"), "prependIfMissingIgnoreCase(xyzabc,xyz,mno)"); 1602 assertEquals("mnoabc", StringUtils.prependIfMissingIgnoreCase("mnoabc", "xyz", "mno"), "prependIfMissingIgnoreCase(mnoabc,xyz,mno)"); 1603 assertEquals("XYZabc", StringUtils.prependIfMissingIgnoreCase("XYZabc", "xyz", "mno"), "prependIfMissingIgnoreCase(XYZabc,xyz,mno)"); 1604 assertEquals("MNOabc", StringUtils.prependIfMissingIgnoreCase("MNOabc", "xyz", "mno"), "prependIfMissingIgnoreCase(MNOabc,xyz,mno)"); 1605 } 1606 1607 @Test testReCapitalize()1608 public void testReCapitalize() { 1609 // reflection type of tests: Sentences. 1610 assertEquals(SENTENCE_UNCAP, StringUtils.uncapitalize(StringUtils.capitalize(SENTENCE_UNCAP)), 1611 "uncapitalize(capitalize(String)) failed"); 1612 assertEquals(SENTENCE_CAP, StringUtils.capitalize(StringUtils.uncapitalize(SENTENCE_CAP)), 1613 "capitalize(uncapitalize(String)) failed"); 1614 1615 // reflection type of tests: One word. 1616 assertEquals(FOO_UNCAP, StringUtils.uncapitalize(StringUtils.capitalize(FOO_UNCAP)), 1617 "uncapitalize(capitalize(String)) failed"); 1618 assertEquals(FOO_CAP, StringUtils.capitalize(StringUtils.uncapitalize(FOO_CAP)), 1619 "capitalize(uncapitalize(String)) failed"); 1620 } 1621 1622 @Test testRemove_char()1623 public void testRemove_char() { 1624 // StringUtils.remove(null, *) = null 1625 assertNull(StringUtils.remove(null, null)); 1626 assertNull(StringUtils.remove(null, 'a')); 1627 1628 // StringUtils.remove("", *) = "" 1629 assertEquals("", StringUtils.remove("", null)); 1630 assertEquals("", StringUtils.remove("", 'a')); 1631 1632 // StringUtils.remove("queued", 'u') = "qeed" 1633 assertEquals("qeed", StringUtils.remove("queued", 'u')); 1634 1635 // StringUtils.remove("queued", 'z') = "queued" 1636 assertEquals("queued", StringUtils.remove("queued", 'z')); 1637 } 1638 1639 @Test testRemove_String()1640 public void testRemove_String() { 1641 // StringUtils.remove(null, *) = null 1642 assertNull(StringUtils.remove(null, null)); 1643 assertNull(StringUtils.remove(null, "")); 1644 assertNull(StringUtils.remove(null, "a")); 1645 1646 // StringUtils.remove("", *) = "" 1647 assertEquals("", StringUtils.remove("", null)); 1648 assertEquals("", StringUtils.remove("", "")); 1649 assertEquals("", StringUtils.remove("", "a")); 1650 1651 // StringUtils.remove(*, null) = * 1652 assertNull(StringUtils.remove(null, null)); 1653 assertEquals("", StringUtils.remove("", null)); 1654 assertEquals("a", StringUtils.remove("a", null)); 1655 1656 // StringUtils.remove(*, "") = * 1657 assertNull(StringUtils.remove(null, "")); 1658 assertEquals("", StringUtils.remove("", "")); 1659 assertEquals("a", StringUtils.remove("a", "")); 1660 1661 // StringUtils.remove("queued", "ue") = "qd" 1662 assertEquals("qd", StringUtils.remove("queued", "ue")); 1663 1664 // StringUtils.remove("queued", "zz") = "queued" 1665 assertEquals("queued", StringUtils.remove("queued", "zz")); 1666 } 1667 1668 @Test testRemoveAll_StringString()1669 public void testRemoveAll_StringString() { 1670 assertNull(StringUtils.removeAll(null, "")); 1671 assertEquals("any", StringUtils.removeAll("any", null)); 1672 1673 assertEquals("any", StringUtils.removeAll("any", "")); 1674 assertEquals("", StringUtils.removeAll("any", ".*")); 1675 assertEquals("", StringUtils.removeAll("any", ".+")); 1676 assertEquals("", StringUtils.removeAll("any", ".?")); 1677 1678 assertEquals("A\nB", StringUtils.removeAll("A<__>\n<__>B", "<.*>")); 1679 assertEquals("AB", StringUtils.removeAll("A<__>\n<__>B", "(?s)<.*>")); 1680 assertEquals("ABC123", StringUtils.removeAll("ABCabc123abc", "[a-z]")); 1681 1682 assertThrows( 1683 PatternSyntaxException.class, 1684 () -> StringUtils.removeAll("any", "{badRegexSyntax}"), 1685 "StringUtils.removeAll expecting PatternSyntaxException"); 1686 } 1687 1688 @Test testRemoveEnd()1689 public void testRemoveEnd() { 1690 // StringUtils.removeEnd("", *) = "" 1691 assertNull(StringUtils.removeEnd(null, null)); 1692 assertNull(StringUtils.removeEnd(null, "")); 1693 assertNull(StringUtils.removeEnd(null, "a")); 1694 1695 // StringUtils.removeEnd(*, null) = * 1696 assertEquals(StringUtils.removeEnd("", null), ""); 1697 assertEquals(StringUtils.removeEnd("", ""), ""); 1698 assertEquals(StringUtils.removeEnd("", "a"), ""); 1699 1700 // All others: 1701 assertEquals(StringUtils.removeEnd("www.domain.com.", ".com"), "www.domain.com."); 1702 assertEquals(StringUtils.removeEnd("www.domain.com", ".com"), "www.domain"); 1703 assertEquals(StringUtils.removeEnd("www.domain", ".com"), "www.domain"); 1704 assertEquals(StringUtils.removeEnd("domain.com", ""), "domain.com"); 1705 assertEquals(StringUtils.removeEnd("domain.com", null), "domain.com"); 1706 } 1707 1708 @Test testRemoveEndIgnoreCase()1709 public void testRemoveEndIgnoreCase() { 1710 // StringUtils.removeEndIgnoreCase("", *) = "" 1711 assertNull(StringUtils.removeEndIgnoreCase(null, null), "removeEndIgnoreCase(null, null)"); 1712 assertNull(StringUtils.removeEndIgnoreCase(null, ""), "removeEndIgnoreCase(null, \"\")"); 1713 assertNull(StringUtils.removeEndIgnoreCase(null, "a"), "removeEndIgnoreCase(null, \"a\")"); 1714 1715 // StringUtils.removeEnd(*, null) = * 1716 assertEquals(StringUtils.removeEndIgnoreCase("", null), "", "removeEndIgnoreCase(\"\", null)"); 1717 assertEquals(StringUtils.removeEndIgnoreCase("", ""), "", "removeEndIgnoreCase(\"\", \"\")"); 1718 assertEquals(StringUtils.removeEndIgnoreCase("", "a"), "", "removeEndIgnoreCase(\"\", \"a\")"); 1719 1720 // All others: 1721 assertEquals(StringUtils.removeEndIgnoreCase("www.domain.com.", ".com"), "www.domain.com.", "removeEndIgnoreCase(\"www.domain.com.\", \".com\")"); 1722 assertEquals(StringUtils.removeEndIgnoreCase("www.domain.com", ".com"), "www.domain", "removeEndIgnoreCase(\"www.domain.com\", \".com\")"); 1723 assertEquals(StringUtils.removeEndIgnoreCase("www.domain", ".com"), "www.domain", "removeEndIgnoreCase(\"www.domain\", \".com\")"); 1724 assertEquals(StringUtils.removeEndIgnoreCase("domain.com", ""), "domain.com", "removeEndIgnoreCase(\"domain.com\", \"\")"); 1725 assertEquals(StringUtils.removeEndIgnoreCase("domain.com", null), "domain.com", "removeEndIgnoreCase(\"domain.com\", null)"); 1726 1727 // Case-insensitive: 1728 assertEquals(StringUtils.removeEndIgnoreCase("www.domain.com", ".COM"), "www.domain", "removeEndIgnoreCase(\"www.domain.com\", \".COM\")"); 1729 assertEquals(StringUtils.removeEndIgnoreCase("www.domain.COM", ".com"), "www.domain", "removeEndIgnoreCase(\"www.domain.COM\", \".com\")"); 1730 } 1731 1732 @Test testRemoveFirst_StringString()1733 public void testRemoveFirst_StringString() { 1734 assertNull(StringUtils.removeFirst(null, "")); 1735 assertEquals("any", StringUtils.removeFirst("any", null)); 1736 1737 assertEquals("any", StringUtils.removeFirst("any", "")); 1738 assertEquals("", StringUtils.removeFirst("any", ".*")); 1739 assertEquals("", StringUtils.removeFirst("any", ".+")); 1740 assertEquals("bc", StringUtils.removeFirst("abc", ".?")); 1741 1742 assertEquals("A\n<__>B", StringUtils.removeFirst("A<__>\n<__>B", "<.*>")); 1743 assertEquals("AB", StringUtils.removeFirst("A<__>\n<__>B", "(?s)<.*>")); 1744 assertEquals("ABCbc123", StringUtils.removeFirst("ABCabc123", "[a-z]")); 1745 assertEquals("ABC123abc", StringUtils.removeFirst("ABCabc123abc", "[a-z]+")); 1746 1747 assertThrows( 1748 PatternSyntaxException.class, 1749 () -> StringUtils.removeFirst("any", "{badRegexSyntax}"), 1750 "StringUtils.removeFirst expecting PatternSyntaxException"); 1751 } 1752 1753 @Test testRemoveIgnoreCase_String()1754 public void testRemoveIgnoreCase_String() { 1755 // StringUtils.removeIgnoreCase(null, *) = null 1756 assertNull(StringUtils.removeIgnoreCase(null, null)); 1757 assertNull(StringUtils.removeIgnoreCase(null, "")); 1758 assertNull(StringUtils.removeIgnoreCase(null, "a")); 1759 1760 // StringUtils.removeIgnoreCase("", *) = "" 1761 assertEquals("", StringUtils.removeIgnoreCase("", null)); 1762 assertEquals("", StringUtils.removeIgnoreCase("", "")); 1763 assertEquals("", StringUtils.removeIgnoreCase("", "a")); 1764 1765 // StringUtils.removeIgnoreCase(*, null) = * 1766 assertNull(StringUtils.removeIgnoreCase(null, null)); 1767 assertEquals("", StringUtils.removeIgnoreCase("", null)); 1768 assertEquals("a", StringUtils.removeIgnoreCase("a", null)); 1769 1770 // StringUtils.removeIgnoreCase(*, "") = * 1771 assertNull(StringUtils.removeIgnoreCase(null, "")); 1772 assertEquals("", StringUtils.removeIgnoreCase("", "")); 1773 assertEquals("a", StringUtils.removeIgnoreCase("a", "")); 1774 1775 // StringUtils.removeIgnoreCase("queued", "ue") = "qd" 1776 assertEquals("qd", StringUtils.removeIgnoreCase("queued", "ue")); 1777 1778 // StringUtils.removeIgnoreCase("queued", "zz") = "queued" 1779 assertEquals("queued", StringUtils.removeIgnoreCase("queued", "zz")); 1780 1781 // IgnoreCase 1782 // StringUtils.removeIgnoreCase("quEUed", "UE") = "qd" 1783 assertEquals("qd", StringUtils.removeIgnoreCase("quEUed", "UE")); 1784 1785 // StringUtils.removeIgnoreCase("queued", "zZ") = "queued" 1786 assertEquals("queued", StringUtils.removeIgnoreCase("queued", "zZ")); 1787 1788 // StringUtils.removeIgnoreCase("\u0130x", "x") = "\u0130" 1789 assertEquals("\u0130", StringUtils.removeIgnoreCase("\u0130x", "x")); 1790 1791 // LANG-1453 1792 StringUtils.removeIgnoreCase("İa", "a"); 1793 } 1794 1795 @Test testRemovePattern_StringString()1796 public void testRemovePattern_StringString() { 1797 assertNull(StringUtils.removePattern(null, "")); 1798 assertEquals("any", StringUtils.removePattern("any", null)); 1799 1800 assertEquals("", StringUtils.removePattern("", "")); 1801 assertEquals("", StringUtils.removePattern("", ".*")); 1802 assertEquals("", StringUtils.removePattern("", ".+")); 1803 1804 assertEquals("AB", StringUtils.removePattern("A<__>\n<__>B", "<.*>")); 1805 assertEquals("AB", StringUtils.removePattern("A<__>\\n<__>B", "<.*>")); 1806 assertEquals("", StringUtils.removePattern("<A>x\\ny</A>", "<A>.*</A>")); 1807 assertEquals("", StringUtils.removePattern("<A>\nxy\n</A>", "<A>.*</A>")); 1808 1809 assertEquals("ABC123", StringUtils.removePattern("ABCabc123", "[a-z]")); 1810 } 1811 1812 @Test testRemoveStartChar()1813 public void testRemoveStartChar() { 1814 // StringUtils.removeStart("", *) = "" 1815 assertNull(StringUtils.removeStart(null, '\0')); 1816 assertNull(StringUtils.removeStart(null, 'a')); 1817 1818 // StringUtils.removeStart(*, null) = * 1819 assertEquals(StringUtils.removeStart("", '\0'), ""); 1820 assertEquals(StringUtils.removeStart("", 'a'), ""); 1821 1822 // All others: 1823 assertEquals(StringUtils.removeStart("/path", '/'), "path"); 1824 assertEquals(StringUtils.removeStart("path", '/'), "path"); 1825 assertEquals(StringUtils.removeStart("path", '\0'), "path"); 1826 } 1827 1828 @Test testRemoveStartString()1829 public void testRemoveStartString() { 1830 // StringUtils.removeStart("", *) = "" 1831 assertNull(StringUtils.removeStart(null, null)); 1832 assertNull(StringUtils.removeStart(null, "")); 1833 assertNull(StringUtils.removeStart(null, "a")); 1834 1835 // StringUtils.removeStart(*, null) = * 1836 assertEquals(StringUtils.removeStart("", null), ""); 1837 assertEquals(StringUtils.removeStart("", ""), ""); 1838 assertEquals(StringUtils.removeStart("", "a"), ""); 1839 1840 // All others: 1841 assertEquals(StringUtils.removeStart("www.domain.com", "www."), "domain.com"); 1842 assertEquals(StringUtils.removeStart("domain.com", "www."), "domain.com"); 1843 assertEquals(StringUtils.removeStart("domain.com", ""), "domain.com"); 1844 assertEquals(StringUtils.removeStart("domain.com", null), "domain.com"); 1845 } 1846 1847 @Test testRemoveStartIgnoreCase()1848 public void testRemoveStartIgnoreCase() { 1849 // StringUtils.removeStart("", *) = "" 1850 assertNull(StringUtils.removeStartIgnoreCase(null, null), "removeStartIgnoreCase(null, null)"); 1851 assertNull(StringUtils.removeStartIgnoreCase(null, ""), "removeStartIgnoreCase(null, \"\")"); 1852 assertNull(StringUtils.removeStartIgnoreCase(null, "a"), "removeStartIgnoreCase(null, \"a\")"); 1853 1854 // StringUtils.removeStart(*, null) = * 1855 assertEquals(StringUtils.removeStartIgnoreCase("", null), "", "removeStartIgnoreCase(\"\", null)"); 1856 assertEquals(StringUtils.removeStartIgnoreCase("", ""), "", "removeStartIgnoreCase(\"\", \"\")"); 1857 assertEquals(StringUtils.removeStartIgnoreCase("", "a"), "", "removeStartIgnoreCase(\"\", \"a\")"); 1858 1859 // All others: 1860 assertEquals(StringUtils.removeStartIgnoreCase("www.domain.com", "www."), "domain.com", "removeStartIgnoreCase(\"www.domain.com\", \"www.\")"); 1861 assertEquals(StringUtils.removeStartIgnoreCase("domain.com", "www."), "domain.com", "removeStartIgnoreCase(\"domain.com\", \"www.\")"); 1862 assertEquals(StringUtils.removeStartIgnoreCase("domain.com", ""), "domain.com", "removeStartIgnoreCase(\"domain.com\", \"\")"); 1863 assertEquals(StringUtils.removeStartIgnoreCase("domain.com", null), "domain.com", "removeStartIgnoreCase(\"domain.com\", null)"); 1864 1865 // Case-insensitive: 1866 assertEquals(StringUtils.removeStartIgnoreCase("www.domain.com", "WWW."), "domain.com", "removeStartIgnoreCase(\"www.domain.com\", \"WWW.\")"); 1867 } 1868 1869 @Test testRepeat_CharInt()1870 public void testRepeat_CharInt() { 1871 assertEquals("zzz", StringUtils.repeat('z', 3)); 1872 assertEquals("", StringUtils.repeat('z', 0)); 1873 assertEquals("", StringUtils.repeat('z', -2)); 1874 } 1875 1876 @Test testRepeat_StringInt()1877 public void testRepeat_StringInt() { 1878 assertNull(StringUtils.repeat(null, 2)); 1879 assertEquals("", StringUtils.repeat("ab", 0)); 1880 assertEquals("", StringUtils.repeat("", 3)); 1881 assertEquals("aaa", StringUtils.repeat("a", 3)); 1882 assertEquals("", StringUtils.repeat("a", -2)); 1883 assertEquals("ababab", StringUtils.repeat("ab", 3)); 1884 assertEquals("abcabcabc", StringUtils.repeat("abc", 3)); 1885 final String str = StringUtils.repeat("a", 10000); // bigger than pad limit 1886 assertEquals(10000, str.length()); 1887 assertTrue(StringUtils.containsOnly(str, 'a')); 1888 } 1889 1890 @Test testRepeat_StringStringInt()1891 public void testRepeat_StringStringInt() { 1892 assertNull(StringUtils.repeat(null, null, 2)); 1893 assertNull(StringUtils.repeat(null, "x", 2)); 1894 assertEquals("", StringUtils.repeat("", null, 2)); 1895 1896 assertEquals("", StringUtils.repeat("ab", "", 0)); 1897 assertEquals("", StringUtils.repeat("", "", 2)); 1898 1899 assertEquals("xx", StringUtils.repeat("", "x", 3)); 1900 1901 assertEquals("?, ?, ?", StringUtils.repeat("?", ", ", 3)); 1902 } 1903 1904 /** 1905 * Test method for 'StringUtils.replaceEach(String, String[], String[])' 1906 */ 1907 @Test testReplace_StringStringArrayStringArray()1908 public void testReplace_StringStringArrayStringArray() { 1909 //JAVADOC TESTS START 1910 assertNull(StringUtils.replaceEach(null, new String[]{"a"}, new String[]{"b"})); 1911 assertEquals(StringUtils.replaceEach("", new String[]{"a"}, new String[]{"b"}), ""); 1912 assertEquals(StringUtils.replaceEach("aba", null, null), "aba"); 1913 assertEquals(StringUtils.replaceEach("aba", new String[0], null), "aba"); 1914 assertEquals(StringUtils.replaceEach("aba", null, new String[0]), "aba"); 1915 assertEquals(StringUtils.replaceEach("aba", new String[]{"a"}, null), "aba"); 1916 1917 assertEquals(StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}), "b"); 1918 assertEquals(StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}), "aba"); 1919 assertEquals(StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}), "wcte"); 1920 assertEquals(StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}), "dcte"); 1921 //JAVADOC TESTS END 1922 1923 assertEquals("bcc", StringUtils.replaceEach("abc", new String[]{"a", "b"}, new String[]{"b", "c"})); 1924 assertEquals("q651.506bera", StringUtils.replaceEach("d216.102oren", 1925 new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", 1926 "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", 1927 "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", 1928 "U", "V", "W", "X", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9"}, 1929 new String[]{"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "a", 1930 "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "N", "O", "P", "Q", 1931 "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "A", "B", "C", "D", "E", "F", "G", 1932 "H", "I", "J", "K", "L", "M", "5", "6", "7", "8", "9", "1", "2", "3", "4"})); 1933 1934 // Test null safety inside arrays - LANG-552 1935 assertEquals(StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{null}), "aba"); 1936 assertEquals(StringUtils.replaceEach("aba", new String[]{"a", "b"}, new String[]{"c", null}), "cbc"); 1937 1938 assertThrows( 1939 IllegalArgumentException.class, 1940 () -> StringUtils.replaceEach("abba", new String[]{"a"}, new String[]{"b", "a"}), 1941 "StringUtils.replaceEach(String, String[], String[]) expecting IllegalArgumentException"); 1942 } 1943 1944 /** 1945 * Test method for 'StringUtils.replaceEachRepeatedly(String, String[], String[])' 1946 */ 1947 @Test testReplace_StringStringArrayStringArrayBoolean()1948 public void testReplace_StringStringArrayStringArrayBoolean() { 1949 //JAVADOC TESTS START 1950 assertNull(StringUtils.replaceEachRepeatedly(null, new String[]{"a"}, new String[]{"b"})); 1951 assertEquals("", StringUtils.replaceEachRepeatedly("", new String[]{"a"}, new String[]{"b"})); 1952 assertEquals("aba", StringUtils.replaceEachRepeatedly("aba", null, null)); 1953 assertEquals("aba", StringUtils.replaceEachRepeatedly("aba", new String[0], null)); 1954 assertEquals("aba", StringUtils.replaceEachRepeatedly("aba", null, new String[0])); 1955 assertEquals("aba", StringUtils.replaceEachRepeatedly("aba", new String[0], null)); 1956 1957 assertEquals("b", StringUtils.replaceEachRepeatedly("aba", new String[]{"a"}, new String[]{""})); 1958 assertEquals("aba", StringUtils.replaceEachRepeatedly("aba", new String[]{null}, new String[]{"a"})); 1959 assertEquals("wcte", StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"})); 1960 assertEquals("tcte", StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"})); 1961 assertEquals("blaan", StringUtils.replaceEachRepeatedly("blllaan", new String[]{"llaan"}, new String[]{"laan"}) ); 1962 1963 assertThrows( 1964 IllegalStateException.class, 1965 () -> StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}), 1966 "Should be a circular reference"); 1967 1968 //JAVADOC TESTS END 1969 } 1970 1971 @Test testReplace_StringStringString()1972 public void testReplace_StringStringString() { 1973 assertNull(StringUtils.replace(null, null, null)); 1974 assertNull(StringUtils.replace(null, null, "any")); 1975 assertNull(StringUtils.replace(null, "any", null)); 1976 assertNull(StringUtils.replace(null, "any", "any")); 1977 1978 assertEquals("", StringUtils.replace("", null, null)); 1979 assertEquals("", StringUtils.replace("", null, "any")); 1980 assertEquals("", StringUtils.replace("", "any", null)); 1981 assertEquals("", StringUtils.replace("", "any", "any")); 1982 1983 assertEquals("FOO", StringUtils.replace("FOO", "", "any")); 1984 assertEquals("FOO", StringUtils.replace("FOO", null, "any")); 1985 assertEquals("FOO", StringUtils.replace("FOO", "F", null)); 1986 assertEquals("FOO", StringUtils.replace("FOO", null, null)); 1987 1988 assertEquals("", StringUtils.replace("foofoofoo", "foo", "")); 1989 assertEquals("barbarbar", StringUtils.replace("foofoofoo", "foo", "bar")); 1990 assertEquals("farfarfar", StringUtils.replace("foofoofoo", "oo", "ar")); 1991 } 1992 1993 @Test testReplace_StringStringStringInt()1994 public void testReplace_StringStringStringInt() { 1995 assertNull(StringUtils.replace(null, null, null, 2)); 1996 assertNull(StringUtils.replace(null, null, "any", 2)); 1997 assertNull(StringUtils.replace(null, "any", null, 2)); 1998 assertNull(StringUtils.replace(null, "any", "any", 2)); 1999 2000 assertEquals("", StringUtils.replace("", null, null, 2)); 2001 assertEquals("", StringUtils.replace("", null, "any", 2)); 2002 assertEquals("", StringUtils.replace("", "any", null, 2)); 2003 assertEquals("", StringUtils.replace("", "any", "any", 2)); 2004 2005 final String str = new String(new char[]{'o', 'o', 'f', 'o', 'o'}); 2006 assertSame(str, StringUtils.replace(str, "x", "", -1)); 2007 2008 assertEquals("f", StringUtils.replace("oofoo", "o", "", -1)); 2009 assertEquals("oofoo", StringUtils.replace("oofoo", "o", "", 0)); 2010 assertEquals("ofoo", StringUtils.replace("oofoo", "o", "", 1)); 2011 assertEquals("foo", StringUtils.replace("oofoo", "o", "", 2)); 2012 assertEquals("fo", StringUtils.replace("oofoo", "o", "", 3)); 2013 assertEquals("f", StringUtils.replace("oofoo", "o", "", 4)); 2014 2015 assertEquals("f", StringUtils.replace("oofoo", "o", "", -5)); 2016 assertEquals("f", StringUtils.replace("oofoo", "o", "", 1000)); 2017 } 2018 2019 @Test testReplaceAll_StringStringString()2020 public void testReplaceAll_StringStringString() { 2021 assertNull(StringUtils.replaceAll(null, "", "")); 2022 2023 assertEquals("any", StringUtils.replaceAll("any", null, "")); 2024 assertEquals("any", StringUtils.replaceAll("any", "", null)); 2025 2026 assertEquals("zzz", StringUtils.replaceAll("", "", "zzz")); 2027 assertEquals("zzz", StringUtils.replaceAll("", ".*", "zzz")); 2028 assertEquals("", StringUtils.replaceAll("", ".+", "zzz")); 2029 assertEquals("ZZaZZbZZcZZ", StringUtils.replaceAll("abc", "", "ZZ")); 2030 2031 assertEquals("z\nz", StringUtils.replaceAll("<__>\n<__>", "<.*>", "z")); 2032 assertEquals("z", StringUtils.replaceAll("<__>\n<__>", "(?s)<.*>", "z")); 2033 2034 assertEquals("ABC___123", StringUtils.replaceAll("ABCabc123", "[a-z]", "_")); 2035 assertEquals("ABC_123", StringUtils.replaceAll("ABCabc123", "[^A-Z0-9]+", "_")); 2036 assertEquals("ABC123", StringUtils.replaceAll("ABCabc123", "[^A-Z0-9]+", "")); 2037 assertEquals("Lorem_ipsum_dolor_sit", 2038 StringUtils.replaceAll("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2")); 2039 2040 assertThrows( 2041 PatternSyntaxException.class, 2042 () -> StringUtils.replaceAll("any", "{badRegexSyntax}", ""), 2043 "StringUtils.replaceAll expecting PatternSyntaxException"); 2044 } 2045 2046 @Test testReplaceChars_StringCharChar()2047 public void testReplaceChars_StringCharChar() { 2048 assertNull(StringUtils.replaceChars(null, 'b', 'z')); 2049 assertEquals("", StringUtils.replaceChars("", 'b', 'z')); 2050 assertEquals("azcza", StringUtils.replaceChars("abcba", 'b', 'z')); 2051 assertEquals("abcba", StringUtils.replaceChars("abcba", 'x', 'z')); 2052 } 2053 2054 @Test testReplaceChars_StringStringString()2055 public void testReplaceChars_StringStringString() { 2056 assertNull(StringUtils.replaceChars(null, null, null)); 2057 assertNull(StringUtils.replaceChars(null, "", null)); 2058 assertNull(StringUtils.replaceChars(null, "a", null)); 2059 assertNull(StringUtils.replaceChars(null, null, "")); 2060 assertNull(StringUtils.replaceChars(null, null, "x")); 2061 2062 assertEquals("", StringUtils.replaceChars("", null, null)); 2063 assertEquals("", StringUtils.replaceChars("", "", null)); 2064 assertEquals("", StringUtils.replaceChars("", "a", null)); 2065 assertEquals("", StringUtils.replaceChars("", null, "")); 2066 assertEquals("", StringUtils.replaceChars("", null, "x")); 2067 2068 assertEquals("abc", StringUtils.replaceChars("abc", null, null)); 2069 assertEquals("abc", StringUtils.replaceChars("abc", null, "")); 2070 assertEquals("abc", StringUtils.replaceChars("abc", null, "x")); 2071 2072 assertEquals("abc", StringUtils.replaceChars("abc", "", null)); 2073 assertEquals("abc", StringUtils.replaceChars("abc", "", "")); 2074 assertEquals("abc", StringUtils.replaceChars("abc", "", "x")); 2075 2076 assertEquals("ac", StringUtils.replaceChars("abc", "b", null)); 2077 assertEquals("ac", StringUtils.replaceChars("abc", "b", "")); 2078 assertEquals("axc", StringUtils.replaceChars("abc", "b", "x")); 2079 2080 assertEquals("ayzya", StringUtils.replaceChars("abcba", "bc", "yz")); 2081 assertEquals("ayya", StringUtils.replaceChars("abcba", "bc", "y")); 2082 assertEquals("ayzya", StringUtils.replaceChars("abcba", "bc", "yzx")); 2083 2084 assertEquals("abcba", StringUtils.replaceChars("abcba", "z", "w")); 2085 assertSame("abcba", StringUtils.replaceChars("abcba", "z", "w")); 2086 2087 // Javadoc examples: 2088 assertEquals("jelly", StringUtils.replaceChars("hello", "ho", "jy")); 2089 assertEquals("ayzya", StringUtils.replaceChars("abcba", "bc", "yz")); 2090 assertEquals("ayya", StringUtils.replaceChars("abcba", "bc", "y")); 2091 assertEquals("ayzya", StringUtils.replaceChars("abcba", "bc", "yzx")); 2092 2093 // From https://issues.apache.org/bugzilla/show_bug.cgi?id=25454 2094 assertEquals("bcc", StringUtils.replaceChars("abc", "ab", "bc")); 2095 assertEquals("q651.506bera", StringUtils.replaceChars("d216.102oren", 2096 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789", 2097 "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM567891234")); 2098 } 2099 2100 @Test testReplaceFirst_StringStringString()2101 public void testReplaceFirst_StringStringString() { 2102 assertNull(StringUtils.replaceFirst(null, "", "")); 2103 2104 assertEquals("any", StringUtils.replaceFirst("any", null, "")); 2105 assertEquals("any", StringUtils.replaceFirst("any", "", null)); 2106 2107 assertEquals("zzz", StringUtils.replaceFirst("", "", "zzz")); 2108 assertEquals("zzz", StringUtils.replaceFirst("", ".*", "zzz")); 2109 assertEquals("", StringUtils.replaceFirst("", ".+", "zzz")); 2110 assertEquals("ZZabc", StringUtils.replaceFirst("abc", "", "ZZ")); 2111 2112 assertEquals("z\n<__>", StringUtils.replaceFirst("<__>\n<__>", "<.*>", "z")); 2113 assertEquals("z", StringUtils.replaceFirst("<__>\n<__>", "(?s)<.*>", "z")); 2114 2115 assertEquals("ABC_bc123", StringUtils.replaceFirst("ABCabc123", "[a-z]", "_")); 2116 assertEquals("ABC_123abc", StringUtils.replaceFirst("ABCabc123abc", "[^A-Z0-9]+", "_")); 2117 assertEquals("ABC123abc", StringUtils.replaceFirst("ABCabc123abc", "[^A-Z0-9]+", "")); 2118 assertEquals("Lorem_ipsum dolor sit", 2119 StringUtils.replaceFirst("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2")); 2120 2121 assertThrows( 2122 PatternSyntaxException.class, 2123 () -> StringUtils.replaceFirst("any", "{badRegexSyntax}", ""), 2124 "StringUtils.replaceFirst expecting PatternSyntaxException"); 2125 } 2126 2127 @Test testReplaceIgnoreCase_StringStringString()2128 public void testReplaceIgnoreCase_StringStringString() { 2129 assertNull(StringUtils.replaceIgnoreCase(null, null, null)); 2130 assertNull(StringUtils.replaceIgnoreCase(null, null, "any")); 2131 assertNull(StringUtils.replaceIgnoreCase(null, "any", null)); 2132 assertNull(StringUtils.replaceIgnoreCase(null, "any", "any")); 2133 2134 assertEquals("", StringUtils.replaceIgnoreCase("", null, null)); 2135 assertEquals("", StringUtils.replaceIgnoreCase("", null, "any")); 2136 assertEquals("", StringUtils.replaceIgnoreCase("", "any", null)); 2137 assertEquals("", StringUtils.replaceIgnoreCase("", "any", "any")); 2138 2139 assertEquals("FOO", StringUtils.replaceIgnoreCase("FOO", "", "any")); 2140 assertEquals("FOO", StringUtils.replaceIgnoreCase("FOO", null, "any")); 2141 assertEquals("FOO", StringUtils.replaceIgnoreCase("FOO", "F", null)); 2142 assertEquals("FOO", StringUtils.replaceIgnoreCase("FOO", null, null)); 2143 2144 assertEquals("", StringUtils.replaceIgnoreCase("foofoofoo", "foo", "")); 2145 assertEquals("barbarbar", StringUtils.replaceIgnoreCase("foofoofoo", "foo", "bar")); 2146 assertEquals("farfarfar", StringUtils.replaceIgnoreCase("foofoofoo", "oo", "ar")); 2147 2148 // IgnoreCase 2149 assertEquals("", StringUtils.replaceIgnoreCase("foofoofoo", "FOO", "")); 2150 assertEquals("barbarbar", StringUtils.replaceIgnoreCase("fooFOOfoo", "foo", "bar")); 2151 assertEquals("farfarfar", StringUtils.replaceIgnoreCase("foofOOfoo", "OO", "ar")); 2152 } 2153 2154 @Test testReplaceIgnoreCase_StringStringStringInt()2155 public void testReplaceIgnoreCase_StringStringStringInt() { 2156 assertNull(StringUtils.replaceIgnoreCase(null, null, null, 2)); 2157 assertNull(StringUtils.replaceIgnoreCase(null, null, "any", 2)); 2158 assertNull(StringUtils.replaceIgnoreCase(null, "any", null, 2)); 2159 assertNull(StringUtils.replaceIgnoreCase(null, "any", "any", 2)); 2160 2161 assertEquals("", StringUtils.replaceIgnoreCase("", null, null, 2)); 2162 assertEquals("", StringUtils.replaceIgnoreCase("", null, "any", 2)); 2163 assertEquals("", StringUtils.replaceIgnoreCase("", "any", null, 2)); 2164 assertEquals("", StringUtils.replaceIgnoreCase("", "any", "any", 2)); 2165 2166 final String str = new String(new char[] { 'o', 'o', 'f', 'o', 'o' }); 2167 assertSame(str, StringUtils.replaceIgnoreCase(str, "x", "", -1)); 2168 2169 assertEquals("f", StringUtils.replaceIgnoreCase("oofoo", "o", "", -1)); 2170 assertEquals("oofoo", StringUtils.replaceIgnoreCase("oofoo", "o", "", 0)); 2171 assertEquals("ofoo", StringUtils.replaceIgnoreCase("oofoo", "o", "", 1)); 2172 assertEquals("foo", StringUtils.replaceIgnoreCase("oofoo", "o", "", 2)); 2173 assertEquals("fo", StringUtils.replaceIgnoreCase("oofoo", "o", "", 3)); 2174 assertEquals("f", StringUtils.replaceIgnoreCase("oofoo", "o", "", 4)); 2175 2176 assertEquals("f", StringUtils.replaceIgnoreCase("oofoo", "o", "", -5)); 2177 assertEquals("f", StringUtils.replaceIgnoreCase("oofoo", "o", "", 1000)); 2178 2179 // IgnoreCase 2180 assertEquals("f", StringUtils.replaceIgnoreCase("oofoo", "O", "", -1)); 2181 assertEquals("oofoo", StringUtils.replaceIgnoreCase("oofoo", "O", "", 0)); 2182 assertEquals("ofoo", StringUtils.replaceIgnoreCase("oofoo", "O", "", 1)); 2183 assertEquals("foo", StringUtils.replaceIgnoreCase("oofoo", "O", "", 2)); 2184 assertEquals("fo", StringUtils.replaceIgnoreCase("oofoo", "O", "", 3)); 2185 assertEquals("f", StringUtils.replaceIgnoreCase("oofoo", "O", "", 4)); 2186 2187 assertEquals("f", StringUtils.replaceIgnoreCase("oofoo", "O", "", -5)); 2188 assertEquals("f", StringUtils.replaceIgnoreCase("oofoo", "O", "", 1000)); 2189 } 2190 2191 @Test testReplaceOnce_StringStringString()2192 public void testReplaceOnce_StringStringString() { 2193 assertNull(StringUtils.replaceOnce(null, null, null)); 2194 assertNull(StringUtils.replaceOnce(null, null, "any")); 2195 assertNull(StringUtils.replaceOnce(null, "any", null)); 2196 assertNull(StringUtils.replaceOnce(null, "any", "any")); 2197 2198 assertEquals("", StringUtils.replaceOnce("", null, null)); 2199 assertEquals("", StringUtils.replaceOnce("", null, "any")); 2200 assertEquals("", StringUtils.replaceOnce("", "any", null)); 2201 assertEquals("", StringUtils.replaceOnce("", "any", "any")); 2202 2203 assertEquals("FOO", StringUtils.replaceOnce("FOO", "", "any")); 2204 assertEquals("FOO", StringUtils.replaceOnce("FOO", null, "any")); 2205 assertEquals("FOO", StringUtils.replaceOnce("FOO", "F", null)); 2206 assertEquals("FOO", StringUtils.replaceOnce("FOO", null, null)); 2207 2208 assertEquals("foofoo", StringUtils.replaceOnce("foofoofoo", "foo", "")); 2209 } 2210 2211 @Test testReplaceOnceIgnoreCase_StringStringString()2212 public void testReplaceOnceIgnoreCase_StringStringString() { 2213 assertNull(StringUtils.replaceOnceIgnoreCase(null, null, null)); 2214 assertNull(StringUtils.replaceOnceIgnoreCase(null, null, "any")); 2215 assertNull(StringUtils.replaceOnceIgnoreCase(null, "any", null)); 2216 assertNull(StringUtils.replaceOnceIgnoreCase(null, "any", "any")); 2217 2218 assertEquals("", StringUtils.replaceOnceIgnoreCase("", null, null)); 2219 assertEquals("", StringUtils.replaceOnceIgnoreCase("", null, "any")); 2220 assertEquals("", StringUtils.replaceOnceIgnoreCase("", "any", null)); 2221 assertEquals("", StringUtils.replaceOnceIgnoreCase("", "any", "any")); 2222 2223 assertEquals("FOO", StringUtils.replaceOnceIgnoreCase("FOO", "", "any")); 2224 assertEquals("FOO", StringUtils.replaceOnceIgnoreCase("FOO", null, "any")); 2225 assertEquals("FOO", StringUtils.replaceOnceIgnoreCase("FOO", "F", null)); 2226 assertEquals("FOO", StringUtils.replaceOnceIgnoreCase("FOO", null, null)); 2227 2228 assertEquals("foofoo", StringUtils.replaceOnceIgnoreCase("foofoofoo", "foo", "")); 2229 2230 // Ignore Case 2231 assertEquals("Foofoo", StringUtils.replaceOnceIgnoreCase("FoOFoofoo", "foo", "")); 2232 } 2233 2234 @Test testReplacePattern_StringStringString()2235 public void testReplacePattern_StringStringString() { 2236 assertNull(StringUtils.replacePattern(null, "", "")); 2237 assertEquals("any", StringUtils.replacePattern("any", null, "")); 2238 assertEquals("any", StringUtils.replacePattern("any", "", null)); 2239 2240 assertEquals("zzz", StringUtils.replacePattern("", "", "zzz")); 2241 assertEquals("zzz", StringUtils.replacePattern("", ".*", "zzz")); 2242 assertEquals("", StringUtils.replacePattern("", ".+", "zzz")); 2243 2244 assertEquals("z", StringUtils.replacePattern("<__>\n<__>", "<.*>", "z")); 2245 assertEquals("z", StringUtils.replacePattern("<__>\\n<__>", "<.*>", "z")); 2246 assertEquals("X", StringUtils.replacePattern("<A>\nxy\n</A>", "<A>.*</A>", "X")); 2247 2248 assertEquals("ABC___123", StringUtils.replacePattern("ABCabc123", "[a-z]", "_")); 2249 assertEquals("ABC_123", StringUtils.replacePattern("ABCabc123", "[^A-Z0-9]+", "_")); 2250 assertEquals("ABC123", StringUtils.replacePattern("ABCabc123", "[^A-Z0-9]+", "")); 2251 assertEquals("Lorem_ipsum_dolor_sit", 2252 StringUtils.replacePattern("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2")); 2253 } 2254 2255 @Test testReverse_String()2256 public void testReverse_String() { 2257 assertNull(StringUtils.reverse(null)); 2258 assertEquals("", StringUtils.reverse("")); 2259 assertEquals("sdrawkcab", StringUtils.reverse("backwards")); 2260 } 2261 2262 @Test testReverseDelimited_StringChar()2263 public void testReverseDelimited_StringChar() { 2264 assertNull(StringUtils.reverseDelimited(null, '.')); 2265 assertEquals("", StringUtils.reverseDelimited("", '.')); 2266 assertEquals("c.b.a", StringUtils.reverseDelimited("a.b.c", '.')); 2267 assertEquals("a b c", StringUtils.reverseDelimited("a b c", '.')); 2268 assertEquals("", StringUtils.reverseDelimited("", '.')); 2269 } 2270 2271 @Test testRightPad_StringInt()2272 public void testRightPad_StringInt() { 2273 assertNull(StringUtils.rightPad(null, 5)); 2274 assertEquals(" ", StringUtils.rightPad("", 5)); 2275 assertEquals("abc ", StringUtils.rightPad("abc", 5)); 2276 assertEquals("abc", StringUtils.rightPad("abc", 2)); 2277 assertEquals("abc", StringUtils.rightPad("abc", -1)); 2278 } 2279 2280 @Test testRightPad_StringIntChar()2281 public void testRightPad_StringIntChar() { 2282 assertNull(StringUtils.rightPad(null, 5, ' ')); 2283 assertEquals(" ", StringUtils.rightPad("", 5, ' ')); 2284 assertEquals("abc ", StringUtils.rightPad("abc", 5, ' ')); 2285 assertEquals("abc", StringUtils.rightPad("abc", 2, ' ')); 2286 assertEquals("abc", StringUtils.rightPad("abc", -1, ' ')); 2287 assertEquals("abcxx", StringUtils.rightPad("abc", 5, 'x')); 2288 final String str = StringUtils.rightPad("aaa", 10000, 'a'); // bigger than pad length 2289 assertEquals(10000, str.length()); 2290 assertTrue(StringUtils.containsOnly(str, 'a')); 2291 } 2292 2293 @Test testRightPad_StringIntString()2294 public void testRightPad_StringIntString() { 2295 assertNull(StringUtils.rightPad(null, 5, "-+")); 2296 assertEquals(" ", StringUtils.rightPad("", 5, " ")); 2297 assertNull(StringUtils.rightPad(null, 8, null)); 2298 assertEquals("abc-+-+", StringUtils.rightPad("abc", 7, "-+")); 2299 assertEquals("abc-+~", StringUtils.rightPad("abc", 6, "-+~")); 2300 assertEquals("abc-+", StringUtils.rightPad("abc", 5, "-+~")); 2301 assertEquals("abc", StringUtils.rightPad("abc", 2, " ")); 2302 assertEquals("abc", StringUtils.rightPad("abc", -1, " ")); 2303 assertEquals("abc ", StringUtils.rightPad("abc", 5, null)); 2304 assertEquals("abc ", StringUtils.rightPad("abc", 5, "")); 2305 } 2306 2307 @Test testRotate_StringInt()2308 public void testRotate_StringInt() { 2309 assertNull(StringUtils.rotate(null, 1)); 2310 assertEquals("", StringUtils.rotate("", 1)); 2311 assertEquals("abcdefg", StringUtils.rotate("abcdefg", 0)); 2312 assertEquals("fgabcde", StringUtils.rotate("abcdefg", 2)); 2313 assertEquals("cdefgab", StringUtils.rotate("abcdefg", -2)); 2314 assertEquals("abcdefg", StringUtils.rotate("abcdefg", 7)); 2315 assertEquals("abcdefg", StringUtils.rotate("abcdefg", -7)); 2316 assertEquals("fgabcde", StringUtils.rotate("abcdefg", 9)); 2317 assertEquals("cdefgab", StringUtils.rotate("abcdefg", -9)); 2318 assertEquals("efgabcd", StringUtils.rotate("abcdefg", 17)); 2319 assertEquals("defgabc", StringUtils.rotate("abcdefg", -17)); 2320 } 2321 2322 @Test testSplit_String()2323 public void testSplit_String() { 2324 assertNull(StringUtils.split(null)); 2325 assertEquals(0, StringUtils.split("").length); 2326 2327 String str = "a b .c"; 2328 String[] res = StringUtils.split(str); 2329 assertEquals(3, res.length); 2330 assertEquals("a", res[0]); 2331 assertEquals("b", res[1]); 2332 assertEquals(".c", res[2]); 2333 2334 str = " a "; 2335 res = StringUtils.split(str); 2336 assertEquals(1, res.length); 2337 assertEquals("a", res[0]); 2338 2339 str = "a" + WHITESPACE + "b" + NON_WHITESPACE + "c"; 2340 res = StringUtils.split(str); 2341 assertEquals(2, res.length); 2342 assertEquals("a", res[0]); 2343 assertEquals("b" + NON_WHITESPACE + "c", res[1]); 2344 } 2345 2346 @Test testSplit_StringChar()2347 public void testSplit_StringChar() { 2348 assertNull(StringUtils.split(null, '.')); 2349 assertEquals(0, StringUtils.split("", '.').length); 2350 2351 String str = "a.b.. c"; 2352 String[] res = StringUtils.split(str, '.'); 2353 assertEquals(3, res.length); 2354 assertEquals("a", res[0]); 2355 assertEquals("b", res[1]); 2356 assertEquals(" c", res[2]); 2357 2358 str = ".a."; 2359 res = StringUtils.split(str, '.'); 2360 assertEquals(1, res.length); 2361 assertEquals("a", res[0]); 2362 2363 str = "a b c"; 2364 res = StringUtils.split(str, ' '); 2365 assertEquals(3, res.length); 2366 assertEquals("a", res[0]); 2367 assertEquals("b", res[1]); 2368 assertEquals("c", res[2]); 2369 } 2370 2371 @Test testSplit_StringString_StringStringInt()2372 public void testSplit_StringString_StringStringInt() { 2373 assertNull(StringUtils.split(null, ".")); 2374 assertNull(StringUtils.split(null, ".", 3)); 2375 2376 assertEquals(0, StringUtils.split("", ".").length); 2377 assertEquals(0, StringUtils.split("", ".", 3).length); 2378 2379 innerTestSplit('.', ".", ' '); 2380 innerTestSplit('.', ".", ','); 2381 innerTestSplit('.', ".,", 'x'); 2382 for (int i = 0; i < WHITESPACE.length(); i++) { 2383 for (int j = 0; j < NON_WHITESPACE.length(); j++) { 2384 innerTestSplit(WHITESPACE.charAt(i), null, NON_WHITESPACE.charAt(j)); 2385 innerTestSplit(WHITESPACE.charAt(i), String.valueOf(WHITESPACE.charAt(i)), NON_WHITESPACE.charAt(j)); 2386 } 2387 } 2388 2389 String[] results; 2390 final String[] expectedResults = {"ab", "de fg"}; 2391 results = StringUtils.split("ab de fg", null, 2); 2392 assertEquals(expectedResults.length, results.length); 2393 for (int i = 0; i < expectedResults.length; i++) { 2394 assertEquals(expectedResults[i], results[i]); 2395 } 2396 2397 final String[] expectedResults2 = {"ab", "cd:ef"}; 2398 results = StringUtils.split("ab:cd:ef", ":", 2); 2399 assertEquals(expectedResults2.length, results.length); 2400 for (int i = 0; i < expectedResults2.length; i++) { 2401 assertEquals(expectedResults2[i], results[i]); 2402 } 2403 } 2404 2405 @Test testSplitByCharacterType()2406 public void testSplitByCharacterType() { 2407 assertNull(StringUtils.splitByCharacterType(null)); 2408 assertEquals(0, StringUtils.splitByCharacterType("").length); 2409 2410 assertTrue(Objects.deepEquals(new String[]{"ab", " ", "de", " ", 2411 "fg"}, StringUtils.splitByCharacterType("ab de fg"))); 2412 2413 assertTrue(Objects.deepEquals(new String[]{"ab", " ", "de", " ", 2414 "fg"}, StringUtils.splitByCharacterType("ab de fg"))); 2415 2416 assertTrue(Objects.deepEquals(new String[]{"ab", ":", "cd", ":", 2417 "ef"}, StringUtils.splitByCharacterType("ab:cd:ef"))); 2418 2419 assertTrue(Objects.deepEquals(new String[]{"number", "5"}, 2420 StringUtils.splitByCharacterType("number5"))); 2421 2422 assertTrue(Objects.deepEquals(new String[]{"foo", "B", "ar"}, 2423 StringUtils.splitByCharacterType("fooBar"))); 2424 2425 assertTrue(Objects.deepEquals(new String[]{"foo", "200", "B", "ar"}, 2426 StringUtils.splitByCharacterType("foo200Bar"))); 2427 2428 assertTrue(Objects.deepEquals(new String[]{"ASFR", "ules"}, 2429 StringUtils.splitByCharacterType("ASFRules"))); 2430 } 2431 2432 @Test testSplitByCharacterTypeCamelCase()2433 public void testSplitByCharacterTypeCamelCase() { 2434 assertNull(StringUtils.splitByCharacterTypeCamelCase(null)); 2435 assertEquals(0, StringUtils.splitByCharacterTypeCamelCase("").length); 2436 2437 assertTrue(Objects.deepEquals(new String[]{"ab", " ", "de", " ", 2438 "fg"}, StringUtils.splitByCharacterTypeCamelCase("ab de fg"))); 2439 2440 assertTrue(Objects.deepEquals(new String[]{"ab", " ", "de", " ", 2441 "fg"}, StringUtils.splitByCharacterTypeCamelCase("ab de fg"))); 2442 2443 assertTrue(Objects.deepEquals(new String[]{"ab", ":", "cd", ":", 2444 "ef"}, StringUtils.splitByCharacterTypeCamelCase("ab:cd:ef"))); 2445 2446 assertTrue(Objects.deepEquals(new String[]{"number", "5"}, 2447 StringUtils.splitByCharacterTypeCamelCase("number5"))); 2448 2449 assertTrue(Objects.deepEquals(new String[]{"foo", "Bar"}, 2450 StringUtils.splitByCharacterTypeCamelCase("fooBar"))); 2451 2452 assertTrue(Objects.deepEquals(new String[]{"foo", "200", "Bar"}, 2453 StringUtils.splitByCharacterTypeCamelCase("foo200Bar"))); 2454 2455 assertTrue(Objects.deepEquals(new String[]{"ASF", "Rules"}, 2456 StringUtils.splitByCharacterTypeCamelCase("ASFRules"))); 2457 } 2458 2459 @Test testSplitByWholeSeparatorPreserveAllTokens_StringString()2460 public void testSplitByWholeSeparatorPreserveAllTokens_StringString() { 2461 assertArrayEquals(null, StringUtils.splitByWholeSeparatorPreserveAllTokens(null, ".")); 2462 2463 assertEquals(0, StringUtils.splitByWholeSeparatorPreserveAllTokens("", ".").length); 2464 2465 // test whitespace 2466 String input = "ab de fg"; 2467 String[] expected = {"ab", "", "", "de", "fg"}; 2468 2469 String[] actual = StringUtils.splitByWholeSeparatorPreserveAllTokens(input, null); 2470 assertEquals(expected.length, actual.length); 2471 for (int i = 0; i < actual.length; i += 1) { 2472 assertEquals(expected[i], actual[i]); 2473 } 2474 2475 // test delimiter singlechar 2476 input = "1::2:::3::::4"; 2477 expected = new String[]{"1", "", "2", "", "", "3", "", "", "", "4"}; 2478 2479 actual = StringUtils.splitByWholeSeparatorPreserveAllTokens(input, ":"); 2480 assertEquals(expected.length, actual.length); 2481 for (int i = 0; i < actual.length; i += 1) { 2482 assertEquals(expected[i], actual[i]); 2483 } 2484 2485 // test delimiter multichar 2486 input = "1::2:::3::::4"; 2487 expected = new String[]{"1", "2", ":3", "", "4"}; 2488 2489 actual = StringUtils.splitByWholeSeparatorPreserveAllTokens(input, "::"); 2490 assertEquals(expected.length, actual.length); 2491 for (int i = 0; i < actual.length; i += 1) { 2492 assertEquals(expected[i], actual[i]); 2493 } 2494 } 2495 2496 @Test testSplitByWholeSeparatorPreserveAllTokens_StringStringInt()2497 public void testSplitByWholeSeparatorPreserveAllTokens_StringStringInt() { 2498 assertArrayEquals(null, StringUtils.splitByWholeSeparatorPreserveAllTokens(null, ".", -1)); 2499 2500 assertEquals(0, StringUtils.splitByWholeSeparatorPreserveAllTokens("", ".", -1).length); 2501 2502 // test whitespace 2503 String input = "ab de fg"; 2504 String[] expected = {"ab", "", "", "de", "fg"}; 2505 2506 String[] actual = StringUtils.splitByWholeSeparatorPreserveAllTokens(input, null, -1); 2507 assertEquals(expected.length, actual.length); 2508 for (int i = 0; i < actual.length; i += 1) { 2509 assertEquals(expected[i], actual[i]); 2510 } 2511 2512 // test delimiter singlechar 2513 input = "1::2:::3::::4"; 2514 expected = new String[]{"1", "", "2", "", "", "3", "", "", "", "4"}; 2515 2516 actual = StringUtils.splitByWholeSeparatorPreserveAllTokens(input, ":", -1); 2517 assertEquals(expected.length, actual.length); 2518 for (int i = 0; i < actual.length; i += 1) { 2519 assertEquals(expected[i], actual[i]); 2520 } 2521 2522 // test delimiter multichar 2523 input = "1::2:::3::::4"; 2524 expected = new String[]{"1", "2", ":3", "", "4"}; 2525 2526 actual = StringUtils.splitByWholeSeparatorPreserveAllTokens(input, "::", -1); 2527 assertEquals(expected.length, actual.length); 2528 for (int i = 0; i < actual.length; i += 1) { 2529 assertEquals(expected[i], actual[i]); 2530 } 2531 2532 // test delimiter char with max 2533 input = "1::2::3:4"; 2534 expected = new String[]{"1", "", "2", ":3:4"}; 2535 2536 actual = StringUtils.splitByWholeSeparatorPreserveAllTokens(input, ":", 4); 2537 assertEquals(expected.length, actual.length); 2538 for (int i = 0; i < actual.length; i += 1) { 2539 assertEquals(expected[i], actual[i]); 2540 } 2541 } 2542 2543 @Test testSplitByWholeString_StringStringBoolean()2544 public void testSplitByWholeString_StringStringBoolean() { 2545 assertArrayEquals(null, StringUtils.splitByWholeSeparator(null, ".")); 2546 2547 assertEquals(0, StringUtils.splitByWholeSeparator("", ".").length); 2548 2549 final String stringToSplitOnNulls = "ab de fg"; 2550 final String[] splitOnNullExpectedResults = {"ab", "de", "fg"}; 2551 2552 final String[] splitOnNullResults = StringUtils.splitByWholeSeparator(stringToSplitOnNulls, null); 2553 assertEquals(splitOnNullExpectedResults.length, splitOnNullResults.length); 2554 for (int i = 0; i < splitOnNullExpectedResults.length; i += 1) { 2555 assertEquals(splitOnNullExpectedResults[i], splitOnNullResults[i]); 2556 } 2557 2558 final String stringToSplitOnCharactersAndString = "abstemiouslyaeiouyabstemiously"; 2559 2560 final String[] splitOnStringExpectedResults = {"abstemiously", "abstemiously"}; 2561 final String[] splitOnStringResults = StringUtils.splitByWholeSeparator(stringToSplitOnCharactersAndString, "aeiouy"); 2562 assertEquals(splitOnStringExpectedResults.length, splitOnStringResults.length); 2563 for (int i = 0; i < splitOnStringExpectedResults.length; i += 1) { 2564 assertEquals(splitOnStringExpectedResults[i], splitOnStringResults[i]); 2565 } 2566 2567 final String[] splitWithMultipleSeparatorExpectedResults = {"ab", "cd", "ef"}; 2568 final String[] splitWithMultipleSeparator = StringUtils.splitByWholeSeparator("ab:cd::ef", ":"); 2569 assertEquals(splitWithMultipleSeparatorExpectedResults.length, splitWithMultipleSeparator.length); 2570 for (int i = 0; i < splitWithMultipleSeparatorExpectedResults.length; i++) { 2571 assertEquals(splitWithMultipleSeparatorExpectedResults[i], splitWithMultipleSeparator[i]); 2572 } 2573 } 2574 2575 @Test testSplitByWholeString_StringStringBooleanInt()2576 public void testSplitByWholeString_StringStringBooleanInt() { 2577 assertArrayEquals(null, StringUtils.splitByWholeSeparator(null, ".", 3)); 2578 2579 assertEquals(0, StringUtils.splitByWholeSeparator("", ".", 3).length); 2580 2581 final String stringToSplitOnNulls = "ab de fg"; 2582 final String[] splitOnNullExpectedResults = {"ab", "de fg"}; 2583 //String[] splitOnNullExpectedResults = { "ab", "de" } ; 2584 2585 final String[] splitOnNullResults = StringUtils.splitByWholeSeparator(stringToSplitOnNulls, null, 2); 2586 assertEquals(splitOnNullExpectedResults.length, splitOnNullResults.length); 2587 for (int i = 0; i < splitOnNullExpectedResults.length; i += 1) { 2588 assertEquals(splitOnNullExpectedResults[i], splitOnNullResults[i]); 2589 } 2590 2591 final String stringToSplitOnCharactersAndString = "abstemiouslyaeiouyabstemiouslyaeiouyabstemiously"; 2592 2593 final String[] splitOnStringExpectedResults = {"abstemiously", "abstemiouslyaeiouyabstemiously"}; 2594 //String[] splitOnStringExpectedResults = { "abstemiously", "abstemiously" } ; 2595 final String[] splitOnStringResults = StringUtils.splitByWholeSeparator(stringToSplitOnCharactersAndString, "aeiouy", 2); 2596 assertEquals(splitOnStringExpectedResults.length, splitOnStringResults.length); 2597 for (int i = 0; i < splitOnStringExpectedResults.length; i++) { 2598 assertEquals(splitOnStringExpectedResults[i], splitOnStringResults[i]); 2599 } 2600 } 2601 2602 @Test testSplitPreserveAllTokens_String()2603 public void testSplitPreserveAllTokens_String() { 2604 assertNull(StringUtils.splitPreserveAllTokens(null)); 2605 assertEquals(0, StringUtils.splitPreserveAllTokens("").length); 2606 2607 String str = "abc def"; 2608 String[] res = StringUtils.splitPreserveAllTokens(str); 2609 assertEquals(2, res.length); 2610 assertEquals("abc", res[0]); 2611 assertEquals("def", res[1]); 2612 2613 str = "abc def"; 2614 res = StringUtils.splitPreserveAllTokens(str); 2615 assertEquals(3, res.length); 2616 assertEquals("abc", res[0]); 2617 assertEquals("", res[1]); 2618 assertEquals("def", res[2]); 2619 2620 str = " abc "; 2621 res = StringUtils.splitPreserveAllTokens(str); 2622 assertEquals(3, res.length); 2623 assertEquals("", res[0]); 2624 assertEquals("abc", res[1]); 2625 assertEquals("", res[2]); 2626 2627 str = "a b .c"; 2628 res = StringUtils.splitPreserveAllTokens(str); 2629 assertEquals(3, res.length); 2630 assertEquals("a", res[0]); 2631 assertEquals("b", res[1]); 2632 assertEquals(".c", res[2]); 2633 2634 str = " a b .c"; 2635 res = StringUtils.splitPreserveAllTokens(str); 2636 assertEquals(4, res.length); 2637 assertEquals("", res[0]); 2638 assertEquals("a", res[1]); 2639 assertEquals("b", res[2]); 2640 assertEquals(".c", res[3]); 2641 2642 str = "a b .c"; 2643 res = StringUtils.splitPreserveAllTokens(str); 2644 assertEquals(5, res.length); 2645 assertEquals("a", res[0]); 2646 assertEquals("", res[1]); 2647 assertEquals("b", res[2]); 2648 assertEquals("", res[3]); 2649 assertEquals(".c", res[4]); 2650 2651 str = " a "; 2652 res = StringUtils.splitPreserveAllTokens(str); 2653 assertEquals(4, res.length); 2654 assertEquals("", res[0]); 2655 assertEquals("a", res[1]); 2656 assertEquals("", res[2]); 2657 assertEquals("", res[3]); 2658 2659 str = " a b"; 2660 res = StringUtils.splitPreserveAllTokens(str); 2661 assertEquals(4, res.length); 2662 assertEquals("", res[0]); 2663 assertEquals("a", res[1]); 2664 assertEquals("", res[2]); 2665 assertEquals("b", res[3]); 2666 2667 str = "a" + WHITESPACE + "b" + NON_WHITESPACE + "c"; 2668 res = StringUtils.splitPreserveAllTokens(str); 2669 assertEquals(WHITESPACE.length() + 1, res.length); 2670 assertEquals("a", res[0]); 2671 for (int i = 1; i < WHITESPACE.length() - 1; i++) { 2672 assertEquals("", res[i]); 2673 } 2674 assertEquals("b" + NON_WHITESPACE + "c", res[WHITESPACE.length()]); 2675 } 2676 2677 @Test testSplitPreserveAllTokens_StringChar()2678 public void testSplitPreserveAllTokens_StringChar() { 2679 assertNull(StringUtils.splitPreserveAllTokens(null, '.')); 2680 assertEquals(0, StringUtils.splitPreserveAllTokens("", '.').length); 2681 2682 String str = "a.b. c"; 2683 String[] res = StringUtils.splitPreserveAllTokens(str, '.'); 2684 assertEquals(3, res.length); 2685 assertEquals("a", res[0]); 2686 assertEquals("b", res[1]); 2687 assertEquals(" c", res[2]); 2688 2689 str = "a.b.. c"; 2690 res = StringUtils.splitPreserveAllTokens(str, '.'); 2691 assertEquals(4, res.length); 2692 assertEquals("a", res[0]); 2693 assertEquals("b", res[1]); 2694 assertEquals("", res[2]); 2695 assertEquals(" c", res[3]); 2696 2697 str = ".a."; 2698 res = StringUtils.splitPreserveAllTokens(str, '.'); 2699 assertEquals(3, res.length); 2700 assertEquals("", res[0]); 2701 assertEquals("a", res[1]); 2702 assertEquals("", res[2]); 2703 2704 str = ".a.."; 2705 res = StringUtils.splitPreserveAllTokens(str, '.'); 2706 assertEquals(4, res.length); 2707 assertEquals("", res[0]); 2708 assertEquals("a", res[1]); 2709 assertEquals("", res[2]); 2710 assertEquals("", res[3]); 2711 2712 str = "..a."; 2713 res = StringUtils.splitPreserveAllTokens(str, '.'); 2714 assertEquals(4, res.length); 2715 assertEquals("", res[0]); 2716 assertEquals("", res[1]); 2717 assertEquals("a", res[2]); 2718 assertEquals("", res[3]); 2719 2720 str = "..a"; 2721 res = StringUtils.splitPreserveAllTokens(str, '.'); 2722 assertEquals(3, res.length); 2723 assertEquals("", res[0]); 2724 assertEquals("", res[1]); 2725 assertEquals("a", res[2]); 2726 2727 str = "a b c"; 2728 res = StringUtils.splitPreserveAllTokens(str, ' '); 2729 assertEquals(3, res.length); 2730 assertEquals("a", res[0]); 2731 assertEquals("b", res[1]); 2732 assertEquals("c", res[2]); 2733 2734 str = "a b c"; 2735 res = StringUtils.splitPreserveAllTokens(str, ' '); 2736 assertEquals(5, res.length); 2737 assertEquals("a", res[0]); 2738 assertEquals("", res[1]); 2739 assertEquals("b", res[2]); 2740 assertEquals("", res[3]); 2741 assertEquals("c", res[4]); 2742 2743 str = " a b c"; 2744 res = StringUtils.splitPreserveAllTokens(str, ' '); 2745 assertEquals(4, res.length); 2746 assertEquals("", res[0]); 2747 assertEquals("a", res[1]); 2748 assertEquals("b", res[2]); 2749 assertEquals("c", res[3]); 2750 2751 str = " a b c"; 2752 res = StringUtils.splitPreserveAllTokens(str, ' '); 2753 assertEquals(5, res.length); 2754 assertEquals("", res[0]); 2755 assertEquals("", res[1]); 2756 assertEquals("a", res[2]); 2757 assertEquals("b", res[3]); 2758 assertEquals("c", res[4]); 2759 2760 str = "a b c "; 2761 res = StringUtils.splitPreserveAllTokens(str, ' '); 2762 assertEquals(4, res.length); 2763 assertEquals("a", res[0]); 2764 assertEquals("b", res[1]); 2765 assertEquals("c", res[2]); 2766 assertEquals("", res[3]); 2767 2768 str = "a b c "; 2769 res = StringUtils.splitPreserveAllTokens(str, ' '); 2770 assertEquals(5, res.length); 2771 assertEquals("a", res[0]); 2772 assertEquals("b", res[1]); 2773 assertEquals("c", res[2]); 2774 assertEquals("", res[3]); 2775 assertEquals("", res[4]); 2776 2777 // Match example in javadoc 2778 { 2779 final String[] results; 2780 final String[] expectedResults = {"a", "", "b", "c"}; 2781 results = StringUtils.splitPreserveAllTokens("a..b.c", '.'); 2782 assertEquals(expectedResults.length, results.length); 2783 for (int i = 0; i < expectedResults.length; i++) { 2784 assertEquals(expectedResults[i], results[i]); 2785 } 2786 } 2787 } 2788 2789 @Test testSplitPreserveAllTokens_StringString_StringStringInt()2790 public void testSplitPreserveAllTokens_StringString_StringStringInt() { 2791 assertNull(StringUtils.splitPreserveAllTokens(null, ".")); 2792 assertNull(StringUtils.splitPreserveAllTokens(null, ".", 3)); 2793 2794 assertEquals(0, StringUtils.splitPreserveAllTokens("", ".").length); 2795 assertEquals(0, StringUtils.splitPreserveAllTokens("", ".", 3).length); 2796 2797 innerTestSplitPreserveAllTokens('.', ".", ' '); 2798 innerTestSplitPreserveAllTokens('.', ".", ','); 2799 innerTestSplitPreserveAllTokens('.', ".,", 'x'); 2800 for (int i = 0; i < WHITESPACE.length(); i++) { 2801 for (int j = 0; j < NON_WHITESPACE.length(); j++) { 2802 innerTestSplitPreserveAllTokens(WHITESPACE.charAt(i), null, NON_WHITESPACE.charAt(j)); 2803 innerTestSplitPreserveAllTokens(WHITESPACE.charAt(i), String.valueOf(WHITESPACE.charAt(i)), NON_WHITESPACE.charAt(j)); 2804 } 2805 } 2806 2807 { 2808 final String[] results; 2809 final String[] expectedResults = {"ab", "de fg"}; 2810 results = StringUtils.splitPreserveAllTokens("ab de fg", null, 2); 2811 assertEquals(expectedResults.length, results.length); 2812 for (int i = 0; i < expectedResults.length; i++) { 2813 assertEquals(expectedResults[i], results[i]); 2814 } 2815 } 2816 2817 { 2818 final String[] results; 2819 final String[] expectedResults = {"ab", " de fg"}; 2820 results = StringUtils.splitPreserveAllTokens("ab de fg", null, 2); 2821 assertEquals(expectedResults.length, results.length); 2822 for (int i = 0; i < expectedResults.length; i++) { 2823 assertEquals(expectedResults[i], results[i]); 2824 } 2825 } 2826 2827 { 2828 final String[] results; 2829 final String[] expectedResults = {"ab", "::de:fg"}; 2830 results = StringUtils.splitPreserveAllTokens("ab:::de:fg", ":", 2); 2831 assertEquals(expectedResults.length, results.length); 2832 for (int i = 0; i < expectedResults.length; i++) { 2833 assertEquals(expectedResults[i], results[i]); 2834 } 2835 } 2836 2837 { 2838 final String[] results; 2839 final String[] expectedResults = {"ab", "", " de fg"}; 2840 results = StringUtils.splitPreserveAllTokens("ab de fg", null, 3); 2841 assertEquals(expectedResults.length, results.length); 2842 for (int i = 0; i < expectedResults.length; i++) { 2843 assertEquals(expectedResults[i], results[i]); 2844 } 2845 } 2846 2847 { 2848 final String[] results; 2849 final String[] expectedResults = {"ab", "", "", "de fg"}; 2850 results = StringUtils.splitPreserveAllTokens("ab de fg", null, 4); 2851 assertEquals(expectedResults.length, results.length); 2852 for (int i = 0; i < expectedResults.length; i++) { 2853 assertEquals(expectedResults[i], results[i]); 2854 } 2855 } 2856 2857 { 2858 final String[] expectedResults = {"ab", "cd:ef"}; 2859 final String[] results; 2860 results = StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 2); 2861 assertEquals(expectedResults.length, results.length); 2862 for (int i = 0; i < expectedResults.length; i++) { 2863 assertEquals(expectedResults[i], results[i]); 2864 } 2865 } 2866 2867 { 2868 final String[] results; 2869 final String[] expectedResults = {"ab", ":cd:ef"}; 2870 results = StringUtils.splitPreserveAllTokens("ab::cd:ef", ":", 2); 2871 assertEquals(expectedResults.length, results.length); 2872 for (int i = 0; i < expectedResults.length; i++) { 2873 assertEquals(expectedResults[i], results[i]); 2874 } 2875 } 2876 2877 { 2878 final String[] results; 2879 final String[] expectedResults = {"ab", "", ":cd:ef"}; 2880 results = StringUtils.splitPreserveAllTokens("ab:::cd:ef", ":", 3); 2881 assertEquals(expectedResults.length, results.length); 2882 for (int i = 0; i < expectedResults.length; i++) { 2883 assertEquals(expectedResults[i], results[i]); 2884 } 2885 } 2886 2887 { 2888 final String[] results; 2889 final String[] expectedResults = {"ab", "", "", "cd:ef"}; 2890 results = StringUtils.splitPreserveAllTokens("ab:::cd:ef", ":", 4); 2891 assertEquals(expectedResults.length, results.length); 2892 for (int i = 0; i < expectedResults.length; i++) { 2893 assertEquals(expectedResults[i], results[i]); 2894 } 2895 } 2896 2897 { 2898 final String[] results; 2899 final String[] expectedResults = {"", "ab", "", "", "cd:ef"}; 2900 results = StringUtils.splitPreserveAllTokens(":ab:::cd:ef", ":", 5); 2901 assertEquals(expectedResults.length, results.length); 2902 for (int i = 0; i < expectedResults.length; i++) { 2903 assertEquals(expectedResults[i], results[i]); 2904 } 2905 } 2906 2907 { 2908 final String[] results; 2909 final String[] expectedResults = {"", "", "ab", "", "", "cd:ef"}; 2910 results = StringUtils.splitPreserveAllTokens("::ab:::cd:ef", ":", 6); 2911 assertEquals(expectedResults.length, results.length); 2912 for (int i = 0; i < expectedResults.length; i++) { 2913 assertEquals(expectedResults[i], results[i]); 2914 } 2915 } 2916 2917 } 2918 2919 // Methods on StringUtils that are immutable in spirit (i.e. calculate the length) 2920 // should take a CharSequence parameter. Methods that are mutable in spirit (i.e. capitalize) 2921 // should take a String or String[] parameter and return String or String[]. 2922 // This test enforces that this is done. 2923 @Test testStringUtilsCharSequenceContract()2924 public void testStringUtilsCharSequenceContract() { 2925 final Class<StringUtils> c = StringUtils.class; 2926 // Methods that are expressly excluded from testStringUtilsCharSequenceContract() 2927 final String[] excludeMethods = { 2928 "public static int org.apache.commons.lang3.StringUtils.compare(java.lang.String,java.lang.String)", 2929 "public static int org.apache.commons.lang3.StringUtils.compare(java.lang.String,java.lang.String,boolean)", 2930 "public static int org.apache.commons.lang3.StringUtils.compareIgnoreCase(java.lang.String,java.lang.String)", 2931 "public static int org.apache.commons.lang3.StringUtils.compareIgnoreCase(java.lang.String,java.lang.String,boolean)", 2932 "public static byte[] org.apache.commons.lang3.StringUtils.getBytes(java.lang.String,java.nio.charset.Charset)", 2933 "public static byte[] org.apache.commons.lang3.StringUtils.getBytes(java.lang.String,java.lang.String) throws java.io.UnsupportedEncodingException" 2934 }; 2935 final Method[] methods = c.getMethods(); 2936 2937 for (final Method m : methods) { 2938 final String methodStr = m.toString(); 2939 if (m.getReturnType() == String.class || m.getReturnType() == String[].class) { 2940 // Assume this is mutable and ensure the first parameter is not CharSequence. 2941 // It may be String or it may be something else (String[], Object, Object[]) so 2942 // don't actively test for that. 2943 final Class<?>[] params = m.getParameterTypes(); 2944 if (params.length > 0 && (params[0] == CharSequence.class || params[0] == CharSequence[].class)) { 2945 assertFalse(ArrayUtils.contains(excludeMethods, methodStr), "The method \"" + methodStr + "\" appears to be mutable in spirit and therefore must not accept a CharSequence"); 2946 } 2947 } else { 2948 // Assume this is immutable in spirit and ensure the first parameter is not String. 2949 // As above, it may be something other than CharSequence. 2950 final Class<?>[] params = m.getParameterTypes(); 2951 if (params.length > 0 && (params[0] == String.class || params[0] == String[].class)) { 2952 assertTrue(ArrayUtils.contains(excludeMethods, methodStr), 2953 "The method \"" + methodStr + "\" appears to be immutable in spirit and therefore must not accept a String"); 2954 } 2955 } 2956 } 2957 } 2958 2959 @Test testSwapCase_String()2960 public void testSwapCase_String() { 2961 assertNull(StringUtils.swapCase(null)); 2962 assertEquals("", StringUtils.swapCase("")); 2963 assertEquals(" ", StringUtils.swapCase(" ")); 2964 2965 assertEquals("i", WordUtils.swapCase("I")); 2966 assertEquals("I", WordUtils.swapCase("i")); 2967 assertEquals("I AM HERE 123", StringUtils.swapCase("i am here 123")); 2968 assertEquals("i aM hERE 123", StringUtils.swapCase("I Am Here 123")); 2969 assertEquals("I AM here 123", StringUtils.swapCase("i am HERE 123")); 2970 assertEquals("i am here 123", StringUtils.swapCase("I AM HERE 123")); 2971 2972 final String test = "This String contains a TitleCase character: \u01C8"; 2973 final String expect = "tHIS sTRING CONTAINS A tITLEcASE CHARACTER: \u01C9"; 2974 assertEquals(expect, WordUtils.swapCase(test)); 2975 assertEquals(expect, StringUtils.swapCase(test)); 2976 } 2977 2978 @Test testToCodePoints()2979 public void testToCodePoints() { 2980 final int orphanedHighSurrogate = 0xD801; 2981 final int orphanedLowSurrogate = 0xDC00; 2982 final int supplementary = 0x2070E; 2983 2984 final int[] codePoints = {'a', orphanedHighSurrogate, 'b', 'c', supplementary, 2985 'd', orphanedLowSurrogate, 'e'}; 2986 final String s = new String(codePoints, 0, codePoints.length); 2987 assertArrayEquals(codePoints, StringUtils.toCodePoints(s)); 2988 2989 assertNull(StringUtils.toCodePoints(null)); 2990 assertArrayEquals(ArrayUtils.EMPTY_INT_ARRAY, StringUtils.toCodePoints("")); 2991 } 2992 2993 /** 2994 * Tests {@link StringUtils#toEncodedString(byte[], Charset)} 2995 * 2996 * @see StringUtils#toEncodedString(byte[], Charset) 2997 */ 2998 @Test testToEncodedString()2999 public void testToEncodedString() { 3000 final String expectedString = "The quick brown fox jumps over the lazy dog."; 3001 String encoding = SystemUtils.FILE_ENCODING; 3002 byte[] expectedBytes = expectedString.getBytes(Charset.defaultCharset()); 3003 // sanity check start 3004 assertArrayEquals(expectedBytes, expectedString.getBytes()); 3005 // sanity check end 3006 assertEquals(expectedString, StringUtils.toEncodedString(expectedBytes, Charset.defaultCharset())); 3007 assertEquals(expectedString, StringUtils.toEncodedString(expectedBytes, Charset.forName(encoding))); 3008 encoding = "UTF-16"; 3009 expectedBytes = expectedString.getBytes(Charset.forName(encoding)); 3010 assertEquals(expectedString, StringUtils.toEncodedString(expectedBytes, Charset.forName(encoding))); 3011 } 3012 3013 /** 3014 * Tests {@link StringUtils#toString(byte[], String)} 3015 * 3016 * @throws java.io.UnsupportedEncodingException because the method under test max throw it 3017 * @see StringUtils#toString(byte[], String) 3018 */ 3019 @Test testToString()3020 public void testToString() throws UnsupportedEncodingException { 3021 final String expectedString = "The quick brown fox jumps over the lazy dog."; 3022 byte[] expectedBytes = expectedString.getBytes(Charset.defaultCharset()); 3023 // sanity check start 3024 assertArrayEquals(expectedBytes, expectedString.getBytes()); 3025 // sanity check end 3026 assertEquals(expectedString, StringUtils.toString(expectedBytes, null)); 3027 assertEquals(expectedString, StringUtils.toString(expectedBytes, SystemUtils.FILE_ENCODING)); 3028 final String encoding = "UTF-16"; 3029 expectedBytes = expectedString.getBytes(Charset.forName(encoding)); 3030 assertEquals(expectedString, StringUtils.toString(expectedBytes, encoding)); 3031 } 3032 3033 @Test testTruncate_StringInt()3034 public void testTruncate_StringInt() { 3035 assertNull(StringUtils.truncate(null, 12)); 3036 assertThrows( 3037 IllegalArgumentException.class, () -> StringUtils.truncate(null, -1), "maxWith cannot be negative"); 3038 assertThrows( 3039 IllegalArgumentException.class, () -> StringUtils.truncate(null, -10), "maxWith cannot be negative"); 3040 assertThrows( 3041 IllegalArgumentException.class, 3042 () -> StringUtils.truncate(null, Integer.MIN_VALUE), 3043 "maxWith cannot be negative"); 3044 assertEquals("", StringUtils.truncate("", 10)); 3045 assertEquals("abc", StringUtils.truncate("abcdefghij", 3)); 3046 assertEquals("abcdef", StringUtils.truncate("abcdefghij", 6)); 3047 assertEquals("", StringUtils.truncate("abcdefghij", 0)); 3048 assertThrows( 3049 IllegalArgumentException.class, 3050 () -> StringUtils.truncate("abcdefghij", -1), 3051 "maxWith cannot be negative"); 3052 assertThrows( 3053 IllegalArgumentException.class, 3054 () -> StringUtils.truncate("abcdefghij", -100), 3055 "maxWith cannot be negative"); 3056 assertThrows( 3057 IllegalArgumentException.class, 3058 () -> StringUtils.truncate("abcdefghij", Integer.MIN_VALUE), 3059 "maxWith cannot be negative"); 3060 assertEquals("abcdefghij", StringUtils.truncate("abcdefghijklmno", 10)); 3061 assertEquals("abcdefghijklmno", StringUtils.truncate("abcdefghijklmno", Integer.MAX_VALUE)); 3062 assertEquals("abcde", StringUtils.truncate("abcdefghijklmno", 5)); 3063 assertEquals("abc", StringUtils.truncate("abcdefghijklmno", 3)); 3064 } 3065 3066 @Test testTruncate_StringIntInt()3067 public void testTruncate_StringIntInt() { 3068 assertNull(StringUtils.truncate(null, 0, 12)); 3069 assertThrows( 3070 IllegalArgumentException.class, () -> StringUtils.truncate(null, -1, 0), "offset cannot be negative"); 3071 assertThrows( 3072 IllegalArgumentException.class, 3073 () -> StringUtils.truncate(null, -10, -4), 3074 "offset cannot be negative"); 3075 assertThrows( 3076 IllegalArgumentException.class, 3077 () -> StringUtils.truncate(null, Integer.MIN_VALUE, Integer.MIN_VALUE), 3078 "offset cannot be negative"); 3079 assertNull(StringUtils.truncate(null, 10, 12)); 3080 assertEquals("", StringUtils.truncate("", 0, 10)); 3081 assertEquals("", StringUtils.truncate("", 2, 10)); 3082 assertEquals("abc", StringUtils.truncate("abcdefghij", 0, 3)); 3083 assertEquals("fghij", StringUtils.truncate("abcdefghij", 5, 6)); 3084 assertEquals("", StringUtils.truncate("abcdefghij", 0, 0)); 3085 assertThrows( 3086 IllegalArgumentException.class, 3087 () -> StringUtils.truncate("abcdefghij", 0, -1), 3088 "maxWith cannot be negative"); 3089 assertThrows( 3090 IllegalArgumentException.class, 3091 () -> StringUtils.truncate("abcdefghij", 0, -10), 3092 "maxWith cannot be negative"); 3093 assertThrows( 3094 IllegalArgumentException.class, 3095 () -> StringUtils.truncate("abcdefghij", 0, -100), 3096 "maxWith cannot be negative"); 3097 assertThrows( 3098 IllegalArgumentException.class, 3099 () -> StringUtils.truncate("abcdefghij", 1, -100), 3100 "maxWith cannot be negative"); 3101 assertThrows( 3102 IllegalArgumentException.class, 3103 () -> StringUtils.truncate("abcdefghij", 0, Integer.MIN_VALUE), 3104 "maxWith cannot be negative"); 3105 assertThrows( 3106 IllegalArgumentException.class, 3107 () -> StringUtils.truncate("abcdefghij", -1, 0), 3108 "offset cannot be negative"); 3109 assertThrows( 3110 IllegalArgumentException.class, 3111 () -> StringUtils.truncate("abcdefghij", -10, 0), 3112 "offset cannot be negative"); 3113 assertThrows( 3114 IllegalArgumentException.class, 3115 () -> StringUtils.truncate("abcdefghij", -100, 1), 3116 "offset cannot be negative"); 3117 assertThrows( 3118 IllegalArgumentException.class, 3119 () -> StringUtils.truncate("abcdefghij", Integer.MIN_VALUE, 0), 3120 "offset cannot be negative"); 3121 assertThrows( 3122 IllegalArgumentException.class, 3123 () -> StringUtils.truncate("abcdefghij", -1, -1), 3124 "offset cannot be negative"); 3125 assertThrows( 3126 IllegalArgumentException.class, 3127 () -> StringUtils.truncate("abcdefghij", -10, -10), 3128 "offset cannot be negative"); 3129 assertThrows( 3130 IllegalArgumentException.class, 3131 () -> StringUtils.truncate("abcdefghij", -100, -100), 3132 "offset cannot be negative"); 3133 assertThrows( 3134 IllegalArgumentException.class, 3135 () -> StringUtils.truncate("abcdefghij", Integer.MIN_VALUE, Integer.MIN_VALUE), 3136 "offset cannot be negative"); 3137 final String raspberry = "raspberry peach"; 3138 assertEquals("peach", StringUtils.truncate(raspberry, 10, 15)); 3139 assertEquals("abcdefghij", StringUtils.truncate("abcdefghijklmno", 0, 10)); 3140 assertEquals("abcdefghijklmno", StringUtils.truncate("abcdefghijklmno", 0, Integer.MAX_VALUE)); 3141 assertEquals("bcdefghijk", StringUtils.truncate("abcdefghijklmno", 1, 10)); 3142 assertEquals("cdefghijkl", StringUtils.truncate("abcdefghijklmno", 2, 10)); 3143 assertEquals("defghijklm", StringUtils.truncate("abcdefghijklmno", 3, 10)); 3144 assertEquals("efghijklmn", StringUtils.truncate("abcdefghijklmno", 4, 10)); 3145 assertEquals("fghijklmno", StringUtils.truncate("abcdefghijklmno", 5, 10)); 3146 assertEquals("fghij", StringUtils.truncate("abcdefghijklmno", 5, 5)); 3147 assertEquals("fgh", StringUtils.truncate("abcdefghijklmno", 5, 3)); 3148 assertEquals("klm", StringUtils.truncate("abcdefghijklmno", 10, 3)); 3149 assertEquals("klmno", StringUtils.truncate("abcdefghijklmno", 10, Integer.MAX_VALUE)); 3150 assertEquals("n", StringUtils.truncate("abcdefghijklmno", 13, 1)); 3151 assertEquals("no", StringUtils.truncate("abcdefghijklmno", 13, Integer.MAX_VALUE)); 3152 assertEquals("o", StringUtils.truncate("abcdefghijklmno", 14, 1)); 3153 assertEquals("o", StringUtils.truncate("abcdefghijklmno", 14, Integer.MAX_VALUE)); 3154 assertEquals("", StringUtils.truncate("abcdefghijklmno", 15, 1)); 3155 assertEquals("", StringUtils.truncate("abcdefghijklmno", 15, Integer.MAX_VALUE)); 3156 assertEquals("", StringUtils.truncate("abcdefghijklmno", Integer.MAX_VALUE, Integer.MAX_VALUE)); 3157 } 3158 3159 @Test testUnCapitalize()3160 public void testUnCapitalize() { 3161 assertNull(StringUtils.uncapitalize(null)); 3162 3163 assertEquals(FOO_UNCAP, StringUtils.uncapitalize(FOO_CAP), "uncapitalize(String) failed"); 3164 assertEquals(FOO_UNCAP, StringUtils.uncapitalize(FOO_UNCAP), "uncapitalize(string) failed"); 3165 assertEquals("", StringUtils.uncapitalize(""), "uncapitalize(empty-string) failed"); 3166 assertEquals("x", StringUtils.uncapitalize("X"), "uncapitalize(single-char-string) failed"); 3167 3168 // Examples from uncapitalize Javadoc 3169 assertEquals("cat", StringUtils.uncapitalize("cat")); 3170 assertEquals("cat", StringUtils.uncapitalize("Cat")); 3171 assertEquals("cAT", StringUtils.uncapitalize("CAT")); 3172 } 3173 3174 @Test testUnescapeSurrogatePairs()3175 public void testUnescapeSurrogatePairs() { 3176 assertEquals("\uD83D\uDE30", StringEscapeUtils.unescapeCsv("\uD83D\uDE30")); 3177 // Examples from https://en.wikipedia.org/wiki/UTF-16 3178 assertEquals("\uD800\uDC00", StringEscapeUtils.unescapeCsv("\uD800\uDC00")); 3179 assertEquals("\uD834\uDD1E", StringEscapeUtils.unescapeCsv("\uD834\uDD1E")); 3180 assertEquals("\uDBFF\uDFFD", StringEscapeUtils.unescapeCsv("\uDBFF\uDFFD")); 3181 assertEquals("\uDBFF\uDFFD", StringEscapeUtils.unescapeHtml3("\uDBFF\uDFFD")); 3182 assertEquals("\uDBFF\uDFFD", StringEscapeUtils.unescapeHtml4("\uDBFF\uDFFD")); 3183 } 3184 3185 @Test testUnwrap_StringChar()3186 public void testUnwrap_StringChar() { 3187 assertNull(StringUtils.unwrap(null, null)); 3188 assertNull(StringUtils.unwrap(null, CharUtils.NUL)); 3189 assertNull(StringUtils.unwrap(null, '1')); 3190 3191 assertEquals("abc", StringUtils.unwrap("abc", null)); 3192 assertEquals("a", StringUtils.unwrap("a", "a")); 3193 assertEquals("", StringUtils.unwrap("aa", "a")); 3194 assertEquals("abc", StringUtils.unwrap("\'abc\'", '\'')); 3195 assertEquals("abc", StringUtils.unwrap("AabcA", 'A')); 3196 assertEquals("AabcA", StringUtils.unwrap("AAabcAA", 'A')); 3197 assertEquals("abc", StringUtils.unwrap("abc", 'b')); 3198 assertEquals("#A", StringUtils.unwrap("#A", '#')); 3199 assertEquals("A#", StringUtils.unwrap("A#", '#')); 3200 assertEquals("ABA", StringUtils.unwrap("AABAA", 'A')); 3201 } 3202 3203 @Test testUnwrap_StringString()3204 public void testUnwrap_StringString() { 3205 assertNull(StringUtils.unwrap(null, null)); 3206 assertNull(StringUtils.unwrap(null, "")); 3207 assertNull(StringUtils.unwrap(null, "1")); 3208 3209 assertEquals("abc", StringUtils.unwrap("abc", null)); 3210 assertEquals("abc", StringUtils.unwrap("abc", "")); 3211 assertEquals("a", StringUtils.unwrap("a", "a")); 3212 assertEquals("ababa", StringUtils.unwrap("ababa", "aba")); 3213 assertEquals("", StringUtils.unwrap("aa", "a")); 3214 assertEquals("abc", StringUtils.unwrap("\'abc\'", "\'")); 3215 assertEquals("abc", StringUtils.unwrap("\"abc\"", "\"")); 3216 assertEquals("abc\"xyz", StringUtils.unwrap("\"abc\"xyz\"", "\"")); 3217 assertEquals("abc\"xyz\"", StringUtils.unwrap("\"abc\"xyz\"\"", "\"")); 3218 assertEquals("abc\'xyz\'", StringUtils.unwrap("\"abc\'xyz\'\"", "\"")); 3219 assertEquals("\"abc\'xyz\'\"", StringUtils.unwrap("AA\"abc\'xyz\'\"AA", "AA")); 3220 assertEquals("\"abc\'xyz\'\"", StringUtils.unwrap("123\"abc\'xyz\'\"123", "123")); 3221 assertEquals("AA\"abc\'xyz\'\"", StringUtils.unwrap("AA\"abc\'xyz\'\"", "AA")); 3222 assertEquals("AA\"abc\'xyz\'\"AA", StringUtils.unwrap("AAA\"abc\'xyz\'\"AAA", "A")); 3223 assertEquals("\"abc\'xyz\'\"AA", StringUtils.unwrap("\"abc\'xyz\'\"AA", "AA")); 3224 } 3225 3226 @Test testUpperCase()3227 public void testUpperCase() { 3228 assertNull(StringUtils.upperCase(null)); 3229 assertNull(StringUtils.upperCase(null, Locale.ENGLISH)); 3230 assertEquals("FOO TEST THING", StringUtils.upperCase("fOo test THING"), "upperCase(String) failed"); 3231 assertEquals("", StringUtils.upperCase(""), "upperCase(empty-string) failed"); 3232 assertEquals("FOO TEST THING", StringUtils.upperCase("fOo test THING", Locale.ENGLISH), 3233 "upperCase(String, Locale) failed"); 3234 assertEquals("", StringUtils.upperCase("", Locale.ENGLISH), 3235 "upperCase(empty-string, Locale) failed"); 3236 } 3237 3238 @Test testWrap_StringChar()3239 public void testWrap_StringChar() { 3240 assertNull(StringUtils.wrap(null, CharUtils.NUL)); 3241 assertNull(StringUtils.wrap(null, '1')); 3242 3243 assertEquals("", StringUtils.wrap("", CharUtils.NUL)); 3244 assertEquals("xabx", StringUtils.wrap("ab", 'x')); 3245 assertEquals("\"ab\"", StringUtils.wrap("ab", '\"')); 3246 assertEquals("\"\"ab\"\"", StringUtils.wrap("\"ab\"", '\"')); 3247 assertEquals("'ab'", StringUtils.wrap("ab", '\'')); 3248 assertEquals("''abcd''", StringUtils.wrap("'abcd'", '\'')); 3249 assertEquals("'\"abcd\"'", StringUtils.wrap("\"abcd\"", '\'')); 3250 assertEquals("\"'abcd'\"", StringUtils.wrap("'abcd'", '\"')); 3251 } 3252 3253 @Test testWrap_StringString()3254 public void testWrap_StringString() { 3255 assertNull(StringUtils.wrap(null, null)); 3256 assertNull(StringUtils.wrap(null, "")); 3257 assertNull(StringUtils.wrap(null, "1")); 3258 3259 assertNull(StringUtils.wrap(null, null)); 3260 assertEquals("", StringUtils.wrap("", "")); 3261 assertEquals("ab", StringUtils.wrap("ab", null)); 3262 assertEquals("xabx", StringUtils.wrap("ab", "x")); 3263 assertEquals("\"ab\"", StringUtils.wrap("ab", "\"")); 3264 assertEquals("\"\"ab\"\"", StringUtils.wrap("\"ab\"", "\"")); 3265 assertEquals("'ab'", StringUtils.wrap("ab", "'")); 3266 assertEquals("''abcd''", StringUtils.wrap("'abcd'", "'")); 3267 assertEquals("'\"abcd\"'", StringUtils.wrap("\"abcd\"", "'")); 3268 assertEquals("\"'abcd'\"", StringUtils.wrap("'abcd'", "\"")); 3269 } 3270 3271 @Test testWrapIfMissing_StringChar()3272 public void testWrapIfMissing_StringChar() { 3273 assertNull(StringUtils.wrapIfMissing(null, CharUtils.NUL)); 3274 assertNull(StringUtils.wrapIfMissing(null, '1')); 3275 3276 assertEquals("", StringUtils.wrapIfMissing("", CharUtils.NUL)); 3277 assertEquals("xabx", StringUtils.wrapIfMissing("ab", 'x')); 3278 assertEquals("\"ab\"", StringUtils.wrapIfMissing("ab", '\"')); 3279 assertEquals("\"ab\"", StringUtils.wrapIfMissing("\"ab\"", '\"')); 3280 assertEquals("'ab'", StringUtils.wrapIfMissing("ab", '\'')); 3281 assertEquals("'abcd'", StringUtils.wrapIfMissing("'abcd'", '\'')); 3282 assertEquals("'\"abcd\"'", StringUtils.wrapIfMissing("\"abcd\"", '\'')); 3283 assertEquals("\"'abcd'\"", StringUtils.wrapIfMissing("'abcd'", '\"')); 3284 assertEquals("/x/", StringUtils.wrapIfMissing("x", '/')); 3285 assertEquals("/x/y/z/", StringUtils.wrapIfMissing("x/y/z", '/')); 3286 assertEquals("/x/y/z/", StringUtils.wrapIfMissing("/x/y/z", '/')); 3287 assertEquals("/x/y/z/", StringUtils.wrapIfMissing("x/y/z/", '/')); 3288 3289 assertSame("/", StringUtils.wrapIfMissing("/", '/')); 3290 assertSame("/x/", StringUtils.wrapIfMissing("/x/", '/')); 3291 } 3292 3293 @Test testWrapIfMissing_StringString()3294 public void testWrapIfMissing_StringString() { 3295 assertNull(StringUtils.wrapIfMissing(null, "\0")); 3296 assertNull(StringUtils.wrapIfMissing(null, "1")); 3297 3298 assertEquals("", StringUtils.wrapIfMissing("", "\0")); 3299 assertEquals("xabx", StringUtils.wrapIfMissing("ab", "x")); 3300 assertEquals("\"ab\"", StringUtils.wrapIfMissing("ab", "\"")); 3301 assertEquals("\"ab\"", StringUtils.wrapIfMissing("\"ab\"", "\"")); 3302 assertEquals("'ab'", StringUtils.wrapIfMissing("ab", "\'")); 3303 assertEquals("'abcd'", StringUtils.wrapIfMissing("'abcd'", "\'")); 3304 assertEquals("'\"abcd\"'", StringUtils.wrapIfMissing("\"abcd\"", "\'")); 3305 assertEquals("\"'abcd'\"", StringUtils.wrapIfMissing("'abcd'", "\"")); 3306 assertEquals("/x/", StringUtils.wrapIfMissing("x", "/")); 3307 assertEquals("/x/y/z/", StringUtils.wrapIfMissing("x/y/z", "/")); 3308 assertEquals("/x/y/z/", StringUtils.wrapIfMissing("/x/y/z", "/")); 3309 assertEquals("/x/y/z/", StringUtils.wrapIfMissing("x/y/z/", "/")); 3310 assertEquals("/", StringUtils.wrapIfMissing("/", "/")); 3311 assertEquals("ab/ab", StringUtils.wrapIfMissing("/", "ab")); 3312 3313 assertSame("ab/ab", StringUtils.wrapIfMissing("ab/ab", "ab")); 3314 assertSame("//x//", StringUtils.wrapIfMissing("//x//", "//")); 3315 } 3316 3317 @Test testToRootLowerCase()3318 public void testToRootLowerCase() { 3319 assertNull(StringUtils.toRootLowerCase(null)); 3320 assertEquals("a", StringUtils.toRootLowerCase("A")); 3321 assertEquals("a", StringUtils.toRootLowerCase("a")); 3322 final Locale TURKISH = Locale.forLanguageTag("tr"); 3323 // Sanity checks: 3324 assertNotEquals("title", "TITLE".toLowerCase(TURKISH)); 3325 assertEquals("title", "TITLE".toLowerCase(Locale.ROOT)); 3326 assertEquals("title", StringUtils.toRootLowerCase("TITLE")); 3327 // Make sure we are not using the default Locale: 3328 final Locale defaultLocale = Locale.getDefault(); 3329 try { 3330 Locale.setDefault(TURKISH); 3331 assertEquals("title", StringUtils.toRootLowerCase("TITLE")); 3332 } finally { 3333 Locale.setDefault(defaultLocale); 3334 } 3335 } 3336 3337 @Test testToRootUpperCase()3338 public void testToRootUpperCase() { 3339 assertNull(StringUtils.toRootUpperCase(null)); 3340 assertEquals("A", StringUtils.toRootUpperCase("a")); 3341 assertEquals("A", StringUtils.toRootUpperCase("A")); 3342 final Locale TURKISH = Locale.forLanguageTag("tr"); 3343 // Sanity checks: 3344 assertNotEquals("TITLE", "title".toUpperCase(TURKISH)); 3345 assertEquals("TITLE", "title".toUpperCase(Locale.ROOT)); 3346 assertEquals("TITLE", StringUtils.toRootUpperCase("title")); 3347 // Make sure we are not using the default Locale: 3348 final Locale defaultLocale = Locale.getDefault(); 3349 try { 3350 Locale.setDefault(TURKISH); 3351 assertEquals("TITLE", StringUtils.toRootUpperCase("title")); 3352 } finally { 3353 Locale.setDefault(defaultLocale); 3354 } 3355 } 3356 3357 @Test testGeorgianSample()3358 public void testGeorgianSample() { 3359 final char[] arrayI = { 3360 //Latin Small Letter dotless I 3361 (char) 0x0131, 3362 //Greek Capital Letter Theta 3363 (char) 0x03F4 3364 }; 3365 final char[] arrayJ = { 3366 //Latin Capital Letter I with dot above 3367 (char) 0x0130, 3368 //Greek Theta Symbol 3369 (char) 0x03D1 3370 }; 3371 for (final char i : arrayI) { 3372 for (final char j : arrayJ) { 3373 final String si = String.valueOf(i); 3374 final String sj = String.valueOf(j); 3375 final boolean res1 = si.equalsIgnoreCase(sj); 3376 final CharSequence ci = new StringBuilder(si); 3377 final CharSequence cj = new StringBuilder(sj); 3378 boolean res2 = StringUtils.startsWithIgnoreCase(ci, cj); 3379 assertEquals(res1, res2, "si : " + si + " sj : " + sj); 3380 res2 = StringUtils.endsWithIgnoreCase(ci, cj); 3381 assertEquals(res1, res2, "si : " + si + " sj : " + sj); 3382 res2 = StringUtils.compareIgnoreCase(ci.toString(), cj.toString()) == 0; 3383 assertEquals(res1, res2, "si : " + si + " sj : " + sj); 3384 res2 = StringUtils.indexOfIgnoreCase(ci.toString(), cj.toString()) == 0; 3385 assertEquals(res1, res2, "si : " + si + " sj : " + sj); 3386 res2 = StringUtils.lastIndexOfIgnoreCase(ci.toString(), cj.toString()) == 0; 3387 assertEquals(res1, res2, "si : " + si + " sj : " + sj); 3388 } 3389 } 3390 } 3391 } 3392