类org.springframework.boot.test.system.CapturedOutput源码实例Demo

下面列出了怎么用org.springframework.boot.test.system.CapturedOutput的API类实例代码及写法,或者点击链接到github查看源代码。

@Test
void testAsymmetricEncryptionIsNotAvailable(CapturedOutput output) {
    doThrow(InvalidKeyUsageException.class).when(mockKms).encrypt(any(EncryptRequest.class));

    try {
        // Asymmetric algorithm is not available, because an outdated AWS SDK is used. The textEncryptor will
        // print a warning and fall back to symmetric algorithm.
        // Trying to use an asymmetric key with the symmetric algorithm will lead to an exception.
        textEncryptor.encrypt(PLAINTEXT);
        failBecauseExceptionWasNotThrown(InvalidKeyUsageException.class);
    } catch (InvalidKeyUsageException ignored) {
        assertThat(output).contains(VERSION_HINT);
        final EncryptRequest expectedRequest = new EncryptRequest()
                .withKeyId("an-asymmetric-key")
                .withPlaintext(ByteBuffer.wrap(PLAINTEXT.getBytes()));
        verify(mockKms).encrypt(eq(expectedRequest));
    }
}
 
@Test
void testAsymmetricDecryptionIsNotAvailable(CapturedOutput output) {
    doThrow(InvalidCiphertextException.class).when(mockKms).decrypt(any(DecryptRequest.class));

    try {
        // Asymmetric algorithm is not available, because an outdated AWS SDK is used. The textEncryptor will
        // print a warning and fall back to symmetric algorithm.
        // Trying to use an asymmetric key with the symmetric algorithm will lead to an exception.
        textEncryptor.decrypt(CIPHERTEXT);
        failBecauseExceptionWasNotThrown(InvalidCiphertextException.class);
    } catch (InvalidCiphertextException ignored) {
        assertThat(output).contains(VERSION_HINT);
        final DecryptRequest expectedRequest = new DecryptRequest()
                .withCiphertextBlob(ByteBuffer.wrap(Base64.getDecoder().decode(CIPHERTEXT.getBytes())));
        verify(mockKms).decrypt(eq(expectedRequest));
    }
}
 
@Test
public void exception_logging_span_handler_logs_synchronous_exceptions(
		CapturedOutput capture) {
	try {
		new RestTemplate().getForObject("http://localhost:" + port() + "/",
				String.class);
		BDDAssertions.fail("should fail due to runtime exception");
	}
	catch (Exception e) {
	}

	then(this.currentTraceContext.get()).isNull();
	MutableSpan fromFirstTraceFilterFlow = spanHandler.takeRemoteSpanWithErrorMessage(
			Kind.SERVER,
			"Request processing failed; nested exception is java.lang.RuntimeException: Throwing exception");
	then(fromFirstTraceFilterFlow.tags()).containsEntry("http.method", "GET")
			.containsEntry("mvc.controller.class", "BasicErrorController");
	// Trace IDs in logs: issue#714
	String hex = fromFirstTraceFilterFlow.traceId();
	thenLogsForExceptionLoggingFilterContainTracingInformation(capture, hex);
}
 
源代码4 项目: spring-cloud-sleuth   文件: FlatMapTests.java
@Test
public void should_work_with_flat_maps_with_on_last_operator_instrumentation(
		CapturedOutput capture) {
	// given
	ConfigurableApplicationContext context = new SpringApplicationBuilder(
			FlatMapTests.TestConfiguration.class, Issue866Configuration.class)
					.web(WebApplicationType.REACTIVE)
					.properties("server.port=0", "spring.jmx.enabled=false",
							"spring.sleuth.reactor.decorate-on-each=false",
							"spring.application.name=TraceWebFlux2Tests",
							"security.basic.enabled=false",
							"management.security.enabled=false")
					.run();
	assertReactorTracing(context, capture);

	try {
		System.setProperty("spring.sleuth.reactor.decorate-on-each", "true");
		// trigger context refreshed
		context.getBean(ContextRefresher.class).refresh();
		assertReactorTracing(context, capture);
	}
	finally {
		System.clearProperty("spring.sleuth.reactor.decorate-on-each");
	}
}
 
@Test
public void should_not_pass_dash_as_default_service_name(
		CapturedOutput outputCapture) {
	log.info("HELLO");

	BDDAssertions.then(outputCapture.toString()).doesNotContain("INFO [-,,,]");
}
 
@Test
public void shouldNotContainAnyTracingInfoInTheLogs(CapturedOutput capture) {
	log.info("hello");

	// prove bootstrap-disabled.yml loaded
	assertThat(applicationName).isEqualTo("foo");

	// spring.application.name is put in the log format by
	// TraceEnvironmentPostProcessor
	// checking for the service name here ensures this isn't accidentally loaded
	BDDAssertions.then(capture.toString()).doesNotContain("[foo");
}
 
private void thenLogsForExceptionLoggingFilterContainTracingInformation(
		CapturedOutput capture, String hex) {
	String[] split = capture.toString().split("\n");
	List<String> list = Arrays.stream(split)
			.filter(s -> s.contains("Uncaught exception thrown"))
			.filter(s -> s.contains(hex + "," + hex + "]"))
			.collect(Collectors.toList());
	then(list).isNotEmpty();
}
 
源代码8 项目: spring-cloud-sleuth   文件: FlatMapTests.java
@Test
public void should_work_with_flat_maps(CapturedOutput capture) {
	// given
	ConfigurableApplicationContext context = new SpringApplicationBuilder(
			FlatMapTests.TestConfiguration.class, Issue866Configuration.class)
					.web(WebApplicationType.REACTIVE)
					.properties("server.port=0", "spring.jmx.enabled=false",
							"spring.application.name=TraceWebFluxTests",
							"security.basic.enabled=false",
							"management.security.enabled=false")
					.run();
	assertReactorTracing(context, capture);
}
 
源代码9 项目: rsc   文件: RscTest.java
@Test
void test(CapturedOutput capture) throws Exception {
	Rsc.main(new String[]{});
	assertThat(capture.toString()).isNotEmpty();
}
 
@AfterEach
void afterEach(CapturedOutput output) {
	assertThat(output).doesNotContain(
			"is not eligible for getting processed by all BeanPostProcessors");
}
 
源代码11 项目: spring-cloud-sleuth   文件: FlatMapTests.java
private void assertReactorTracing(ConfigurableApplicationContext context,
		CapturedOutput capture) {
	TestSpanHandler spans = context.getBean(TestSpanHandler.class);
	int port = context.getBean(Environment.class).getProperty("local.server.port",
			Integer.class);
	RequestSender sender = context.getBean(RequestSender.class);
	TestConfiguration config = context.getBean(TestConfiguration.class);
	FactoryUser factoryUser = context.getBean(FactoryUser.class);
	sender.port = port;
	spans.clear();

	Awaitility.await().untilAsserted(() -> {
		// when
		LOGGER.info("Start");
		spans.clear();
		String firstTraceId = flatMapTraceId(spans, callFlatMap(port).block());
		// then
		LOGGER.info("Checking first trace id");
		thenAllWebClientCallsHaveSameTraceId(firstTraceId, sender);
		thenSpanInFooHasSameTraceId(firstTraceId, config);
		spans.clear();
		LOGGER.info("All web client calls have same trace id");

		// when
		LOGGER.info("Second trace start");
		String secondTraceId = flatMapTraceId(spans, callFlatMap(port).block());
		// then
		then(firstTraceId).as("Id will not be reused between calls")
				.isNotEqualTo(secondTraceId);
		LOGGER.info("Id was not reused between calls");
		thenSpanInFooHasSameTraceId(secondTraceId, config);
		LOGGER.info("Span in Foo has same trace id");
		// and
		List<String> requestUri = Arrays.stream(capture.toString().split("\n"))
				.filter(s -> s.contains("Received a request to uri"))
				.map(s -> s.split(",")[1]).collect(Collectors.toList());
		LOGGER.info(
				"TracingFilter should not have any trace when receiving a request "
						+ requestUri);
		then(requestUri).as(
				"TracingFilter should not have any trace when receiving a request")
				.containsOnly("");
		// and #866
		then(factoryUser.wasSchedulerWrapped).isTrue();
		LOGGER.info("Factory was wrapped");
	});
}
 
 类所在包
 同包方法