ContextLoaderUtils.java 13.9 KB
Newer Older
1
/*
2
 * Copyright 2002-2019 the original author or authors.
3 4 5 6 7
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
S
Spring Operator 已提交
8
 *      https://www.apache.org/licenses/LICENSE-2.0
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.test.context.support;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
28

29
import org.springframework.core.annotation.AnnotationUtils;
S
Sam Brannen 已提交
30 31 32
import org.springframework.core.annotation.MergedAnnotation;
import org.springframework.core.annotation.MergedAnnotations;
import org.springframework.core.annotation.MergedAnnotations.SearchStrategy;
33 34 35 36
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextConfigurationAttributes;
import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.SmartContextLoader;
S
Sam Brannen 已提交
37 38
import org.springframework.test.context.TestConfiguration;
import org.springframework.test.context.TestConfiguration.EnclosingConfiguration;
P
Phillip Webb 已提交
39
import org.springframework.test.util.MetaAnnotationUtils.UntypedAnnotationDescriptor;
40 41 42
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

P
Phillip Webb 已提交
43 44 45
import static org.springframework.core.annotation.AnnotationUtils.getAnnotation;
import static org.springframework.core.annotation.AnnotationUtils.isAnnotationDeclaredLocally;
import static org.springframework.test.util.MetaAnnotationUtils.findAnnotationDescriptorForTypes;
46 47

/**
48 49 50 51
 * Utility methods for resolving {@link ContextConfigurationAttributes} from the
 * {@link ContextConfiguration @ContextConfiguration} and
 * {@link ContextHierarchy @ContextHierarchy} annotations for use with
 * {@link SmartContextLoader SmartContextLoaders}.
52 53 54 55 56
 *
 * @author Sam Brannen
 * @since 3.1
 * @see SmartContextLoader
 * @see ContextConfigurationAttributes
57
 * @see ContextConfiguration
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
 * @see ContextHierarchy
 */
abstract class ContextLoaderUtils {

	static final String GENERATED_CONTEXT_HIERARCHY_LEVEL_PREFIX = "ContextHierarchyLevel#";

	private static final Log logger = LogFactory.getLog(ContextLoaderUtils.class);


	/**
	 * Resolve the list of lists of {@linkplain ContextConfigurationAttributes context
	 * configuration attributes} for the supplied {@linkplain Class test class} and its
	 * superclasses, taking into account context hierarchies declared via
	 * {@link ContextHierarchy @ContextHierarchy} and
	 * {@link ContextConfiguration @ContextConfiguration}.
	 * <p>The outer list represents a top-down ordering of context configuration
	 * attributes, where each element in the list represents the context configuration
	 * declared on a given test class in the class hierarchy. Each nested list
	 * contains the context configuration attributes declared either via a single
	 * instance of {@code @ContextConfiguration} on the particular class or via
	 * multiple instances of {@code @ContextConfiguration} declared within a
	 * single {@code @ContextHierarchy} instance on the particular class.
	 * Furthermore, each nested list maintains the order in which
	 * {@code @ContextConfiguration} instances are declared.
	 * <p>Note that the {@link ContextConfiguration#inheritLocations inheritLocations} and
	 * {@link ContextConfiguration#inheritInitializers() inheritInitializers} flags of
	 * {@link ContextConfiguration @ContextConfiguration} will <strong>not</strong>
	 * be taken into consideration. If these flags need to be honored, that must be
	 * handled manually when traversing the nested lists returned by this method.
	 * @param testClass the class for which to resolve the context hierarchy attributes
	 * (must not be {@code null})
	 * @return the list of lists of configuration attributes for the specified class;
	 * never {@code null}
S
Sam Brannen 已提交
91
	 * @throws IllegalArgumentException if the supplied class is {@code null}; or if
92
	 * neither {@code @ContextConfiguration} nor {@code @ContextHierarchy} is
S
Sam Brannen 已提交
93 94
	 * <em>present</em> on the supplied class
	 * @throws IllegalStateException if a test class or composed annotation
95 96 97 98 99 100 101 102 103 104
	 * in the class hierarchy declares both {@code @ContextConfiguration} and
	 * {@code @ContextHierarchy} as top-level annotations.
	 * @since 3.2.2
	 * @see #buildContextHierarchyMap(Class)
	 * @see #resolveContextConfigurationAttributes(Class)
	 */
	@SuppressWarnings("unchecked")
	static List<List<ContextConfigurationAttributes>> resolveContextHierarchyAttributes(Class<?> testClass) {
		Assert.notNull(testClass, "Class must not be null");

105 106
		Class<ContextConfiguration> contextConfigType = ContextConfiguration.class;
		Class<ContextHierarchy> contextHierarchyType = ContextHierarchy.class;
107
		List<List<ContextConfigurationAttributes>> hierarchyAttributes = new ArrayList<>();
108

J
Juergen Hoeller 已提交
109 110
		UntypedAnnotationDescriptor desc =
				findAnnotationDescriptorForTypes(testClass, contextConfigType, contextHierarchyType);
111
		Assert.notNull(desc, () -> String.format(
J
Juergen Hoeller 已提交
112 113
					"Could not find an 'annotation declaring class' for annotation type [%s] or [%s] and test class [%s]",
					contextConfigType.getName(), contextHierarchyType.getName(), testClass.getName()));
114

J
Juergen Hoeller 已提交
115 116 117
		while (desc != null) {
			Class<?> rootDeclaringClass = desc.getRootDeclaringClass();
			Class<?> declaringClass = desc.getDeclaringClass();
118 119 120 121 122

			boolean contextConfigDeclaredLocally = isAnnotationDeclaredLocally(contextConfigType, declaringClass);
			boolean contextHierarchyDeclaredLocally = isAnnotationDeclaredLocally(contextHierarchyType, declaringClass);

			if (contextConfigDeclaredLocally && contextHierarchyDeclaredLocally) {
J
Juergen Hoeller 已提交
123 124 125
				String msg = String.format("Class [%s] has been configured with both @ContextConfiguration " +
						"and @ContextHierarchy. Only one of these annotations may be declared on a test class " +
						"or composed annotation.", declaringClass.getName());
126 127 128 129
				logger.error(msg);
				throw new IllegalStateException(msg);
			}

130
			List<ContextConfigurationAttributes> configAttributesList = new ArrayList<>();
131 132

			if (contextConfigDeclaredLocally) {
133
				ContextConfiguration contextConfiguration = AnnotationUtils.synthesizeAnnotation(
J
Juergen Hoeller 已提交
134 135 136
						desc.getAnnotationAttributes(), ContextConfiguration.class, desc.getRootDeclaringClass());
				convertContextConfigToConfigAttributesAndAddToList(
						contextConfiguration, rootDeclaringClass, configAttributesList);
137 138 139
			}
			else if (contextHierarchyDeclaredLocally) {
				ContextHierarchy contextHierarchy = getAnnotation(declaringClass, contextHierarchyType);
140 141 142 143 144
				if (contextHierarchy != null) {
					for (ContextConfiguration contextConfiguration : contextHierarchy.value()) {
						convertContextConfigToConfigAttributesAndAddToList(
								contextConfiguration, rootDeclaringClass, configAttributesList);
					}
145 146 147 148
				}
			}
			else {
				// This should theoretically never happen...
J
Juergen Hoeller 已提交
149 150
				String msg = String.format("Test class [%s] has been configured with neither @ContextConfiguration " +
						"nor @ContextHierarchy as a class-level annotation.", rootDeclaringClass.getName());
151 152 153 154 155
				logger.error(msg);
				throw new IllegalStateException(msg);
			}

			hierarchyAttributes.add(0, configAttributesList);
J
Juergen Hoeller 已提交
156 157
			desc = findAnnotationDescriptorForTypes(
					rootDeclaringClass.getSuperclass(), contextConfigType, contextHierarchyType);
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
		}

		return hierarchyAttributes;
	}

	/**
	 * Build a <em>context hierarchy map</em> for the supplied {@linkplain Class
	 * test class} and its superclasses, taking into account context hierarchies
	 * declared via {@link ContextHierarchy @ContextHierarchy} and
	 * {@link ContextConfiguration @ContextConfiguration}.
	 * <p>Each value in the map represents the consolidated list of {@linkplain
	 * ContextConfigurationAttributes context configuration attributes} for a
	 * given level in the context hierarchy (potentially across the test class
	 * hierarchy), keyed by the {@link ContextConfiguration#name() name} of the
	 * context hierarchy level.
	 * <p>If a given level in the context hierarchy does not have an explicit
	 * name (i.e., configured via {@link ContextConfiguration#name}), a name will
	 * be generated for that hierarchy level by appending the numerical level to
	 * the {@link #GENERATED_CONTEXT_HIERARCHY_LEVEL_PREFIX}.
	 * @param testClass the class for which to resolve the context hierarchy map
	 * (must not be {@code null})
	 * @return a map of context configuration attributes for the context hierarchy,
	 * keyed by context hierarchy level name; never {@code null}
	 * @throws IllegalArgumentException if the lists of context configuration
	 * attributes for each level in the {@code @ContextHierarchy} do not define
	 * unique context configuration within the overall hierarchy.
	 * @since 3.2.2
	 * @see #resolveContextHierarchyAttributes(Class)
	 */
	static Map<String, List<ContextConfigurationAttributes>> buildContextHierarchyMap(Class<?> testClass) {
S
Sam Brannen 已提交
188
		Map<String, List<ContextConfigurationAttributes>> map = new LinkedHashMap<>();
189 190 191 192 193 194 195 196 197 198 199 200 201 202
		int hierarchyLevel = 1;

		for (List<ContextConfigurationAttributes> configAttributesList : resolveContextHierarchyAttributes(testClass)) {
			for (ContextConfigurationAttributes configAttributes : configAttributesList) {
				String name = configAttributes.getName();

				// Assign a generated name?
				if (!StringUtils.hasText(name)) {
					name = GENERATED_CONTEXT_HIERARCHY_LEVEL_PREFIX + hierarchyLevel;
				}

				// Encountered a new context hierarchy level?
				if (!map.containsKey(name)) {
					hierarchyLevel++;
203
					map.put(name, new ArrayList<>());
204 205 206 207 208 209 210
				}

				map.get(name).add(configAttributes);
			}
		}

		// Check for uniqueness
211
		Set<List<ContextConfigurationAttributes>> set = new HashSet<>(map.values());
212
		if (set.size() != map.size()) {
J
Juergen Hoeller 已提交
213 214 215
			String msg = String.format("The @ContextConfiguration elements configured via @ContextHierarchy in " +
					"test class [%s] and its superclasses must define unique contexts per hierarchy level.",
					testClass.getName());
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
			logger.error(msg);
			throw new IllegalStateException(msg);
		}

		return map;
	}

	/**
	 * Resolve the list of {@linkplain ContextConfigurationAttributes context
	 * configuration attributes} for the supplied {@linkplain Class test class} and its
	 * superclasses.
	 * <p>Note that the {@link ContextConfiguration#inheritLocations inheritLocations} and
	 * {@link ContextConfiguration#inheritInitializers() inheritInitializers} flags of
	 * {@link ContextConfiguration @ContextConfiguration} will <strong>not</strong>
	 * be taken into consideration. If these flags need to be honored, that must be
	 * handled manually when traversing the list returned by this method.
J
Juergen Hoeller 已提交
232 233
	 * @param testClass the class for which to resolve the configuration attributes
	 * (must not be {@code null})
234 235 236 237 238 239 240 241 242 243
	 * @return the list of configuration attributes for the specified class, ordered
	 * <em>bottom-up</em> (i.e., as if we were traversing up the class hierarchy);
	 * never {@code null}
	 * @throws IllegalArgumentException if the supplied class is {@code null} or if
	 * {@code @ContextConfiguration} is not <em>present</em> on the supplied class
	 */
	static List<ContextConfigurationAttributes> resolveContextConfigurationAttributes(Class<?> testClass) {
		Assert.notNull(testClass, "Class must not be null");

		Class<ContextConfiguration> annotationType = ContextConfiguration.class;
S
Sam Brannen 已提交
244
		MergedAnnotations mergedAnnotations = MergedAnnotations.from(testClass, getSearchStrategy(testClass));
S
Sam Brannen 已提交
245 246 247
		Assert.isTrue(mergedAnnotations.isPresent(annotationType), () -> String.format(
			"Could not find an 'annotation declaring class' for annotation type [%s] and class [%s]",
			annotationType.getName(), testClass.getName()));
248

249
		List<ContextConfigurationAttributes> attributesList = new ArrayList<>();
S
Sam Brannen 已提交
250 251
		mergedAnnotations.stream(annotationType).forEach(mergedAnnotation ->
				resolveContextConfigurationAttributes(attributesList, mergedAnnotation));
252 253 254
		return attributesList;
	}

S
Sam Brannen 已提交
255 256 257 258 259 260 261 262 263 264 265 266
	private static SearchStrategy getSearchStrategy(Class<?> testClass) {
		EnclosingConfiguration enclosingConfiguration =
			MergedAnnotations.from(testClass, SearchStrategy.TYPE_HIERARCHY_AND_ENCLOSING_CLASSES)
				.stream(TestConfiguration.class)
				.map(mergedAnnotation -> mergedAnnotation.getEnum("value", EnclosingConfiguration.class))
				.findFirst()
				.orElse(EnclosingConfiguration.OVERRIDE);
		return (enclosingConfiguration == EnclosingConfiguration.INHERIT ?
				SearchStrategy.TYPE_HIERARCHY_AND_ENCLOSING_CLASSES :
				SearchStrategy.TYPE_HIERARCHY);
	}

267
	private static void resolveContextConfigurationAttributes(List<ContextConfigurationAttributes> attributesList,
S
Sam Brannen 已提交
268 269 270 271 272
			MergedAnnotation<ContextConfiguration> mergedAnnotation) {

		Class<?> rootDeclaringClass = (Class<?>) mergedAnnotation.getSource();
		convertContextConfigToConfigAttributesAndAddToList(mergedAnnotation.synthesize(),
				rootDeclaringClass, attributesList);
273 274
	}

275 276 277 278 279 280
	/**
	 * Convenience method for creating a {@link ContextConfigurationAttributes}
	 * instance from the supplied {@link ContextConfiguration} annotation and
	 * declaring class and then adding the attributes to the supplied list.
	 */
	private static void convertContextConfigToConfigAttributesAndAddToList(ContextConfiguration contextConfiguration,
S
Sam Brannen 已提交
281
			Class<?> declaringClass, List<ContextConfigurationAttributes> attributesList) {
J
Juergen Hoeller 已提交
282

283 284
		if (logger.isTraceEnabled()) {
			logger.trace(String.format("Retrieved @ContextConfiguration [%s] for declaring class [%s].",
J
Juergen Hoeller 已提交
285
					contextConfiguration, declaringClass.getName()));
286
		}
J
Juergen Hoeller 已提交
287 288
		ContextConfigurationAttributes attributes =
				new ContextConfigurationAttributes(declaringClass, contextConfiguration);
289 290 291 292 293 294
		if (logger.isTraceEnabled()) {
			logger.trace("Resolved context configuration attributes: " + attributes);
		}
		attributesList.add(attributes);
	}

295
}