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.builder;
19  
20  import static org.junit.jupiter.api.Assertions.assertNotNull;
21  
22  import java.util.ArrayList;
23  import java.util.HashMap;
24  import java.util.List;
25  import java.util.Map;
26  
27  import org.junit.jupiter.api.Test;
28  
29  /**
30   * Tests {@code ToStringStyle} collection toString can overflow the stack.
31   *
32   * Pre-patch: appendDetail(StringBuffer, String, Collection) calls buffer.append(coll) which invokes the collection's own toString(), bypassing the cycle
33   * registry. Two mutually-referencing ArrayLists cause StackOverflowError. Post-patch: the cycle is detected and a safe representation is produced.
34   */
35  class ToStringBuilderAppendCycleTest {
36  
37      @Test
38      void testMutuallyCyclicCollection() {
39          final List<Object> a = new ArrayList<>();
40          final List<Object> b = new ArrayList<>();
41          a.add(b);
42          b.add(a);
43          assertNotNull(new ToStringBuilder(new Object(), ToStringStyle.DEFAULT_STYLE).append("field", a).build());
44      }
45  
46      @Test
47      void testMutuallyCyclicMap() {
48          final Map<Object, Object> a = new HashMap<>();
49          final Map<Object, Object> b = new HashMap<>();
50          a.put(b, b);
51          b.put(a, a);
52          assertNotNull(new ToStringBuilder(new Object(), ToStringStyle.DEFAULT_STYLE).append("field", a).build());
53      }
54  
55      @Test
56      void testSelfReferentialCollection() {
57          final List<Object> a = new ArrayList<>();
58          a.add(a);
59          assertNotNull(new ToStringBuilder(new Object(), ToStringStyle.DEFAULT_STYLE).append("field", a).build());
60      }
61  
62      @Test
63      void testSelfReferentialObjectArray() {
64          final Object[] a = { null };
65          a[0] = a;
66          assertNotNull(new ToStringBuilder(new Object(), ToStringStyle.DEFAULT_STYLE).append("field", a).build());
67      }
68  }