View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.monitoring;
20  
21  import static org.junit.Assert.assertFalse;
22  import static org.junit.Assert.assertTrue;
23  
24  import java.io.PrintWriter;
25  import java.io.StringWriter;
26  
27  import org.apache.hadoop.hbase.testclassification.SmallTests;
28  import org.junit.Test;
29  import org.junit.experimental.categories.Category;
30  
31  /**
32   * Test case for the MemoryBoundedLogMessageBuffer utility.
33   * Ensures that it uses no more memory than it's supposed to,
34   * and that it properly deals with multibyte encodings.
35   */
36  @Category(SmallTests.class)
37  public class TestMemoryBoundedLogMessageBuffer {
38  
39    private static final long TEN_KB = 10 * 1024;
40    private static final String JP_TEXT = "こんにちは";
41    
42    @Test
43    public void testBuffer() {
44      MemoryBoundedLogMessageBuffer buf =
45        new MemoryBoundedLogMessageBuffer(TEN_KB);
46      
47      for (int i = 0; i < 1000; i++) {
48        buf.add("hello " + i);
49      }
50      assertTrue("Usage too big: " + buf.estimateHeapUsage(),
51          buf.estimateHeapUsage() < TEN_KB);
52      assertTrue("Too many retained: " + buf.getMessages().size(),
53          buf.getMessages().size() < 100);
54      StringWriter sw = new StringWriter();
55      buf.dumpTo(new PrintWriter(sw));
56      String dump = sw.toString();
57      String eol = System.getProperty("line.separator");
58      assertFalse("The early log messages should be evicted",
59          dump.contains("hello 1" + eol));
60      assertTrue("The late log messages should be retained",
61          dump.contains("hello 999" + eol));
62    }
63  
64    @Test
65    public void testNonAsciiEncoding() {
66      MemoryBoundedLogMessageBuffer buf =
67        new MemoryBoundedLogMessageBuffer(TEN_KB);
68  
69      buf.add(JP_TEXT);
70      StringWriter sw = new StringWriter();
71      buf.dumpTo(new PrintWriter(sw));
72      String dump = sw.toString();
73      assertTrue(dump.contains(JP_TEXT));
74    }
75  
76  }
77