001package org.hl7.fhir.utilities.tests.execution.junit4;
002
003import java.util.ArrayList;
004import java.util.Collections;
005import java.util.List;
006import java.util.regex.Pattern;
007import java.util.stream.Collectors;
008
009import org.hl7.fhir.utilities.tests.execution.CliTestSummary;
010import org.hl7.fhir.utilities.tests.execution.ModuleTestExecutor;
011import org.junit.runner.Description;
012import org.junit.runner.JUnitCore;
013import org.junit.runner.notification.Failure;
014import org.junit.runner.notification.RunListener;
015
016import lombok.Getter;
017import org.slf4j.Logger;
018
019public class JUnit4TestExecutor extends ModuleTestExecutor {
020
021  @Getter
022  private final String moduleName;
023
024  private final List<String> classNames;
025  public JUnit4TestExecutor(String moduleName, List<String> classNames) {
026    this.moduleName = moduleName + " (JUnit4)";
027    this.classNames = Collections.unmodifiableList(new ArrayList<>(classNames));
028  }
029
030  private class JUnit4RunListener extends RunListener {
031
032    Logger log;
033    public JUnit4RunListener(Logger log) {
034      this.log = log;
035    }
036
037    @Override
038    public void testStarted(Description description) {
039      ModuleTestExecutor.printTestStarted(log, description.getDisplayName());
040    }
041
042    @Override
043    public void testFinished(Description description) {
044      ModuleTestExecutor.printTestFinished(log, description.getDisplayName(),
045        "FINISHED");
046    }
047
048    @Override
049    public void testFailure(Failure failure) {
050      ModuleTestExecutor.printTestFailed(log,
051
052        failure.getDescription().getDisplayName(),
053        failure.getException()
054      );
055    }
056  }
057
058  public CliTestSummary executeTests(Logger log, String classNameFilter) {
059
060    JUnitCore junit = new JUnitCore();
061
062    junit.addListener(new JUnit4RunListener(log));
063
064    Pattern pattern = classNameFilter != null ? Pattern.compile(classNameFilter) : null;
065
066    List<Class<?>> classes = classNames.stream()
067      .filter(className -> pattern == null ? true : pattern.matcher(className).matches())
068      .map(className -> {
069        try {
070          return Class.forName(className);
071        } catch (ClassNotFoundException e) {
072          throw new RuntimeException(e);
073        }
074      })
075      .collect(Collectors.toList());
076
077    Class<?>[] classArray = new Class[classes.size()];
078    classes.toArray(classArray);
079
080      org.junit.runner.Result result = junit.run(classArray);
081      return new JUnit4TestSummaryAdapter(result);
082
083  }
084
085}