/*
 * 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.autoconfigure.kafka;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.producer.Producer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafkaStreams;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.StreamsBuilderFactoryBean;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.messaging.handler.annotation.Header;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Integration tests for {@link KafkaAutoConfiguration}.
 *
 * @author Gary Russell
 * @author Stephane Nicoll
 */
class KafkaAutoConfigurationIntegrationTests {

	private static final String TEST_TOPIC = "testTopic";

	private static final String ADMIN_CREATED_TOPIC = "adminCreatedTopic";

	public static final EmbeddedKafkaBroker embeddedKafka = new EmbeddedKafkaBroker(1, true, TEST_TOPIC);

	private AnnotationConfigApplicationContext context;

	@BeforeAll
	static void setUp() {
		embeddedKafka.afterPropertiesSet();
	}

	@AfterEach
	void close() {
		if (this.context != null) {
			this.context.close();
		}
	}

	@AfterAll
	static void tearDown() {
		embeddedKafka.destroy();
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Test
	void testEndToEnd() throws Exception {
		load(KafkaConfig.class, "spring.kafka.bootstrap-servers:" + getEmbeddedKafkaBrokersAsString(),
				"spring.kafka.consumer.group-id=testGroup", "spring.kafka.consumer.auto-offset-reset=earliest");
		KafkaTemplate<String, String> template = this.context.getBean(KafkaTemplate.class);
		template.send(TEST_TOPIC, "foo", "bar");
		Listener listener = this.context.getBean(Listener.class);
		assertThat(listener.latch.await(30, TimeUnit.SECONDS)).isTrue();
		assertThat(listener.key).isEqualTo("foo");
		assertThat(listener.received).isEqualTo("bar");

		DefaultKafkaProducerFactory producerFactory = this.context.getBean(DefaultKafkaProducerFactory.class);
		Producer producer = producerFactory.createProducer();
		assertThat(producer.partitionsFor(ADMIN_CREATED_TOPIC).size()).isEqualTo(10);
		producer.close();
	}

	@Test
	void testStreams() {
		load(KafkaStreamsConfig.class, "spring.application.name:my-app",
				"spring.kafka.bootstrap-servers:" + getEmbeddedKafkaBrokersAsString());
		assertThat(this.context.getBean(StreamsBuilderFactoryBean.class).isAutoStartup()).isTrue();
	}

	private void load(Class<?> config, String... environment) {
		this.context = doLoad(new Class<?>[] { config }, environment);
	}

	private AnnotationConfigApplicationContext doLoad(Class<?>[] configs, String... environment) {
		AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
		applicationContext.register(configs);
		applicationContext.register(KafkaAutoConfiguration.class);
		TestPropertyValues.of(environment).applyTo(applicationContext);
		applicationContext.refresh();
		return applicationContext;
	}

	private String getEmbeddedKafkaBrokersAsString() {
		return embeddedKafka.getBrokersAsString();
	}

	@Configuration(proxyBeanMethods = false)
	static class KafkaConfig {

		@Bean
		public Listener listener() {
			return new Listener();
		}

		@Bean
		public NewTopic adminCreated() {
			return new NewTopic(ADMIN_CREATED_TOPIC, 10, (short) 1);
		}

	}

	@Configuration(proxyBeanMethods = false)
	@EnableKafkaStreams
	static class KafkaStreamsConfig {

	}

	public static class Listener {

		private final CountDownLatch latch = new CountDownLatch(1);

		private volatile String received;

		private volatile String key;

		@KafkaListener(topics = TEST_TOPIC)
		public void listen(String foo, @Header(KafkaHeaders.RECEIVED_MESSAGE_KEY) String key) {
			this.received = foo;
			this.key = key;
			this.latch.countDown();
		}

	}

}

@@ -891,91 +891,12 @@
 fter
-All;%0Aimport org.junit.jupiter.api.AfterEach;%0Aimport org.junit.jupiter.api.BeforeAll
+Each
 ;%0Aim
@@ -1372,24 +1372,78 @@
 actoryBean;%0A
+import org.springframework.kafka.config.TopicBuilder;%0A
 import org.s
@@ -1643,16 +1643,96 @@
 ka.test.
+condition.EmbeddedKafkaCondition;%0Aimport org.springframework.kafka.test.context.
 Embedded
@@ -1736,22 +1736,16 @@
 dedKafka
-Broker
 ;%0Aimport
@@ -1981,16 +1981,91 @@
 oll%0A */%0A
+@EmbeddedKafka(topics = KafkaAutoConfigurationIntegrationTests.TEST_TOPIC)%0A
 class Ka
@@ -2102,30 +2102,29 @@
 nTests %7B%0A%0A%09p
-rivate
+ublic
  static fina
@@ -2238,239 +2238,58 @@
 %0A%0A%09p
-ublic static final EmbeddedKafkaBroker embeddedKafka = new EmbeddedKafkaBroker(1, true, TEST_TOPIC);%0A%0A%09private AnnotationConfigApplicationContext context;%0A%0A%09@BeforeAll%0A%09static void setUp() %7B%0A%09%09embeddedKafka.afterPropertiesSet();%0A%09%7D
+rivate AnnotationConfigApplicationContext context;
 %0A%0A%09@
@@ -2381,76 +2381,8 @@
 %09%7D%0A%0A
-%09@AfterAll%0A%09static void tearDown() %7B%0A%09%09embeddedKafka.destroy();%0A%09%7D%0A%0A
 %09@Su
@@ -4176,17 +4176,17 @@
 %09return 
-e
+E
 mbeddedK
@@ -4189,16 +4189,37 @@
 dedKafka
+Condition.getBroker()
 .getBrok
@@ -4435,20 +4435,25 @@
 urn 
-new NewTopic
+TopicBuilder.name
 (ADM
@@ -4472,23 +4472,43 @@
 OPIC
-, 10, (short) 1
+).partitions(10).replicas(1).build(
 );%0A%09

Use @EmbeddedKafka for Integration Tests