001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.io.encoding;
019
020import static org.junit.Assert.assertSame;
021import static org.junit.Assert.assertThrows;
022import static org.mockito.ArgumentMatchers.any;
023
024import org.apache.hadoop.hbase.HBaseClassTestRule;
025import org.apache.hadoop.hbase.io.compress.Compression.Algorithm;
026import org.apache.hadoop.hbase.testclassification.MiscTests;
027import org.apache.hadoop.hbase.testclassification.SmallTests;
028import org.apache.hadoop.util.ReflectionUtils;
029import org.junit.ClassRule;
030import org.junit.Test;
031import org.junit.experimental.categories.Category;
032import org.junit.runner.RunWith;
033import org.mockito.Mock;
034import org.mockito.MockedStatic;
035import org.mockito.junit.MockitoJUnitRunner;
036
037/**
038 * Test for HBASE-23342
039 */
040@RunWith(MockitoJUnitRunner.class)
041@Category({ MiscTests.class, SmallTests.class })
042public class TestEncodedDataBlock {
043
044  @ClassRule
045  public static final HBaseClassTestRule CLASS_RULE =
046    HBaseClassTestRule.forClass(TestEncodedDataBlock.class);
047
048  // for generating exception
049  @Mock
050  private MockedStatic<ReflectionUtils> mockedReflectionUtils;
051
052  private static final byte[] INPUT_BYTES = new byte[] { 0, 1, 0, 0, 1, 2, 3, 0, 0, 1, 0, 0, 1, 2,
053    3, 0, 0, 1, 0, 0, 1, 2, 3, 0, 0, 1, 0, 0, 1, 2, 3, 0 };
054
055  @SuppressWarnings("unchecked")
056  @Test
057  public void testGetCompressedSize() throws Exception {
058    RuntimeException inject = new RuntimeException("inject error");
059    mockedReflectionUtils.when(() -> ReflectionUtils.newInstance(any(Class.class), any()))
060      .thenThrow(inject);
061    RuntimeException error = assertThrows(RuntimeException.class,
062      () -> EncodedDataBlock.getCompressedSize(Algorithm.GZ, null, INPUT_BYTES, 0, 0));
063    // make sure we get the injected error instead of NPE
064    assertSame(inject, error);
065  }
066
067}