GeezerVison is showing github.com — Support CSV headers in display names in parameterized tests · junit-team/junit-framework@4ef6e70
File treeExpand file treeCollapse file tree Open diff view settings main/java/org/junit/jupiter/params/provider java/org/junit/jupiter/params resources/org/junit/jupiter/params
Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: documentation/src/docs/asciidoc/release-notes/release-notes-5.8.2.adoc +7-1Lines changed: 7 additions & 1 deletion - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
| 6 | 6 | *Scope:* | 7 | 7 |
| 8 | 8 | * Text blocks in `@CsvSource` are treated like CSV files | | 9 | +* CSV headers in display names for `@CsvSource` and `@CsvFileSource` | 9 | 10 | * Custom quote character support in `@CsvSource` and `@CsvFileSource` | 10 | 11 |
| 11 | 12 | For a complete list of all _closed_ issues and pull requests for this release, consult the | @@ -29,8 +30,13 @@ No changes. | 29 | 30 | quoted strings. See the | 30 | 31 | <<../user-guide/index.adoc#writing-tests-parameterized-tests-sources-CsvSource, User | 31 | 32 | Guide>> for details and examples. | | 33 | +* CSV headers can now be used in display names in parameterized tests. See | | 34 | + <<../user-guide/index.adoc#writing-tests-parameterized-tests-sources-CsvSource, | | 35 | + `@CsvSource`>> and | | 36 | + <<../user-guide/index.adoc#writing-tests-parameterized-tests-sources-CsvFileSource, | | 37 | + `@CsvFileSource`>> in the User Guide for details and examples. | 32 | 38 | * The quote character for _quoted strings_ in `@CsvSource` and `@CsvFileSource` is now | 33 | | - configurable via new `quoteCharacter` attributes in each annotation. | | 39 | + configurable via a new `quoteCharacter` attribute in each annotation. | 34 | 40 |
| 35 | 41 |
| 36 | 42 | [[release-notes-5.8.2-junit-vintage]] | |
Collapse file Copy file name to clipboardExpand all lines: documentation/src/docs/asciidoc/user-guide/writing-tests.adoc +44-5Lines changed: 44 additions & 5 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -1332,7 +1332,9 @@ include::{testDir}/example/ExternalMethodSourceDemo.java[tags=external_MethodSou | 1332 | 1332 |
| 1333 | 1333 | `@CsvSource` allows you to express argument lists as comma-separated values (i.e., CSV | 1334 | 1334 | `String` literals). Each string provided via the `value` attribute in `@CsvSource` | 1335 | | -represents a CSV record and results in one invocation of the parameterized test. | | 1335 | +represents a CSV record and results in one invocation of the parameterized test. The first | | 1336 | +record may optionally be used to supply CSV headers (see the Javadoc for the | | 1337 | +`useHeadersInDisplayName` attribute for details and an example). | 1336 | 1338 |
| 1337 | 1339 | [source,java,indent=0] | 1338 | 1340 | ---- | @@ -1375,12 +1377,16 @@ by default. This behavior can be changed by setting the | 1375 | 1377 | If the programming language you are using supports _text blocks_ -- for example, Java SE | 1376 | 1378 | 15 or higher -- you can alternatively use the `textBlock` attribute of `@CsvSource`. Each | 1377 | 1379 | record within a text block represents a CSV record and results in one invocation of the | 1378 | | -parameterized test. Using a text block, the previous example can be implemented as follows. | | 1380 | +parameterized test. The first record may optionally be used to supply CSV headers by | | 1381 | +setting the `useHeadersInDisplayName` attribute to `true` as in the example below. | | 1382 | + | | 1383 | +Using a text block, the previous example can be implemented as follows. | 1379 | 1384 |
| 1380 | 1385 | [source,java,indent=0] | 1381 | 1386 | ---- | 1382 | | -@ParameterizedTest | 1383 | | -@CsvSource(textBlock = """ | | 1387 | +@ParameterizedTest(name = "[{index}] {arguments}") | | 1388 | +@CsvSource(useHeadersInDisplayName = true, textBlock = """ | | 1389 | + FRUIT, RANK | 1384 | 1390 | apple, 1 | 1385 | 1391 | banana, 2 | 1386 | 1392 | 'lemon, lime', 0xF1 | @@ -1391,6 +1397,15 @@ void testWithCsvSource(String fruit, int rank) { | 1391 | 1397 | } | 1392 | 1398 | ---- | 1393 | 1399 |
| | 1400 | +The generated display names for the previous example include the CSV header names. | | 1401 | + | | 1402 | +---- | | 1403 | +[1] FRUIT = apple, RANK = 1 | | 1404 | +[2] FRUIT = banana, RANK = 2 | | 1405 | +[3] FRUIT = lemon, lime, RANK = 0xF1 | | 1406 | +[4] FRUIT = strawberry, RANK = 700_000 | | 1407 | +---- | | 1408 | + | 1394 | 1409 | In contrast to CSV records supplied via the `value` attribute, a text block can contain | 1395 | 1410 | comments. Any line beginning with a `+++#+++` symbol will be treated as a comment and | 1396 | 1411 | ignored. Note, however, that the `+++#+++` symbol must be the first character on the line | @@ -1435,7 +1450,11 @@ your text block. | 1435 | 1450 |
| 1436 | 1451 | `@CsvFileSource` lets you use comma-separated value (CSV) files from the classpath or the | 1437 | 1452 | local file system. Each record from a CSV file results in one invocation of the | 1438 | | -parameterized test. | | 1453 | +parameterized test. The first record may optionally be used to supply CSV headers. You can | | 1454 | +instruct JUnit to ignore the headers via the `numLinesToSkip` attribute. If you would like | | 1455 | +for the headers to be used in the display names, you can set the `useHeadersInDisplayName` | | 1456 | +attribute to `true`. The examples below demonstrate the use of `numLinesToSkip` and | | 1457 | +`useHeadersInDisplayName`. | 1439 | 1458 |
| 1440 | 1459 | The default delimiter is a comma (`,`), but you can use another character by setting the | 1441 | 1460 | `delimiter` attribute. Alternatively, the `delimiterString` attribute allows you to use a | @@ -1457,6 +1476,26 @@ include::{testDir}/example/ParameterizedTestDemo.java[tags=CsvFileSource_example | 1457 | 1476 | include::{testResourcesDir}/two-column.csv[] | 1458 | 1477 | ---- | 1459 | 1478 |
| | 1479 | +The following listing shows the generated display names for the first two parameterized | | 1480 | +test methods above. | | 1481 | + | | 1482 | +---- | | 1483 | +[1] country=Sweden, reference=1 | | 1484 | +[2] country=Poland, reference=2 | | 1485 | +[3] country=United States of America, reference=3 | | 1486 | +[4] country=France, reference=700_000 | | 1487 | +---- | | 1488 | + | | 1489 | +The following listing shows the generated display names for the last parameterized test | | 1490 | +method above that uses CSV header names. | | 1491 | + | | 1492 | +---- | | 1493 | +[1] COUNTRY = Sweden, REFERENCE = 1 | | 1494 | +[2] COUNTRY = Poland, REFERENCE = 2 | | 1495 | +[3] COUNTRY = United States of America, REFERENCE = 3 | | 1496 | +[4] COUNTRY = France, REFERENCE = 700_000 | | 1497 | +---- | | 1498 | + | 1460 | 1499 | In contrast to the default syntax used in `@CsvSource`, `@CsvFileSource` uses a double | 1461 | 1500 | quote (`+++"+++`) as the quote character by default, but this can be changed via the | 1462 | 1501 | `quoteCharacter` attribute. See the `"United States of America"` value in the example | |
Collapse file Copy file name to clipboardExpand all lines: documentation/src/test/java/example/ParameterizedTestDemo.java +7Lines changed: 7 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -236,6 +236,13 @@ void testWithCsvFileSourceFromFile(String country, int reference) { | 236 | 236 | assertNotNull(country); | 237 | 237 | assertNotEquals(0, reference); | 238 | 238 | } | | 239 | + | | 240 | + @ParameterizedTest(name = "[{index}] {arguments}") | | 241 | + @CsvFileSource(resources = "/two-column.csv", useHeadersInDisplayName = true) | | 242 | + void testWithCsvFileSourceAndHeaders(String country, int reference) { | | 243 | + assertNotNull(country); | | 244 | + assertNotEquals(0, reference); | | 245 | + } | 239 | 246 | // end::CsvFileSource_example[] | 240 | 247 |
| 241 | 248 | // tag::ArgumentsSource_example[] | |
Collapse file Copy file name to clipboardExpand all lines: documentation/src/test/resources/two-column.csv +1-1Lines changed: 1 addition & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
| 1 | | -Country, Reference | | 1 | +COUNTRY, REFERENCE | 2 | 2 | Sweden, 1 | 3 | 3 | Poland, 2 | 4 | 4 | "United States of America", 3 | |
Collapse file Copy file name to clipboardExpand all lines: junit-jupiter-params/src/main/java/org/junit/jupiter/params/provider/CsvArgumentsProvider.java +69-27Lines changed: 69 additions & 27 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 15 | 15 |
| 16 | 16 | import java.io.StringReader; | 17 | 17 | import java.lang.annotation.Annotation; | | 18 | +import java.util.ArrayList; | 18 | 19 | import java.util.Arrays; | 19 | 20 | import java.util.List; | 20 | 21 | import java.util.Set; | | 23 | 24 |
| 24 | 25 | import com.univocity.parsers.csv.CsvParser; | 25 | 26 |
| | 27 | +import org.junit.jupiter.api.Named; | 26 | 28 | import org.junit.jupiter.api.extension.ExtensionContext; | 27 | 29 | import org.junit.jupiter.params.support.AnnotationConsumer; | 28 | 30 | import org.junit.platform.commons.PreconditionViolationException; | @@ -53,56 +55,96 @@ public Stream<? extends Arguments> provideArguments(ExtensionContext context) { | 53 | 55 | Preconditions.condition(this.annotation.value().length > 0 ^ textBlockDeclared, | 54 | 56 | () -> "@CsvSource must be declared with either `value` or `textBlock` but not both"); | 55 | 57 |
| 56 | | - if (textBlockDeclared) { | 57 | | - return parseTextBlock(this.annotation.textBlock()).stream().map(Arguments::of); | 58 | | - } | 59 | | - | 60 | | - AtomicInteger index = new AtomicInteger(0); | 61 | | - // @formatter:off | 62 | | - return Arrays.stream(this.annotation.value()) | 63 | | - .map(line -> parseLine(line, index.incrementAndGet())) | 64 | | - .map(Arguments::of); | 65 | | - // @formatter:on | | 58 | + return textBlockDeclared ? parseTextBlock() : parseValueArray(); | 66 | 59 | } | 67 | 60 |
| 68 | | - private List<String[]> parseTextBlock(String textBlock) { | | 61 | + private Stream<Arguments> parseTextBlock() { | | 62 | + String textBlock = this.annotation.textBlock(); | | 63 | + boolean useHeadersInDisplayName = this.annotation.useHeadersInDisplayName(); | | 64 | + List<Arguments> argumentsList = new ArrayList<>(); | | 65 | + | 69 | 66 | try { | 70 | | - AtomicInteger index = new AtomicInteger(0); | 71 | 67 | List<String[]> csvRecords = this.csvParser.parseAll(new StringReader(textBlock)); | | 68 | + String[] headers = useHeadersInDisplayName ? getHeaders(this.csvParser) : null; | | 69 | + | | 70 | + AtomicInteger index = new AtomicInteger(0); | 72 | 71 | for (String[] csvRecord : csvRecords) { | 73 | 72 | index.incrementAndGet(); | 74 | 73 | Preconditions.notNull(csvRecord, | 75 | | - () -> "Line at index " + index.get() + " contains invalid CSV: \"\"\"\n" + textBlock + "\n\"\"\""); | 76 | | - processNullValues(csvRecord, this.nullValues); | | 74 | + () -> "Record at index " + index + " contains invalid CSV: \"\"\"\n" + textBlock + "\n\"\"\""); | | 75 | + argumentsList.add(processCsvRecord(csvRecord, this.nullValues, useHeadersInDisplayName, headers)); | 77 | 76 | } | 78 | | - return csvRecords; | 79 | 77 | } | 80 | 78 | catch (Throwable throwable) { | 81 | 79 | throw handleCsvException(throwable, this.annotation); | 82 | 80 | } | | 81 | + | | 82 | + return argumentsList.stream(); | 83 | 83 | } | 84 | 84 |
| 85 | | - private String[] parseLine(String line, int index) { | | 85 | + private Stream<Arguments> parseValueArray() { | | 86 | + boolean useHeadersInDisplayName = this.annotation.useHeadersInDisplayName(); | | 87 | + List<Arguments> argumentsList = new ArrayList<>(); | | 88 | + | 86 | 89 | try { | 87 | | - String[] csvRecord = this.csvParser.parseLine(line + LINE_SEPARATOR); | 88 | | - Preconditions.notNull(csvRecord, | 89 | | - () -> "Line at index " + index + " contains invalid CSV: \"" + line + "\""); | 90 | | - processNullValues(csvRecord, this.nullValues); | 91 | | - return csvRecord; | | 90 | + String[] headers = null; | | 91 | + AtomicInteger index = new AtomicInteger(0); | | 92 | + for (String input : this.annotation.value()) { | | 93 | + index.incrementAndGet(); | | 94 | + String[] csvRecord = this.csvParser.parseLine(input + LINE_SEPARATOR); | | 95 | + // Lazily retrieve headers if necessary. | | 96 | + if (useHeadersInDisplayName && headers == null) { | | 97 | + headers = getHeaders(this.csvParser); | | 98 | + } | | 99 | + Preconditions.notNull(csvRecord, | | 100 | + () -> "Record at index " + index + " contains invalid CSV: \"" + input + "\""); | | 101 | + argumentsList.add(processCsvRecord(csvRecord, this.nullValues, useHeadersInDisplayName, headers)); | | 102 | + } | 92 | 103 | } | 93 | 104 | catch (Throwable throwable) { | 94 | 105 | throw handleCsvException(throwable, this.annotation); | 95 | 106 | } | | 107 | + | | 108 | + return argumentsList.stream(); | 96 | 109 | } | 97 | 110 |
| 98 | | - static void processNullValues(String[] csvRecord, Set<String> nullValues) { | 99 | | - if (!nullValues.isEmpty()) { | 100 | | - for (int i = 0; i < csvRecord.length; i++) { | 101 | | - if (nullValues.contains(csvRecord[i])) { | 102 | | - csvRecord[i] = null; | 103 | | - } | | 111 | + // Cannot get parsed headers until after parsing has started. | | 112 | + static String[] getHeaders(CsvParser csvParser) { | | 113 | + return Arrays.stream(csvParser.getContext().parsedHeaders())// | | 114 | + .map(String::trim)// | | 115 | + .toArray(String[]::new); | | 116 | + } | | 117 | + | | 118 | + /** | | 119 | + * Processes custom null values, supports wrapping of column values in | | 120 | + * {@link Named} if necessary (for CSV header support), and returns the | | 121 | + * CSV record wrapped in an {@link Arguments} instance. | | 122 | + */ | | 123 | + static Arguments processCsvRecord(Object[] csvRecord, Set<String> nullValues, boolean useHeadersInDisplayName, | | 124 | + String[] headers) { | | 125 | + | | 126 | + // Nothing to process? | | 127 | + if (nullValues.isEmpty() && !useHeadersInDisplayName) { | | 128 | + return Arguments.of(csvRecord); | | 129 | + } | | 130 | + | | 131 | + Preconditions.condition(!useHeadersInDisplayName || (csvRecord.length <= headers.length), | | 132 | + () -> String.format( | | 133 | + "The number of columns (%d) exceeds the number of supplied headers (%d) in CSV record: %s", | | 134 | + csvRecord.length, headers.length, Arrays.toString(csvRecord))); | | 135 | + | | 136 | + Object[] arguments = new Object[csvRecord.length]; | | 137 | + for (int i = 0; i < csvRecord.length; i++) { | | 138 | + Object column = csvRecord[i]; | | 139 | + if (nullValues.contains(column)) { | | 140 | + column = null; | | 141 | + } | | 142 | + if (useHeadersInDisplayName) { | | 143 | + column = Named.of(headers[i] + " = " + column, column); | 104 | 144 | } | | 145 | + arguments[i] = column; | 105 | 146 | } | | 147 | + return Arguments.of(arguments); | 106 | 148 | } | 107 | 149 |
| 108 | 150 | /** | |
Collapse file Copy file name to clipboardExpand all lines: junit-jupiter-params/src/main/java/org/junit/jupiter/params/provider/CsvFileArgumentsProvider.java +18-10Lines changed: 18 additions & 10 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 13 | 13 | import static java.util.Spliterators.spliteratorUnknownSize; | 14 | 14 | import static java.util.stream.Collectors.toList; | 15 | 15 | import static java.util.stream.StreamSupport.stream; | 16 | | -import static org.junit.jupiter.params.provider.Arguments.arguments; | | 16 | +import static org.junit.jupiter.params.provider.CsvArgumentsProvider.getHeaders; | 17 | 17 | import static org.junit.jupiter.params.provider.CsvArgumentsProvider.handleCsvException; | 18 | | -import static org.junit.jupiter.params.provider.CsvArgumentsProvider.processNullValues; | | 18 | +import static org.junit.jupiter.params.provider.CsvArgumentsProvider.processCsvRecord; | 19 | 19 | import static org.junit.jupiter.params.provider.CsvParserFactory.createParserFor; | 20 | 20 | import static org.junit.platform.commons.util.CollectionUtils.toSet; | 21 | 21 |
| @@ -119,41 +119,49 @@ private static class CsvParserIterator implements Iterator<Arguments> { | 119 | 119 |
| 120 | 120 | private final CsvParser csvParser; | 121 | 121 | private final CsvFileSource annotation; | | 122 | + private final boolean useHeadersInDisplayName; | 122 | 123 | private final Set<String> nullValues; | 123 | | - private Object[] nextCsvRecord; | | 124 | + private Arguments nextArguments; | | 125 | + private String[] headers; | 124 | 126 |
| 125 | 127 | CsvParserIterator(CsvParser csvParser, CsvFileSource annotation) { | 126 | 128 | this.csvParser = csvParser; | 127 | 129 | this.annotation = annotation; | | 130 | + this.useHeadersInDisplayName = annotation.useHeadersInDisplayName(); | 128 | 131 | this.nullValues = toSet(annotation.nullValues()); | 129 | 132 | advance(); | 130 | 133 | } | 131 | 134 |
| 132 | 135 | @Override | 133 | 136 | public boolean hasNext() { | 134 | | - return this.nextCsvRecord != null; | | 137 | + return this.nextArguments != null; | 135 | 138 | } | 136 | 139 |
| 137 | 140 | @Override | 138 | 141 | public Arguments next() { | 139 | | - Arguments result = arguments(this.nextCsvRecord); | | 142 | + Arguments result = this.nextArguments; | 140 | 143 | advance(); | 141 | 144 | return result; | 142 | 145 | } | 143 | 146 |
| 144 | 147 | private void advance() { | 145 | | - String[] csvRecord = null; | 146 | 148 | try { | 147 | | - csvRecord = this.csvParser.parseNext(); | | 149 | + String[] csvRecord = this.csvParser.parseNext(); | 148 | 150 | if (csvRecord != null) { | 149 | | - processNullValues(csvRecord, this.nullValues); | | 151 | + // Lazily retrieve headers if necessary. | | 152 | + if (this.useHeadersInDisplayName && this.headers == null) { | | 153 | + this.headers = getHeaders(this.csvParser); | | 154 | + } | | 155 | + this.nextArguments = processCsvRecord(csvRecord, this.nullValues, this.useHeadersInDisplayName, | | 156 | + this.headers); | | 157 | + } | | 158 | + else { | | 159 | + this.nextArguments = null; | 150 | 160 | } | 151 | 161 | } | 152 | 162 | catch (Throwable throwable) { | 153 | 163 | handleCsvException(throwable, this.annotation); | 154 | 164 | } | 155 | | - | 156 | | - this.nextCsvRecord = csvRecord; | 157 | 165 | } | 158 | 166 |
| 159 | 167 | } | |
Collapse file Copy file name to clipboardExpand all lines: junit-jupiter-params/src/main/java/org/junit/jupiter/params/provider/CsvFileSource.java +31-1Lines changed: 31 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
| 27 | 27 | * or {@link #files}. | 28 | 28 | * | 29 | 29 | * <p>The CSV records parsed from these resources and files will be provided as | 30 | | - * arguments to the annotated {@code @ParameterizedTest} method. | | 30 | + * arguments to the annotated {@code @ParameterizedTest} method. Note that the | | 31 | + * first record may optionally be used to supply CSV headers (see | | 32 | + * {@link #useHeadersInDisplayName}). | 31 | 33 | * | 32 | 34 | * <p>Any line beginning with a {@code #} symbol will be interpreted as a comment | 33 | 35 | * and will be ignored. | | 95 | 97 | */ | 96 | 98 | String lineSeparator() default "\n"; | 97 | 99 |
| | 100 | + /** | | 101 | + * Configures whether the first CSV record should be treated as header names | | 102 | + * for columns. | | 103 | + * | | 104 | + * <p>When set to {@code true}, the header names will be used in the | | 105 | + * generated display name for each {@code @ParameterizedTest} method | | 106 | + * invocation. When using this feature, you must ensure that the display name | | 107 | + * pattern for {@code @ParameterizedTest} includes | | 108 | + * {@value org.junit.jupiter.params.ParameterizedTest#ARGUMENTS_PLACEHOLDER} instead of | | 109 | + * {@value org.junit.jupiter.params.ParameterizedTest#ARGUMENTS_WITH_NAMES_PLACEHOLDER} | | 110 | + * as demonstrated in the example below. | | 111 | + * | | 112 | + * <p>Defaults to {@code false}. | | 113 | + * | | 114 | + * | | 115 | + * <h4>Example</h4> | | 116 | + * <pre class="code"> | | 117 | + * {@literal @}ParameterizedTest(name = "[{index}] {arguments}") | | 118 | + * {@literal @}CsvFileSource(resources = "fruits.csv", useHeadersInDisplayName = true) | | 119 | + * void test(String fruit, int rank) { | | 120 | + * // ... | | 121 | + * }</pre> | | 122 | + * | | 123 | + * @since 5.8.2 | | 124 | + */ | | 125 | + @API(status = EXPERIMENTAL, since = "5.8.2") | | 126 | + boolean useHeadersInDisplayName() default false; | | 127 | + | 98 | 128 | /** | 99 | 129 | * The quote character to use for <em>quoted strings</em>. | 100 | 130 | * | |
|