View Javadoc
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    *      https://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  
18  package org.apache.commons.lang3;
19  
20  import static org.junit.jupiter.api.Assertions.assertEquals;
21  
22  import org.junit.jupiter.api.Test;
23  
24  /**
25   * Tests {@code StringUtils#indexOfAny(...)}} methods.
26   * <p>
27   * Negative start index can crash new indexOfAny overload.
28   * </p>
29   * <p>
30   * indexOfAny(CharSequence, int, char...) does not clamp negative csStart. When csStart < 0, the loop starts at a negative index causing
31   * StringIndexOutOfBoundsException.
32   * </p>
33   * <p>
34   * Pre-patch: indexOfAny("abc", -1, 'a') throws StringIndexOutOfBoundsException.
35   * </p>
36   * <p>
37   * Post-patch: returns 0 (clamped to 0 per StringUtils convention).
38   * </p>
39   */
40  public class StringUtilsIndexOfAnyTest {
41  
42      @Test
43      public void testLargeNegativeStartIndexClampsToZero() {
44          assertEquals(0, StringUtils.indexOfAny("abc", Integer.MIN_VALUE, 'a'));
45      }
46  
47      @Test
48      public void testNegativeStartIndexClampsToZero() {
49          // With csStart clamped to 0, the search finds 'a' at index 0
50          assertEquals(0, StringUtils.indexOfAny("abc", -1, 'a'));
51      }
52  
53      @Test
54      public void testNegativeStartIndexDoesNotThrow() {
55          assertEquals(0, StringUtils.indexOfAny("abc", -1, 'a'));
56      }
57  
58      @Test
59      public void testPositiveStartIndexWorksNormally() {
60          // Start after 'a', should find 'b' at index 1
61          assertEquals(1, StringUtils.indexOfAny("abc", 1, 'b'));
62      }
63  
64      @Test
65      public void testZeroStartIndexWorksNormally() {
66          assertEquals(1, StringUtils.indexOfAny("abc", 0, 'b'));
67      }
68  }