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; 019 020import java.util.Map; 021import java.util.concurrent.ConcurrentHashMap; 022import org.junit.runner.notification.RunListener; 023 024/** 025 * Listen to the test progress and check the usage of: 026 * <ul> 027 * <li>threads</li> 028 * <li>open file descriptor</li> 029 * <li>max open file descriptor</li> 030 * </ul> 031 * <p> 032 * When surefire forkMode=once/always/perthread, this code is executed on the forked process. 033 */ 034public class ResourceCheckerJUnitListener extends RunListener { 035 036 private final Map<String, ResourceChecker> rcs = new ConcurrentHashMap<>(); 037 038 /** 039 * To be implemented by sub classes if they want to add specific ResourceAnalyzer. 040 */ 041 protected void addResourceAnalyzer(ResourceChecker rc) { 042 } 043 044 private void start(String testName) { 045 ResourceChecker rc = new ResourceChecker(testName); 046 JUnitResourceCheckers.addResourceAnalyzer(rc); 047 addResourceAnalyzer(rc); 048 rcs.put(testName, rc); 049 rc.start(); 050 } 051 052 private void end(String testName) { 053 ResourceChecker rc = rcs.remove(testName); 054 assert rc != null; 055 rc.end(); 056 } 057 058 /** 059 * Get the test name from the JUnit Description 060 * @return the string for the short test name 061 */ 062 private String descriptionToShortTestName(org.junit.runner.Description description) { 063 final int toRemove = "org.apache.hadoop.hbase.".length(); 064 return description.getTestClass().getName().substring(toRemove) + "#" 065 + description.getMethodName(); 066 } 067 068 @Override 069 public void testStarted(org.junit.runner.Description description) throws java.lang.Exception { 070 start(descriptionToShortTestName(description)); 071 } 072 073 @Override 074 public void testFinished(org.junit.runner.Description description) throws java.lang.Exception { 075 end(descriptionToShortTestName(description)); 076 } 077}