Debian Codegraph @

junit-jupiter-api/src/main/java/org/junit/jupiter/api/DisplayNameGenerator.java

raw symbols SCIP
1 /*
2 * Copyright 2015-2024 the original author or authors.
3 *
4 * All rights reserved. This program and the accompanying materials are
5 * made available under the terms of the Eclipse Public License v2.0 which
6 * accompanies this distribution and is available at
7 *
8 * https://www.eclipse.org/legal/epl-v20.html
9 */
10
11 package org.junit.jupiter.api;
12
13 import static org.apiguardian.api.API.Status.STABLE;
14 import static org.junit.platform.commons.support.ModifierSupport.isStatic;
15 import static org.junit.platform.commons.util.AnnotationUtils.findAnnotation;
16
17 import java.lang.reflect.Method;
18 import java.util.Optional;
19 import java.util.function.Predicate;
20
21 import org.apiguardian.api.API;
22 import org.junit.platform.commons.util.ClassUtils;
23 import org.junit.platform.commons.util.Preconditions;
24 import org.junit.platform.commons.util.ReflectionUtils;
25
26 /**
27 * {@code DisplayNameGenerator} defines the SPI for generating display names
28 * programmatically.
29 *
30 * <p>Display names are typically used for test reporting in IDEs and build
31 * tools and may contain spaces, special characters, and even emoji.
32 *
33 * <p>Concrete implementations must have a <em>default constructor</em>.
34 *
35 * <p>A {@link DisplayNameGenerator} can be configured <em>globally</em> for the
36 * entire test suite via the {@value #DEFAULT_GENERATOR_PROPERTY_NAME}
37 * configuration parameter (see the User Guide for details) or <em>locally</em>
38 * for a test class via the {@link DisplayNameGeneration @DisplayNameGeneration}
39 * annotation.
40 *
41 * <h2>Built-in Implementations</h2>
42 * <ul>
43 * <li>{@link Standard}</li>
44 * <li>{@link Simple}</li>
45 * <li>{@link ReplaceUnderscores}</li>
46 * <li>{@link IndicativeSentences}</li>
47 * </ul>
48 *
49 * @since 5.4
50 * @see DisplayName @DisplayName
51 * @see DisplayNameGeneration @DisplayNameGeneration
52 */
53 @API(status = STABLE, since = "5.7")
54 public interface DisplayNameGenerator {
55
56 /**
57 * Property name used to set the default display name generator class name:
58 * {@value}
59 *
60 * <h4>Supported Values</h4>
61 *
62 * <p>Supported values include fully qualified class names for types that
63 * implement {@link DisplayNameGenerator}.
64 *
65 * <p>If not specified, the default is
66 * {@link DisplayNameGenerator.Standard}.
67 *
68 * @since 5.5
69 */
70 @API(status = STABLE, since = "5.9")
71 String DEFAULT_GENERATOR_PROPERTY_NAME = "junit.jupiter.displayname.generator.default";
72
73 /**
74 * Generate a display name for the given top-level or {@code static} nested test class.
75 *
76 * <p>If it returns {@code null}, the default display name generator will be used instead.
77 *
78 * @param testClass the class to generate a name for; never {@code null}
79 * @return the display name for the class; never blank
80 */
81 String generateDisplayNameForClass(Class<?> testClass);
82
83 /**
84 * Generate a display name for the given {@link Nested @Nested} inner test class.
85 *
86 * <p>If it returns {@code null}, the default display name generator will be used instead.
87 *
88 * @param nestedClass the class to generate a name for; never {@code null}
89 * @return the display name for the nested class; never blank
90 */
91 String generateDisplayNameForNestedClass(Class<?> nestedClass);
92
93 /**
94 * Generate a display name for the given method.
95 *
96 * <p>If it returns {@code null}, the default display name generator will be used instead.
97 *
98 * @implNote The class instance supplied as {@code testClass} may differ from
99 * the class returned by {@code testMethod.getDeclaringClass()} &mdash; for
100 * example, when a test method is inherited from a superclass.
101 *
102 * @param testClass the class the test method is invoked on; never {@code null}
103 * @param testMethod method to generate a display name for; never {@code null}
104 * @return the display name for the test; never blank
105 */
106 String generateDisplayNameForMethod(Class<?> testClass, Method testMethod);
107
108 /**
109 * Generate a string representation of the formal parameters of the supplied
110 * method, consisting of the {@linkplain Class#getSimpleName() simple names}
111 * of the parameter types, separated by commas, and enclosed in parentheses.
112 *
113 * @param method the method from to extract the parameter types from; never
114 * {@code null}
115 * @return a string representation of all parameter types of the supplied
116 * method or {@code "()"} if the method declares no parameters
117 */
118 static String parameterTypesAsString(Method method) {
119 Preconditions.notNull(method, "Method must not be null");
120 return '(' + ClassUtils.nullSafeToString(Class::getSimpleName, method.getParameterTypes()) + ')';
121 }
122
123 /**
124 * Standard {@code DisplayNameGenerator}.
125 *
126 * <p>This implementation matches the standard display name generation
127 * behavior in place since JUnit Jupiter 5.0 was released.
128 */
129 class Standard implements DisplayNameGenerator {
130
131 static final DisplayNameGenerator INSTANCE = new Standard();
132
133 public Standard() {
134 }
135
136 @Override
137 public String generateDisplayNameForClass(Class<?> testClass) {
138 String name = testClass.getName();
139 int lastDot = name.lastIndexOf('.');
140 return name.substring(lastDot + 1);
141 }
142
143 @Override
144 public String generateDisplayNameForNestedClass(Class<?> nestedClass) {
145 return nestedClass.getSimpleName();
146 }
147
148 @Override
149 public String generateDisplayNameForMethod(Class<?> testClass, Method testMethod) {
150 return testMethod.getName() + parameterTypesAsString(testMethod);
151 }
152 }
153
154 /**
155 * Simple {@code DisplayNameGenerator} that removes trailing parentheses
156 * for methods with no parameters.
157 *
158 * <p>This generator extends the functionality of {@link Standard} by
159 * removing parentheses ({@code '()'}) found at the end of method names
160 * with no parameters.
161 */
162 class Simple extends Standard {
163
164 static final DisplayNameGenerator INSTANCE = new Simple();
165
166 public Simple() {
167 }
168
169 @Override
170 public String generateDisplayNameForMethod(Class<?> testClass, Method testMethod) {
171 String displayName = testMethod.getName();
172 if (hasParameters(testMethod)) {
173 displayName += ' ' + parameterTypesAsString(testMethod);
174 }
175 return displayName;
176 }
177
178 private static boolean hasParameters(Method method) {
179 return method.getParameterCount() > 0;
180 }
181
182 }
183
184 /**
185 * {@code DisplayNameGenerator} that replaces underscores with spaces.
186 *
187 * <p>This generator extends the functionality of {@link Simple} by
188 * replacing all underscores ({@code '_'}) found in class and method names
189 * with spaces ({@code ' '}).
190 */
191 class ReplaceUnderscores extends Simple {
192
193 static final DisplayNameGenerator INSTANCE = new ReplaceUnderscores();
194
195 public ReplaceUnderscores() {
196 }
197
198 @Override
199 public String generateDisplayNameForClass(Class<?> testClass) {
200 return replaceUnderscores(super.generateDisplayNameForClass(testClass));
201 }
202
203 @Override
204 public String generateDisplayNameForNestedClass(Class<?> nestedClass) {
205 return replaceUnderscores(super.generateDisplayNameForNestedClass(nestedClass));
206 }
207
208 @Override
209 public String generateDisplayNameForMethod(Class<?> testClass, Method testMethod) {
210 return replaceUnderscores(super.generateDisplayNameForMethod(testClass, testMethod));
211 }
212
213 private static String replaceUnderscores(String name) {
214 return name.replace('_', ' ');
215 }
216
217 }
218
219 /**
220 * {@code DisplayNameGenerator} that generates complete sentences.
221 *
222 * <p>This generator generates display names that build up complete sentences
223 * by concatenating the names of the test and the enclosing classes. The
224 * sentence fragments are concatenated using a separator. The separator and
225 * the display name generator for individual sentence fragments can be configured
226 * via the {@link IndicativeSentencesGeneration @IndicativeSentencesGeneration}
227 * annotation.
228 *
229 * @since 5.7
230 */
231 @API(status = STABLE, since = "5.10")
232 class IndicativeSentences implements DisplayNameGenerator {
233
234 static final DisplayNameGenerator INSTANCE = new IndicativeSentences();
235
236 public IndicativeSentences() {
237 }
238
239 @Override
240 public String generateDisplayNameForClass(Class<?> testClass) {
241 return getGeneratorFor(testClass).generateDisplayNameForClass(testClass);
242 }
243
244 @Override
245 public String generateDisplayNameForNestedClass(Class<?> nestedClass) {
246 return getSentenceBeginning(nestedClass);
247 }
248
249 @Override
250 public String generateDisplayNameForMethod(Class<?> testClass, Method testMethod) {
251 return getSentenceBeginning(testClass) + getFragmentSeparator(testClass)
252 + getGeneratorFor(testClass).generateDisplayNameForMethod(testClass, testMethod);
253 }
254
255 private String getSentenceBeginning(Class<?> testClass) {
256 Class<?> enclosingClass = testClass.getEnclosingClass();
257 boolean topLevelTestClass = (enclosingClass == null || isStatic(testClass));
258 Optional<String> displayName = findAnnotation(testClass, DisplayName.class)//
259 .map(DisplayName::value).map(String::trim);
260
261 if (topLevelTestClass) {
262 if (displayName.isPresent()) {
263 return displayName.get();
264 }
265 Class<? extends DisplayNameGenerator> generatorClass = findDisplayNameGeneration(testClass)//
266 .map(DisplayNameGeneration::value)//
267 .filter(not(IndicativeSentences.class))//
268 .orElse(null);
269 if (generatorClass != null) {
270 return getDisplayNameGenerator(generatorClass).generateDisplayNameForClass(testClass);
271 }
272 return generateDisplayNameForClass(testClass);
273 }
274
275 // Only build prefix based on the enclosing class if the enclosing
276 // class is also configured to use the IndicativeSentences generator.
277 boolean buildPrefix = findDisplayNameGeneration(enclosingClass)//
278 .map(DisplayNameGeneration::value)//
279 .filter(IndicativeSentences.class::equals)//
280 .isPresent();
281
282 String prefix = (buildPrefix ? getSentenceBeginning(enclosingClass) + getFragmentSeparator(testClass) : "");
283
284 return prefix + displayName.orElseGet(
285 () -> getGeneratorFor(testClass).generateDisplayNameForNestedClass(testClass));
286 }
287
288 /**
289 * Get the sentence fragment separator.
290 *
291 * <p>If {@link IndicativeSentencesGeneration @IndicativeSentencesGeneration}
292 * is present (searching enclosing classes if not found locally), the
293 * configured {@link IndicativeSentencesGeneration#separator() separator}
294 * will be used. Otherwise, {@link IndicativeSentencesGeneration#DEFAULT_SEPARATOR}
295 * will be used.
296 *
297 * @param testClass the test class to search on for {@code @IndicativeSentencesGeneration}
298 * @return the sentence fragment separator
299 */
300 private static String getFragmentSeparator(Class<?> testClass) {
301 return findIndicativeSentencesGeneration(testClass)//
302 .map(IndicativeSentencesGeneration::separator)//
303 .orElse(IndicativeSentencesGeneration.DEFAULT_SEPARATOR);
304 }
305
306 /**
307 * Get the display name generator to use for the supplied test class.
308 *
309 * <p>If {@link IndicativeSentencesGeneration @IndicativeSentencesGeneration}
310 * is present (searching enclosing classes if not found locally), the
311 * configured {@link IndicativeSentencesGeneration#generator() generator}
312 * will be used. Otherwise, {@link IndicativeSentencesGeneration#DEFAULT_GENERATOR}
313 * will be used.
314 *
315 * @param testClass the test class to search on for {@code @IndicativeSentencesGeneration}
316 * @return the {@code DisplayNameGenerator} instance to use
317 */
318 private static DisplayNameGenerator getGeneratorFor(Class<?> testClass) {
319 return findIndicativeSentencesGeneration(testClass)//
320 .map(IndicativeSentencesGeneration::generator)//
321 .filter(not(IndicativeSentences.class))//
322 .map(DisplayNameGenerator::getDisplayNameGenerator)//
323 .orElseGet(() -> getDisplayNameGenerator(IndicativeSentencesGeneration.DEFAULT_GENERATOR));
324 }
325
326 /**
327 * Find the first {@code DisplayNameGeneration} annotation that is either
328 * <em>directly present</em>, <em>meta-present</em>, or <em>indirectly present</em>
329 * on the supplied {@code testClass} or on an enclosing class.
330 *
331 * @param testClass the test class on which to find the annotation; never {@code null}
332 * @return an {@code Optional} containing the annotation, potentially empty if not found
333 */
334 private static Optional<DisplayNameGeneration> findDisplayNameGeneration(Class<?> testClass) {
335 return findAnnotation(testClass, DisplayNameGeneration.class, true);
336 }
337
338 /**
339 * Find the first {@code IndicativeSentencesGeneration} annotation that is either
340 * <em>directly present</em>, <em>meta-present</em>, or <em>indirectly present</em>
341 * on the supplied {@code testClass} or on an enclosing class.
342 *
343 * @param testClass the test class on which to find the annotation; never {@code null}
344 * @return an {@code Optional} containing the annotation, potentially empty if not found
345 */
346 private static Optional<IndicativeSentencesGeneration> findIndicativeSentencesGeneration(Class<?> testClass) {
347 return findAnnotation(testClass, IndicativeSentencesGeneration.class, true);
348 }
349
350 private static Predicate<Class<?>> not(Class<?> clazz) {
351 return ((Predicate<Class<?>>) clazz::equals).negate();
352 }
353
354 }
355
356 /**
357 * Return the {@code DisplayNameGenerator} instance corresponding to the
358 * given {@code Class}.
359 *
360 * @param generatorClass the generator's {@code Class}; never {@code null},
361 * has to be a {@code DisplayNameGenerator} implementation
362 * @return a {@code DisplayNameGenerator} implementation instance
363 */
364 static DisplayNameGenerator getDisplayNameGenerator(Class<?> generatorClass) {
365 Preconditions.notNull(generatorClass, "Class must not be null");
366 Preconditions.condition(DisplayNameGenerator.class.isAssignableFrom(generatorClass),
367 "Class must be a DisplayNameGenerator implementation");
368 if (generatorClass == Standard.class) {
369 return Standard.INSTANCE;
370 }
371 if (generatorClass == Simple.class) {
372 return Simple.INSTANCE;
373 }
374 if (generatorClass == ReplaceUnderscores.class) {
375 return ReplaceUnderscores.INSTANCE;
376 }
377 if (generatorClass == IndicativeSentences.class) {
378 return IndicativeSentences.INSTANCE;
379 }
380 return (DisplayNameGenerator) ReflectionUtils.newInstance(generatorClass);
381 }
382
383 }