Use Gradle test fixture support for spring-core

See gh-23550
This commit is contained in:
Sam Brannen
2019-12-28 11:44:40 +01:00
parent 75fd391fc7
commit 5718bf424b
224 changed files with 552 additions and 453 deletions

View File

@@ -16,7 +16,7 @@
package example.type;
import org.springframework.stereotype.Component;
import org.springframework.core.test.fixtures.stereotype.Component;
/**
* We must use a standalone set of types to ensure that no one else is loading

View File

@@ -42,10 +42,10 @@ import org.springframework.core.annotation.AnnotationUtilsTests.ExtendsBaseClass
import org.springframework.core.annotation.AnnotationUtilsTests.ImplementsInterfaceWithGenericAnnotatedMethod;
import org.springframework.core.annotation.AnnotationUtilsTests.WebController;
import org.springframework.core.annotation.AnnotationUtilsTests.WebMapping;
import org.springframework.core.test.fixtures.stereotype.Component;
import org.springframework.core.test.fixtures.stereotype.Indexed;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Indexed;
import org.springframework.util.MultiValueMap;
import static java.util.Arrays.asList;

View File

@@ -39,8 +39,8 @@ import org.junit.jupiter.api.Test;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.subpackage.NonPublicAnnotatedClass;
import org.springframework.core.test.fixtures.stereotype.Component;
import org.springframework.lang.NonNullApi;
import org.springframework.stereotype.Component;
import static java.util.Arrays.asList;
import static java.util.Arrays.stream;
@@ -928,7 +928,7 @@ class AnnotationUtilsTests {
Map<String, Object> map = Collections.singletonMap(VALUE, 42L);
assertThatIllegalStateException().isThrownBy(() ->
synthesizeAnnotation(map, Component.class, null).value())
.withMessageContaining("Attribute 'value' in annotation org.springframework.stereotype.Component "
.withMessageContaining("Attribute 'value' in annotation org.springframework.core.test.fixtures.stereotype.Component "
+ "should be compatible with java.lang.String but a java.lang.Long value was returned");
}

View File

@@ -43,9 +43,9 @@ import org.springframework.core.Ordered;
import org.springframework.core.annotation.MergedAnnotation.Adapt;
import org.springframework.core.annotation.MergedAnnotations.SearchStrategy;
import org.springframework.core.annotation.subpackage.NonPublicAnnotatedClass;
import org.springframework.core.test.fixtures.stereotype.Component;
import org.springframework.core.test.fixtures.stereotype.Indexed;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Indexed;
import org.springframework.util.ClassUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ReflectionUtils;
@@ -1770,7 +1770,7 @@ class MergedAnnotationsTests {
MergedAnnotation<Component> annotation = MergedAnnotation.of(Component.class, map);
assertThatIllegalStateException().isThrownBy(() -> annotation.synthesize().value())
.withMessage("Attribute 'value' in annotation " +
"org.springframework.stereotype.Component should be " +
"org.springframework.core.test.fixtures.stereotype.Component should be " +
"compatible with java.lang.String but a java.lang.Long value was returned");
}

View File

@@ -1,429 +0,0 @@
/*
* Copyright 2002-2019 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.codec;
import java.time.Duration;
import java.util.Map;
import java.util.function.Consumer;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.ResolvableType;
import org.springframework.core.io.buffer.AbstractLeakCheckingTests;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.MimeType;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Abstract base class for {@link Decoder} unit tests. Subclasses need to implement
* {@link #canDecode()}, {@link #decode()} and {@link #decodeToMono()}, possibly using the wide
* variety of helper methods like {@link #testDecodeAll} or {@link #testDecodeToMonoAll}.
*
* @author Arjen Poutsma
* @since 5.1.3
*/
@SuppressWarnings("ProtectedField")
public abstract class AbstractDecoderTests<D extends Decoder<?>> extends AbstractLeakCheckingTests {
/**
* The decoder to test.
*/
protected D decoder;
/**
* Construct a new {@code AbstractDecoderTests} instance for the given decoder.
* @param decoder the decoder
*/
protected AbstractDecoderTests(D decoder) {
Assert.notNull(decoder, "Encoder must not be null");
this.decoder = decoder;
}
/**
* Subclasses should implement this method to test {@link Decoder#canDecode}.
*/
@Test
public abstract void canDecode() throws Exception;
/**
* Subclasses should implement this method to test {@link Decoder#decode}, possibly using
* {@link #testDecodeAll} or other helper methods.
*/
@Test
public abstract void decode() throws Exception;
/**
* Subclasses should implement this method to test {@link Decoder#decodeToMono}, possibly using
* {@link #testDecodeToMonoAll}.
*/
@Test
public abstract void decodeToMono() throws Exception;
// Flux
/**
* Helper methods that tests for a variety of {@link Flux} decoding scenarios. This methods
* invokes:
* <ul>
* <li>{@link #testDecode(Publisher, ResolvableType, Consumer, MimeType, Map)}</li>
* <li>{@link #testDecodeError(Publisher, ResolvableType, MimeType, Map)}</li>
* <li>{@link #testDecodeCancel(Publisher, ResolvableType, MimeType, Map)}</li>
* <li>{@link #testDecodeEmpty(ResolvableType, MimeType, Map)}</li>
* </ul>
*
* @param input the input to be provided to the decoder
* @param outputClass the desired output class
* @param stepConsumer a consumer to {@linkplain StepVerifier verify} the output
* @param <T> the output type
*/
protected <T> void testDecodeAll(Publisher<DataBuffer> input, Class<? extends T> outputClass,
Consumer<StepVerifier.FirstStep<T>> stepConsumer) {
testDecodeAll(input, ResolvableType.forClass(outputClass), stepConsumer, null, null);
}
/**
* Helper methods that tests for a variety of {@link Flux} decoding scenarios. This methods
* invokes:
* <ul>
* <li>{@link #testDecode(Publisher, ResolvableType, Consumer, MimeType, Map)}</li>
* <li>{@link #testDecodeError(Publisher, ResolvableType, MimeType, Map)}</li>
* <li>{@link #testDecodeCancel(Publisher, ResolvableType, MimeType, Map)}</li>
* <li>{@link #testDecodeEmpty(ResolvableType, MimeType, Map)}</li>
* </ul>
*
* @param input the input to be provided to the decoder
* @param outputType the desired output type
* @param stepConsumer a consumer to {@linkplain StepVerifier verify} the output
* @param mimeType the mime type to use for decoding. May be {@code null}.
* @param hints the hints used for decoding. May be {@code null}.
* @param <T> the output type
*/
protected <T> void testDecodeAll(Publisher<DataBuffer> input, ResolvableType outputType,
Consumer<StepVerifier.FirstStep<T>> stepConsumer,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
testDecode(input, outputType, stepConsumer, mimeType, hints);
testDecodeError(input, outputType, mimeType, hints);
testDecodeCancel(input, outputType, mimeType, hints);
testDecodeEmpty(outputType, mimeType, hints);
}
/**
* Test a standard {@link Decoder#decode decode} scenario. For example:
* <pre class="code">
* byte[] bytes1 = ...
* byte[] bytes2 = ...
*
* Flux&lt;DataBuffer&gt; input = Flux.concat(
* dataBuffer(bytes1),
* dataBuffer(bytes2));
*
* testDecodeAll(input, byte[].class, step -&gt; step
* .consumeNextWith(expectBytes(bytes1))
* .consumeNextWith(expectBytes(bytes2))
* .verifyComplete());
* </pre>
*
* @param input the input to be provided to the decoder
* @param outputClass the desired output class
* @param stepConsumer a consumer to {@linkplain StepVerifier verify} the output
* @param <T> the output type
*/
protected <T> void testDecode(Publisher<DataBuffer> input, Class<? extends T> outputClass,
Consumer<StepVerifier.FirstStep<T>> stepConsumer) {
testDecode(input, ResolvableType.forClass(outputClass), stepConsumer, null, null);
}
/**
* Test a standard {@link Decoder#decode decode} scenario. For example:
* <pre class="code">
* byte[] bytes1 = ...
* byte[] bytes2 = ...
*
* Flux&lt;DataBuffer&gt; input = Flux.concat(
* dataBuffer(bytes1),
* dataBuffer(bytes2));
*
* testDecodeAll(input, byte[].class, step -&gt; step
* .consumeNextWith(expectBytes(bytes1))
* .consumeNextWith(expectBytes(bytes2))
* .verifyComplete());
* </pre>
*
* @param input the input to be provided to the decoder
* @param outputType the desired output type
* @param stepConsumer a consumer to {@linkplain StepVerifier verify} the output
* @param mimeType the mime type to use for decoding. May be {@code null}.
* @param hints the hints used for decoding. May be {@code null}.
* @param <T> the output type
*/
@SuppressWarnings("unchecked")
protected <T> void testDecode(Publisher<DataBuffer> input, ResolvableType outputType,
Consumer<StepVerifier.FirstStep<T>> stepConsumer,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
Flux<T> result = (Flux<T>) this.decoder.decode(input, outputType, mimeType, hints);
StepVerifier.FirstStep<T> step = StepVerifier.create(result);
stepConsumer.accept(step);
}
/**
* Test a {@link Decoder#decode decode} scenario where the input stream contains an error.
* This test method will feed the first element of the {@code input} stream to the decoder,
* followed by an {@link InputException}.
* The result is expected to contain one "normal" element, followed by the error.
*
* @param input the input to be provided to the decoder
* @param outputType the desired output type
* @param mimeType the mime type to use for decoding. May be {@code null}.
* @param hints the hints used for decoding. May be {@code null}.
* @see InputException
*/
protected void testDecodeError(Publisher<DataBuffer> input, ResolvableType outputType,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
Flux<DataBuffer> buffer = Mono.from(input).concatWith(Flux.error(new InputException()));
assertThatExceptionOfType(InputException.class).isThrownBy(() ->
this.decoder.decode(buffer, outputType, mimeType, hints).blockLast(Duration.ofSeconds(5)));
}
/**
* Test a {@link Decoder#decode decode} scenario where the input stream is canceled.
* This test method will feed the first element of the {@code input} stream to the decoder,
* followed by a cancel signal.
* The result is expected to contain one "normal" element.
*
* @param input the input to be provided to the decoder
* @param outputType the desired output type
* @param mimeType the mime type to use for decoding. May be {@code null}.
* @param hints the hints used for decoding. May be {@code null}.
*/
protected void testDecodeCancel(Publisher<DataBuffer> input, ResolvableType outputType,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
Flux<?> result = this.decoder.decode(input, outputType, mimeType, hints);
StepVerifier.create(result).expectNextCount(1).thenCancel().verify();
}
/**
* Test a {@link Decoder#decode decode} scenario where the input stream is empty.
* The output is expected to be empty as well.
*
* @param outputType the desired output type
* @param mimeType the mime type to use for decoding. May be {@code null}.
* @param hints the hints used for decoding. May be {@code null}.
*/
protected void testDecodeEmpty(ResolvableType outputType, @Nullable MimeType mimeType,
@Nullable Map<String, Object> hints) {
Flux<DataBuffer> input = Flux.empty();
Flux<?> result = this.decoder.decode(input, outputType, mimeType, hints);
StepVerifier.create(result).verifyComplete();
}
// Mono
/**
* Helper methods that tests for a variety of {@link Mono} decoding scenarios. This methods
* invokes:
* <ul>
* <li>{@link #testDecodeToMono(Publisher, ResolvableType, Consumer, MimeType, Map)}</li>
* <li>{@link #testDecodeToMonoError(Publisher, ResolvableType, MimeType, Map)}</li>
* <li>{@link #testDecodeToMonoCancel(Publisher, ResolvableType, MimeType, Map)}</li>
* <li>{@link #testDecodeToMonoEmpty(ResolvableType, MimeType, Map)}</li>
* </ul>
*
* @param input the input to be provided to the decoder
* @param outputClass the desired output class
* @param stepConsumer a consumer to {@linkplain StepVerifier verify} the output
* @param <T> the output type
*/
protected <T> void testDecodeToMonoAll(Publisher<DataBuffer> input,
Class<? extends T> outputClass, Consumer<StepVerifier.FirstStep<T>> stepConsumer) {
testDecodeToMonoAll(input, ResolvableType.forClass(outputClass), stepConsumer, null, null);
}
/**
* Helper methods that tests for a variety of {@link Mono} decoding scenarios. This methods
* invokes:
* <ul>
* <li>{@link #testDecodeToMono(Publisher, ResolvableType, Consumer, MimeType, Map)}</li>
* <li>{@link #testDecodeToMonoError(Publisher, ResolvableType, MimeType, Map)}</li>
* <li>{@link #testDecodeToMonoCancel(Publisher, ResolvableType, MimeType, Map)}</li>
* <li>{@link #testDecodeToMonoEmpty(ResolvableType, MimeType, Map)}</li>
* </ul>
*
* @param input the input to be provided to the decoder
* @param outputType the desired output type
* @param stepConsumer a consumer to {@linkplain StepVerifier verify} the output
* @param mimeType the mime type to use for decoding. May be {@code null}.
* @param hints the hints used for decoding. May be {@code null}.
* @param <T> the output type
*/
protected <T> void testDecodeToMonoAll(Publisher<DataBuffer> input, ResolvableType outputType,
Consumer<StepVerifier.FirstStep<T>> stepConsumer,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
testDecodeToMono(input, outputType, stepConsumer, mimeType, hints);
testDecodeToMonoError(input, outputType, mimeType, hints);
testDecodeToMonoCancel(input, outputType, mimeType, hints);
testDecodeToMonoEmpty(outputType, mimeType, hints);
}
/**
* Test a standard {@link Decoder#decodeToMono decode} scenario. For example:
* <pre class="code">
* byte[] bytes1 = ...
* byte[] bytes2 = ...
* byte[] allBytes = ... // bytes1 + bytes2
*
* Flux&lt;DataBuffer&gt; input = Flux.concat(
* dataBuffer(bytes1),
* dataBuffer(bytes2));
*
* testDecodeAll(input, byte[].class, step -&gt; step
* .consumeNextWith(expectBytes(allBytes))
* .verifyComplete());
* </pre>
*
* @param input the input to be provided to the decoder
* @param outputClass the desired output class
* @param stepConsumer a consumer to {@linkplain StepVerifier verify} the output
* @param <T> the output type
*/
protected <T> void testDecodeToMono(Publisher<DataBuffer> input,
Class<? extends T> outputClass, Consumer<StepVerifier.FirstStep<T>> stepConsumer) {
testDecodeToMono(input, ResolvableType.forClass(outputClass), stepConsumer, null, null);
}
/**
* Test a standard {@link Decoder#decodeToMono decode} scenario. For example:
* <pre class="code">
* byte[] bytes1 = ...
* byte[] bytes2 = ...
* byte[] allBytes = ... // bytes1 + bytes2
*
* Flux&lt;DataBuffer&gt; input = Flux.concat(
* dataBuffer(bytes1),
* dataBuffer(bytes2));
*
* testDecodeAll(input, byte[].class, step -&gt; step
* .consumeNextWith(expectBytes(allBytes))
* .verifyComplete());
* </pre>
*
* @param input the input to be provided to the decoder
* @param outputType the desired output type
* @param stepConsumer a consumer to {@linkplain StepVerifier verify} the output
* @param mimeType the mime type to use for decoding. May be {@code null}.
* @param hints the hints used for decoding. May be {@code null}.
* @param <T> the output type
*/
@SuppressWarnings("unchecked")
protected <T> void testDecodeToMono(Publisher<DataBuffer> input, ResolvableType outputType,
Consumer<StepVerifier.FirstStep<T>> stepConsumer,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
Mono<T> result = (Mono<T>) this.decoder.decodeToMono(input, outputType, mimeType, hints);
StepVerifier.FirstStep<T> step = StepVerifier.create(result);
stepConsumer.accept(step);
}
/**
* Test a {@link Decoder#decodeToMono decode} scenario where the input stream contains an error.
* This test method will feed the first element of the {@code input} stream to the decoder,
* followed by an {@link InputException}.
* The result is expected to contain the error.
*
* @param input the input to be provided to the decoder
* @param outputType the desired output type
* @param mimeType the mime type to use for decoding. May be {@code null}.
* @param hints the hints used for decoding. May be {@code null}.
* @see InputException
*/
protected void testDecodeToMonoError(Publisher<DataBuffer> input, ResolvableType outputType,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
input = Mono.from(input).concatWith(Flux.error(new InputException()));
Mono<?> result = this.decoder.decodeToMono(input, outputType, mimeType, hints);
StepVerifier.create(result).expectError(InputException.class).verify();
}
/**
* Test a {@link Decoder#decodeToMono decode} scenario where the input stream is canceled.
* This test method will immediately cancel the output stream.
*
* @param input the input to be provided to the decoder
* @param outputType the desired output type
* @param mimeType the mime type to use for decoding. May be {@code null}.
* @param hints the hints used for decoding. May be {@code null}.
*/
protected void testDecodeToMonoCancel(Publisher<DataBuffer> input, ResolvableType outputType,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
Mono<?> result = this.decoder.decodeToMono(input, outputType, mimeType, hints);
StepVerifier.create(result).thenCancel().verify();
}
/**
* Test a {@link Decoder#decodeToMono decode} scenario where the input stream is empty.
* The output is expected to be empty as well.
*
* @param outputType the desired output type
* @param mimeType the mime type to use for decoding. May be {@code null}.
* @param hints the hints used for decoding. May be {@code null}.
*/
protected void testDecodeToMonoEmpty(ResolvableType outputType, @Nullable MimeType mimeType,
@Nullable Map<String, Object> hints) {
Mono<?> result = this.decoder.decodeToMono(Flux.empty(), outputType, mimeType, hints);
StepVerifier.create(result).verifyComplete();
}
/**
* Creates a deferred {@link DataBuffer} containing the given bytes.
* @param bytes the bytes that are to be stored in the buffer
* @return the deferred buffer
*/
protected Mono<DataBuffer> dataBuffer(byte[] bytes) {
return Mono.fromCallable(() -> {
DataBuffer dataBuffer = this.bufferFactory.allocateBuffer(bytes.length);
dataBuffer.write(bytes);
return dataBuffer;
});
}
/**
* Exception used in {@link #testDecodeError} and {@link #testDecodeToMonoError}
*/
@SuppressWarnings("serial")
public static class InputException extends RuntimeException {}
}

View File

@@ -1,275 +0,0 @@
/*
* Copyright 2002-2019 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.codec;
import java.util.Map;
import java.util.function.Consumer;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
import org.springframework.core.ResolvableType;
import org.springframework.core.io.buffer.AbstractLeakCheckingTests;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.MimeType;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.core.io.buffer.DataBufferUtils.release;
/**
* Abstract base class for {@link Encoder} unit tests. Subclasses need to implement
* {@link #canEncode()} and {@link #encode()}, possibly using the wide
* * variety of helper methods like {@link #testEncodeAll}.
*
* @author Arjen Poutsma
* @since 5.1.3
*/
@SuppressWarnings("ProtectedField")
public abstract class AbstractEncoderTests<E extends Encoder<?>> extends AbstractLeakCheckingTests {
/**
* The encoder to test.
*/
protected final E encoder;
/**
* Construct a new {@code AbstractEncoderTestCase} for the given parameters.
* @param encoder the encoder
*/
protected AbstractEncoderTests(E encoder) {
Assert.notNull(encoder, "Encoder must not be null");
this.encoder = encoder;
}
/**
* Subclasses should implement this method to test {@link Encoder#canEncode}.
*/
@Test
public abstract void canEncode() throws Exception;
/**
* Subclasses should implement this method to test {@link Encoder#encode}, possibly using
* {@link #testEncodeAll} or other helper methods.
*/
@Test
public abstract void encode() throws Exception;
/**
* Helper methods that tests for a variety of encoding scenarios. This methods
* invokes:
* <ul>
* <li>{@link #testEncode(Publisher, ResolvableType, Consumer, MimeType, Map)}</li>
* <li>{@link #testEncodeError(Publisher, ResolvableType, MimeType, Map)}</li>
* <li>{@link #testEncodeCancel(Publisher, ResolvableType, MimeType, Map)}</li>
* <li>{@link #testEncodeEmpty(ResolvableType, MimeType, Map)}</li>
* </ul>
*
* @param input the input to be provided to the encoder
* @param inputClass the input class
* @param stepConsumer a consumer to {@linkplain StepVerifier verify} the output
* @param <T> the output type
*/
protected <T> void testEncodeAll(Publisher<? extends T> input, Class<? extends T> inputClass,
Consumer<StepVerifier.FirstStep<DataBuffer>> stepConsumer) {
testEncodeAll(input, ResolvableType.forClass(inputClass), stepConsumer, null, null);
}
/**
* Helper methods that tests for a variety of decoding scenarios. This methods
* invokes:
* <ul>
* <li>{@link #testEncode(Publisher, ResolvableType, Consumer, MimeType, Map)}</li>
* <li>{@link #testEncodeError(Publisher, ResolvableType, MimeType, Map)}</li>
* <li>{@link #testEncodeCancel(Publisher, ResolvableType, MimeType, Map)}</li>
* <li>{@link #testEncodeEmpty(ResolvableType, MimeType, Map)}</li>
* </ul>
*
* @param input the input to be provided to the encoder
* @param inputType the input type
* @param stepConsumer a consumer to {@linkplain StepVerifier verify} the output
* @param mimeType the mime type to use for decoding. May be {@code null}.
* @param hints the hints used for decoding. May be {@code null}.
* @param <T> the output type
*/
protected <T> void testEncodeAll(Publisher<? extends T> input, ResolvableType inputType,
Consumer<StepVerifier.FirstStep<DataBuffer>> stepConsumer,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
testEncode(input, inputType, stepConsumer, mimeType, hints);
testEncodeError(input, inputType, mimeType, hints);
testEncodeCancel(input, inputType, mimeType, hints);
testEncodeEmpty(inputType, mimeType, hints);
}
/**
* Test a standard {@link Encoder#encode encode} scenario.
*
* @param input the input to be provided to the encoder
* @param inputClass the input class
* @param stepConsumer a consumer to {@linkplain StepVerifier verify} the output
* @param <T> the output type
*/
protected <T> void testEncode(Publisher<? extends T> input, Class<? extends T> inputClass,
Consumer<StepVerifier.FirstStep<DataBuffer>> stepConsumer) {
testEncode(input, ResolvableType.forClass(inputClass), stepConsumer, null, null);
}
/**
* Test a standard {@link Encoder#encode encode} scenario.
*
* @param input the input to be provided to the encoder
* @param inputType the input type
* @param stepConsumer a consumer to {@linkplain StepVerifier verify} the output
* @param mimeType the mime type to use for decoding. May be {@code null}.
* @param hints the hints used for decoding. May be {@code null}.
* @param <T> the output type
*/
protected <T> void testEncode(Publisher<? extends T> input, ResolvableType inputType,
Consumer<StepVerifier.FirstStep<DataBuffer>> stepConsumer,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
Flux<DataBuffer> result = encoder().encode(input, this.bufferFactory, inputType,
mimeType, hints);
StepVerifier.FirstStep<DataBuffer> step = StepVerifier.create(result);
stepConsumer.accept(step);
}
/**
* Test a {@link Encoder#encode encode} scenario where the input stream contains an error.
* This test method will feed the first element of the {@code input} stream to the encoder,
* followed by an {@link InputException}.
* The result is expected to contain one "normal" element, followed by the error.
*
* @param input the input to be provided to the encoder
* @param inputType the input type
* @param mimeType the mime type to use for decoding. May be {@code null}.
* @param hints the hints used for decoding. May be {@code null}.
* @see InputException
*/
protected void testEncodeError(Publisher<?> input, ResolvableType inputType,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
input = Flux.concat(
Flux.from(input).take(1),
Flux.error(new InputException()));
Flux<DataBuffer> result = encoder().encode(input, this.bufferFactory, inputType,
mimeType, hints);
StepVerifier.create(result)
.consumeNextWith(DataBufferUtils::release)
.expectError(InputException.class)
.verify();
}
/**
* Test a {@link Encoder#encode encode} scenario where the input stream is canceled.
* This test method will feed the first element of the {@code input} stream to the decoder,
* followed by a cancel signal.
* The result is expected to contain one "normal" element.
*
* @param input the input to be provided to the encoder
* @param inputType the input type
* @param mimeType the mime type to use for decoding. May be {@code null}.
* @param hints the hints used for decoding. May be {@code null}.
*/
protected void testEncodeCancel(Publisher<?> input, ResolvableType inputType,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
Flux<DataBuffer> result = encoder().encode(input, this.bufferFactory, inputType, mimeType,
hints);
StepVerifier.create(result)
.consumeNextWith(DataBufferUtils::release)
.thenCancel()
.verify();
}
/**
* Test a {@link Encoder#encode encode} scenario where the input stream is empty.
* The output is expected to be empty as well.
*
* @param inputType the input type
* @param mimeType the mime type to use for decoding. May be {@code null}.
* @param hints the hints used for decoding. May be {@code null}.
*/
protected void testEncodeEmpty(ResolvableType inputType, @Nullable MimeType mimeType,
@Nullable Map<String, Object> hints) {
Flux<?> input = Flux.empty();
Flux<DataBuffer> result = encoder().encode(input, this.bufferFactory, inputType,
mimeType, hints);
StepVerifier.create(result)
.verifyComplete();
}
/**
* Create a result consumer that expects the given bytes.
* @param expected the expected bytes
* @return a consumer that expects the given data buffer to be equal to {@code expected}
*/
protected final Consumer<DataBuffer> expectBytes(byte[] expected) {
return dataBuffer -> {
byte[] resultBytes = new byte[dataBuffer.readableByteCount()];
dataBuffer.read(resultBytes);
release(dataBuffer);
assertThat(resultBytes).isEqualTo(expected);
};
}
/**
* Create a result consumer that expects the given string, using the UTF-8 encoding.
* @param expected the expected string
* @return a consumer that expects the given data buffer to be equal to {@code expected}
*/
protected Consumer<DataBuffer> expectString(String expected) {
return dataBuffer -> {
byte[] resultBytes = new byte[dataBuffer.readableByteCount()];
dataBuffer.read(resultBytes);
release(dataBuffer);
String actual = new String(resultBytes, UTF_8);
assertThat(actual).isEqualTo(expected);
};
}
@SuppressWarnings("unchecked")
private <T> Encoder<T> encoder() {
return (Encoder<T>) this.encoder;
}
/**
* Exception used in {@link #testEncodeError}.
*/
@SuppressWarnings("serial")
public static class InputException extends RuntimeException {
}
}

View File

@@ -24,6 +24,7 @@ import reactor.core.publisher.Flux;
import org.springframework.core.ResolvableType;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.test.fixtures.codec.AbstractDecoderTests;
import org.springframework.util.MimeTypeUtils;
import static org.assertj.core.api.Assertions.assertThat;

View File

@@ -22,6 +22,7 @@ import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
import org.springframework.core.ResolvableType;
import org.springframework.core.test.fixtures.codec.AbstractEncoderTests;
import org.springframework.util.MimeTypeUtils;
import static org.assertj.core.api.Assertions.assertThat;

View File

@@ -25,6 +25,7 @@ import reactor.core.publisher.Flux;
import org.springframework.core.ResolvableType;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.test.fixtures.codec.AbstractDecoderTests;
import org.springframework.util.MimeTypeUtils;
import static org.assertj.core.api.Assertions.assertThat;

View File

@@ -23,6 +23,7 @@ import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
import org.springframework.core.ResolvableType;
import org.springframework.core.test.fixtures.codec.AbstractEncoderTests;
import org.springframework.util.MimeTypeUtils;
import static org.assertj.core.api.Assertions.assertThat;

View File

@@ -23,6 +23,7 @@ import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
import org.springframework.core.ResolvableType;
import org.springframework.core.test.fixtures.codec.AbstractEncoderTests;
import org.springframework.util.MimeTypeUtils;
import static java.nio.charset.StandardCharsets.ISO_8859_1;

View File

@@ -25,6 +25,7 @@ import reactor.core.publisher.Flux;
import org.springframework.core.ResolvableType;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.test.fixtures.codec.AbstractDecoderTests;
import org.springframework.util.MimeTypeUtils;
import static org.assertj.core.api.Assertions.assertThat;

View File

@@ -24,6 +24,7 @@ import reactor.core.publisher.Mono;
import org.springframework.core.ResolvableType;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.test.fixtures.codec.AbstractEncoderTests;
import org.springframework.util.MimeTypeUtils;
import static org.assertj.core.api.Assertions.assertThat;

View File

@@ -28,6 +28,7 @@ import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.test.fixtures.codec.AbstractDecoderTests;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.StreamUtils;

View File

@@ -28,6 +28,7 @@ import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.test.fixtures.codec.AbstractEncoderTests;
import org.springframework.lang.Nullable;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;

View File

@@ -29,11 +29,11 @@ import reactor.test.StepVerifier;
import org.springframework.core.ResolvableType;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.buffer.AbstractLeakCheckingTests;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.support.DataBufferTestUtils;
import org.springframework.core.io.support.ResourceRegion;
import org.springframework.core.test.fixtures.io.buffer.AbstractLeakCheckingTests;
import org.springframework.core.test.fixtures.io.buffer.DataBufferTestUtils;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;

View File

@@ -30,6 +30,7 @@ import reactor.test.StepVerifier;
import org.springframework.core.ResolvableType;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferLimitException;
import org.springframework.core.test.fixtures.codec.AbstractDecoderTests;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;

View File

@@ -51,13 +51,13 @@ import org.springframework.core.convert.ConversionFailedException;
import org.springframework.core.convert.ConverterNotFoundException;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.tests.EnabledForTestGroups;
import org.springframework.core.test.fixtures.EnabledForTestGroups;
import org.springframework.util.ClassUtils;
import org.springframework.util.StopWatch;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.tests.TestGroup.PERFORMANCE;
import static org.springframework.core.test.fixtures.TestGroup.PERFORMANCE;
/**
* Unit tests for {@link DefaultConversionService}.

View File

@@ -43,8 +43,8 @@ import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.core.convert.converter.GenericConverter;
import org.springframework.core.io.DescriptiveResource;
import org.springframework.core.io.Resource;
import org.springframework.core.test.fixtures.EnabledForTestGroups;
import org.springframework.lang.Nullable;
import org.springframework.tests.EnabledForTestGroups;
import org.springframework.util.StopWatch;
import org.springframework.util.StringUtils;
@@ -54,7 +54,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.springframework.tests.TestGroup.PERFORMANCE;
import static org.springframework.core.test.fixtures.TestGroup.PERFORMANCE;
/**
* Unit tests for {@link GenericConversionService}.

View File

@@ -1,87 +0,0 @@
/*
* Copyright 2002-2018 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.env;
public class DummyEnvironment implements Environment {
@Override
public boolean containsProperty(String key) {
return false;
}
@Override
public String getProperty(String key) {
return null;
}
@Override
public String getProperty(String key, String defaultValue) {
return null;
}
@Override
public <T> T getProperty(String key, Class<T> targetType) {
return null;
}
@Override
public <T> T getProperty(String key, Class<T> targetType, T defaultValue) {
return null;
}
@Override
public String getRequiredProperty(String key) throws IllegalStateException {
return null;
}
@Override
public <T> T getRequiredProperty(String key, Class<T> targetType) throws IllegalStateException {
return null;
}
@Override
public String resolvePlaceholders(String text) {
return null;
}
@Override
public String resolveRequiredPlaceholders(String text) throws IllegalArgumentException {
return null;
}
@Override
public String[] getActiveProfiles() {
return null;
}
@Override
public String[] getDefaultProfiles() {
return null;
}
@Deprecated
@Override
public boolean acceptsProfiles(String... profiles) {
return false;
}
@Override
public boolean acceptsProfiles(Profiles profiles) {
return false;
}
}

View File

@@ -20,7 +20,7 @@ import java.util.Iterator;
import org.junit.jupiter.api.Test;
import org.springframework.mock.env.MockPropertySource;
import org.springframework.core.test.fixtures.env.MockPropertySource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

View File

@@ -24,7 +24,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.core.convert.ConverterNotFoundException;
import org.springframework.mock.env.MockPropertySource;
import org.springframework.core.test.fixtures.env.MockPropertySource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

View File

@@ -16,17 +16,16 @@
package org.springframework.core.env;
import java.lang.reflect.Field;
import java.security.AccessControlException;
import java.security.Permission;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.core.SpringProperties;
import org.springframework.mock.env.MockPropertySource;
import org.springframework.core.test.fixtures.env.EnvironmentTestUtils;
import org.springframework.core.test.fixtures.env.MockPropertySource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
@@ -465,8 +464,8 @@ public class StandardEnvironmentTests {
@Test
void getSystemEnvironment_withAndWithoutSecurityManager() {
getModifiableSystemEnvironment().put(ALLOWED_PROPERTY_NAME, ALLOWED_PROPERTY_VALUE);
getModifiableSystemEnvironment().put(DISALLOWED_PROPERTY_NAME, DISALLOWED_PROPERTY_VALUE);
EnvironmentTestUtils.getModifiableSystemEnvironment().put(ALLOWED_PROPERTY_NAME, ALLOWED_PROPERTY_VALUE);
EnvironmentTestUtils.getModifiableSystemEnvironment().put(DISALLOWED_PROPERTY_NAME, DISALLOWED_PROPERTY_VALUE);
{
Map<String, Object> systemEnvironment = environment.getSystemEnvironment();
@@ -500,68 +499,8 @@ public class StandardEnvironmentTests {
}
System.setSecurityManager(oldSecurityManager);
getModifiableSystemEnvironment().remove(ALLOWED_PROPERTY_NAME);
getModifiableSystemEnvironment().remove(DISALLOWED_PROPERTY_NAME);
}
@SuppressWarnings("unchecked")
public static Map<String, String> getModifiableSystemEnvironment() {
// for os x / linux
Class<?>[] classes = Collections.class.getDeclaredClasses();
Map<String, String> env = System.getenv();
for (Class<?> cl : classes) {
if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
try {
Field field = cl.getDeclaredField("m");
field.setAccessible(true);
Object obj = field.get(env);
if (obj != null && obj.getClass().getName().equals("java.lang.ProcessEnvironment$StringEnvironment")) {
return (Map<String, String>) obj;
}
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
// for windows
Class<?> processEnvironmentClass;
try {
processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
try {
Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
theCaseInsensitiveEnvironmentField.setAccessible(true);
Object obj = theCaseInsensitiveEnvironmentField.get(null);
return (Map<String, String>) obj;
}
catch (NoSuchFieldException ex) {
// do nothing
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
try {
Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
theEnvironmentField.setAccessible(true);
Object obj = theEnvironmentField.get(null);
return (Map<String, String>) obj;
}
catch (NoSuchFieldException ex) {
// do nothing
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
throw new IllegalStateException();
EnvironmentTestUtils.getModifiableSystemEnvironment().remove(ALLOWED_PROPERTY_NAME);
EnvironmentTestUtils.getModifiableSystemEnvironment().remove(DISALLOWED_PROPERTY_NAME);
}
}

View File

@@ -1,169 +0,0 @@
/*
* Copyright 2002-2019 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.io.buffer;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Stream;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.PoolArenaMetric;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.PooledByteBufAllocatorMetric;
import io.netty.buffer.UnpooledByteBufAllocator;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import reactor.core.publisher.Mono;
import org.springframework.core.io.buffer.support.DataBufferTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.params.provider.Arguments.arguments;
/**
* Base class for tests that read or write data buffers with an extension to check
* that allocated buffers have been released.
*
* @author Arjen Poutsma
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
public abstract class AbstractDataBufferAllocatingTests {
@RegisterExtension
AfterEachCallback leakDetector = context -> waitForDataBufferRelease(Duration.ofSeconds(2));
protected DataBufferFactory bufferFactory;
protected DataBuffer createDataBuffer(int capacity) {
return this.bufferFactory.allocateBuffer(capacity);
}
protected DataBuffer stringBuffer(String value) {
return byteBuffer(value.getBytes(StandardCharsets.UTF_8));
}
protected Mono<DataBuffer> deferStringBuffer(String value) {
return Mono.defer(() -> Mono.just(stringBuffer(value)));
}
protected DataBuffer byteBuffer(byte[] value) {
DataBuffer buffer = this.bufferFactory.allocateBuffer(value.length);
buffer.write(value);
return buffer;
}
protected void release(DataBuffer... buffers) {
Arrays.stream(buffers).forEach(DataBufferUtils::release);
}
protected Consumer<DataBuffer> stringConsumer(String expected) {
return dataBuffer -> {
String value = DataBufferTestUtils.dumpString(dataBuffer, StandardCharsets.UTF_8);
DataBufferUtils.release(dataBuffer);
assertThat(value).isEqualTo(expected);
};
}
/**
* Wait until allocations are at 0, or the given duration elapses.
*/
private void waitForDataBufferRelease(Duration duration) throws InterruptedException {
Instant start = Instant.now();
while (true) {
try {
verifyAllocations();
break;
}
catch (AssertionError ex) {
if (Instant.now().isAfter(start.plus(duration))) {
throw ex;
}
}
Thread.sleep(50);
}
}
private void verifyAllocations() {
if (this.bufferFactory instanceof NettyDataBufferFactory) {
ByteBufAllocator allocator = ((NettyDataBufferFactory) this.bufferFactory).getByteBufAllocator();
if (allocator instanceof PooledByteBufAllocator) {
Instant start = Instant.now();
while (true) {
PooledByteBufAllocatorMetric metric = ((PooledByteBufAllocator) allocator).metric();
long total = getAllocations(metric.directArenas()) + getAllocations(metric.heapArenas());
if (total == 0) {
return;
}
if (Instant.now().isBefore(start.plus(Duration.ofSeconds(5)))) {
try {
Thread.sleep(50);
}
catch (InterruptedException ex) {
// ignore
}
continue;
}
assertThat(total).as("ByteBuf Leak: " + total + " unreleased allocations").isEqualTo(0);
}
}
}
}
private static long getAllocations(List<PoolArenaMetric> metrics) {
return metrics.stream().mapToLong(PoolArenaMetric::numActiveAllocations).sum();
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@ParameterizedTest(name = "[{index}] {0}")
@MethodSource("org.springframework.core.io.buffer.AbstractDataBufferAllocatingTests#dataBufferFactories()")
public @interface ParameterizedDataBufferAllocatingTest {
}
public static Stream<Arguments> dataBufferFactories() {
return Stream.of(
arguments("NettyDataBufferFactory - UnpooledByteBufAllocator - preferDirect = true",
new NettyDataBufferFactory(new UnpooledByteBufAllocator(true))),
arguments("NettyDataBufferFactory - UnpooledByteBufAllocator - preferDirect = false",
new NettyDataBufferFactory(new UnpooledByteBufAllocator(false))),
// disable caching for reliable leak detection, see https://github.com/netty/netty/issues/5275
arguments("NettyDataBufferFactory - PooledByteBufAllocator - preferDirect = true",
new NettyDataBufferFactory(new PooledByteBufAllocator(true, 1, 1, 4096, 2, 0, 0, 0, true))),
arguments("NettyDataBufferFactory - PooledByteBufAllocator - preferDirect = false",
new NettyDataBufferFactory(new PooledByteBufAllocator(false, 1, 1, 4096, 2, 0, 0, 0, true))),
arguments("DefaultDataBufferFactory - preferDirect = true",
new DefaultDataBufferFactory(true)),
arguments("DefaultDataBufferFactory - preferDirect = false",
new DefaultDataBufferFactory(false))
);
}
}

View File

@@ -1,47 +0,0 @@
/*
* Copyright 2002-2019 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.io.buffer;
import org.junit.jupiter.api.AfterEach;
/**
* Abstract base class for unit tests that allocate data buffers via a {@link DataBufferFactory}.
* After each unit test, this base class checks whether all created buffers have been released,
* throwing an {@link AssertionError} if not.
*
* @author Arjen Poutsma
* @since 5.1.3
* @see LeakAwareDataBufferFactory
*/
public abstract class AbstractLeakCheckingTests {
/**
* The data buffer factory.
*/
@SuppressWarnings("ProtectedField")
protected final LeakAwareDataBufferFactory bufferFactory = new LeakAwareDataBufferFactory();
/**
* Checks whether any of the data buffers created by {@link #bufferFactory} have not been
* released, throwing an assertion error if so.
*/
@AfterEach
final void checkForLeaks() {
this.bufferFactory.checkForLeaks();
}
}

View File

@@ -22,6 +22,8 @@ import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import org.springframework.core.test.fixtures.io.buffer.AbstractDataBufferAllocatingTests;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;

View File

@@ -45,7 +45,8 @@ import reactor.test.StepVerifier;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.buffer.support.DataBufferTestUtils;
import org.springframework.core.test.fixtures.io.buffer.AbstractDataBufferAllocatingTests;
import org.springframework.core.test.fixtures.io.buffer.DataBufferTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;

View File

@@ -1,92 +0,0 @@
/*
* Copyright 2002-2019 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.io.buffer;
import org.springframework.util.Assert;
/**
* DataBuffer implementation created by {@link LeakAwareDataBufferFactory}.
*
* @author Arjen Poutsma
*/
class LeakAwareDataBuffer extends DataBufferWrapper implements PooledDataBuffer {
private final AssertionError leakError;
private final LeakAwareDataBufferFactory dataBufferFactory;
LeakAwareDataBuffer(DataBuffer delegate, LeakAwareDataBufferFactory dataBufferFactory) {
super(delegate);
Assert.notNull(dataBufferFactory, "DataBufferFactory must not be null");
this.dataBufferFactory = dataBufferFactory;
this.leakError = createLeakError(delegate);
}
private static AssertionError createLeakError(DataBuffer delegate) {
String message = String.format("DataBuffer leak detected: {%s} has not been released.%n" +
"Stack trace of buffer allocation statement follows:",
delegate);
AssertionError result = new AssertionError(message);
// remove first four irrelevant stack trace elements
StackTraceElement[] oldTrace = result.getStackTrace();
StackTraceElement[] newTrace = new StackTraceElement[oldTrace.length - 4];
System.arraycopy(oldTrace, 4, newTrace, 0, oldTrace.length - 4);
result.setStackTrace(newTrace);
return result;
}
AssertionError leakError() {
return this.leakError;
}
@Override
public boolean isAllocated() {
DataBuffer delegate = dataBuffer();
return delegate instanceof PooledDataBuffer &&
((PooledDataBuffer) delegate).isAllocated();
}
@Override
public PooledDataBuffer retain() {
DataBuffer delegate = dataBuffer();
if (delegate instanceof PooledDataBuffer) {
((PooledDataBuffer) delegate).retain();
}
return this;
}
@Override
public boolean release() {
DataBuffer delegate = dataBuffer();
if (delegate instanceof PooledDataBuffer) {
((PooledDataBuffer) delegate).release();
}
return isAllocated();
}
@Override
public LeakAwareDataBufferFactory factory() {
return this.dataBufferFactory;
}
@Override
public String toString() {
return String.format("LeakAwareDataBuffer (%s)", dataBuffer());
}
}

View File

@@ -1,142 +0,0 @@
/*
* Copyright 2002-2019 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.io.buffer;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import io.netty.buffer.PooledByteBufAllocator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
/**
* Implementation of the {@code DataBufferFactory} interface that keeps track of
* memory leaks.
* <p>Useful for unit tests that handle data buffers. Simply inherit from
* {@link AbstractLeakCheckingTests} or call {@link #checkForLeaks()} in
* a JUnit <em>after</em> method yourself, and any buffers that have not been
* released will result in an {@link AssertionError}.
*
* @author Arjen Poutsma
* @see LeakAwareDataBufferFactory
*/
public class LeakAwareDataBufferFactory implements DataBufferFactory {
private static final Log logger = LogFactory.getLog(LeakAwareDataBufferFactory.class);
private final DataBufferFactory delegate;
private final List<LeakAwareDataBuffer> created = new ArrayList<>();
private final AtomicBoolean trackCreated = new AtomicBoolean(true);
/**
* Creates a new {@code LeakAwareDataBufferFactory} by wrapping a
* {@link DefaultDataBufferFactory}.
*/
public LeakAwareDataBufferFactory() {
this(new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT));
}
/**
* Creates a new {@code LeakAwareDataBufferFactory} by wrapping the given delegate.
* @param delegate the delegate buffer factory to wrap.
*/
public LeakAwareDataBufferFactory(DataBufferFactory delegate) {
Assert.notNull(delegate, "Delegate must not be null");
this.delegate = delegate;
}
/**
* Checks whether all of the data buffers allocated by this factory have also been released.
* If not, then an {@link AssertionError} is thrown. Typically used from a JUnit <em>after</em>
* method.
*/
public void checkForLeaks() {
this.trackCreated.set(false);
Instant start = Instant.now();
while (true) {
if (this.created.stream().noneMatch(LeakAwareDataBuffer::isAllocated)) {
return;
}
if (Instant.now().isBefore(start.plus(Duration.ofSeconds(5)))) {
try {
Thread.sleep(50);
}
catch (InterruptedException ex) {
// ignore
}
continue;
}
List<AssertionError> errors = this.created.stream()
.filter(LeakAwareDataBuffer::isAllocated)
.map(LeakAwareDataBuffer::leakError)
.collect(Collectors.toList());
errors.forEach(it -> logger.error("Leaked error: ", it));
throw new AssertionError(errors.size() + " buffer leaks detected (see logs above)");
}
}
@Override
public DataBuffer allocateBuffer() {
return createLeakAwareDataBuffer(this.delegate.allocateBuffer());
}
@Override
public DataBuffer allocateBuffer(int initialCapacity) {
return createLeakAwareDataBuffer(this.delegate.allocateBuffer(initialCapacity));
}
private DataBuffer createLeakAwareDataBuffer(DataBuffer delegateBuffer) {
LeakAwareDataBuffer dataBuffer = new LeakAwareDataBuffer(delegateBuffer, this);
if (this.trackCreated.get()) {
this.created.add(dataBuffer);
}
return dataBuffer;
}
@Override
public DataBuffer wrap(ByteBuffer byteBuffer) {
return this.delegate.wrap(byteBuffer);
}
@Override
public DataBuffer wrap(byte[] bytes) {
return this.delegate.wrap(bytes);
}
@Override
public DataBuffer join(List<? extends DataBuffer> dataBuffers) {
// Remove LeakAwareDataBuffer wrapper so delegate can find native buffers
dataBuffers = dataBuffers.stream()
.map(o -> o instanceof LeakAwareDataBuffer ? ((LeakAwareDataBuffer) o).dataBuffer() : o)
.collect(Collectors.toList());
return new LeakAwareDataBuffer(this.delegate.join(dataBuffers), this);
}
}

View File

@@ -18,6 +18,8 @@ package org.springframework.core.io.buffer;
import org.junit.jupiter.api.Test;
import org.springframework.core.test.fixtures.io.buffer.LeakAwareDataBufferFactory;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.core.io.buffer.DataBufferUtils.release;

View File

@@ -1,62 +0,0 @@
/*
* Copyright 2002-2016 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.io.buffer.support;
import java.nio.charset.Charset;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.util.Assert;
/**
* Utility class for working with {@link DataBuffer}s in tests.
*
* <p>Note that this class is in the {@code test} tree of the project:
* the methods contained herein are not suitable for production code bases.
*
* @author Arjen Poutsma
*/
public abstract class DataBufferTestUtils {
/**
* Dump all the bytes in the given data buffer, and returns them as a byte array.
* <p>Note that this method reads the entire buffer into the heap, which might
* consume a lot of memory.
* @param buffer the data buffer to dump the bytes of
* @return the bytes in the given data buffer
*/
public static byte[] dumpBytes(DataBuffer buffer) {
Assert.notNull(buffer, "'buffer' must not be null");
byte[] bytes = new byte[buffer.readableByteCount()];
buffer.read(bytes);
return bytes;
}
/**
* Dump all the bytes in the given data buffer, and returns them as a string.
* <p>Note that this method reads the entire buffer into the heap, which might
* consume a lot of memory.
* @param buffer the data buffer to dump the string contents of
* @param charset the charset of the data
* @return the string representation of the given data buffer
*/
public static String dumpString(DataBuffer buffer, Charset charset) {
Assert.notNull(charset, "'charset' must not be null");
byte[] bytes = dumpBytes(buffer);
return new String(bytes, charset);
}
}

View File

@@ -18,9 +18,10 @@ package org.springframework.core.io.buffer.support;
import java.nio.charset.StandardCharsets;
import org.springframework.core.io.buffer.AbstractDataBufferAllocatingTests;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.test.fixtures.io.buffer.AbstractDataBufferAllocatingTests;
import org.springframework.core.test.fixtures.io.buffer.DataBufferTestUtils;
import static org.assertj.core.api.Assertions.assertThat;

View File

@@ -14,7 +14,7 @@
* limitations under the License.
*/
package org.springframework.tests;
package org.springframework.core.test.fixtures;
import java.util.Collections;
import java.util.EnumSet;
@@ -26,12 +26,12 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link TestGroup}.
* Tests for {@link TestGroup} parsing.
*
* @author Phillip Webb
* @author Sam Brannen
*/
class TestGroupTests {
class TestGroupParsingTests {
@Test
void parseNull() {

View File

@@ -14,9 +14,10 @@
* limitations under the License.
*/
package org.springframework.tests;
package org.springframework.core.test.fixtures;
import java.util.Arrays;
import java.util.Set;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@@ -28,17 +29,20 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.springframework.tests.Assume.TEST_GROUPS_SYSTEM_PROPERTY;
import static org.springframework.tests.TestGroup.LONG_RUNNING;
import static org.springframework.tests.TestGroup.PERFORMANCE;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.springframework.core.test.fixtures.TestGroup.LONG_RUNNING;
import static org.springframework.core.test.fixtures.TestGroup.PERFORMANCE;
/**
* Tests for {@link Assume}.
* Tests for {@link TestGroup}.
*
* @author Sam Brannen
* @since 5.0
*/
class AssumeTests {
class TestGroupTests {
private static final String TEST_GROUPS_SYSTEM_PROPERTY = "testGroups";
private String originalTestGroups;
@@ -59,25 +63,22 @@ class AssumeTests {
}
@Test
@SuppressWarnings("deprecation")
void assumeGroupWithNoActiveTestGroups() {
setTestGroups("");
assertThatExceptionOfType(TestAbortedException.class).isThrownBy(() -> Assume.group(LONG_RUNNING));
assertThatExceptionOfType(TestAbortedException.class).isThrownBy(() -> assumeGroup(LONG_RUNNING));
}
@Test
@SuppressWarnings("deprecation")
void assumeGroupWithNoMatchingActiveTestGroup() {
setTestGroups(PERFORMANCE);
assertThatExceptionOfType(TestAbortedException.class).isThrownBy(() -> Assume.group(LONG_RUNNING));
assertThatExceptionOfType(TestAbortedException.class).isThrownBy(() -> assumeGroup(LONG_RUNNING));
}
@Test
@SuppressWarnings("deprecation")
void assumeGroupWithMatchingActiveTestGroup() {
setTestGroups(LONG_RUNNING);
assertThatCode(() -> Assume.group(LONG_RUNNING))
assertThatCode(() -> assumeGroup(LONG_RUNNING))
.as("assumption should NOT have failed")
.doesNotThrowAnyException();
}
@@ -92,7 +93,6 @@ class AssumeTests {
assertBogusActiveTestGroupBehavior("all-bogus");
}
@SuppressWarnings("deprecation")
private void assertBogusActiveTestGroupBehavior(String testGroups) {
// Should result in something similar to the following:
//
@@ -102,7 +102,7 @@ class AssumeTests {
setTestGroups(testGroups);
assertThatIllegalStateException()
.isThrownBy(() -> Assume.group(LONG_RUNNING))
.isThrownBy(() -> assumeGroup(LONG_RUNNING))
.withMessageStartingWith("Failed to parse '" + TEST_GROUPS_SYSTEM_PROPERTY + "' system property: ")
.withCauseInstanceOf(IllegalArgumentException.class)
.satisfies(ex ->
@@ -119,4 +119,15 @@ class AssumeTests {
System.setProperty(TEST_GROUPS_SYSTEM_PROPERTY, testGroups);
}
/**
* Assume that a particular {@link TestGroup} is active.
* @param group the group that must be active
* @throws org.opentest4j.TestAbortedException if the assumption fails
*/
private static void assumeGroup(TestGroup group) {
Set<TestGroup> testGroups = TestGroup.loadTestGroups();
assumeTrue(testGroups.contains(group),
() -> "Requires inactive test group " + group + "; active test groups: " + testGroups);
}
}

View File

@@ -33,10 +33,10 @@ import org.junit.jupiter.api.Test;
import org.springframework.core.annotation.AliasFor;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.test.fixtures.stereotype.Component;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
import org.springframework.stereotype.Component;
import static org.assertj.core.api.Assertions.assertThat;

View File

@@ -21,11 +21,11 @@ import example.type.InheritedAnnotation;
import example.type.NonInheritedAnnotation;
import org.junit.jupiter.api.Test;
import org.springframework.core.test.fixtures.stereotype.Component;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Component;
import static org.assertj.core.api.Assertions.assertThat;

View File

@@ -88,7 +88,7 @@ class AspectJTypeFilterTests {
@Test
void annotationPatternMatches() throws Exception {
assertMatch("example.type.AspectJTypeFilterTestsTypes$SomeClassAnnotatedWithComponent",
"@org.springframework.stereotype.Component *..*");
"@org.springframework.core.test.fixtures.stereotype.Component *..*");
assertMatch("example.type.AspectJTypeFilterTestsTypes$SomeClassAnnotatedWithComponent",
"@* *..*");
assertMatch("example.type.AspectJTypeFilterTestsTypes$SomeClassAnnotatedWithComponent",
@@ -96,9 +96,9 @@ class AspectJTypeFilterTests {
assertMatch("example.type.AspectJTypeFilterTestsTypes$SomeClassAnnotatedWithComponent",
"@*..*Component *..*");
assertMatch("example.type.AspectJTypeFilterTestsTypes$SomeClassAnnotatedWithComponent",
"@org.springframework.stereotype.Component *..*Component");
"@org.springframework.core.test.fixtures.stereotype.Component *..*Component");
assertMatch("example.type.AspectJTypeFilterTestsTypes$SomeClassAnnotatedWithComponent",
"@org.springframework.stereotype.Component *");
"@org.springframework.core.test.fixtures.stereotype.Component *");
}
@Test

View File

@@ -22,13 +22,13 @@ import org.junit.jupiter.api.Test;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.core.test.fixtures.EnabledForTestGroups;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.tests.EnabledForTestGroups;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.tests.TestGroup.LONG_RUNNING;
import static org.springframework.core.test.fixtures.TestGroup.LONG_RUNNING;
/**
* Unit tests for checking the behaviour of {@link CachingMetadataReaderFactory} under

View File

@@ -16,21 +16,18 @@
package org.springframework.core.type;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE, ElementType.METHOD})
/**
* Copy of the {@code @Scope} annotation for testing purposes.
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Scope {
/**
* Specifies the scope to use for instances of the annotated class.
* @return the desired scope
*/
String value() default "singleton";
}

View File

@@ -1,106 +0,0 @@
/*
* Copyright 2002-2017 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.mock.env;
import java.util.Properties;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
/**
* Simple {@link PropertySource} implementation for use in testing. Accepts
* a user-provided {@link Properties} object, or if omitted during construction,
* the implementation will initialize its own.
*
* The {@link #setProperty} and {@link #withProperty} methods are exposed for
* convenience, for example:
* <pre>
* {@code
* PropertySource<?> source = new MockPropertySource().withProperty("foo", "bar");
* }
* </pre>
*
* @author Chris Beams
* @since 3.1
* @see org.springframework.mock.env.MockEnvironment
*/
public class MockPropertySource extends PropertiesPropertySource {
/**
* {@value} is the default name for {@link MockPropertySource} instances not
* otherwise given an explicit name.
* @see #MockPropertySource()
* @see #MockPropertySource(String)
*/
public static final String MOCK_PROPERTIES_PROPERTY_SOURCE_NAME = "mockProperties";
/**
* Create a new {@code MockPropertySource} named {@value #MOCK_PROPERTIES_PROPERTY_SOURCE_NAME}
* that will maintain its own internal {@link Properties} instance.
*/
public MockPropertySource() {
this(new Properties());
}
/**
* Create a new {@code MockPropertySource} with the given name that will
* maintain its own internal {@link Properties} instance.
* @param name the {@linkplain #getName() name} of the property source
*/
public MockPropertySource(String name) {
this(name, new Properties());
}
/**
* Create a new {@code MockPropertySource} named {@value #MOCK_PROPERTIES_PROPERTY_SOURCE_NAME}
* and backed by the given {@link Properties} object.
* @param properties the properties to use
*/
public MockPropertySource(Properties properties) {
this(MOCK_PROPERTIES_PROPERTY_SOURCE_NAME, properties);
}
/**
* Create a new {@code MockPropertySource} with the given name and backed by the given
* {@link Properties} object
* @param name the {@linkplain #getName() name} of the property source
* @param properties the properties to use
*/
public MockPropertySource(String name, Properties properties) {
super(name, properties);
}
/**
* Set the given property on the underlying {@link Properties} object.
*/
public void setProperty(String name, Object value) {
this.source.put(name, value);
}
/**
* Convenient synonym for {@link #setProperty} that returns the current instance.
* Useful for method chaining and fluent-style use.
* @return this {@link MockPropertySource} instance
*/
public MockPropertySource withProperty(String name, Object value) {
this.setProperty(name, value);
return this;
}
}

View File

@@ -1,46 +0,0 @@
/*
* Copyright 2002-2017 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.stereotype;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Indicates that an annotated class is a "component".
* Such classes are considered as candidates for auto-detection
* when using annotation-based configuration and classpath scanning.
*
* @author Mark Fisher
* @since 2.5
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {
/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any (or empty String otherwise)
*/
String value() default "";
}

View File

@@ -1,34 +0,0 @@
/*
* Copyright 2002-2016 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.stereotype;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Copy of the standard {@code Indexed} annotation for testing purposes.
*
* @author Stephane Nicoll
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Indexed {
}

View File

@@ -1,77 +0,0 @@
/*
* Copyright 2002-2019 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.tests;
import java.util.Set;
import org.apache.commons.logging.Log;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* Provides utility methods that allow JUnit tests to assume certain conditions
* hold {@code true}. If the assumption fails, it means the test should be
* aborted.
*
* <p>Tests can be categorized into {@link TestGroup}s. Active groups are enabled using
* the 'testGroups' system property, usually activated from the gradle command line:
*
* <pre class="code">
* gradle test -PtestGroups="performance"
* </pre>
*
* <p>Groups can be activated as a comma separated list of values, or using the
* pseudo group 'all'. See {@link TestGroup} for a list of valid groups.
*
* @author Rob Winch
* @author Phillip Webb
* @author Sam Brannen
* @since 3.2
* @see EnabledForTestGroups @EnabledForTestGroups
* @see #notLogging(Log)
* @see TestGroup
*/
public abstract class Assume {
static final String TEST_GROUPS_SYSTEM_PROPERTY = "testGroups";
/**
* Assume that a particular {@link TestGroup} is active.
* @param group the group that must be active
* @throws org.opentest4j.TestAbortedException if the assumption fails
* @deprecated as of Spring Framework 5.2 in favor of {@link EnabledForTestGroups}
*/
@Deprecated
public static void group(TestGroup group) {
Set<TestGroup> testGroups = TestGroup.loadTestGroups();
assumeTrue(testGroups.contains(group),
() -> "Requires inactive test group " + group + "; active test groups: " + testGroups);
}
/**
* Assume that the specified log is not set to Trace or Debug.
* @param log the log to test
* @throws org.opentest4j.TestAbortedException if the assumption fails
*/
public static void notLogging(Log log) {
assumeFalse(log.isTraceEnabled());
assumeFalse(log.isDebugEnabled());
}
}

View File

@@ -1,47 +0,0 @@
/*
* Copyright 2002-2019 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.tests;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.api.extension.ExtendWith;
/**
* {@code @EnabledForTestGroups} is used to enable the annotated test class or
* test method for one or more {@link TestGroup} {@linkplain #value values}.
*
* @author Sam Brannen
* @since 5.2
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@ExtendWith(TestGroupsCondition.class)
public @interface EnabledForTestGroups {
/**
* One or more {@link TestGroup}s that must be active.
*/
TestGroup[] value();
}

View File

@@ -1,121 +0,0 @@
/*
* Copyright 2002-2019 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.tests;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import org.springframework.util.StringUtils;
import static java.lang.String.format;
/**
* A test group used to limit when certain tests are run.
*
* @see EnabledForTestGroups @EnabledForTestGroups
* @see Assume#group(TestGroup)
* @author Phillip Webb
* @author Chris Beams
* @author Sam Brannen
*/
public enum TestGroup {
/**
* Tests that take a considerable amount of time to run. Any test lasting longer than
* 500ms should be considered a candidate in order to avoid making the overall test
* suite too slow to run during the normal development cycle.
*/
LONG_RUNNING,
/**
* Performance-related tests that may fail unpredictably based on CPU profile and load.
* Any test using {@link Thread#sleep}, {@link Object#wait}, Spring's
* {@code StopWatch}, etc. should be considered a candidate as their successful
* execution is likely to be based on events occurring within a given time window.
*/
PERFORMANCE;
/**
* Determine if this {@link TestGroup} is active.
* @since 5.2
*/
public boolean isActive() {
return loadTestGroups().contains(this);
}
private static final String TEST_GROUPS_SYSTEM_PROPERTY = "testGroups";
/**
* Load test groups dynamically instead of during static initialization in
* order to avoid a {@link NoClassDefFoundError} being thrown while attempting
* to load collaborator classes.
*/
static Set<TestGroup> loadTestGroups() {
try {
return TestGroup.parse(System.getProperty(TEST_GROUPS_SYSTEM_PROPERTY));
}
catch (Exception ex) {
throw new IllegalStateException("Failed to parse '" + TEST_GROUPS_SYSTEM_PROPERTY +
"' system property: " + ex.getMessage(), ex);
}
}
/**
* Parse the specified comma separated string of groups.
* @param value the comma separated string of groups
* @return a set of groups
* @throws IllegalArgumentException if any specified group name is not a
* valid {@link TestGroup}
*/
static Set<TestGroup> parse(String value) throws IllegalArgumentException {
if (!StringUtils.hasText(value)) {
return Collections.emptySet();
}
String originalValue = value;
value = value.trim();
if ("ALL".equalsIgnoreCase(value)) {
return EnumSet.allOf(TestGroup.class);
}
if (value.toUpperCase().startsWith("ALL-")) {
Set<TestGroup> groups = EnumSet.allOf(TestGroup.class);
groups.removeAll(parseGroups(originalValue, value.substring(4)));
return groups;
}
return parseGroups(originalValue, value);
}
private static Set<TestGroup> parseGroups(String originalValue, String value) throws IllegalArgumentException {
Set<TestGroup> groups = new HashSet<>();
for (String group : value.split(",")) {
try {
groups.add(valueOf(group.trim().toUpperCase()));
}
catch (IllegalArgumentException ex) {
throw new IllegalArgumentException(format(
"Unable to find test group '%s' when parsing testGroups value: '%s'. " +
"Available groups include: [%s]", group.trim(), originalValue,
StringUtils.arrayToCommaDelimitedString(TestGroup.values())));
}
}
return groups;
}
}

View File

@@ -1,57 +0,0 @@
/*
* Copyright 2002-2019 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.tests;
import java.util.Arrays;
import java.util.Optional;
import org.junit.jupiter.api.extension.ConditionEvaluationResult;
import org.junit.jupiter.api.extension.ExecutionCondition;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.springframework.util.Assert;
import static org.junit.jupiter.api.extension.ConditionEvaluationResult.disabled;
import static org.junit.jupiter.api.extension.ConditionEvaluationResult.enabled;
import static org.junit.platform.commons.support.AnnotationSupport.findAnnotation;
/**
* {@link ExecutionCondition} for Spring's {@link TestGroup} support.
*
* @author Sam Brannen
* @since 5.2
* @see EnabledForTestGroups @EnabledForTestGroups
*/
class TestGroupsCondition implements ExecutionCondition {
private static final ConditionEvaluationResult ENABLED_BY_DEFAULT = enabled("@EnabledForTestGroups is not present");
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
Optional<EnabledForTestGroups> optional = findAnnotation(context.getElement(), EnabledForTestGroups.class);
if (!optional.isPresent()) {
return ENABLED_BY_DEFAULT;
}
TestGroup[] testGroups = optional.get().value();
Assert.state(testGroups.length > 0, "You must declare at least one TestGroup in @EnabledForTestGroups");
return (Arrays.stream(testGroups).anyMatch(TestGroup::isActive)) ?
enabled("Enabled for TestGroups: " + Arrays.toString(testGroups)) :
disabled("Disabled for TestGroups: " + Arrays.toString(testGroups));
}
}

View File

@@ -1,39 +0,0 @@
/*
* Copyright 2002-2016 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.tests;
import org.springframework.core.io.ClassPathResource;
/**
* Convenience utilities for common operations with test resources.
*
* @author Chris Beams
*/
public abstract class TestResourceUtils {
/**
* Load a {@link ClassPathResource} qualified by the simple name of clazz,
* and relative to the package for clazz.
* <p>Example: given a clazz 'com.foo.BarTests' and a resourceSuffix of 'context.xml',
* this method will return a ClassPathResource representing com/foo/BarTests-context.xml
* <p>Intended for use loading context configuration XML files within JUnit tests.
*/
public static ClassPathResource qualifiedResource(Class<?> clazz, String resourceSuffix) {
return new ClassPathResource(String.format("%s-%s", clazz.getSimpleName(), resourceSuffix), clazz);
}
}

View File

@@ -1,34 +0,0 @@
/*
* Copyright 2002-2013 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.tests;
/**
* This interface can be implemented by cacheable objects or cache entries,
* to enable the freshness of objects to be checked.
*
* @author Rod Johnson
*/
public interface TimeStamped {
/**
* Return the timestamp for this object.
* @return long the timestamp for this object,
* as returned by System.currentTimeMillis()
*/
long getTimeStamp();
}

View File

@@ -1,54 +0,0 @@
/*
* Copyright 2002-2019 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.tests;
import java.io.StringWriter;
import org.assertj.core.api.AssertProvider;
import org.xmlunit.assertj.XmlAssert;
/**
* {@link AssertProvider} to allow XML content assertions. Ultimately delegates
* to {@link XmlAssert}.
*
* @author Phillip Webb
*/
public class XmlContent implements AssertProvider<XmlContentAssert> {
private Object source;
private XmlContent(Object source) {
this.source = source;
}
@Override
public XmlContentAssert assertThat() {
return new XmlContentAssert(this.source);
}
public static XmlContent from(Object source) {
return of(source);
}
public static XmlContent of(Object source) {
if (source instanceof StringWriter) {
return of(source.toString());
}
return new XmlContent(source);
}
}

View File

@@ -1,65 +0,0 @@
/*
* Copyright 2002-2019 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.tests;
import org.assertj.core.api.AbstractAssert;
import org.w3c.dom.Node;
import org.xmlunit.assertj.XmlAssert;
import org.xmlunit.diff.DifferenceEvaluator;
import org.xmlunit.diff.NodeMatcher;
import org.xmlunit.util.Predicate;
/**
* Assertions exposed by {@link XmlContent}.
*
* @author Phillip Webb
*/
public class XmlContentAssert extends AbstractAssert<XmlContentAssert, Object> {
XmlContentAssert(Object actual) {
super(actual, XmlContentAssert.class);
}
public XmlContentAssert isSimilarTo(Object control) {
XmlAssert.assertThat(actual).and(control).areSimilar();
return this;
}
public XmlContentAssert isSimilarTo(Object control, Predicate<Node> nodeFilter) {
XmlAssert.assertThat(actual).and(control).withNodeFilter(nodeFilter).areSimilar();
return this;
}
public XmlContentAssert isSimilarTo(String control,
DifferenceEvaluator differenceEvaluator) {
XmlAssert.assertThat(actual).and(control).withDifferenceEvaluator(
differenceEvaluator).areSimilar();
return this;
}
public XmlContentAssert isSimilarToIgnoringWhitespace(Object control) {
XmlAssert.assertThat(actual).and(control).ignoreWhitespace().areSimilar();
return this;
}
public XmlContentAssert isSimilarToIgnoringWhitespace(String control, NodeMatcher nodeMatcher) {
XmlAssert.assertThat(actual).and(control).ignoreWhitespace().withNodeMatcher(nodeMatcher).areSimilar();
return this;
}
}

View File

@@ -20,6 +20,7 @@ import java.util.LinkedList;
import org.junit.jupiter.api.Test;
import org.springframework.core.test.fixtures.io.SerializationTestUtils;
import org.springframework.tests.sample.objects.TestObject;
import static org.assertj.core.api.Assertions.assertThat;

View File

@@ -27,12 +27,12 @@ import java.util.List;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.tests.EnabledForTestGroups;
import org.springframework.core.test.fixtures.EnabledForTestGroups;
import org.springframework.tests.sample.objects.TestObject;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.springframework.tests.TestGroup.PERFORMANCE;
import static org.springframework.core.test.fixtures.TestGroup.PERFORMANCE;
/**
* @author Rob Harrop

View File

@@ -1,67 +0,0 @@
/*
* Copyright 2002-2019 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
/**
* Utilities for testing serializability of objects.
* Exposes static methods for use in other test cases.
*
* @author Rod Johnson
*/
public class SerializationTestUtils {
public static void testSerialization(Object o) throws IOException {
OutputStream baos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(o);
}
}
public static boolean isSerializable(Object o) throws IOException {
try {
testSerialization(o);
return true;
}
catch (NotSerializableException ex) {
return false;
}
}
public static Object serializeAndDeserialize(Object o) throws IOException, ClassNotFoundException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(o);
oos.flush();
}
baos.flush();
byte[] bytes = baos.toByteArray();
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
try (ObjectInputStream ois = new ObjectInputStream(is)) {
return ois.readObject();
}
}
}

View File

@@ -25,14 +25,14 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Test for static utility to help with serialization.
* Unit tests for {@link SerializationUtils}.
*
* @author Dave Syer
* @since 3.0.5
*/
class SerializationUtilsTests {
private static BigInteger FOO = new BigInteger(
private static final BigInteger FOO = new BigInteger(
"-9702942423549012526722364838327831379660941553432801565505143675386108883970811292563757558516603356009681061" +
"5697574744209306031461371833798723505120163874786203211176873686513374052845353833564048");
@@ -44,21 +44,17 @@ class SerializationUtilsTests {
@Test
void deserializeUndefined() throws Exception {
byte[] bytes = FOO.toByteArray();
assertThatIllegalStateException().isThrownBy(() ->
SerializationUtils.deserialize(bytes));
assertThatIllegalStateException().isThrownBy(() -> SerializationUtils.deserialize(FOO.toByteArray()));
}
@Test
void serializeNonSerializable() throws Exception {
assertThatIllegalArgumentException().isThrownBy(() ->
SerializationUtils.serialize(new Object()));
assertThatIllegalArgumentException().isThrownBy(() -> SerializationUtils.serialize(new Object()));
}
@Test
void deserializeNonSerializable() throws Exception {
assertThatIllegalArgumentException().isThrownBy(() ->
SerializationUtils.deserialize("foo".getBytes()));
assertThatIllegalArgumentException().isThrownBy(() -> SerializationUtils.deserialize("foo".getBytes()));
}
@Test

View File

@@ -34,7 +34,7 @@ import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xmlunit.util.Predicate;
import org.springframework.tests.XmlContent;
import org.springframework.core.test.fixtures.xml.XmlContent;
import static org.assertj.core.api.Assertions.assertThat;

View File

@@ -28,7 +28,7 @@ import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.springframework.tests.XmlContent;
import org.springframework.core.test.fixtures.xml.XmlContent;
import static org.assertj.core.api.Assertions.assertThat;

View File

@@ -30,7 +30,7 @@ import javax.xml.stream.events.XMLEvent;
import org.junit.jupiter.api.Test;
import org.springframework.tests.XmlContent;
import org.springframework.core.test.fixtures.xml.XmlContent;
import static javax.xml.stream.XMLStreamConstants.END_DOCUMENT;
import static javax.xml.stream.XMLStreamConstants.END_ELEMENT;

View File

@@ -31,7 +31,7 @@ import javax.xml.transform.stream.StreamSource;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.tests.XmlContent;
import org.springframework.core.test.fixtures.xml.XmlContent;
import static org.assertj.core.api.Assertions.assertThat;

View File

@@ -34,7 +34,7 @@ import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.springframework.tests.XmlContent;
import org.springframework.core.test.fixtures.xml.XmlContent;
import static org.assertj.core.api.Assertions.assertThat;

View File

@@ -31,7 +31,7 @@ import org.junit.jupiter.api.Test;
import org.w3c.dom.Node;
import org.xmlunit.util.Predicate;
import org.springframework.tests.XmlContent;
import org.springframework.core.test.fixtures.xml.XmlContent;
import static org.assertj.core.api.Assertions.assertThat;

View File

@@ -27,7 +27,7 @@ import org.junit.jupiter.api.Test;
import org.w3c.dom.Node;
import org.xmlunit.util.Predicate;
import org.springframework.tests.XmlContent;
import org.springframework.core.test.fixtures.xml.XmlContent;
import static org.assertj.core.api.Assertions.assertThat;