aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/junit/internal/runners/rules/RuleMemberValidator.java
blob: 36de4f1062972ff5295462b2c48bd5f0d33aba69 (plain)
1
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
package org.junit.internal.runners.rules;

import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.rules.MethodRule;
import org.junit.rules.TestRule;
import org.junit.runners.model.FrameworkMember;
import org.junit.runners.model.TestClass;

import java.lang.annotation.Annotation;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

/**
 * A RuleMemberValidator validates the rule fields/methods of a
 * {@link org.junit.runners.model.TestClass}. All reasons for rejecting the
 * {@code TestClass} are written to a list of errors.
 *
 * <p>There are four slightly different validators. The {@link #CLASS_RULE_VALIDATOR}
 * validates fields with a {@link ClassRule} annotation and the
 * {@link #RULE_VALIDATOR} validates fields with a {@link Rule} annotation.</p>
 *
 * <p>The {@link #CLASS_RULE_METHOD_VALIDATOR}
 * validates methods with a {@link ClassRule} annotation and the
 * {@link #RULE_METHOD_VALIDATOR} validates methods with a {@link Rule} annotation.</p>
 */
public class RuleMemberValidator {
    /**
     * Validates fields with a {@link ClassRule} annotation.
     */
    public static final RuleMemberValidator CLASS_RULE_VALIDATOR =
            classRuleValidatorBuilder()
            .withValidator(new DeclaringClassMustBePublic())
            .withValidator(new MemberMustBeStatic())
            .withValidator(new MemberMustBePublic())
            .withValidator(new FieldMustBeATestRule())
            .build();
    /**
     * Validates fields with a {@link Rule} annotation.
     */
    public static final RuleMemberValidator RULE_VALIDATOR =
            testRuleValidatorBuilder()
            .withValidator(new MemberMustBeNonStaticOrAlsoClassRule())
            .withValidator(new MemberMustBePublic())
            .withValidator(new FieldMustBeARule())
            .build();
    /**
     * Validates methods with a {@link ClassRule} annotation.
     */
    public static final RuleMemberValidator CLASS_RULE_METHOD_VALIDATOR =
            classRuleValidatorBuilder()
            .forMethods()
            .withValidator(new DeclaringClassMustBePublic())
            .withValidator(new MemberMustBeStatic())
            .withValidator(new MemberMustBePublic())
            .withValidator(new MethodMustBeATestRule())
            .build();

    /**
     * Validates methods with a {@link Rule} annotation.
     */
    public static final RuleMemberValidator RULE_METHOD_VALIDATOR =
            testRuleValidatorBuilder()
            .forMethods()
            .withValidator(new MemberMustBeNonStaticOrAlsoClassRule())
            .withValidator(new MemberMustBePublic())
            .withValidator(new MethodMustBeARule())
            .build();

    private final Class<? extends Annotation> annotation;
    private final boolean methods;
    private final List<RuleValidator> validatorStrategies;

    RuleMemberValidator(Builder builder) {
        this.annotation = builder.annotation;
        this.methods = builder.methods;
        this.validatorStrategies = builder.validators;
    }

    /**
     * Validate the {@link org.junit.runners.model.TestClass} and adds reasons
     * for rejecting the class to a list of errors.
     *
     * @param target the {@code TestClass} to validate.
     * @param errors the list of errors.
     */
    public void validate(TestClass target, List<Throwable> errors) {
        List<? extends FrameworkMember<?>> members = methods ? target.getAnnotatedMethods(annotation)
                : target.getAnnotatedFields(annotation);

        for (FrameworkMember<?> each : members) {
            validateMember(each, errors);
        }
    }

    private void validateMember(FrameworkMember<?> member, List<Throwable> errors) {
        for (RuleValidator strategy : validatorStrategies) {
            strategy.validate(member, annotation, errors);
        }
    }

    private static Builder classRuleValidatorBuilder() {
        return new Builder(ClassRule.class);
    }

    private static Builder testRuleValidatorBuilder() {
        return new Builder(Rule.class);
    }

    private static class Builder {
        private final Class<? extends Annotation> annotation;
        private boolean methods;
        private final List<RuleValidator> validators;

        private Builder(Class<? extends Annotation> annotation) {
            this.annotation = annotation;
            this.methods = false;
            this.validators = new ArrayList<RuleValidator>();
        }

        Builder forMethods() {
            methods = true;
            return this;
        }

        Builder withValidator(RuleValidator validator) {
            validators.add(validator);
            return this;
        }

        RuleMemberValidator build() {
            return new RuleMemberValidator(this);
        }
    }

    private static boolean isRuleType(FrameworkMember<?> member) {
        return isMethodRule(member) || isTestRule(member);
    }

    private static boolean isTestRule(FrameworkMember<?> member) {
        return TestRule.class.isAssignableFrom(member.getType());
    }

    private static boolean isMethodRule(FrameworkMember<?> member) {
        return MethodRule.class.isAssignableFrom(member.getType());
    }

    /**
     * Encapsulates a single piece of validation logic, used to determine if {@link org.junit.Rule} and
     * {@link org.junit.ClassRule} annotations have been used correctly
     */
    interface RuleValidator {
        /**
         * Examine the given member and add any violations of the strategy's validation logic to the given list of errors
         * @param member The member (field or member) to examine
         * @param annotation The type of rule annotation on the member
         * @param errors The list of errors to add validation violations to
         */
        void validate(FrameworkMember<?> member, Class<? extends Annotation> annotation, List<Throwable> errors);
    }

    /**
     * Requires the validated member to be non-static
     */
    private static final class MemberMustBeNonStaticOrAlsoClassRule implements RuleValidator {
        public void validate(FrameworkMember<?> member, Class<? extends Annotation> annotation, List<Throwable> errors) {
            boolean isMethodRuleMember = isMethodRule(member);
            boolean isClassRuleAnnotated = (member.getAnnotation(ClassRule.class) != null);

            // We disallow:
            //  - static MethodRule members
            //  - static @Rule annotated members
            //    - UNLESS they're also @ClassRule annotated
            // Note that MethodRule cannot be annotated with @ClassRule
            if (member.isStatic() && (isMethodRuleMember || !isClassRuleAnnotated)) {
                String message;
                if (isMethodRule(member)) {
                    message = "must not be static.";
                } else {
                    message = "must not be static or it must be annotated with @ClassRule.";
                }
                errors.add(new ValidationError(member, annotation, message));
            }
        }
    }

    /**
     * Requires the member to be static
     */
    private static final class MemberMustBeStatic implements RuleValidator {
        public void validate(FrameworkMember<?> member, Class<? extends Annotation> annotation, List<Throwable> errors) {
            if (!member.isStatic()) {
                errors.add(new ValidationError(member, annotation,
                        "must be static."));
            }
        }
    }

    /**
     * Requires the member's declaring class to be public
     */
    private static final class DeclaringClassMustBePublic implements RuleValidator {
        public void validate(FrameworkMember<?> member, Class<? extends Annotation> annotation, List<Throwable> errors) {
            if (!isDeclaringClassPublic(member)) {
                errors.add(new ValidationError(member, annotation,
                        "must be declared in a public class."));
            }
        }

        private boolean isDeclaringClassPublic(FrameworkMember<?> member) {
            return Modifier.isPublic(member.getDeclaringClass().getModifiers());
        }
    }

    /**
     * Requires the member to be public
     */
    private static final class MemberMustBePublic implements RuleValidator {
        public void validate(FrameworkMember<?> member, Class<? extends Annotation> annotation, List<Throwable> errors) {
            if (!member.isPublic()) {
                errors.add(new ValidationError(member, annotation,
                        "must be public."));
            }
        }
    }

    /**
     * Requires the member is a field implementing {@link org.junit.rules.MethodRule} or {@link org.junit.rules.TestRule}
     */
    private static final class FieldMustBeARule implements RuleValidator {
        public void validate(FrameworkMember<?> member, Class<? extends Annotation> annotation, List<Throwable> errors) {
            if (!isRuleType(member)) {
                errors.add(new ValidationError(member, annotation,
                        "must implement MethodRule or TestRule."));
            }
        }
    }

    /**
     * Require the member to return an implementation of {@link org.junit.rules.MethodRule} or
     * {@link org.junit.rules.TestRule}
     */
    private static final class MethodMustBeARule implements RuleValidator {
        public void validate(FrameworkMember<?> member, Class<? extends Annotation> annotation, List<Throwable> errors) {
            if (!isRuleType(member)) {
                errors.add(new ValidationError(member, annotation,
                        "must return an implementation of MethodRule or TestRule."));
            }
        }
    }
    
    /**
     * Require the member to return an implementation of {@link org.junit.rules.TestRule}
     */
    private static final class MethodMustBeATestRule implements RuleValidator {
        public void validate(FrameworkMember<?> member,
                Class<? extends Annotation> annotation, List<Throwable> errors) {
            if (!isTestRule(member)) {
                errors.add(new ValidationError(member, annotation, 
                        "must return an implementation of TestRule."));
            }
        }
    }
    
    /**
     * Requires the member is a field implementing {@link org.junit.rules.TestRule}
     */
    private static final class FieldMustBeATestRule implements RuleValidator {

        public void validate(FrameworkMember<?> member,
                Class<? extends Annotation> annotation, List<Throwable> errors) {
            if (!isTestRule(member)) {
                errors.add(new ValidationError(member, annotation,
                        "must implement TestRule."));
            }
        }
    }
}