Merge pull request #8125 from eugenp/revert-8119-BAEL-3275-2

Revert "BAEL-3275: Using blocking queue for pub-sub"
This commit is contained in:
Eric Martin
2019-10-31 20:43:47 -05:00
committed by GitHub
parent db85c8f275
commit 3225470df5
20543 changed files with 1642750 additions and 0 deletions
@@ -0,0 +1,61 @@
package com.baeldung.annotation.servletcomponentscan;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootAnnotatedApp.class)
public class SpringBootWithServletComponentIntegrationTest {
@Autowired
private ServletContext servletContext;
@Test
public void givenServletContext_whenAccessAttrs_thenFoundAttrsPutInServletListner() {
assertNotNull(servletContext);
assertNotNull(servletContext.getAttribute("servlet-context-attr"));
assertEquals("test", servletContext.getAttribute("servlet-context-attr"));
}
@Test
public void givenServletContext_whenCheckHelloFilterMappings_thenCorrect() {
assertNotNull(servletContext);
FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter");
assertNotNull(filterRegistration);
assertTrue(filterRegistration.getServletNameMappings().contains("echo servlet"));
}
@Autowired
private TestRestTemplate restTemplate;
@Test
public void givenServletFilter_whenGetHello_thenRequestFiltered() {
ResponseEntity<String> responseEntity = this.restTemplate.getForEntity("/hello", String.class);
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
assertEquals("filtering hello", responseEntity.getBody());
}
@Test
public void givenFilterAndServlet_whenPostEcho_thenEchoFiltered() {
ResponseEntity<String> responseEntity = this.restTemplate.postForEntity("/echo", "echo", String.class);
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
assertEquals("filtering echo", responseEntity.getBody());
}
}
@@ -0,0 +1,49 @@
package com.baeldung.annotation.servletcomponentscan;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootPlainApp.class)
public class SpringBootWithoutServletComponentIntegrationTest {
@Autowired
private ServletContext servletContext;
@Autowired
private TestRestTemplate restTemplate;
@Test
public void givenServletContext_whenAccessAttrs_thenNotFound() {
assertNull(servletContext.getAttribute("servlet-context-attr"));
}
@Test
public void givenServletFilter_whenGetHello_thenEndpointNotFound() {
ResponseEntity<String> responseEntity = this.restTemplate.getForEntity("/hello", String.class);
assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode());
}
@Test
public void givenServletContext_whenCheckFilterMappings_thenEmpty() {
assertNotNull(servletContext);
FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter");
assertNull(filterRegistration);
}
}
@@ -0,0 +1,70 @@
package com.baeldung.beanvalidation.application;
import com.baeldung.beanvalidation.application.controllers.UserController;
import com.baeldung.beanvalidation.application.repositories.UserRepository;
import java.nio.charset.Charset;
import static org.assertj.core.api.Assertions.assertThat;
import org.hamcrest.core.Is;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
@RunWith(SpringRunner.class)
@WebMvcTest
@AutoConfigureMockMvc
public class UserControllerIntegrationTest {
@MockBean
private UserRepository userRepository;
@Autowired
UserController userController;
@Autowired
private MockMvc mockMvc;
@Test
public void whenUserControllerInjected_thenNotNull() throws Exception {
assertThat(userController).isNotNull();
}
@Test
public void whenGetRequestToUsers_thenCorrectResponse() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/users")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8));
}
@Test
public void whenPostRequestToUsersAndValidUser_thenCorrectResponse() throws Exception {
MediaType textPlainUtf8 = new MediaType(MediaType.TEXT_PLAIN, Charset.forName("UTF-8"));
String user = "{\"name\": \"bob\", \"email\" : \"bob@domain.com\"}";
mockMvc.perform(MockMvcRequestBuilders.post("/users")
.content(user)
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(textPlainUtf8));
}
@Test
public void whenPostRequestToUsersAndInValidUser_thenCorrectReponse() throws Exception {
String user = "{\"name\": \"\", \"email\" : \"bob@domain.com\"}";
mockMvc.perform(MockMvcRequestBuilders.post("/users")
.content(user)
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isBadRequest())
.andExpect(MockMvcResultMatchers.jsonPath("$.name", Is.is("Name is mandatory")))
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8));
}
}
@@ -0,0 +1,101 @@
package com.baeldung.displayallbeans;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.beans.BeansEndpoint.ContextBeans;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(properties = { "management.port=0", "management.endpoints.web.exposure.include=*" })
public class DisplayBeanIntegrationTest {
@LocalServerPort
private int port;
@Value("${local.management.port}")
private int mgt;
@Autowired
private TestRestTemplate testRestTemplate;
@Autowired
private WebApplicationContext context;
private static final String ACTUATOR_PATH = "/actuator";
@Test
public void givenRestTemplate_whenAccessServerUrl_thenHttpStatusOK() throws Exception {
ResponseEntity<String> entity = this.testRestTemplate.getForEntity("http://localhost:" + this.port + "/displayallbeans", String.class);
then(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@Test
public void givenRestTemplate_whenAccessEndpointUrl_thenHttpStatusOK() throws Exception {
ParameterizedTypeReference<Map<String, ContextBeans>> responseType = new ParameterizedTypeReference<Map<String, ContextBeans>>() {
};
RequestEntity<Void> requestEntity = RequestEntity.get(new URI("http://localhost:" + this.mgt + ACTUATOR_PATH + "/beans"))
.accept(MediaType.APPLICATION_JSON)
.build();
ResponseEntity<Map<String, ContextBeans>> entity = this.testRestTemplate.exchange(requestEntity, responseType);
then(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@Test
public void givenRestTemplate_whenAccessEndpointUrl_thenReturnsBeanNames() throws Exception {
RequestEntity<Void> requestEntity = RequestEntity.get(new URI("http://localhost:" + this.mgt + ACTUATOR_PATH + "/beans"))
.accept(MediaType.APPLICATION_JSON)
.build();
ResponseEntity<BeanActuatorResponse> entity = this.testRestTemplate.exchange(requestEntity, BeanActuatorResponse.class);
Collection<String> beanNamesList = entity.getBody()
.getBeans();
assertThat(beanNamesList).contains("fooController", "fooService");
}
@Test
public void givenWebApplicationContext_whenAccessGetBeanDefinitionNames_thenReturnsBeanNames() throws Exception {
String[] beanNames = context.getBeanDefinitionNames();
List<String> beanNamesList = Arrays.asList(beanNames);
assertThat(beanNamesList).contains("fooController", "fooService");
}
private static class BeanActuatorResponse {
private Map<String, Map<String, Map<String, Map<String, Object>>>> contexts;
public Collection<String> getBeans() {
return this.contexts.get("application")
.get("beans")
.keySet();
}
public Map<String, Map<String, Map<String, Map<String, Object>>>> getContexts() {
return contexts;
}
}
}
@@ -0,0 +1,47 @@
package com.baeldung.failureanalyzer;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collection;
import java.util.stream.Collectors;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.boot.SpringApplication;
import com.baeldung.failureanalyzer.utils.ListAppender;
import ch.qos.logback.classic.spi.ILoggingEvent;
public class FailureAnalyzerAppIntegrationTest {
private static final String EXPECTED_ANALYSIS_DESCRIPTION_TITLE = "Description:";
private static final String EXPECTED_ANALYSIS_DESCRIPTION_CONTENT = "The bean myDAO could not be injected as com.baeldung.failureanalyzer.MyDAO because it is of type com.baeldung.failureanalyzer.MySecondDAO";
private static final String EXPECTED_ANALYSIS_ACTION_TITLE = "Action:";
private static final String EXPECTED_ANALYSIS_ACTION_CONTENT = "Consider creating a bean with name myDAO of type com.baeldung.failureanalyzer.MyDAO";
@BeforeEach
public void clearLogList() {
ListAppender.clearEventList();
}
@Test
public void givenBeanCreationErrorInContext_whenContextLoaded_thenFailureAnalyzerLogsReport() {
try {
SpringApplication.run(FailureAnalyzerApplication.class);
} catch (BeanCreationException e) {
Collection<String> allLoggedEntries = ListAppender.getEvents()
.stream()
.map(ILoggingEvent::getFormattedMessage)
.collect(Collectors.toList());
assertThat(allLoggedEntries).anyMatch(entry -> entry.contains(EXPECTED_ANALYSIS_DESCRIPTION_TITLE))
.anyMatch(entry -> entry.contains(EXPECTED_ANALYSIS_DESCRIPTION_CONTENT))
.anyMatch(entry -> entry.contains(EXPECTED_ANALYSIS_ACTION_TITLE))
.anyMatch(entry -> entry.contains(EXPECTED_ANALYSIS_ACTION_CONTENT));
return;
}
throw new IllegalStateException("Context load should be failing due to a BeanCreationException!");
}
}
@@ -0,0 +1,25 @@
package com.baeldung.failureanalyzer.utils;
import java.util.ArrayList;
import java.util.List;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
public class ListAppender extends AppenderBase<ILoggingEvent> {
static private List<ILoggingEvent> events = new ArrayList<>();
@Override
protected void append(ILoggingEvent eventObject) {
events.add(eventObject);
}
public static List<ILoggingEvent> getEvents() {
return events;
}
public static void clearEventList() {
events.clear();
}
}
@@ -0,0 +1,43 @@
package com.baeldung.git;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = CommitIdApplication.class)
@TestPropertySource(properties = { "spring.jmx.default-domain=test" })
public class CommitIdIntegrationTest {
private static final Logger LOG = LoggerFactory.getLogger(CommitIdIntegrationTest.class);
@Value("${git.commit.message.short:UNKNOWN}")
private String commitMessage;
@Value("${git.branch:UNKNOWN}")
private String branch;
@Value("${git.commit.id:UNKNOWN}")
private String commitId;
@Test
public void whenInjecting_shouldDisplay() throws Exception {
LOG.info(commitId);
LOG.info(commitMessage);
LOG.info(branch);
assertThat(commitMessage).isNotEqualTo("UNKNOWN");
assertThat(branch).isNotEqualTo("UNKNOWN");
assertThat(commitId).isNotEqualTo("UNKNOWN");
}
}
@@ -0,0 +1,35 @@
package com.baeldung.intro;
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
public class AppLiveTest {
@Autowired
private MockMvc mvc;
@Test
public void getIndex() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo("Index Page")));
}
@Test
public void getLocal() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/local").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo("/local")));
}
}
@@ -0,0 +1,109 @@
package com.baeldung.jsondateformat;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = ContactApp.class)
@TestPropertySource(properties = {
"spring.jackson.date-format=yyyy-MM-dd HH:mm:ss"
})
public class ContactAppUnitTest {
private final ObjectMapper mapper = new ObjectMapper();
@Autowired
TestRestTemplate restTemplate;
@LocalServerPort
int port;
String url;
@Before
public void before() {
url=String.format("http://localhost:%s", port);
}
@Test
public void givenJsonFormatAnnotationAndJava8DateType_whenGet_thenReturnExpectedDateFormat() throws IOException, ParseException {
ResponseEntity<String> response = restTemplate.getForEntity(url + "/contacts", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
assertNotNull(birthdayDate);
assertNotNull(lastUpdateTime);
}
@Test
public void givenJsonFormatAnnotationAndLegacyDateType_whenGet_thenReturnExpectedDateFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity(url + "/contacts/javaUtilDate", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
assertNotNull(birthdayDate);
assertNotNull(lastUpdateTime);
}
@Test
public void givenDefaultDateFormatInAppPropertiesAndLegacyDateType_whenGet_thenReturnExpectedDateFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity(url + "/contacts/plainWithJavaUtilDate", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
assertNotNull(birthdayDate);
assertNotNull(lastUpdateTime);
}
@Test(expected = DateTimeParseException.class)
public void givenDefaultDateFormatInAppPropertiesAndJava8DateType_whenGet_thenNotApplyFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity(url + "/contacts/plain", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
}
@@ -0,0 +1,76 @@
package com.baeldung.jsondateformat;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = ContactApp.class)
public class ContactAppWithObjectMapperCustomizerUnitTest {
private final ObjectMapper mapper = new ObjectMapper();
@Autowired
TestRestTemplate restTemplate;
@LocalServerPort
int port;
String url;
@Before
public void before() {
url=String.format("http://localhost:%s", port);
}
@Test
public void givenDefaultDateFormatInAppPropertiesAndLegacyDateType_whenGet_thenReturnExpectedDateFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity(url + "/contacts/plainWithJavaUtilDate", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
assertNotNull(birthdayDate);
assertNotNull(lastUpdateTime);
}
@Test
public void givenDefaultDateFormatInAppPropertiesAndJava8DateType_whenGet_thenReturnExpectedDateFormat() throws IOException {
ResponseEntity<String> response = restTemplate.getForEntity(url + "/contacts/plain", String.class);
assertEquals(200, response.getStatusCodeValue());
List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});
LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
assertNotNull(birthdayDate);
assertNotNull(lastUpdateTime);
}
}
@@ -0,0 +1,170 @@
package com.baeldung.kong;
import com.baeldung.kong.domain.APIObject;
import com.baeldung.kong.domain.ConsumerObject;
import com.baeldung.kong.domain.KeyAuthObject;
import com.baeldung.kong.domain.PluginObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.*;
import org.springframework.test.context.junit4.SpringRunner;
import java.net.URI;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT;
/**
* @author aiet
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = DEFINED_PORT, classes = StockApp.class)
public class KongAdminAPILiveTest {
private String getStockPrice(String code) {
try {
return restTemplate.getForObject(new URI("http://localhost:8080/stock/" + code), String.class);
} catch (Exception ignored) {
}
return null;
}
@Before
public void init() {
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
}
@Autowired
TestRestTemplate restTemplate;
@Test
public void givenEndpoint_whenQueryStockPrice_thenPriceCorrect() {
String response = getStockPrice("btc");
assertEquals("10000", response);
response = getStockPrice("eth");
assertEquals("N/A", response);
}
@Test
public void givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong() throws Exception {
restTemplate.delete("http://localhost:8001/apis/stock-api");
APIObject stockAPI = new APIObject("stock-api", "stock.api", "http://localhost:9090", "/");
HttpEntity<APIObject> apiEntity = new HttpEntity<>(stockAPI);
ResponseEntity<String> addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class);
assertEquals(HttpStatus.CREATED, addAPIResp.getStatusCode());
addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class);
assertEquals(HttpStatus.CONFLICT, addAPIResp.getStatusCode());
String apiListResp = restTemplate.getForObject("http://localhost:8001/apis/", String.class);
assertTrue(apiListResp.contains("stock-api"));
HttpHeaders headers = new HttpHeaders();
headers.set("Host", "stock.api");
RequestEntity<String> requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc"));
ResponseEntity<String> stockPriceResp = restTemplate.exchange(requestEntity, String.class);
assertEquals("10000", stockPriceResp.getBody());
}
@Test
public void givenKongAdminAPI_whenAddAPIConsumer_thenAdded() {
restTemplate.delete("http://localhost:8001/consumers/eugenp");
ConsumerObject consumer = new ConsumerObject("eugenp");
HttpEntity<ConsumerObject> addConsumerEntity = new HttpEntity<>(consumer);
ResponseEntity<String> addConsumerResp = restTemplate.postForEntity("http://localhost:8001/consumers/", addConsumerEntity, String.class);
assertEquals(HttpStatus.CREATED, addConsumerResp.getStatusCode());
addConsumerResp = restTemplate.postForEntity("http://localhost:8001/consumers", addConsumerEntity, String.class);
assertEquals(HttpStatus.CONFLICT, addConsumerResp.getStatusCode());
String consumerListResp = restTemplate.getForObject("http://localhost:8001/consumers/", String.class);
assertTrue(consumerListResp.contains("eugenp"));
}
@Test
public void givenAPI_whenEnableAuth_thenAnonymousDenied() throws Exception {
String apiListResp = restTemplate.getForObject("http://localhost:8001/apis/", String.class);
if (!apiListResp.contains("stock-api")) {
givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong();
}
PluginObject authPlugin = new PluginObject("key-auth");
ResponseEntity<String> enableAuthResp = restTemplate.postForEntity("http://localhost:8001/apis/stock-api/plugins", new HttpEntity<>(authPlugin), String.class);
assertTrue(HttpStatus.CREATED == enableAuthResp.getStatusCode() || HttpStatus.CONFLICT == enableAuthResp.getStatusCode());
String pluginsResp = restTemplate.getForObject("http://localhost:8001/apis/stock-api/plugins", String.class);
assertTrue(pluginsResp.contains("key-auth"));
HttpHeaders headers = new HttpHeaders();
headers.set("Host", "stock.api");
RequestEntity<String> requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/stock/btc"));
ResponseEntity<String> stockPriceResp = restTemplate.exchange(requestEntity, String.class);
assertEquals(HttpStatus.UNAUTHORIZED, stockPriceResp.getStatusCode());
}
@Test
public void givenAPIAuthEnabled_whenAddKey_thenAccessAllowed() throws Exception {
String apiListResp = restTemplate.getForObject("http://localhost:8001/apis/", String.class);
if (!apiListResp.contains("stock-api")) {
givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong();
}
String consumerListResp = restTemplate.getForObject("http://localhost:8001/consumers/", String.class);
if (!consumerListResp.contains("eugenp")) {
givenKongAdminAPI_whenAddAPIConsumer_thenAdded();
}
PluginObject authPlugin = new PluginObject("key-auth");
ResponseEntity<String> enableAuthResp = restTemplate.postForEntity("http://localhost:8001/apis/stock-api/plugins", new HttpEntity<>(authPlugin), String.class);
assertTrue(HttpStatus.CREATED == enableAuthResp.getStatusCode() || HttpStatus.CONFLICT == enableAuthResp.getStatusCode());
final String consumerKey = "eugenp.pass";
KeyAuthObject keyAuth = new KeyAuthObject(consumerKey);
ResponseEntity<String> keyAuthResp = restTemplate.postForEntity("http://localhost:8001/consumers/eugenp/key-auth", new HttpEntity<>(keyAuth), String.class);
assertTrue(HttpStatus.CREATED == keyAuthResp.getStatusCode() || HttpStatus.CONFLICT == keyAuthResp.getStatusCode());
HttpHeaders headers = new HttpHeaders();
headers.set("Host", "stock.api");
headers.set("apikey", consumerKey);
RequestEntity<String> requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc"));
ResponseEntity<String> stockPriceResp = restTemplate.exchange(requestEntity, String.class);
assertEquals("10000", stockPriceResp.getBody());
headers.set("apikey", "wrongpass");
requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc"));
stockPriceResp = restTemplate.exchange(requestEntity, String.class);
assertEquals(HttpStatus.FORBIDDEN, stockPriceResp.getStatusCode());
}
@Test
public void givenAdminAPIProxy_whenAddAPIViaProxy_thenAPIAdded() throws Exception {
APIObject adminAPI = new APIObject("admin-api", "admin.api", "http://localhost:8001", "/admin-api");
HttpEntity<APIObject> apiEntity = new HttpEntity<>(adminAPI);
ResponseEntity<String> addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class);
assertTrue(HttpStatus.CREATED == addAPIResp.getStatusCode() || HttpStatus.CONFLICT == addAPIResp.getStatusCode());
HttpHeaders headers = new HttpHeaders();
headers.set("Host", "admin.api");
APIObject baeldungAPI = new APIObject("baeldung-api", "baeldung.com", "http://ww.baeldung.com", "/");
RequestEntity<APIObject> requestEntity = new RequestEntity<>(baeldungAPI, headers, HttpMethod.POST, new URI("http://localhost:8000/admin-api/apis"));
addAPIResp = restTemplate.exchange(requestEntity, String.class);
assertTrue(HttpStatus.CREATED == addAPIResp.getStatusCode() || HttpStatus.CONFLICT == addAPIResp.getStatusCode());
}
}
@@ -0,0 +1,75 @@
package com.baeldung.kong;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT;
import java.net.URI;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.kong.domain.APIObject;
import com.baeldung.kong.domain.TargetObject;
import com.baeldung.kong.domain.UpstreamObject;
/**
* @author aiet
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = DEFINED_PORT, classes = StockApp.class, properties = "server.servlet.contextPath=/springbootapp")
public class KongLoadBalanceLiveTest {
@Before
public void init() {
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
}
@Autowired
TestRestTemplate restTemplate;
@Test
public void givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong() throws Exception {
UpstreamObject upstream = new UpstreamObject("stock.api.service");
ResponseEntity<String> addUpstreamResp = restTemplate.postForEntity("http://localhost:8001/upstreams", new HttpEntity<>(upstream), String.class);
assertTrue(HttpStatus.CREATED == addUpstreamResp.getStatusCode() || HttpStatus.CONFLICT == addUpstreamResp.getStatusCode());
TargetObject testTarget = new TargetObject("localhost:8080", 10);
ResponseEntity<String> addTargetResp = restTemplate.postForEntity("http://localhost:8001/upstreams/stock.api.service/targets", new HttpEntity<>(testTarget), String.class);
assertTrue(HttpStatus.CREATED == addTargetResp.getStatusCode() || HttpStatus.CONFLICT == addTargetResp.getStatusCode());
TargetObject releaseTarget = new TargetObject("localhost:9090", 40);
addTargetResp = restTemplate.postForEntity("http://localhost:8001/upstreams/stock.api.service/targets", new HttpEntity<>(releaseTarget), String.class);
assertTrue(HttpStatus.CREATED == addTargetResp.getStatusCode() || HttpStatus.CONFLICT == addTargetResp.getStatusCode());
APIObject stockAPI = new APIObject("balanced-stock-api", "balanced.stock.api", "http://stock.api.service", "/");
HttpEntity<APIObject> apiEntity = new HttpEntity<>(stockAPI);
ResponseEntity<String> addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class);
assertTrue(HttpStatus.CREATED == addAPIResp.getStatusCode() || HttpStatus.CONFLICT == addAPIResp.getStatusCode());
HttpHeaders headers = new HttpHeaders();
headers.set("Host", "balanced.stock.api");
for (int i = 0; i < 1000; i++) {
RequestEntity<String> requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc"));
ResponseEntity<String> stockPriceResp = restTemplate.exchange(requestEntity, String.class);
assertEquals("10000", stockPriceResp.getBody());
}
int releaseCount = restTemplate.getForObject("http://localhost:9090/springbootapp/stock/reqcount", Integer.class);
int testCount = restTemplate.getForObject("http://localhost:8080/springbootapp/stock/reqcount", Integer.class);
assertTrue(Math.round(releaseCount * 1.0 / testCount) == 4);
}
}
@@ -0,0 +1,54 @@
package com.baeldung.kong.domain;
/**
* @author aiet
*/
public class APIObject {
public APIObject() {
}
public APIObject(String name, String hosts, String upstream_url, String uris) {
this.name = name;
this.hosts = hosts;
this.upstream_url = upstream_url;
this.uris = uris;
}
private String name;
private String hosts;
private String upstream_url;
private String uris;
public String getUris() {
return uris;
}
public void setUris(String uris) {
this.uris = uris;
}
public String getUpstream_url() {
return upstream_url;
}
public void setUpstream_url(String upstream_url) {
this.upstream_url = upstream_url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHosts() {
return hosts;
}
public void setHosts(String hosts) {
this.hosts = hosts;
}
}
@@ -0,0 +1,35 @@
package com.baeldung.kong.domain;
/**
* @author aiet
*/
public class ConsumerObject {
private String username;
private String custom_id;
public ConsumerObject(String username) {
this.username = username;
}
public ConsumerObject(String username, String custom_id) {
this.username = username;
this.custom_id = custom_id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getCustom_id() {
return custom_id;
}
public void setCustom_id(String custom_id) {
this.custom_id = custom_id;
}
}
@@ -0,0 +1,21 @@
package com.baeldung.kong.domain;
/**
* @author aiet
*/
public class KeyAuthObject {
public KeyAuthObject(String key) {
this.key = key;
}
private String key;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
@@ -0,0 +1,30 @@
package com.baeldung.kong.domain;
/**
* @author aiet
*/
public class PluginObject {
private String name;
private String consumer_id;
public PluginObject(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getConsumer_id() {
return consumer_id;
}
public void setConsumer_id(String consumer_id) {
this.consumer_id = consumer_id;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.kong.domain;
/**
* @author aiet
*/
public class TargetObject {
public TargetObject(String target, int weight) {
this.target = target;
this.weight = weight;
}
private String target;
private int weight;
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}
@@ -0,0 +1,21 @@
package com.baeldung.kong.domain;
/**
* @author aiet
*/
public class UpstreamObject {
public UpstreamObject(String name) {
this.name = name;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,36 @@
package com.baeldung.servletinitializer;
import static org.hamcrest.CoreMatchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import com.baeldung.servletinitializer.WarInitializerApplication.WarInitializerController;
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = WarInitializerController.class)
public class WarInitializerApplicationIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Test
public void whenContextRootUrlIsAccessed_thenStatusIsOk() throws Exception {
mockMvc.perform(get("/"))
.andExpect(status().is(200));
}
@Test
public void whenContextRootUrlIsAccesed_thenCorrectStringIsReturned() throws Exception {
mockMvc.perform(get("/"))
.andExpect(content().string(containsString("WarInitializerApplication is up and running!")));
}
}
@@ -0,0 +1,62 @@
package com.baeldung.toggle;
import static org.junit.Assert.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = ToggleApplication.class)
@AutoConfigureMockMvc
public class ToggleIntegrationTest {
@Autowired
private EmployeeRepository employeeRepository;
@Autowired
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void givenFeaturePropertyFalse_whenIncreaseSalary_thenNoIncrease() throws Exception {
Employee emp = new Employee(1, 2000);
employeeRepository.save(emp);
System.setProperty("employee.feature", "false");
mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200));
emp = employeeRepository.findById(1L).orElse(null);
assertEquals("salary incorrect", 2000, emp.getSalary(), 0.5);
}
@Test
public void givenFeaturePropertyTrue_whenIncreaseSalary_thenIncrease() throws Exception {
Employee emp = new Employee(1, 2000);
employeeRepository.save(emp);
System.setProperty("employee.feature", "true");
mockMvc.perform(post("/increaseSalary").param("id", emp.getId() + "")).andExpect(status().is(200));
emp = employeeRepository.findById(1L).orElse(null);
assertEquals("salary incorrect", 2200, emp.getSalary(), 0.5);
}
}
@@ -0,0 +1,34 @@
package com.baeldung.utils;
import com.baeldung.utils.controller.UtilsController;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public class UtilsControllerIntegrationTest {
@InjectMocks
private UtilsController utilsController;
private MockMvc mockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(utilsController).build();
}
@Test
public void givenParameter_setRequestParam_andSetSessionAttribute() throws Exception {
String param = "testparam";
this.mockMvc.perform(post("/setParam").param("param", param).sessionAttr("parameter", param)).andExpect(status().isOk());
}
}