1 package fr.ifremer.tutti.persistence.test;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 import org.apache.commons.logging.Log;
28 import org.apache.commons.logging.LogFactory;
29 import org.junit.rules.TestRule;
30 import org.junit.runner.Description;
31 import org.junit.runner.notification.Failure;
32 import org.junit.runners.model.Statement;
33
34 import java.util.HashMap;
35 import java.util.Map;
36
37
38
39
40
41
42
43 public class CleanResourcesRule implements TestRule {
44
45
46 private static final Log log = LogFactory.getLog(CleanResourcesRule.class);
47
48 private static final Map<Description, DatabaseResource> RESSOURCES_BY_DESCRIPTIONS = new HashMap<>();
49
50 public static void registerDescription(Description description, DatabaseResource databaseResource) {
51 RESSOURCES_BY_DESCRIPTIONS.put(description, databaseResource);
52 }
53
54 public static void cleanResources(Description description) {
55
56 DatabaseResource databaseResource = RESSOURCES_BY_DESCRIPTIONS.get(description);
57
58 if (databaseResource != null) {
59
60 if (log.isInfoEnabled()) {
61 log.info("Try to clean resources for test: " + description);
62 }
63
64 Failure failure = TuttiRunListener.getFailureForDescription(description);
65
66
67 if (failure == null) {
68
69 if (log.isInfoEnabled()) {
70 log.info("Clean resources (no failure found) for test: " + description);
71 }
72 databaseResource.cleanResources(description);
73
74 } else {
75
76 if (log.isWarnEnabled()) {
77 log.warn("Keep resources ((found failure) for test: " + description);
78 }
79
80 }
81
82 }
83
84 }
85
86 @Override
87 public Statement apply(final Statement base, final Description description) {
88
89 return new Statement() {
90 @Override
91 public void evaluate() throws Throwable {
92 try {
93 base.evaluate();
94 } finally {
95 after(description);
96 }
97 }
98 };
99 }
100
101 protected void after(Description description) {
102
103 cleanResources(description);
104
105 for (Description childDescription : description.getChildren()) {
106
107 cleanResources(childDescription);
108
109 }
110
111 }
112
113 }