From b50415062b3d9243c770ac7c59875a6076681bd1 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Fri, 26 Aug 2022 15:20:16 +0200 Subject: [PATCH] Clean up warnings and polish tests This commit also modifies ResourceWebHandlerTests.getResourceFromFileSystem() so that it passes in the IDE. --- .../core/io/buffer/DefaultDataBuffer.java | 1 + .../core/codec/Netty5BufferEncoderTests.java | 6 +- .../core/io/buffer/DataBufferTests.java | 8 +- .../LeakAwareDataBufferFactoryTests.java | 8 +- .../io/buffer/LeakAwareDataBufferFactory.java | 2 +- .../DefaultMetadataExtractorTests.java | 28 +-- .../LeakAwareNettyDataBufferFactory.java | 27 +-- .../rsocket/MetadataEncoderTests.java | 27 ++- .../messaging/rsocket/PayloadUtilsTests.java | 25 +-- .../server/samples/bind/WebFilterTests.java | 8 +- .../multipart/MultipartWriterSupport.java | 1 + .../codec/protobuf/ProtobufDecoderTests.java | 21 ++- .../reactive/AsyncIntegrationTests.java | 3 +- .../reactive/ChannelSendOperatorTests.java | 32 ++-- .../HttpHeadResponseDecoratorTests.java | 17 +- .../reactive/ServerHttpResponseTests.java | 18 +- .../resource/ResourceWebHandlerTests.java | 160 +++++++++--------- ...mpleUrlHandlerMappingIntegrationTests.java | 12 +- ...pingMessageConversionIntegrationTests.java | 4 +- .../view/freemarker/FreeMarkerViewTests.java | 12 +- 20 files changed, 206 insertions(+), 214 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/core/io/buffer/DefaultDataBuffer.java b/spring-core/src/main/java/org/springframework/core/io/buffer/DefaultDataBuffer.java index fd146b68461..2d3645cc86f 100644 --- a/spring-core/src/main/java/org/springframework/core/io/buffer/DefaultDataBuffer.java +++ b/spring-core/src/main/java/org/springframework/core/io/buffer/DefaultDataBuffer.java @@ -506,6 +506,7 @@ public class DefaultDataBuffer implements DataBuffer { } @Override + @SuppressWarnings("deprecation") public DefaultDataBuffer capacity(int newCapacity) { throw new UnsupportedOperationException("Changing the capacity of a sliced buffer is not supported"); } diff --git a/spring-core/src/test/java/org/springframework/core/codec/Netty5BufferEncoderTests.java b/spring-core/src/test/java/org/springframework/core/codec/Netty5BufferEncoderTests.java index ee619d36079..072b33c801c 100644 --- a/spring-core/src/test/java/org/springframework/core/codec/Netty5BufferEncoderTests.java +++ b/spring-core/src/test/java/org/springframework/core/codec/Netty5BufferEncoderTests.java @@ -42,8 +42,8 @@ class Netty5BufferEncoderTests extends AbstractEncoderTests super(new Netty5BufferEncoder()); } - @Override @Test + @Override public void canEncode() { assertThat(this.encoder.canEncode(ResolvableType.forClass(Buffer.class), MimeTypeUtils.TEXT_PLAIN)).isTrue(); @@ -56,8 +56,9 @@ class Netty5BufferEncoderTests extends AbstractEncoderTests assertThat(this.encoder.canEncode(ResolvableType.NONE, null)).isFalse(); } - @Override @Test + @Override + @SuppressWarnings("resource") public void encode() { Flux input = Flux.just(this.fooBytes, this.barBytes) .map(DefaultBufferAllocators.preferredAllocator()::copyOf); @@ -67,4 +68,5 @@ class Netty5BufferEncoderTests extends AbstractEncoderTests .consumeNextWith(expectBytes(this.barBytes)) .verifyComplete()); } + } diff --git a/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferTests.java b/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferTests.java index 1739a47229b..db2e6991cf3 100644 --- a/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/buffer/DataBufferTests.java @@ -389,6 +389,7 @@ class DataBufferTests extends AbstractDataBufferAllocatingTests { } @ParameterizedDataBufferAllocatingTest + @SuppressWarnings("deprecation") void increaseCapacity(DataBufferFactory bufferFactory) { super.bufferFactory = bufferFactory; @@ -402,6 +403,7 @@ class DataBufferTests extends AbstractDataBufferAllocatingTests { } @ParameterizedDataBufferAllocatingTest + @SuppressWarnings("deprecation") void decreaseCapacityLowReadPosition(DataBufferFactory bufferFactory) { assumeFalse(bufferFactory instanceof Netty5DataBufferFactory, "Netty 5 does not support decreasing the capacity"); @@ -417,6 +419,7 @@ class DataBufferTests extends AbstractDataBufferAllocatingTests { } @ParameterizedDataBufferAllocatingTest + @SuppressWarnings("deprecation") void decreaseCapacityHighReadPosition(DataBufferFactory bufferFactory) { assumeFalse(bufferFactory instanceof Netty5DataBufferFactory, "Netty 5 does not support decreasing the capacity"); @@ -433,13 +436,13 @@ class DataBufferTests extends AbstractDataBufferAllocatingTests { } @ParameterizedDataBufferAllocatingTest + @SuppressWarnings("deprecation") void capacityLessThanZero(DataBufferFactory bufferFactory) { super.bufferFactory = bufferFactory; DataBuffer buffer = createDataBuffer(1); try { - assertThatIllegalArgumentException().isThrownBy(() -> - buffer.capacity(-1)); + assertThatIllegalArgumentException().isThrownBy(() -> buffer.capacity(-1)); } finally { release(buffer); @@ -754,6 +757,7 @@ class DataBufferTests extends AbstractDataBufferAllocatingTests { } @ParameterizedDataBufferAllocatingTest + @SuppressWarnings("deprecation") void spr16351(DataBufferFactory bufferFactory) { super.bufferFactory = bufferFactory; diff --git a/spring-core/src/test/java/org/springframework/core/io/buffer/LeakAwareDataBufferFactoryTests.java b/spring-core/src/test/java/org/springframework/core/io/buffer/LeakAwareDataBufferFactoryTests.java index 64531c0865d..ddc356699e0 100644 --- a/spring-core/src/test/java/org/springframework/core/io/buffer/LeakAwareDataBufferFactoryTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/buffer/LeakAwareDataBufferFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,11 +32,11 @@ class LeakAwareDataBufferFactoryTests { @Test + @SuppressWarnings("deprecation") void leak() { DataBuffer dataBuffer = this.bufferFactory.allocateBuffer(); try { - assertThatExceptionOfType(AssertionError.class).isThrownBy( - this.bufferFactory::checkForLeaks); + assertThatExceptionOfType(AssertionError.class).isThrownBy(this.bufferFactory::checkForLeaks); } finally { release(dataBuffer); @@ -45,7 +45,7 @@ class LeakAwareDataBufferFactoryTests { @Test void noLeak() { - DataBuffer dataBuffer = this.bufferFactory.allocateBuffer(); + DataBuffer dataBuffer = this.bufferFactory.allocateBuffer(256); release(dataBuffer); this.bufferFactory.checkForLeaks(); } diff --git a/spring-core/src/testFixtures/java/org/springframework/core/testfixture/io/buffer/LeakAwareDataBufferFactory.java b/spring-core/src/testFixtures/java/org/springframework/core/testfixture/io/buffer/LeakAwareDataBufferFactory.java index 64f2b0684ce..00360760fb7 100644 --- a/spring-core/src/testFixtures/java/org/springframework/core/testfixture/io/buffer/LeakAwareDataBufferFactory.java +++ b/spring-core/src/testFixtures/java/org/springframework/core/testfixture/io/buffer/LeakAwareDataBufferFactory.java @@ -99,7 +99,7 @@ public class LeakAwareDataBufferFactory implements DataBufferFactory { List errors = this.created.stream() .filter(LeakAwareDataBuffer::isAllocated) .map(LeakAwareDataBuffer::leakError) - .collect(Collectors.toList()); + .toList(); errors.forEach(it -> logger.error("Leaked error: ", it)); throw new AssertionError(errors.size() + " buffer leaks detected (see logs above)"); diff --git a/spring-messaging/src/test/java/org/springframework/messaging/rsocket/DefaultMetadataExtractorTests.java b/spring-messaging/src/test/java/org/springframework/messaging/rsocket/DefaultMetadataExtractorTests.java index 1c3cd882f5d..68753e24649 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/rsocket/DefaultMetadataExtractorTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/rsocket/DefaultMetadataExtractorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,12 +47,11 @@ import static org.springframework.util.MimeTypeUtils.TEXT_HTML; import static org.springframework.util.MimeTypeUtils.TEXT_PLAIN; import static org.springframework.util.MimeTypeUtils.TEXT_XML; - /** * Unit tests for {@link DefaultMetadataExtractor}. * @author Rossen Stoyanchev */ -public class DefaultMetadataExtractorTests { +class DefaultMetadataExtractorTests { private static MimeType COMPOSITE_METADATA = MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString()); @@ -64,21 +63,21 @@ public class DefaultMetadataExtractorTests { @BeforeEach - public void setUp() { + void setUp() { DataBufferFactory bufferFactory = new LeakAwareNettyDataBufferFactory(PooledByteBufAllocator.DEFAULT); this.strategies = RSocketStrategies.builder().dataBufferFactory(bufferFactory).build(); this.extractor = new DefaultMetadataExtractor(StringDecoder.allMimeTypes()); } @AfterEach - public void tearDown() throws InterruptedException { + void tearDown() throws InterruptedException { DataBufferFactory bufferFactory = this.strategies.dataBufferFactory(); ((LeakAwareNettyDataBufferFactory) bufferFactory).checkForLeaks(Duration.ofSeconds(5)); } @Test - public void compositeMetadataWithDefaultSettings() { + void compositeMetadataWithDefaultSettings() { MetadataEncoder metadataEncoder = new MetadataEncoder(COMPOSITE_METADATA, this.strategies) .route("toA") .metadata("text data", TEXT_PLAIN) @@ -94,7 +93,7 @@ public class DefaultMetadataExtractorTests { } @Test - public void compositeMetadataWithMimeTypeRegistrations() { + void compositeMetadataWithMimeTypeRegistrations() { this.extractor.metadataToExtract(TEXT_PLAIN, String.class, "text-entry"); this.extractor.metadataToExtract(TEXT_HTML, String.class, "html-entry"); this.extractor.metadataToExtract(TEXT_XML, String.class, "xml-entry"); @@ -118,7 +117,7 @@ public class DefaultMetadataExtractorTests { } @Test - public void route() { + void route() { MimeType metaMimeType = MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_ROUTING.getString()); MetadataEncoder metadataEncoder = new MetadataEncoder(metaMimeType, this.strategies).route("toA"); DataBuffer metadata = metadataEncoder.encode().block(); @@ -130,7 +129,7 @@ public class DefaultMetadataExtractorTests { } @Test - public void routeAsText() { + void routeAsText() { this.extractor.metadataToExtract(TEXT_PLAIN, String.class, ROUTE_KEY); MetadataEncoder metadataEncoder = new MetadataEncoder(TEXT_PLAIN, this.strategies).route("toA"); @@ -143,7 +142,7 @@ public class DefaultMetadataExtractorTests { } @Test - public void routeWithCustomFormatting() { + void routeWithCustomFormatting() { this.extractor.metadataToExtract(TEXT_PLAIN, String.class, (text, result) -> { String[] items = text.split(":"); Assert.isTrue(items.length == 2, "Expected two items"); @@ -163,7 +162,7 @@ public class DefaultMetadataExtractorTests { } @Test - public void nonCompositeMetadataCanBeReadTwice() { + void nonCompositeMetadataCanBeReadTwice() { DefaultMetadataExtractor extractor = new DefaultMetadataExtractor(new TestDecoder()); extractor.metadataToExtract(TEXT_PLAIN, String.class, "name"); @@ -181,7 +180,7 @@ public class DefaultMetadataExtractorTests { } @Test - public void noDecoder() { + void noDecoder() { DefaultMetadataExtractor extractor = new DefaultMetadataExtractor(Collections.singletonList(new ByteArrayDecoder()) ); @@ -193,7 +192,7 @@ public class DefaultMetadataExtractorTests { private Payload createPayload(DataBuffer metadata) { - return PayloadUtils.createPayload(this.strategies.dataBufferFactory().allocateBuffer(), metadata); + return PayloadUtils.createPayload(this.strategies.dataBufferFactory().allocateBuffer(256), metadata); } @@ -203,7 +202,7 @@ public class DefaultMetadataExtractorTests { */ private static class TestDecoder extends AbstractDataBufferDecoder { - public TestDecoder() { + TestDecoder() { super(TEXT_PLAIN); } @@ -217,4 +216,5 @@ public class DefaultMetadataExtractorTests { return new String(bytes, StandardCharsets.UTF_8); } } + } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/rsocket/LeakAwareNettyDataBufferFactory.java b/spring-messaging/src/test/java/org/springframework/messaging/rsocket/LeakAwareNettyDataBufferFactory.java index 23c0f020b2b..42bcfd35a7d 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/rsocket/LeakAwareNettyDataBufferFactory.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/rsocket/LeakAwareNettyDataBufferFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,8 +52,8 @@ public class LeakAwareNettyDataBufferFactory extends NettyDataBufferFactory { while (true) { try { this.created.forEach(info -> { - if (((PooledDataBuffer) info.getDataBuffer()).isAllocated()) { - throw info.getError(); + if (((PooledDataBuffer) info.dataBuffer()).isAllocated()) { + throw info.error(); } }); break; @@ -73,6 +73,7 @@ public class LeakAwareNettyDataBufferFactory extends NettyDataBufferFactory { @Override + @SuppressWarnings("deprecation") public NettyDataBuffer allocateBuffer() { return (NettyDataBuffer) recordHint(super.allocateBuffer()); } @@ -105,23 +106,7 @@ public class LeakAwareNettyDataBufferFactory extends NettyDataBufferFactory { } - private static class DataBufferLeakInfo { - - private final DataBuffer dataBuffer; - - private final AssertionError error; - - DataBufferLeakInfo(DataBuffer dataBuffer, AssertionError error) { - this.dataBuffer = dataBuffer; - this.error = error; - } - - DataBuffer getDataBuffer() { - return this.dataBuffer; - } - - AssertionError getError() { - return this.error; - } + private static record DataBufferLeakInfo(DataBuffer dataBuffer, AssertionError error) { } + } diff --git a/spring-messaging/src/test/java/org/springframework/messaging/rsocket/MetadataEncoderTests.java b/spring-messaging/src/test/java/org/springframework/messaging/rsocket/MetadataEncoderTests.java index eaea5c2b429..95ac059ca0b 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/rsocket/MetadataEncoderTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/rsocket/MetadataEncoderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,11 +42,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** - * * @author Rossen Stoyanchev * @since 5.2 */ -public class MetadataEncoderTests { +class MetadataEncoderTests { private static MimeType COMPOSITE_METADATA = MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString()); @@ -56,7 +55,7 @@ public class MetadataEncoderTests { @Test - public void compositeMetadata() { + void compositeMetadata() { Mono asyncMeta1 = Mono.delay(Duration.ofMillis(1)).map(aLong -> "Async Metadata 1"); Mono asyncMeta2 = Mono.delay(Duration.ofMillis(1)).map(aLong -> "Async Metadata 2"); @@ -102,7 +101,7 @@ public class MetadataEncoderTests { } @Test - public void routeWithRoutingMimeType() { + void routeWithRoutingMimeType() { MimeType mimeType = MimeTypeUtils.parseMimeType( WellKnownMimeType.MESSAGE_RSOCKET_ROUTING.getString()); @@ -117,7 +116,7 @@ public class MetadataEncoderTests { } @Test - public void routeWithTextPlainMimeType() { + void routeWithTextPlainMimeType() { DataBuffer buffer = new MetadataEncoder(MimeTypeUtils.TEXT_PLAIN, this.strategies) .route("toA") @@ -128,7 +127,7 @@ public class MetadataEncoderTests { } @Test - public void routeWithVars() { + void routeWithVars() { DataBuffer buffer = new MetadataEncoder(MimeTypeUtils.TEXT_PLAIN, this.strategies) .route("a.{b}.{c}.d", "BBB", "C.C.C") @@ -139,7 +138,7 @@ public class MetadataEncoderTests { } @Test - public void metadataWithTextPlainMimeType() { + void metadataWithTextPlainMimeType() { DataBuffer buffer = new MetadataEncoder(MimeTypeUtils.TEXT_PLAIN, this.strategies) .metadata(Unpooled.wrappedBuffer("Raw data".getBytes(UTF_8)), null) @@ -150,7 +149,7 @@ public class MetadataEncoderTests { } @Test - public void metadataWithByteBuf() { + void metadataWithByteBuf() { DataBuffer buffer = new MetadataEncoder(MimeTypeUtils.TEXT_PLAIN, this.strategies) .metadata("toA", null) @@ -161,7 +160,7 @@ public class MetadataEncoderTests { } @Test - public void compositeRequiredForMultipleEntries() { + void compositeRequiredForMultipleEntries() { // Route, metadata MetadataEncoder encoder1 = new MetadataEncoder(MimeTypeUtils.TEXT_PLAIN, this.strategies); @@ -186,7 +185,7 @@ public class MetadataEncoderTests { } @Test - public void mimeTypeRequiredForCompositeEntries() { + void mimeTypeRequiredForCompositeEntries() { MetadataEncoder encoder = new MetadataEncoder(COMPOSITE_METADATA, this.strategies); assertThatThrownBy(() -> encoder.metadata("toA", null)) @@ -194,7 +193,7 @@ public class MetadataEncoderTests { } @Test - public void mimeTypeDoesNotMatchConnectionMetadataMimeType() { + void mimeTypeDoesNotMatchConnectionMetadataMimeType() { MetadataEncoder encoder = new MetadataEncoder(MimeTypeUtils.TEXT_PLAIN, this.strategies); assertThatThrownBy(() -> encoder.metadata("toA", MimeTypeUtils.APPLICATION_JSON)) @@ -203,7 +202,7 @@ public class MetadataEncoderTests { } @Test - public void defaultDataBufferFactory() { + void defaultDataBufferFactory() { DefaultDataBufferFactory bufferFactory = DefaultDataBufferFactory.sharedInstance; RSocketStrategies strategies = RSocketStrategies.builder().dataBufferFactory(bufferFactory).build(); @@ -213,7 +212,7 @@ public class MetadataEncoderTests { .block(); ByteBuf byteBuf = new NettyDataBufferFactory(ByteBufAllocator.DEFAULT) - .wrap(buffer.asByteBuffer()) + .wrap(buffer.toByteBuffer()) .getNativeBuffer(); CompositeMetadata entries = new CompositeMetadata(byteBuf, false); diff --git a/spring-messaging/src/test/java/org/springframework/messaging/rsocket/PayloadUtilsTests.java b/spring-messaging/src/test/java/org/springframework/messaging/rsocket/PayloadUtilsTests.java index 8346fab1b43..2fb1571290a 100644 --- a/spring-messaging/src/test/java/org/springframework/messaging/rsocket/PayloadUtilsTests.java +++ b/spring-messaging/src/test/java/org/springframework/messaging/rsocket/PayloadUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,23 +37,24 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link PayloadUtils}. + * * @author Rossen Stoyanchev * @since 5.2 */ -public class PayloadUtilsTests { +class PayloadUtilsTests { private LeakAwareNettyDataBufferFactory nettyBufferFactory = new LeakAwareNettyDataBufferFactory(PooledByteBufAllocator.DEFAULT); @AfterEach - public void tearDown() throws Exception { + void tearDown() throws Exception { this.nettyBufferFactory.checkForLeaks(Duration.ofSeconds(5)); } @Test - public void retainAndReleaseWithNettyFactory() { + void retainAndReleaseWithNettyFactory() { Payload payload = ByteBufPayload.create("sample data"); DataBuffer buffer = PayloadUtils.retainDataAndReleasePayload(payload, this.nettyBufferFactory); try { @@ -67,7 +68,7 @@ public class PayloadUtilsTests { } @Test - public void retainAndReleaseWithDefaultFactory() { + void retainAndReleaseWithDefaultFactory() { Payload payload = ByteBufPayload.create("sample data"); DataBuffer buffer = PayloadUtils.retainDataAndReleasePayload(payload, DefaultDataBufferFactory.sharedInstance); @@ -76,7 +77,7 @@ public class PayloadUtilsTests { } @Test - public void createWithNettyBuffers() { + void createWithNettyBuffers() { NettyDataBuffer data = createNettyDataBuffer("sample data"); NettyDataBuffer metadata = createNettyDataBuffer("sample metadata"); @@ -92,7 +93,7 @@ public class PayloadUtilsTests { } @Test - public void createWithDefaultBuffers() { + void createWithDefaultBuffers() { DataBuffer data = createDefaultDataBuffer("sample data"); DataBuffer metadata = createDefaultDataBuffer("sample metadata"); Payload payload = PayloadUtils.createPayload(data, metadata); @@ -103,7 +104,7 @@ public class PayloadUtilsTests { } @Test - public void createWithNettyAndDefaultBuffers() { + void createWithNettyAndDefaultBuffers() { NettyDataBuffer data = createNettyDataBuffer("sample data"); DefaultDataBuffer metadata = createDefaultDataBuffer("sample metadata"); Payload payload = PayloadUtils.createPayload(data, metadata); @@ -118,7 +119,7 @@ public class PayloadUtilsTests { } @Test - public void createWithDefaultAndNettyBuffers() { + void createWithDefaultAndNettyBuffers() { DefaultDataBuffer data = createDefaultDataBuffer("sample data"); NettyDataBuffer metadata = createNettyDataBuffer("sample metadata"); Payload payload = PayloadUtils.createPayload(data, metadata); @@ -133,7 +134,7 @@ public class PayloadUtilsTests { } @Test - public void createWithNettyBuffer() { + void createWithNettyBuffer() { NettyDataBuffer data = createNettyDataBuffer("sample data"); Payload payload = PayloadUtils.createPayload(data); try { @@ -146,7 +147,7 @@ public class PayloadUtilsTests { } @Test - public void createWithDefaultBuffer() { + void createWithDefaultBuffer() { DataBuffer data = createDefaultDataBuffer("sample data"); Payload payload = PayloadUtils.createPayload(data); @@ -162,7 +163,7 @@ public class PayloadUtilsTests { } private DefaultDataBuffer createDefaultDataBuffer(String content) { - DefaultDataBuffer buffer = DefaultDataBufferFactory.sharedInstance.allocateBuffer(); + DefaultDataBuffer buffer = DefaultDataBufferFactory.sharedInstance.allocateBuffer(256); buffer.write(content, StandardCharsets.UTF_8); return buffer; } diff --git a/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/bind/WebFilterTests.java b/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/bind/WebFilterTests.java index 586494208f7..c0d840382a8 100644 --- a/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/bind/WebFilterTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/bind/WebFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,13 +30,13 @@ import org.springframework.web.server.WebFilter; * Tests for a {@link WebFilter}. * @author Rossen Stoyanchev */ -public class WebFilterTests { +class WebFilterTests { @Test - public void testWebFilter() throws Exception { + void webFilter() { WebFilter filter = (exchange, chain) -> { - DataBuffer buffer = DefaultDataBufferFactory.sharedInstance.allocateBuffer(); + DataBuffer buffer = DefaultDataBufferFactory.sharedInstance.allocateBuffer(256); buffer.write("It works!".getBytes(StandardCharsets.UTF_8)); return exchange.getResponse().writeWith(Mono.just(buffer)); }; diff --git a/spring-web/src/main/java/org/springframework/http/codec/multipart/MultipartWriterSupport.java b/spring-web/src/main/java/org/springframework/http/codec/multipart/MultipartWriterSupport.java index 87f02e53476..0bd3bfa2306 100644 --- a/spring-web/src/main/java/org/springframework/http/codec/multipart/MultipartWriterSupport.java +++ b/spring-web/src/main/java/org/springframework/http/codec/multipart/MultipartWriterSupport.java @@ -165,6 +165,7 @@ public class MultipartWriterSupport extends LoggingCodecSupport { protected Mono generatePartHeaders(HttpHeaders headers, DataBufferFactory bufferFactory) { return Mono.fromCallable(() -> { + @SuppressWarnings("resource") FastByteArrayOutputStream bos = new FastByteArrayOutputStream(); for (Map.Entry> entry : headers.entrySet()) { byte[] headerName = entry.getKey().getBytes(getCharset()); diff --git a/spring-web/src/test/java/org/springframework/http/codec/protobuf/ProtobufDecoderTests.java b/spring-web/src/test/java/org/springframework/http/codec/protobuf/ProtobufDecoderTests.java index 40501537dbc..6f239dea7fb 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/protobuf/ProtobufDecoderTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/protobuf/ProtobufDecoderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,12 +65,11 @@ public class ProtobufDecoderTests extends AbstractDecoderTests @Test public void extensionRegistryNull() { - assertThatIllegalArgumentException().isThrownBy(() -> - new ProtobufDecoder(null)); + assertThatIllegalArgumentException().isThrownBy(() -> new ProtobufDecoder(null)); } - @Override @Test + @Override public void canDecode() { assertThat(this.decoder.canDecode(forClass(Msg.class), null)).isTrue(); assertThat(this.decoder.canDecode(forClass(Msg.class), PROTOBUF_MIME_TYPE)).isTrue(); @@ -79,8 +78,8 @@ public class ProtobufDecoderTests extends AbstractDecoderTests assertThat(this.decoder.canDecode(forClass(Object.class), PROTOBUF_MIME_TYPE)).isFalse(); } - @Override @Test + @Override public void decodeToMono() { Mono input = dataBuffer(this.testMsg1); @@ -107,8 +106,9 @@ public class ProtobufDecoderTests extends AbstractDecoderTests .verifyComplete()); } - @Override @Test + @Override + @SuppressWarnings("deprecation") public void decode() { Flux input = Flux.just(this.testMsg1, this.testMsg2) .flatMap(msg -> Mono.defer(() -> { @@ -130,9 +130,8 @@ public class ProtobufDecoderTests extends AbstractDecoderTests } @Test + @SuppressWarnings("deprecation") public void decodeSplitChunks() { - - Flux input = Flux.just(this.testMsg1, this.testMsg2) .flatMap(msg -> Mono.defer(() -> { DataBuffer buffer = this.bufferFactory.allocateBuffer(); @@ -163,6 +162,7 @@ public class ProtobufDecoderTests extends AbstractDecoderTests } @Test // SPR-17429 + @SuppressWarnings("deprecation") public void decodeSplitMessageSize() { this.decoder.setMaxMessageSize(100009); StringBuilder builder = new StringBuilder(); @@ -201,6 +201,7 @@ public class ProtobufDecoderTests extends AbstractDecoderTests } @Test + @SuppressWarnings("deprecation") public void decodeMergedChunks() throws IOException { DataBuffer buffer = this.bufferFactory.allocateBuffer(); this.testMsg1.writeDelimitedTo(buffer.asOutputStream()); @@ -220,8 +221,7 @@ public class ProtobufDecoderTests extends AbstractDecoderTests this.decoder.setMaxMessageSize(1); Mono input = dataBuffer(this.testMsg1); - testDecode(input, Msg.class, step -> step - .verifyError(DecodingException.class)); + testDecode(input, Msg.class, step -> step.verifyError(DecodingException.class)); } private Mono dataBuffer(Msg msg) { @@ -233,5 +233,4 @@ public class ProtobufDecoderTests extends AbstractDecoderTests }); } - } diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/AsyncIntegrationTests.java b/spring-web/src/test/java/org/springframework/http/server/reactive/AsyncIntegrationTests.java index 224bc1c4180..e092e94f37f 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/AsyncIntegrationTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/AsyncIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,6 +61,7 @@ class AsyncIntegrationTests extends AbstractHttpHandlerIntegrationTests { private class AsyncHandler implements HttpHandler { @Override + @SuppressWarnings("deprecation") public Mono handle(ServerHttpRequest request, ServerHttpResponse response) { return response.writeWith(Flux.just("h", "e", "l", "l", "o") .delayElements(Duration.ofMillis(100)) diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/ChannelSendOperatorTests.java b/spring-web/src/test/java/org/springframework/http/server/reactive/ChannelSendOperatorTests.java index cc1468359d0..3de547ec2f2 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/ChannelSendOperatorTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/ChannelSendOperatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,13 +43,13 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Rossen Stoyanchev * @author Stephane Maldini */ -public class ChannelSendOperatorTests { +class ChannelSendOperatorTests { private final OneByOneAsyncWriter writer = new OneByOneAsyncWriter(); @Test - public void errorBeforeFirstItem() throws Exception { + void errorBeforeFirstItem() throws Exception { IllegalStateException error = new IllegalStateException("boo"); Mono completion = Mono.error(error).as(this::sendOperator); Signal signal = completion.materialize().block(); @@ -59,7 +59,7 @@ public class ChannelSendOperatorTests { } @Test - public void completionBeforeFirstItem() throws Exception { + void completionBeforeFirstItem() throws Exception { Mono completion = Flux.empty().as(this::sendOperator); Signal signal = completion.materialize().block(); @@ -71,7 +71,7 @@ public class ChannelSendOperatorTests { } @Test - public void writeOneItem() throws Exception { + void writeOneItem() throws Exception { Mono completion = Flux.just("one").as(this::sendOperator); Signal signal = completion.materialize().block(); @@ -85,7 +85,7 @@ public class ChannelSendOperatorTests { @Test - public void writeMultipleItems() { + void writeMultipleItems() { List items = Arrays.asList("one", "two", "three"); Mono completion = Flux.fromIterable(items).as(this::sendOperator); Signal signal = completion.materialize().block(); @@ -101,7 +101,7 @@ public class ChannelSendOperatorTests { } @Test - public void errorAfterMultipleItems() { + void errorAfterMultipleItems() { IllegalStateException error = new IllegalStateException("boo"); Flux publisher = Flux.generate(() -> 0, (idx , subscriber) -> { int i = ++idx; @@ -125,12 +125,12 @@ public class ChannelSendOperatorTests { } @Test // gh-22720 - public void cancelWhileItemCached() { + void cancelWhileItemCached() { LeakAwareDataBufferFactory bufferFactory = new LeakAwareDataBufferFactory(); ChannelSendOperator operator = new ChannelSendOperator<>( Mono.fromCallable(() -> { - DataBuffer dataBuffer = bufferFactory.allocateBuffer(); + DataBuffer dataBuffer = bufferFactory.allocateBuffer(256); dataBuffer.write("foo", StandardCharsets.UTF_8); return dataBuffer; }), @@ -148,7 +148,7 @@ public class ChannelSendOperatorTests { } @Test // gh-22720 - public void errorFromWriteSourceWhileItemCached() { + void errorFromWriteSourceWhileItemCached() { // 1. First item received // 2. writeFunction applied and writeCompletionBarrier subscribed to it @@ -159,7 +159,7 @@ public class ChannelSendOperatorTests { ChannelSendOperator operator = new ChannelSendOperator<>( Flux.create(sink -> { - DataBuffer dataBuffer = bufferFactory.allocateBuffer(); + DataBuffer dataBuffer = bufferFactory.allocateBuffer(256); dataBuffer.write("foo", StandardCharsets.UTF_8); sink.next(dataBuffer); sink.error(new IllegalStateException("err")); @@ -169,7 +169,6 @@ public class ChannelSendOperatorTests { return Mono.never(); }); - operator.subscribe(new BaseSubscriber() {}); try { writeSubscriber.signalDemand(1); // Let cached signals ("foo" and error) be published.. @@ -183,7 +182,7 @@ public class ChannelSendOperatorTests { } @Test // gh-22720 - public void errorFromWriteFunctionWhileItemCached() { + void errorFromWriteFunctionWhileItemCached() { // 1. First item received // 2. writeFunction applied and writeCompletionBarrier subscribed to it @@ -193,7 +192,7 @@ public class ChannelSendOperatorTests { ChannelSendOperator operator = new ChannelSendOperator<>( Flux.create(sink -> { - DataBuffer dataBuffer = bufferFactory.allocateBuffer(); + DataBuffer dataBuffer = bufferFactory.allocateBuffer(256); dataBuffer.write("foo", StandardCharsets.UTF_8); sink.next(dataBuffer); }), @@ -207,7 +206,7 @@ public class ChannelSendOperatorTests { } @Test // gh-23175 - public void errorInWriteFunction() { + void errorInWriteFunction() { StepVerifier .create(new ChannelSendOperator<>(Mono.just("one"), p -> { @@ -251,7 +250,7 @@ public class ChannelSendOperatorTests { private final Subscriber subscriber; - public WriteSubscriber(Subscriber subscriber) { + WriteSubscriber(Subscriber subscriber) { this.subscriber = subscriber; } @@ -284,7 +283,6 @@ public class ChannelSendOperatorTests { private static class ZeroDemandSubscriber extends BaseSubscriber { - @Override protected void hookOnSubscribe(Subscription subscription) { // Just subscribe without requesting diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/HttpHeadResponseDecoratorTests.java b/spring-web/src/test/java/org/springframework/http/server/reactive/HttpHeadResponseDecoratorTests.java index 182016ecea6..b61ef6c386a 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/HttpHeadResponseDecoratorTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/HttpHeadResponseDecoratorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,9 +34,10 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link HttpHeadResponseDecorator}. + * * @author Rossen Stoyanchev */ -public class HttpHeadResponseDecoratorTests { +class HttpHeadResponseDecoratorTests { private final LeakAwareDataBufferFactory bufferFactory = new LeakAwareDataBufferFactory(new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT)); @@ -46,27 +47,27 @@ public class HttpHeadResponseDecoratorTests { @AfterEach - public void tearDown() { + void tearDown() { this.bufferFactory.checkForLeaks(); } @Test - public void writeWithFlux() { + void writeWithFlux() { Flux body = Flux.just(toDataBuffer("data1"), toDataBuffer("data2")); this.response.writeWith(body).block(); assertThat(this.response.getHeaders().getContentLength()).isEqualTo(-1); } @Test - public void writeWithMono() { + void writeWithMono() { Mono body = Mono.just(toDataBuffer("data1,data2")); this.response.writeWith(body).block(); assertThat(this.response.getHeaders().getContentLength()).isEqualTo(11); } @Test // gh-23484 - public void writeWithGivenContentLength() { + void writeWithGivenContentLength() { int length = 15; this.response.getHeaders().setContentLength(length); this.response.writeWith(Flux.empty()).block(); @@ -74,7 +75,7 @@ public class HttpHeadResponseDecoratorTests { } @Test // gh-25908 - public void writeWithGivenTransferEncoding() { + void writeWithGivenTransferEncoding() { Flux body = Flux.just(toDataBuffer("data1"), toDataBuffer("data2")); this.response.getHeaders().add(HttpHeaders.TRANSFER_ENCODING, "chunked"); this.response.writeWith(body).block(); @@ -82,7 +83,7 @@ public class HttpHeadResponseDecoratorTests { } private DataBuffer toDataBuffer(String s) { - DataBuffer buffer = this.bufferFactory.allocateBuffer(); + DataBuffer buffer = this.bufferFactory.allocateBuffer(256); buffer.write(s.getBytes(StandardCharsets.UTF_8)); return buffer; } diff --git a/spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpResponseTests.java b/spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpResponseTests.java index a12825b5c1a..afb7d42b608 100644 --- a/spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpResponseTests.java +++ b/spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpResponseTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,7 +56,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Sebastien Deleuze * @author Brian Clozel */ -public class ServerHttpResponseTests { +class ServerHttpResponseTests { @Test void writeWith() { @@ -68,9 +68,9 @@ public class ServerHttpResponseTests { assertThat(response.cookiesWritten).isTrue(); assertThat(response.body.size()).isEqualTo(3); - assertThat(new String(response.body.get(0).asByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("a"); - assertThat(new String(response.body.get(1).asByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("b"); - assertThat(new String(response.body.get(2).asByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("c"); + assertThat(new String(response.body.get(0).toByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("a"); + assertThat(new String(response.body.get(1).toByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("b"); + assertThat(new String(response.body.get(2).toByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("c"); } @Test // SPR-14952 @@ -84,7 +84,7 @@ public class ServerHttpResponseTests { assertThat(response.cookiesWritten).isTrue(); assertThat(response.body.size()).isEqualTo(1); - assertThat(new String(response.body.get(0).asByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("foo"); + assertThat(new String(response.body.get(0).toByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("foo"); } @Test @@ -139,9 +139,9 @@ public class ServerHttpResponseTests { assertThat(response.getCookies().getFirst("ID")).isSameAs(cookie); assertThat(response.body.size()).isEqualTo(3); - assertThat(new String(response.body.get(0).asByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("a"); - assertThat(new String(response.body.get(1).asByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("b"); - assertThat(new String(response.body.get(2).asByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("c"); + assertThat(new String(response.body.get(0).toByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("a"); + assertThat(new String(response.body.get(1).toByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("b"); + assertThat(new String(response.body.get(2).toByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("c"); } @Test diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceWebHandlerTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceWebHandlerTests.java index 9a378354613..5fa5f11a183 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceWebHandlerTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceWebHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,16 +17,19 @@ package org.springframework.web.reactive.resource; import java.io.IOException; +import java.nio.file.Paths; import java.time.Duration; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; @@ -44,6 +47,7 @@ import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.server.PathContainer; +import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; import org.springframework.web.reactive.HandlerMapping; import org.springframework.web.server.MethodNotAllowedException; @@ -67,8 +71,9 @@ import static org.mockito.Mockito.mock; * Unit tests for {@link ResourceWebHandler}. * * @author Rossen Stoyanchev + * @author Sam Brannen */ -public class ResourceWebHandlerTests { +class ResourceWebHandlerTests { private static final Duration TIMEOUT = Duration.ofSeconds(1); @@ -76,11 +81,11 @@ public class ResourceWebHandlerTests { @BeforeEach - public void setup() throws Exception { - List locations = new ArrayList<>(2); - locations.add(new ClassPathResource("test/", getClass())); - locations.add(new ClassPathResource("testalternatepath/", getClass())); - locations.add(new ClassPathResource("META-INF/resources/webjars/")); + void setup() throws Exception { + List locations = List.of( + new ClassPathResource("test/", getClass()), + new ClassPathResource("testalternatepath/", getClass()), + new ClassPathResource("META-INF/resources/webjars/")); this.handler = new ResourceWebHandler(); this.handler.setLocations(locations); @@ -90,7 +95,7 @@ public class ResourceWebHandlerTests { @Test - public void getResource() throws Exception { + void getResource() throws Exception { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); setPathWithinHandlerMapping(exchange, "foo.css"); this.handler.handle(exchange).block(TIMEOUT); @@ -107,7 +112,7 @@ public class ResourceWebHandlerTests { } @Test - public void getResourceHttpHeader() throws Exception { + void getResourceHttpHeader() throws Exception { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.head("")); setPathWithinHandlerMapping(exchange, "foo.css"); this.handler.handle(exchange).block(TIMEOUT); @@ -127,7 +132,7 @@ public class ResourceWebHandlerTests { } @Test - public void getResourceHttpOptions() { + void getResourceHttpOptions() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.options("")); setPathWithinHandlerMapping(exchange, "foo.css"); this.handler.handle(exchange).block(TIMEOUT); @@ -137,7 +142,7 @@ public class ResourceWebHandlerTests { } @Test - public void getResourceNoCache() throws Exception { + void getResourceNoCache() throws Exception { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); setPathWithinHandlerMapping(exchange, "foo.css"); this.handler.setCacheControl(CacheControl.noStore()); @@ -152,7 +157,7 @@ public class ResourceWebHandlerTests { } @Test - public void getVersionedResource() throws Exception { + void getVersionedResource() throws Exception { VersionResourceResolver versionResolver = new VersionResourceResolver(); versionResolver.addFixedVersionStrategy("versionString", "/**"); this.handler.setResourceResolvers(Arrays.asList(versionResolver, new PathResourceResolver())); @@ -168,7 +173,7 @@ public class ResourceWebHandlerTests { } @Test - public void getResourceWithHtmlMediaType() throws Exception { + void getResourceWithHtmlMediaType() throws Exception { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); setPathWithinHandlerMapping(exchange, "foo.html"); this.handler.handle(exchange).block(TIMEOUT); @@ -183,7 +188,7 @@ public class ResourceWebHandlerTests { } @Test - public void getResourceFromAlternatePath() throws Exception { + void getResourceFromAlternatePath() throws Exception { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); setPathWithinHandlerMapping(exchange, "baz.css"); this.handler.handle(exchange).block(TIMEOUT); @@ -200,7 +205,7 @@ public class ResourceWebHandlerTests { } @Test - public void getResourceFromSubDirectory() { + void getResourceFromSubDirectory() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); setPathWithinHandlerMapping(exchange, "js/foo.js"); this.handler.handle(exchange).block(TIMEOUT); @@ -210,7 +215,7 @@ public class ResourceWebHandlerTests { } @Test - public void getResourceFromSubDirectoryOfAlternatePath() { + void getResourceFromSubDirectoryOfAlternatePath() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); setPathWithinHandlerMapping(exchange, "js/baz.js"); this.handler.handle(exchange).block(TIMEOUT); @@ -221,11 +226,11 @@ public class ResourceWebHandlerTests { } @Test - public void getResourceWithRegisteredMediaType() throws Exception { + void getResourceWithRegisteredMediaType() throws Exception { MediaType mediaType = new MediaType("foo", "bar"); ResourceWebHandler handler = new ResourceWebHandler(); - handler.setLocations(Collections.singletonList(new ClassPathResource("test/", getClass()))); + handler.setLocations(List.of(new ClassPathResource("test/", getClass()))); handler.setMediaTypes(Collections.singletonMap("bar", mediaType)); handler.afterPropertiesSet(); @@ -239,12 +244,12 @@ public class ResourceWebHandlerTests { } @Test - public void getResourceFromFileSystem() throws Exception { - String path = new ClassPathResource("", getClass()).getFile().getCanonicalPath() - .replace('\\', '/').replace("classes/java", "resources") + "/"; + void getResourceFromFileSystem() throws Exception { + String packagePath = ClassUtils.classPackageAsResourcePath(getClass()); + String path = Paths.get("src/test/resources", packagePath).normalize() + "/"; ResourceWebHandler handler = new ResourceWebHandler(); - handler.setLocations(Collections.singletonList(new FileSystemResource(path))); + handler.setLocations(List.of(new FileSystemResource(path))); handler.afterPropertiesSet(); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); @@ -258,7 +263,7 @@ public class ResourceWebHandlerTests { } @Test // gh-27538, gh-27624 - public void filterNonExistingLocations() throws Exception { + void filterNonExistingLocations() throws Exception { List inputLocations = Arrays.asList( new ClassPathResource("test/", getClass()), new ClassPathResource("testalternatepath/", getClass()), @@ -276,8 +281,8 @@ public class ResourceWebHandlerTests { } @Test // SPR-14577 - public void getMediaTypeWithFavorPathExtensionOff() throws Exception { - List paths = Collections.singletonList(new ClassPathResource("test/", getClass())); + void getMediaTypeWithFavorPathExtensionOff() throws Exception { + List paths = List.of(new ClassPathResource("test/", getClass())); ResourceWebHandler handler = new ResourceWebHandler(); handler.setLocations(paths); handler.afterPropertiesSet(); @@ -291,7 +296,7 @@ public class ResourceWebHandlerTests { } @Test - public void testInvalidPath() throws Exception { + void invalidPath() throws Exception { // Use mock ResourceResolver: i.e. we're only testing upfront validations... @@ -302,8 +307,8 @@ public class ResourceWebHandlerTests { given(resolver.resolveResource(any(), any(), any(), any())).willReturn(Mono.just(resource)); ResourceWebHandler handler = new ResourceWebHandler(); - handler.setLocations(Collections.singletonList(new ClassPathResource("test/", getClass()))); - handler.setResourceResolvers(Collections.singletonList(resolver)); + handler.setLocations(List.of(new ClassPathResource("test/", getClass()))); + handler.setResourceResolvers(List.of(resolver)); handler.afterPropertiesSet(); testInvalidPath("../testsecret/secret.txt", handler); @@ -311,7 +316,7 @@ public class ResourceWebHandlerTests { testInvalidPath(":/../../testsecret/secret.txt", handler); Resource location = new UrlResource(getClass().getResource("./test/")); - this.handler.setLocations(Collections.singletonList(location)); + handler.setLocations(List.of(location)); Resource secretResource = new UrlResource(getClass().getResource("testsecret/secret.txt")); String secretPath = secretResource.getURL().getPath(); @@ -336,34 +341,29 @@ public class ResourceWebHandlerTests { }).verify(TIMEOUT); } - @Test - public void testResolvePathWithTraversal() throws Exception { - for (HttpMethod method : HttpMethod.values()) { - testResolvePathWithTraversal(method); - } - } - - private void testResolvePathWithTraversal(HttpMethod httpMethod) throws Exception { + @ParameterizedTest + @MethodSource("httpMethods") + void resolvePathWithTraversal(HttpMethod method) throws Exception { Resource location = new ClassPathResource("test/", getClass()); - this.handler.setLocations(Collections.singletonList(location)); + this.handler.setLocations(List.of(location)); - testResolvePathWithTraversal(httpMethod, "../testsecret/secret.txt", location); - testResolvePathWithTraversal(httpMethod, "test/../../testsecret/secret.txt", location); - testResolvePathWithTraversal(httpMethod, ":/../../testsecret/secret.txt", location); + testResolvePathWithTraversal(method, "../testsecret/secret.txt", location); + testResolvePathWithTraversal(method, "test/../../testsecret/secret.txt", location); + testResolvePathWithTraversal(method, ":/../../testsecret/secret.txt", location); location = new UrlResource(getClass().getResource("./test/")); - this.handler.setLocations(Collections.singletonList(location)); + this.handler.setLocations(List.of(location)); Resource secretResource = new UrlResource(getClass().getResource("testsecret/secret.txt")); String secretPath = secretResource.getURL().getPath(); - testResolvePathWithTraversal(httpMethod, "file:" + secretPath, location); - testResolvePathWithTraversal(httpMethod, "/file:" + secretPath, location); - testResolvePathWithTraversal(httpMethod, "url:" + secretPath, location); - testResolvePathWithTraversal(httpMethod, "/url:" + secretPath, location); - testResolvePathWithTraversal(httpMethod, "////../.." + secretPath, location); - testResolvePathWithTraversal(httpMethod, "/%2E%2E/testsecret/secret.txt", location); - testResolvePathWithTraversal(httpMethod, "%2F%2F%2E%2E%2F%2Ftestsecret/secret.txt", location); - testResolvePathWithTraversal(httpMethod, "url:" + secretPath, location); + testResolvePathWithTraversal(method, "file:" + secretPath, location); + testResolvePathWithTraversal(method, "/file:" + secretPath, location); + testResolvePathWithTraversal(method, "url:" + secretPath, location); + testResolvePathWithTraversal(method, "/url:" + secretPath, location); + testResolvePathWithTraversal(method, "////../.." + secretPath, location); + testResolvePathWithTraversal(method, "/%2E%2E/testsecret/secret.txt", location); + testResolvePathWithTraversal(method, "%2F%2F%2E%2E%2F%2Ftestsecret/secret.txt", location); + testResolvePathWithTraversal(method, "url:" + secretPath, location); // The following tests fail with a MalformedURLException on Windows // testResolvePathWithTraversal(location, "/" + secretPath); @@ -387,7 +387,7 @@ public class ResourceWebHandlerTests { } @Test - public void processPath() { + void processPath() { assertThat(this.handler.processPath("/foo/bar")).isSameAs("/foo/bar"); assertThat(this.handler.processPath("foo/bar")).isSameAs("foo/bar"); @@ -416,7 +416,7 @@ public class ResourceWebHandlerTests { } @Test - public void initAllowedLocations() { + void initAllowedLocations() { PathResourceResolver resolver = (PathResourceResolver) this.handler.getResourceResolvers().get(0); Resource[] locations = resolver.getAllowedLocations(); @@ -427,7 +427,7 @@ public class ResourceWebHandlerTests { } @Test - public void initAllowedLocationsWithExplicitConfiguration() throws Exception { + void initAllowedLocationsWithExplicitConfiguration() throws Exception { ClassPathResource location1 = new ClassPathResource("test/", getClass()); ClassPathResource location2 = new ClassPathResource("testalternatepath/", getClass()); @@ -435,7 +435,7 @@ public class ResourceWebHandlerTests { pathResolver.setAllowedLocations(location1); ResourceWebHandler handler = new ResourceWebHandler(); - handler.setResourceResolvers(Collections.singletonList(pathResolver)); + handler.setResourceResolvers(List.of(pathResolver)); handler.setLocations(Arrays.asList(location1, location2)); handler.afterPropertiesSet(); @@ -445,7 +445,7 @@ public class ResourceWebHandlerTests { } @Test - public void notModified() throws Exception { + void notModified() throws Exception { MockServerWebExchange exchange = MockServerWebExchange.from( MockServerHttpRequest.get("").ifModifiedSince(resourceLastModified("test/foo.css"))); @@ -455,7 +455,7 @@ public class ResourceWebHandlerTests { } @Test - public void modified() throws Exception { + void modified() throws Exception { long timestamp = resourceLastModified("test/foo.css") / 1000 * 1000 - 1; MockServerHttpRequest request = MockServerHttpRequest.get("").ifModifiedSince(timestamp).build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); @@ -467,7 +467,7 @@ public class ResourceWebHandlerTests { } @Test - public void directory() { + void directory() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); setPathWithinHandlerMapping(exchange, "js/"); StepVerifier.create(this.handler.handle(exchange)) @@ -478,7 +478,7 @@ public class ResourceWebHandlerTests { } @Test - public void directoryInJarFile() { + void directoryInJarFile() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); setPathWithinHandlerMapping(exchange, "underscorejs/"); StepVerifier.create(this.handler.handle(exchange)) @@ -489,7 +489,7 @@ public class ResourceWebHandlerTests { } @Test - public void missingResourcePath() { + void missingResourcePath() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); setPathWithinHandlerMapping(exchange, ""); StepVerifier.create(this.handler.handle(exchange)) @@ -500,29 +500,24 @@ public class ResourceWebHandlerTests { } @Test - public void noPathWithinHandlerMappingAttribute() { + void noPathWithinHandlerMappingAttribute() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); assertThatIllegalArgumentException().isThrownBy(() -> this.handler.handle(exchange).block(TIMEOUT)); } @Test - public void unsupportedHttpMethod() { + void unsupportedHttpMethod() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("")); setPathWithinHandlerMapping(exchange, "foo.css"); assertThatExceptionOfType(MethodNotAllowedException.class).isThrownBy(() -> this.handler.handle(exchange).block(TIMEOUT)); } - @Test - public void resourceNotFound() throws Exception { - for (HttpMethod method : HttpMethod.values()) { - resourceNotFound(method); - } - } - - private void resourceNotFound(HttpMethod httpMethod) { - MockServerHttpRequest request = MockServerHttpRequest.method(httpMethod, "").build(); + @ParameterizedTest + @MethodSource("httpMethods") + void resourceNotFound(HttpMethod method) throws Exception { + MockServerHttpRequest request = MockServerHttpRequest.method(method, "").build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); setPathWithinHandlerMapping(exchange, "not-there.css"); Mono mono = this.handler.handle(exchange); @@ -540,7 +535,7 @@ public class ResourceWebHandlerTests { } @Test - public void partialContentByteRange() { + void partialContentByteRange() { MockServerHttpRequest request = MockServerHttpRequest.get("").header("Range", "bytes=0-1").build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); setPathWithinHandlerMapping(exchange, "foo.txt"); @@ -556,7 +551,7 @@ public class ResourceWebHandlerTests { } @Test - public void partialContentByteRangeNoEnd() { + void partialContentByteRangeNoEnd() { MockServerHttpRequest request = MockServerHttpRequest.get("").header("range", "bytes=9-").build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); setPathWithinHandlerMapping(exchange, "foo.txt"); @@ -572,7 +567,7 @@ public class ResourceWebHandlerTests { } @Test - public void partialContentByteRangeLargeEnd() { + void partialContentByteRangeLargeEnd() { MockServerHttpRequest request = MockServerHttpRequest.get("").header("range", "bytes=9-10000").build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); setPathWithinHandlerMapping(exchange, "foo.txt"); @@ -588,7 +583,7 @@ public class ResourceWebHandlerTests { } @Test - public void partialContentSuffixRange() { + void partialContentSuffixRange() { MockServerHttpRequest request = MockServerHttpRequest.get("").header("range", "bytes=-1").build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); setPathWithinHandlerMapping(exchange, "foo.txt"); @@ -604,7 +599,7 @@ public class ResourceWebHandlerTests { } @Test - public void partialContentSuffixRangeLargeSuffix() { + void partialContentSuffixRangeLargeSuffix() { MockServerHttpRequest request = MockServerHttpRequest.get("").header("range", "bytes=-11").build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); setPathWithinHandlerMapping(exchange, "foo.txt"); @@ -620,7 +615,7 @@ public class ResourceWebHandlerTests { } @Test - public void partialContentInvalidRangeHeader() { + void partialContentInvalidRangeHeader() { MockServerHttpRequest request = MockServerHttpRequest.get("").header("range", "bytes=foo bar").build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); setPathWithinHandlerMapping(exchange, "foo.txt"); @@ -635,7 +630,7 @@ public class ResourceWebHandlerTests { } @Test - public void partialContentMultipleByteRanges() { + void partialContentMultipleByteRanges() { MockServerHttpRequest request = MockServerHttpRequest.get("").header("Range", "bytes=0-1, 4-5, 8-9").build(); MockServerWebExchange exchange = MockServerWebExchange.from(request); setPathWithinHandlerMapping(exchange, "foo.txt"); @@ -648,7 +643,7 @@ public class ResourceWebHandlerTests { String boundary = "--" + exchange.getResponse().getHeaders().getContentType().toString().substring(30); Mono reduced = Flux.from(exchange.getResponse().getBody()) - .reduce(DefaultDataBufferFactory.sharedInstance.allocateBuffer(), (previous, current) -> { + .reduce(DefaultDataBufferFactory.sharedInstance.allocateBuffer(256), (previous, current) -> { previous.write(current); DataBufferUtils.release(current); return previous; @@ -679,7 +674,7 @@ public class ResourceWebHandlerTests { } @Test // SPR-14005 - public void doOverwriteExistingCacheControlHeaders() { + void doOverwriteExistingCacheControlHeaders() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); exchange.getResponse().getHeaders().setCacheControl(CacheControl.noStore().getHeaderValue()); setPathWithinHandlerMapping(exchange, "foo.css"); @@ -723,4 +718,9 @@ public class ResourceWebHandlerTests { .verify(); } + + static Stream httpMethods() { + return Arrays.stream(HttpMethod.values()); + } + } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/SimpleUrlHandlerMappingIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/SimpleUrlHandlerMappingIntegrationTests.java index 07c6692606e..f323bf1b85e 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/SimpleUrlHandlerMappingIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/SimpleUrlHandlerMappingIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,7 +67,7 @@ class SimpleUrlHandlerMappingIntegrationTests extends AbstractHttpHandlerIntegra @ParameterizedHttpServerTest - void testRequestToFooHandler(HttpServer httpServer) throws Exception { + void requestToFooHandler(HttpServer httpServer) throws Exception { startServer(httpServer); URI url = new URI("http://localhost:" + this.port + "/foo"); @@ -79,7 +79,7 @@ class SimpleUrlHandlerMappingIntegrationTests extends AbstractHttpHandlerIntegra } @ParameterizedHttpServerTest - public void testRequestToBarHandler(HttpServer httpServer) throws Exception { + public void requestToBarHandler(HttpServer httpServer) throws Exception { startServer(httpServer); URI url = new URI("http://localhost:" + this.port + "/bar"); @@ -91,7 +91,7 @@ class SimpleUrlHandlerMappingIntegrationTests extends AbstractHttpHandlerIntegra } @ParameterizedHttpServerTest - void testRequestToHeaderSettingHandler(HttpServer httpServer) throws Exception { + void requestToHeaderSettingHandler(HttpServer httpServer) throws Exception { startServer(httpServer); URI url = new URI("http://localhost:" + this.port + "/header"); @@ -103,7 +103,7 @@ class SimpleUrlHandlerMappingIntegrationTests extends AbstractHttpHandlerIntegra } @ParameterizedHttpServerTest - void testHandlerNotFound(HttpServer httpServer) throws Exception { + void handlerNotFound(HttpServer httpServer) throws Exception { startServer(httpServer); URI url = new URI("http://localhost:" + this.port + "/oops"); @@ -117,7 +117,7 @@ class SimpleUrlHandlerMappingIntegrationTests extends AbstractHttpHandlerIntegra } private static DataBuffer asDataBuffer(String text) { - DefaultDataBuffer buffer = DefaultDataBufferFactory.sharedInstance.allocateBuffer(); + DefaultDataBuffer buffer = DefaultDataBufferFactory.sharedInstance.allocateBuffer(256); return buffer.write(text.getBytes(StandardCharsets.UTF_8)); } diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingMessageConversionIntegrationTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingMessageConversionIntegrationTests.java index 7a64f0a0d31..bd25e99a281 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingMessageConversionIntegrationTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingMessageConversionIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -487,7 +487,7 @@ public class RequestMappingMessageConversionIntegrationTests extends AbstractReq public Publisher getPublisher() { Jackson2JsonEncoder encoder = new Jackson2JsonEncoder(); return encoder.encode(Mono.just(new Person("Robert")), DefaultDataBufferFactory.sharedInstance, - ResolvableType.forClass(Person.class), JSON, Collections.emptyMap()).map(DataBuffer::asByteBuffer); + ResolvableType.forClass(Person.class), JSON, Collections.emptyMap()).map(DataBuffer::toByteBuffer); } @GetMapping("/flux") diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/freemarker/FreeMarkerViewTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/freemarker/FreeMarkerViewTests.java index 54d8f805232..fbaeabaa41b 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/freemarker/FreeMarkerViewTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/result/view/freemarker/FreeMarkerViewTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -79,16 +79,16 @@ public class FreeMarkerViewTests { FreeMarkerView view = new FreeMarkerView(); view.setApplicationContext(this.context); view.setUrl("anythingButNull"); - assertThatExceptionOfType(ApplicationContextException.class).isThrownBy( - view::afterPropertiesSet) + assertThatExceptionOfType(ApplicationContextException.class) + .isThrownBy(view::afterPropertiesSet) .withMessageContaining("Must define a single FreeMarkerConfig bean"); } @Test public void noTemplateName() throws Exception { FreeMarkerView freeMarkerView = new FreeMarkerView(); - assertThatIllegalArgumentException().isThrownBy( - freeMarkerView::afterPropertiesSet) + assertThatIllegalArgumentException() + .isThrownBy(freeMarkerView::afterPropertiesSet) .withMessageContaining("Property 'url' is required"); } @@ -141,7 +141,7 @@ public class FreeMarkerViewTests { private static String asString(DataBuffer dataBuffer) { - ByteBuffer byteBuffer = dataBuffer.asByteBuffer(); + ByteBuffer byteBuffer = dataBuffer.toByteBuffer(); final byte[] bytes = new byte[byteBuffer.remaining()]; byteBuffer.get(bytes); return new String(bytes, StandardCharsets.UTF_8);