Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/main/java/org/apache/commons/lang3/RandomStringUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,19 @@ public static String random(int count, int start, int end, final boolean letters
throw new IllegalArgumentException("The chars array must not be empty");
}

if (chars!=null) {
if (start>=chars.length) {
throw new IllegalArgumentException(
"Parameter start (" +start+ ") must be less than chars.length ("+chars.length+")"
);
}
if (end>chars.length) {
throw new IllegalArgumentException(
"Parameter end ("+end+") must be less than or equal to chars.length ("+chars.length+")"
);
}
}

if (start == 0 && end == 0) {
if (chars != null) {
end = chars.length;
Expand Down
24 changes: 19 additions & 5 deletions src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,7 @@
package org.apache.commons.lang3;

import static org.apache.commons.lang3.LangAssertions.assertIllegalArgumentException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assertions.*;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
Expand Down Expand Up @@ -815,4 +811,22 @@ void testRandomWithChars(final RandomStringUtils rsu) {
assertNotEquals(r1, r3);
assertNotEquals(r2, r3);
}

@Test
void testStartEndOutOfRangeWithChars_shouldThrow() {
final char[] chars = { 'a', 'b', 'c' };
final Random random = new Random();
IllegalArgumentException ex;

ex=assertThrows(IllegalArgumentException.class, () ->
RandomStringUtils.random(5,5,10,false,false,chars,random)
);
System.out.println("Caught exception: " + ex.getMessage());

ex=assertThrows(IllegalArgumentException.class, () ->
RandomStringUtils.random(5,0,5,false,false,chars,random)
);
System.out.println("Caught exception: " + ex.getMessage());
}

}