Split up JUnit 5 OutputCapture class

Split the JUnit 5 `OutputCapture` class into separate `OutputExtension`
and `CapturedOutput` classes. The JUnit 5 callback methods are now
contained only in the `OutputExtension` class so no longer pollute the
public API that users will interact with.

The `CapturedOutput` class has also been updated to capture System.err
and System.out separately to allow distinct assertions if required.

Closes gh-17029
This commit is contained in:
Phillip Webb
2019-05-30 21:51:07 -07:00
parent 68a3fbd7a0
commit d11d5ceb29
49 changed files with 761 additions and 313 deletions

View File

@@ -0,0 +1,314 @@
/*
* Copyright 2012-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.boot.test.extension;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
import org.junit.jupiter.api.extension.Extension;
import org.springframework.boot.ansi.AnsiOutput;
import org.springframework.boot.ansi.AnsiOutput.Enabled;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
/**
* Provides access to {@link System#out System.out} and {@link System#err System.err}
* output that has been capture by the {@link OutputExtension}. Can be used to apply
* assertions either using AssertJ or standard JUnit assertions. For example:
* <pre class="code">
* assertThat(output).contains("started"); // Checks all output
* assertThat(output.getErr()).contains("failed"); // Only checks System.err
* assertThat(output.getOut()).contains("ok"); // Only checks System.put
* </pre>
*
* @author Madhura Bhave
* @author Phillip Webb
* @since 2.2.0
* @see OutputExtension
*/
public class CapturedOutput implements CharSequence, Extension {
private final Deque<SystemCapture> systemCaptures = new ArrayDeque<>();
private AnsiOutputState ansiOutputState;
protected CapturedOutput() {
}
/**
* Push a new system capture session onto the stack.
*/
protected final void push() {
if (this.systemCaptures.isEmpty()) {
this.ansiOutputState = AnsiOutputState.saveAndDisable();
}
this.systemCaptures.addLast(new SystemCapture());
}
/**
* Pop the last system capture session from the stack.
*/
protected final void pop() {
this.systemCaptures.removeLast().release();
if (this.systemCaptures.isEmpty() && this.ansiOutputState != null) {
this.ansiOutputState.restore();
this.ansiOutputState = null;
}
}
@Override
public int length() {
return toString().length();
}
@Override
public char charAt(int index) {
return toString().charAt(index);
}
@Override
public CharSequence subSequence(int start, int end) {
return toString().subSequence(start, end);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof CapturedOutput || obj instanceof CharSequence) {
return getAll().equals(obj.toString());
}
return false;
}
@Override
public int hashCode() {
return toString().hashCode();
}
@Override
public String toString() {
return getAll();
}
/**
* Return all content (both {@link System#out System.out} and {@link System#err
* System.err}) in the order that it was was captured.
* @return all captured output
*/
public String getAll() {
return get((type) -> true);
}
/**
* Return {@link System#out System.out} content in the order that it was was captured.
* @return {@link System#out System.out} captured output
*/
public String getOut() {
return get(Type.OUT::equals);
}
/**
* Return {@link System#err System.err} content in the order that it was was captured.
* @return {@link System#err System.err} captured output
*/
public String getErr() {
return get(Type.ERR::equals);
}
private String get(Predicate<Type> filter) {
Assert.state(!this.systemCaptures.isEmpty(),
"No system captures found. Check that you have used @RegisterExtension "
+ "or @ExtendWith and the fields are not private");
StringBuilder builder = new StringBuilder();
for (SystemCapture systemCapture : this.systemCaptures) {
systemCapture.append(builder, filter);
}
return builder.toString();
}
/**
* A capture session that captures {@link System#out System.out} and {@link System#out
* System.err}.
*/
private static class SystemCapture {
private final PrintStreamCapture out;
private final PrintStreamCapture err;
private final List<CapturedString> capturedStrings = Collections
.synchronizedList(new ArrayList<>());
SystemCapture() {
this.out = new PrintStreamCapture(System.out, this::captureOut);
this.err = new PrintStreamCapture(System.err, this::captureErr);
System.setOut(this.out);
System.setErr(this.err);
}
public void release() {
System.setOut(this.out.getParent());
System.setErr(this.err.getParent());
}
private void captureOut(String string) {
this.capturedStrings.add(new CapturedString(Type.OUT, string));
}
private void captureErr(String string) {
this.capturedStrings.add(new CapturedString(Type.ERR, string));
}
public void append(StringBuilder builder, Predicate<Type> filter) {
for (CapturedString stringCapture : this.capturedStrings) {
if (filter.test(stringCapture.getType())) {
builder.append(stringCapture);
}
}
}
}
/**
* A {@link PrintStream} implementation that captures written strings.
*/
private static class PrintStreamCapture extends PrintStream {
private final PrintStream parent;
PrintStreamCapture(PrintStream parent, Consumer<String> copy) {
super(new OutputStreamCapture(getSystemStream(parent), copy));
this.parent = parent;
}
public PrintStream getParent() {
return this.parent;
}
private static PrintStream getSystemStream(PrintStream printStream) {
while (printStream instanceof PrintStreamCapture) {
return ((PrintStreamCapture) printStream).getParent();
}
return printStream;
}
}
/**
* An {@link OutputStream} implementation that captures written strings.
*/
private static class OutputStreamCapture extends OutputStream {
private final PrintStream systemStream;
private final Consumer<String> copy;
OutputStreamCapture(PrintStream systemStream, Consumer<String> copy) {
this.systemStream = systemStream;
this.copy = copy;
}
@Override
public void write(int b) throws IOException {
write(new byte[] { (byte) (b & 0xFF) });
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
this.copy.accept(new String(b, off, len));
this.systemStream.write(b, off, len);
}
@Override
public void flush() throws IOException {
this.systemStream.flush();
}
}
/**
* A captured string that forms part of the full output.
*/
private static class CapturedString {
private final Type type;
private final String string;
CapturedString(Type type, String string) {
this.type = type;
this.string = string;
}
public Type getType() {
return this.type;
}
@Override
public String toString() {
return this.string;
}
}
/**
* Types of content that can be captured.
*/
private enum Type {
OUT, ERR
}
/**
* Save disable and restore AnsiOutput without it needing to be on the classpath.
*/
private static class AnsiOutputState {
private Enabled saved;
AnsiOutputState() {
this.saved = AnsiOutput.getEnabled();
AnsiOutput.setEnabled(Enabled.NEVER);
}
public void restore() {
AnsiOutput.setEnabled(this.saved);
}
public static AnsiOutputState saveAndDisable() {
if (!ClassUtils.isPresent("org.springframework.boot.ansi.AnsiOutput",
CapturedOutput.class.getClassLoader())) {
return null;
}
return new AnsiOutputState();
}
}
}

View File

@@ -1,210 +0,0 @@
/*
* Copyright 2012-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.boot.test.extension;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
import org.springframework.boot.ansi.AnsiOutput;
/**
* JUnit5 {@code @Extension} to capture output from System.out and System.err.
*
* @author Madhura Bhave
* @since 2.2.0
*/
public class OutputCapture implements BeforeEachCallback, AfterEachCallback,
BeforeAllCallback, ParameterResolver, CharSequence {
private CaptureOutputStream captureOut;
private CaptureOutputStream captureErr;
private ByteArrayOutputStream methodLevelCopy;
private ByteArrayOutputStream classLevelCopy;
@Override
public void afterEach(ExtensionContext context) {
releaseOutput();
}
@Override
public void beforeEach(ExtensionContext context) {
releaseOutput();
this.methodLevelCopy = new ByteArrayOutputStream();
captureOutput(this.methodLevelCopy);
}
private void captureOutput(ByteArrayOutputStream copy) {
AnsiOutputControl.get().disableAnsiOutput();
this.captureOut = new CaptureOutputStream(System.out, copy);
this.captureErr = new CaptureOutputStream(System.err, copy);
System.setOut(new PrintStream(this.captureOut));
System.setErr(new PrintStream(this.captureErr));
}
private void releaseOutput() {
if (this.captureOut == null) {
return;
}
AnsiOutputControl.get().enabledAnsiOutput();
System.setOut(this.captureOut.getOriginal());
System.setErr(this.captureErr.getOriginal());
this.methodLevelCopy = null;
}
private void flush() {
try {
this.captureOut.flush();
this.captureErr.flush();
}
catch (IOException ex) {
// ignore
}
}
@Override
public int length() {
return this.toString().length();
}
@Override
public char charAt(int index) {
return this.toString().charAt(index);
}
@Override
public CharSequence subSequence(int start, int end) {
return this.toString().subSequence(start, end);
}
@Override
public String toString() {
flush();
if (this.classLevelCopy == null && this.methodLevelCopy == null) {
return "";
}
StringBuilder builder = new StringBuilder();
if (this.classLevelCopy != null) {
builder.append(this.classLevelCopy.toString());
}
builder.append(this.methodLevelCopy.toString());
return builder.toString();
}
@Override
public void beforeAll(ExtensionContext context) {
this.classLevelCopy = new ByteArrayOutputStream();
captureOutput(this.classLevelCopy);
}
@Override
public boolean supportsParameter(ParameterContext parameterContext,
ExtensionContext extensionContext) throws ParameterResolutionException {
return OutputCapture.class.equals(parameterContext.getParameter().getType());
}
@Override
public Object resolveParameter(ParameterContext parameterContext,
ExtensionContext extensionContext) throws ParameterResolutionException {
return this;
}
private static class CaptureOutputStream extends OutputStream {
private final PrintStream original;
private final OutputStream copy;
CaptureOutputStream(PrintStream original, OutputStream copy) {
this.original = original;
this.copy = copy;
}
@Override
public void write(int b) throws IOException {
this.copy.write(b);
this.original.write(b);
this.original.flush();
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
this.copy.write(b, off, len);
this.original.write(b, off, len);
}
public PrintStream getOriginal() {
return this.original;
}
@Override
public void flush() throws IOException {
this.copy.flush();
this.original.flush();
}
}
/**
* Allow AnsiOutput to not be on the test classpath.
*/
private static class AnsiOutputControl {
public void disableAnsiOutput() {
}
public void enabledAnsiOutput() {
}
public static AnsiOutputControl get() {
try {
Class.forName("org.springframework.boot.ansi.AnsiOutput");
return new AnsiPresentOutputControl();
}
catch (ClassNotFoundException ex) {
return new AnsiOutputControl();
}
}
}
private static class AnsiPresentOutputControl extends AnsiOutputControl {
@Override
public void disableAnsiOutput() {
AnsiOutput.setEnabled(AnsiOutput.Enabled.NEVER);
}
@Override
public void enabledAnsiOutput() {
AnsiOutput.setEnabled(AnsiOutput.Enabled.DETECT);
}
}
}

View File

@@ -0,0 +1,118 @@
/*
* Copyright 2012-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.boot.test.extension;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
import org.junit.jupiter.api.extension.RegisterExtension;
/**
* JUnit5 {@code @Extension} to capture output {@link System#out System.out} and
* {@link System#err System.err}. Can be used on a test class via
* {@link ExtendWith @ExtendWith}, or on field using
* {@link RegisterExtension @RegisterExtension}. This extension provides access to
* {@link CapturedOutput} instances which can be used to assert that the correct output
* was written.
* <p>
* To use with {@link ExtendWith @ExtendWith}, inject the {@link CapturedOutput} as a test
* argument: <pre class="code">
* &#064;ExtendWith(OutputExtension.class)
* class MyTest {
*
* &#064;Test
* void test(CapturedOutput output) {
* assertThat(output).contains("ok");
* }
*
* }
* </pre>
* <p>
* To use with {@link RegisterExtension @RegisterExtension}, use the {@link #capture()
* capture} factory method: argument: <pre class="code">
* class MyTest {
*
* &#064;RegisterExtension
* CapturedOutput output = OutputExtension.capture();
*
* &#064;Test
* void test() {
* assertThat(output).contains("ok");
* }
*
* }
* </pre>
*
* @author Madhura Bhave
* @author Phillip Webb
* @since 2.2.0
* @see CapturedOutput
*/
public class OutputExtension extends CapturedOutput implements BeforeAllCallback,
AfterAllCallback, BeforeEachCallback, AfterEachCallback, ParameterResolver {
OutputExtension() {
// Package private to prevent users from directly creating an instance.
}
@Override
public void beforeAll(ExtensionContext context) throws Exception {
push();
}
@Override
public void afterAll(ExtensionContext context) throws Exception {
pop();
}
@Override
public void beforeEach(ExtensionContext context) throws Exception {
push();
}
@Override
public void afterEach(ExtensionContext context) throws Exception {
pop();
}
@Override
public boolean supportsParameter(ParameterContext parameterContext,
ExtensionContext extensionContext) throws ParameterResolutionException {
return CapturedOutput.class.equals(parameterContext.getParameter().getType());
}
@Override
public Object resolveParameter(ParameterContext parameterContext,
ExtensionContext extensionContext) throws ParameterResolutionException {
return this;
}
/**
* Factory method for use with {@link RegisterExtension @RegisterExtension} fields.
* @return a new {@link CapturedOutput} instance
*/
public static CapturedOutput capture() {
return new OutputExtension();
}
}

View File

@@ -0,0 +1,180 @@
/*
* Copyright 2012-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.boot.test.extension;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.NoSuchElementException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link CapturedOutput}.
*
* @author Phillip Webb
*/
class CapturedOutputTests {
private PrintStream originalOut;
private PrintStream originalErr;
private TestPrintStream systemOut;
private TestPrintStream systemErr;
private CapturedOutput output = new CapturedOutput();
@BeforeEach
void replaceSystemStreams() {
this.originalOut = System.out;
this.originalErr = System.err;
this.systemOut = new TestPrintStream();
this.systemErr = new TestPrintStream();
System.setOut(this.systemOut);
System.setErr(this.systemErr);
}
@AfterEach
void restoreSystemStreams() {
System.setOut(this.originalOut);
System.setErr(this.originalErr);
}
@Test
void pushWhenEmptyStartsCapture() {
System.out.print("A");
this.output.push();
System.out.print("B");
assertThat(this.output).isEqualTo("B");
}
@Test
void pushWhenHasExistingStartesNewCapture() {
System.out.print("A");
this.output.push();
System.out.print("B");
this.output.push();
System.out.print("C");
assertThat(this.output).isEqualTo("BC");
}
@Test
void popWhenEmptyThrowsException() {
assertThatExceptionOfType(NoSuchElementException.class)
.isThrownBy(this.output::pop);
}
@Test
void popWhenHasExistingEndsCapture() {
this.output.push();
System.out.print("A");
this.output.pop();
System.out.print("B");
assertThat(this.systemOut.toString()).isEqualTo("AB");
}
@Test
void captureAlsoWritesToSystemOut() {
this.output.push();
System.out.print("A");
assertThat(this.systemOut.toString()).isEqualTo("A");
}
@Test
void captureAlsoWritesToSystemErr() {
this.output.push();
System.err.print("A");
assertThat(this.systemErr.toString()).isEqualTo("A");
}
@Test
void lengthReturnsCapturedLength() {
this.output.push();
System.out.print("ABC");
assertThat(this.output.length()).isEqualTo(3);
}
@Test
void charAtReturnsCapturedCharAt() {
this.output.push();
System.out.print("ABC");
assertThat(this.output.charAt(1)).isEqualTo('B');
}
@Test
void subSequenceReturnsCapturedSubSequence() {
this.output.push();
System.out.print("ABC");
assertThat(this.output.subSequence(1, 3)).isEqualTo("BC");
}
@Test
void getAllReturnsAllCapturedOutput() {
this.output.push();
System.out.print("A");
System.err.print("B");
System.out.print("C");
assertThat(this.output.getAll()).isEqualTo("ABC");
}
@Test
void toStringReturnsAllCapturedOutput() {
this.output.push();
System.out.print("A");
System.err.print("B");
System.out.print("C");
assertThat(this.output.toString()).isEqualTo("ABC");
}
@Test
void getErrReturnsOnlyCapturedErrOutput() {
this.output.push();
System.out.print("A");
System.err.print("B");
System.out.print("C");
assertThat(this.output.getErr()).isEqualTo("B");
}
@Test
void getOutReturnsOnlyCapturedOutOutput() {
this.output.push();
System.out.print("A");
System.err.print("B");
System.out.print("C");
assertThat(this.output.getOut()).isEqualTo("AC");
}
private static class TestPrintStream extends PrintStream {
TestPrintStream() {
super(new ByteArrayOutputStream());
}
@Override
public String toString() {
return this.out.toString();
}
}
}

View File

@@ -23,21 +23,21 @@ import org.junit.jupiter.api.extension.ExtensionContext;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link OutputCapture} when used via {@link ExtendWith @ExtendWith}.
* Tests for {@link OutputExtension} when used via {@link ExtendWith @ExtendWith}.
*
* @author Madhura Bhave
*/
@ExtendWith(OutputCapture.class)
@ExtendWith(OutputCaptureExtendWithTests.BeforeAllExtension.class)
class OutputCaptureExtendWithTests {
@ExtendWith(OutputExtension.class)
@ExtendWith(OutputExtensionExtendWithTests.BeforeAllExtension.class)
class OutputExtensionExtendWithTests {
@Test
void captureShouldReturnOutputCapturedBeforeTestMethod(OutputCapture output) {
void captureShouldReturnOutputCapturedBeforeTestMethod(CapturedOutput output) {
assertThat(output).contains("Before all").doesNotContain("Hello");
}
@Test
void captureShouldReturnAllCapturedOutput(OutputCapture output) {
void captureShouldReturnAllCapturedOutput(CapturedOutput output) {
System.out.println("Hello World");
System.err.println("Error!!!");
assertThat(output).contains("Before all").contains("Hello World")

View File

@@ -21,15 +21,15 @@ import org.junit.jupiter.api.extension.RegisterExtension;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link OutputCapture} when used via
* Tests for {@link OutputExtension} when used via
* {@link RegisterExtension @RegisterExtension}.
*
* @author Madhura Bhave
*/
class OutputCaptureRegisterExtensionTests {
class OutputExtensionRegisterExtensionTests {
@RegisterExtension
OutputCapture output = new OutputCapture();
CapturedOutput output = OutputExtension.capture();
@Test
void captureShouldReturnAllCapturedOutput() {