1. package junit.runner;
  2. import java.util.*;
  3. import java.io.*;
  4. /**
  5. * An implementation of a TestCollector that consults the
  6. * class path. It considers all classes on the class path
  7. * excluding classes in JARs. It leaves it up to subclasses
  8. * to decide whether a class is a runnable Test.
  9. *
  10. * @see TestCollector
  11. */
  12. public abstract class ClassPathTestCollector implements TestCollector {
  13. static final int SUFFIX_LENGTH= ".class".length();
  14. public ClassPathTestCollector() {
  15. }
  16. public Enumeration collectTests() {
  17. String classPath= System.getProperty("java.class.path");
  18. Hashtable result = collectFilesInPath(classPath);
  19. return result.elements();
  20. }
  21. public Hashtable collectFilesInPath(String classPath) {
  22. Hashtable result= collectFilesInRoots(splitClassPath(classPath));
  23. return result;
  24. }
  25. Hashtable collectFilesInRoots(Vector roots) {
  26. Hashtable result= new Hashtable(100);
  27. Enumeration e= roots.elements();
  28. while (e.hasMoreElements())
  29. gatherFiles(new File((String)e.nextElement()), "", result);
  30. return result;
  31. }
  32. void gatherFiles(File classRoot, String classFileName, Hashtable result) {
  33. File thisRoot= new File(classRoot, classFileName);
  34. if (thisRoot.isFile()) {
  35. if (isTestClass(classFileName)) {
  36. String className= classNameFromFile(classFileName);
  37. result.put(className, className);
  38. }
  39. return;
  40. }
  41. String[] contents= thisRoot.list();
  42. if (contents != null) {
  43. for (int i= 0; i < contents.length; i++)
  44. gatherFiles(classRoot, classFileName+File.separatorChar+contents[i], result);
  45. }
  46. }
  47. Vector splitClassPath(String classPath) {
  48. Vector result= new Vector();
  49. String separator= System.getProperty("path.separator");
  50. StringTokenizer tokenizer= new StringTokenizer(classPath, separator);
  51. while (tokenizer.hasMoreTokens())
  52. result.addElement(tokenizer.nextToken());
  53. return result;
  54. }
  55. protected boolean isTestClass(String classFileName) {
  56. return
  57. classFileName.endsWith(".class") &&
  58. classFileName.indexOf('$') < 0 &&
  59. classFileName.indexOf("Test") > 0;
  60. }
  61. protected String classNameFromFile(String classFileName) {
  62. // convert /a/b.class to a.b
  63. String s= classFileName.substring(0, classFileName.length()-SUFFIX_LENGTH);
  64. String s2= s.replace(File.separatorChar, '.');
  65. if (s2.startsWith("."))
  66. return s2.substring(1);
  67. return s2;
  68. }
  69. }