View Javadoc
1   package com.github.valfirst.slf4jtest;
2   
3   import static org.junit.platform.commons.support.AnnotationSupport.findAnnotation;
4   
5   import java.util.Optional;
6   import org.junit.jupiter.api.extension.BeforeEachCallback;
7   import org.junit.jupiter.api.extension.BeforeTestExecutionCallback;
8   import org.junit.jupiter.api.extension.ExtensionContext;
9   
10  /**
11   * @author Valery Yatsynovich
12   */
13  public class TestLoggerFactoryExtension implements BeforeEachCallback, BeforeTestExecutionCallback {
14  
15      private final CleanupStage cleanupStage;
16  
17      public TestLoggerFactoryExtension() {
18          this(CleanupStage.BEFORE_TEST_EXECUTION);
19      }
20  
21      public TestLoggerFactoryExtension(CleanupStage cleanupStage) {
22          this.cleanupStage = cleanupStage;
23      }
24  
25      @Override
26      public void beforeEach(ExtensionContext context) {
27          if (calculateCleanupStage(context) == CleanupStage.BEFORE_EACH) {
28              TestLoggerFactory.clear();
29          }
30      }
31  
32      @Override
33      public void beforeTestExecution(ExtensionContext context) {
34          if (calculateCleanupStage(context) == CleanupStage.BEFORE_TEST_EXECUTION) {
35              TestLoggerFactory.clear();
36          }
37      }
38  
39      private CleanupStage calculateCleanupStage(ExtensionContext context) {
40          // Inspired by Mockito
41          return this.retrieveAnnotationFromTestClasses(context)
42                  .map(TestLoggerFactorySettings::cleanupStage)
43                  .orElse(cleanupStage);
44      }
45  
46      private Optional<TestLoggerFactorySettings> retrieveAnnotationFromTestClasses(
47              final ExtensionContext context) {
48          ExtensionContext currentContext = context;
49          Optional<TestLoggerFactorySettings> annotation;
50  
51          do {
52              annotation = findAnnotation(currentContext.getElement(), TestLoggerFactorySettings.class);
53  
54              if (!currentContext.getParent().isPresent()) {
55                  break;
56              }
57  
58              currentContext = currentContext.getParent().get();
59          } while (!annotation.isPresent() && currentContext != context.getRoot());
60  
61          return annotation;
62      }
63  }