changed formatter

This commit is contained in:
2026-05-17 00:26:46 +02:00
parent 4d96524adb
commit a8ecf65180
17 changed files with 180 additions and 191 deletions
@@ -13,10 +13,8 @@ public class CorsConfig implements WebMvcConfigurer {
@Override @Override
public void addCorsMappings(CorsRegistry registry) { public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") registry.addMapping("/**").allowedOrigins(allowedOrigins)
.allowedOrigins(allowedOrigins)
.allowedMethods("GET", "POST", "DELETE", "OPTIONS") .allowedMethods("GET", "POST", "DELETE", "OPTIONS")
.allowedHeaders("Content-Type", "Accept") .allowedHeaders("Content-Type", "Accept").allowCredentials(true);
.allowCredentials(true);
} }
} }
@@ -2,4 +2,5 @@ package com.vaessl.app.connection;
import java.time.Instant; import java.time.Instant;
public record AuthResponse(String serviceType, Instant expiresAt) {} public record AuthResponse(String serviceType, Instant expiresAt) {
}
@@ -28,8 +28,7 @@ public class ConnectionController {
private final ConnectionService connectionService; private final ConnectionService connectionService;
@PostMapping("/login") @PostMapping("/login")
public ResponseEntity<AuthResponse> login( public ResponseEntity<AuthResponse> login(@Valid @RequestBody ConnectionRequest request,
@Valid @RequestBody ConnectionRequest request,
HttpServletRequest httpReq) { HttpServletRequest httpReq) {
LoginResult result = connectionService.login(request); LoginResult result = connectionService.login(request);
@@ -53,21 +52,21 @@ public class ConnectionController {
} }
List<ConnectionStatusResponse> statuses = new ArrayList<>(); List<ConnectionStatusResponse> statuses = new ArrayList<>();
Collections.list(session.getAttributeNames()).stream() Collections.list(session.getAttributeNames()).stream().filter(k -> k.endsWith(SUFFIX))
.filter(k -> k.endsWith(SUFFIX))
.forEach(k -> { .forEach(k -> {
String serviceType = k.replace(SUFFIX, ""); String serviceType = k.replace(SUFFIX, "");
Long id = (Long) session.getAttribute(k); Long id = (Long) session.getAttribute(k);
ConnectionStatusResponse status = connectionService.getConnectionStatus(serviceType, id); ConnectionStatusResponse status =
if (status != null) statuses.add(status); connectionService.getConnectionStatus(serviceType, id);
if (status != null)
statuses.add(status);
}); });
return ResponseEntity.ok(statuses); return ResponseEntity.ok(statuses);
} }
@DeleteMapping("/connections/{serviceType}") @DeleteMapping("/connections/{serviceType}")
public ResponseEntity<Void> logout( public ResponseEntity<Void> logout(@PathVariable("serviceType") String serviceType,
@PathVariable("serviceType") String serviceType,
HttpServletRequest httpReq) { HttpServletRequest httpReq) {
HttpSession session = httpReq.getSession(false); HttpSession session = httpReq.getSession(false);
@@ -14,7 +14,8 @@ import lombok.NoArgsConstructor;
import lombok.Setter; import lombok.Setter;
@Entity @Entity
@Table(name = "connections", uniqueConstraints = { @UniqueConstraint(columnNames = { "appUrl", "username" }) }) @Table(name = "connections",
uniqueConstraints = {@UniqueConstraint(columnNames = {"appUrl", "username"})})
@Inheritance(strategy = InheritanceType.SINGLE_TABLE) @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "service_type") @DiscriminatorColumn(name = "service_type")
@Getter @Getter
@@ -4,12 +4,9 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
public record ConnectionRequest( public record ConnectionRequest(@NotBlank(message = "App URL is mandatory") String appUrl,
@NotBlank(message = "App URL is mandatory") String appUrl,
@NotBlank(message = "Service type is mandatory") String serviceType, @NotBlank(message = "Service type is mandatory") String serviceType,
String username, String username, String password, String apiKey,
String password,
String apiKey,
@JsonProperty(defaultValue = "false") Boolean stayLoggedIn) { @JsonProperty(defaultValue = "false") Boolean stayLoggedIn) {
public ConnectionRequest { public ConnectionRequest {
@@ -18,8 +15,8 @@ public record ConnectionRequest(
} }
} }
public ConnectionRequest(String appUrl, String serviceType, String username, String password, public ConnectionRequest(String appUrl, String serviceType, String username,
Boolean stayLoggedIn) { String password, Boolean stayLoggedIn) {
this(appUrl, serviceType, username, password, null, stayLoggedIn); this(appUrl, serviceType, username, password, null, stayLoggedIn);
} }
} }
@@ -3,10 +3,11 @@ package com.vaessl.app.connection;
import java.time.Instant; import java.time.Instant;
import java.util.Map; import java.util.Map;
public record ConnectionResponse(String token, Instant expiresAt, Map<String, Object> extraResponseData) { public record ConnectionResponse(String token, Instant expiresAt,
Map<String, Object> extraResponseData) {
public String getExtraVar(String key) { public String getExtraVar(String key) {
if(extraResponseData == null) { if (extraResponseData == null) {
return null; return null;
} else { } else {
Object value = extraResponseData.get(key); Object value = extraResponseData.get(key);
@@ -50,13 +50,14 @@ public class ConnectionService {
public ConnectionStatusResponse getConnectionStatus(String serviceType, Long connectionId) { public ConnectionStatusResponse getConnectionStatus(String serviceType, Long connectionId) {
ConnectionEntity entity = cRepository.findById(connectionId).orElse(null); ConnectionEntity entity = cRepository.findById(connectionId).orElse(null);
if (entity == null) return null; if (entity == null)
return null;
ConnectionProvider provider = providerRegistry.get(serviceType); ConnectionProvider provider = providerRegistry.get(serviceType);
Instant expiresAt = (provider != null) ? provider.getTokenExpiry(entity) : null; Instant expiresAt = (provider != null) ? provider.getTokenExpiry(entity) : null;
boolean connected = expiresAt == null || expiresAt.isAfter(Instant.now()); boolean connected = expiresAt == null || expiresAt.isAfter(Instant.now());
return new ConnectionStatusResponse(serviceType, entity.getAppUrl(), return new ConnectionStatusResponse(serviceType, entity.getAppUrl(), entity.getUsername(),
entity.getUsername(), expiresAt, connected); expiresAt, connected);
} }
} }
@@ -2,9 +2,6 @@ package com.vaessl.app.connection;
import java.time.Instant; import java.time.Instant;
public record ConnectionStatusResponse( public record ConnectionStatusResponse(String serviceType, String appUrl, String username,
String serviceType, Instant expiresAt, boolean connected) {
String appUrl, }
String username,
Instant expiresAt,
boolean connected) {}
@@ -1,9 +1,7 @@
package com.vaessl.app.connection; package com.vaessl.app.connection;
public enum Endpoint { public enum Endpoint {
HOMEBOX_LOGIN("/api/v1/users/login"), HOMEBOX_LOGIN("/api/v1/users/login"), LOGIN("/login"), CONNECTION_STATUS("/connections/status");
LOGIN("/login"),
CONNECTION_STATUS("/connections/status");
private final String value; private final String value;
@@ -2,4 +2,5 @@ package com.vaessl.app.connection;
import java.time.Instant; import java.time.Instant;
public record LoginResult(Long connectionId, Instant expiresAt) {} public record LoginResult(Long connectionId, Instant expiresAt) {
}
@@ -8,7 +8,7 @@ public enum ServiceType {
private final String value; private final String value;
private ServiceType(String value){ private ServiceType(String value) {
this.value = value; this.value = value;
} }
} }
@@ -5,11 +5,13 @@ import org.springframework.http.HttpStatus;
import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.annotation.JsonValue;
public enum ErrorMessage { public enum ErrorMessage {
BAD_REQUEST_EMPTY_FIELDS(HttpStatus.BAD_REQUEST, "Fields must not be empty."), UNAUTHORIZED_WRONG_LOGIN( BAD_REQUEST_EMPTY_FIELDS(HttpStatus.BAD_REQUEST,
HttpStatus.UNAUTHORIZED, "Invalid username or password."), SERVICE_UNAVAILABLE_UNREACHABLE_URL( "Fields must not be empty."), UNAUTHORIZED_WRONG_LOGIN(HttpStatus.UNAUTHORIZED,
HttpStatus.SERVICE_UNAVAILABLE, "The target URL is unreachable."), SERVER_ERROR_GENERAL( "Invalid username or password."), SERVICE_UNAVAILABLE_UNREACHABLE_URL(
"The external app returned a server error: "), WRONG_SERVICE_TYPE(HttpStatus.NOT_FOUND, HttpStatus.SERVICE_UNAVAILABLE,
"No such service type."); "The target URL is unreachable."), SERVER_ERROR_GENERAL(
"The external app returned a server error: "), WRONG_SERVICE_TYPE(
HttpStatus.NOT_FOUND, "No such service type.");
private final HttpStatus status; private final HttpStatus status;
private final String message; private final String message;
@@ -19,8 +19,8 @@ public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class) @ExceptionHandler(MethodArgumentNotValidException.class)
public ProblemDetail handleEmptyCredentialInput(MethodArgumentNotValidException e) { public ProblemDetail handleEmptyCredentialInput(MethodArgumentNotValidException e) {
String defaultMessages = e.getBindingResult().getFieldErrors().stream().map(FieldError::getDefaultMessage) String defaultMessages = e.getBindingResult().getFieldErrors().stream()
.collect(Collectors.joining(", ")); .map(FieldError::getDefaultMessage).collect(Collectors.joining(", "));
return ProblemDetail.forStatusAndDetail(BAD_REQUEST_EMPTY_FIELDS.getStatus(), return ProblemDetail.forStatusAndDetail(BAD_REQUEST_EMPTY_FIELDS.getStatus(),
BAD_REQUEST_EMPTY_FIELDS.getMessage() + " [" + defaultMessages + "]"); BAD_REQUEST_EMPTY_FIELDS.getMessage() + " [" + defaultMessages + "]");
@@ -43,14 +43,14 @@ public class GlobalExceptionHandler {
@ExceptionHandler(HttpServerErrorException.class) @ExceptionHandler(HttpServerErrorException.class)
public ProblemDetail handleTimeoutOrNotFound(HttpServerErrorException e) { public ProblemDetail handleTimeoutOrNotFound(HttpServerErrorException e) {
return ProblemDetail return ProblemDetail.forStatusAndDetail(e.getStatusCode(),
.forStatusAndDetail(e.getStatusCode(), SERVER_ERROR_GENERAL.getMessage() + e.getStatusText());
SERVER_ERROR_GENERAL.getMessage() + e.getStatusText());
} }
@ExceptionHandler(WrongServiceTypeException.class) @ExceptionHandler(WrongServiceTypeException.class)
public ProblemDetail handleWrongServiceType(WrongServiceTypeException e) { public ProblemDetail handleWrongServiceType(WrongServiceTypeException e) {
return ProblemDetail.forStatusAndDetail(WRONG_SERVICE_TYPE.getStatus(), WRONG_SERVICE_TYPE.getMessage()); return ProblemDetail.forStatusAndDetail(WRONG_SERVICE_TYPE.getStatus(),
WRONG_SERVICE_TYPE.getMessage());
} }
@ExceptionHandler(EmptyCredentialsException.class) @ExceptionHandler(EmptyCredentialsException.class)
@@ -20,8 +20,7 @@ class ApplicationTests {
private DataSource dataSource; private DataSource dataSource;
@Test @Test
void contextLoads() { void contextLoads() {}
}
@Test @Test
void connectionToTestDbWorks() throws SQLException { void connectionToTestDbWorks() throws SQLException {
@@ -24,134 +24,131 @@ import org.springframework.test.web.servlet.MvcResult;
@WireMockTest @WireMockTest
class ConnectionControllerTest { class ConnectionControllerTest {
@Autowired @Autowired
MockMvc mockMvc; MockMvc mockMvc;
private static final String TEST_USER = "admin"; private static final String TEST_USER = "admin";
private static final String TEST_PASS = "pw"; private static final String TEST_PASS = "pw";
private static final String LOGIN_PATH = LOGIN.getValue(); private static final String LOGIN_PATH = LOGIN.getValue();
private static final String STATUS_PATH = CONNECTION_STATUS.getValue(); private static final String STATUS_PATH = CONNECTION_STATUS.getValue();
private static final String LOGOUT_PATH = "/connections/HOMEBOX"; private static final String LOGOUT_PATH = "/connections/HOMEBOX";
private static final String VALID_HOMEBOX_RESPONSE = """ private static final String VALID_HOMEBOX_RESPONSE = """
{ {
"token": "fake-jwt-token", "token": "fake-jwt-token",
"attachmentToken": "fake-attach", "attachmentToken": "fake-attach",
"expiresAt": "2099-01-01T00:00:00Z" "expiresAt": "2099-01-01T00:00:00Z"
} }
"""; """;
private static final String EXPIRED_HOMEBOX_RESPONSE = """ private static final String EXPIRED_HOMEBOX_RESPONSE = """
{ {
"token": "expired-token", "token": "expired-token",
"attachmentToken": "fake-attach", "attachmentToken": "fake-attach",
"expiresAt": "2000-01-01T00:00:00Z" "expiresAt": "2000-01-01T00:00:00Z"
} }
"""; """;
@Test @Test
void shouldReturnEmptyListWhenNoActiveSession() throws Exception { void shouldReturnEmptyListWhenNoActiveSession() throws Exception {
mockMvc.perform(get(STATUS_PATH)) mockMvc.perform(get(STATUS_PATH)).andExpect(status().isOk())
.andExpect(status().isOk()) .andExpect(content().json("[]"));
.andExpect(content().json("[]")); }
}
@Test @Test
void shouldReturnConnectionStatusWithConnectedTrueAfterLogin(WireMockRuntimeInfo wm) throws Exception { void shouldReturnConnectionStatusWithConnectedTrueAfterLogin(WireMockRuntimeInfo wm)
WireMock.stubFor(WireMock.post(HOMEBOX_LOGIN.getValue()).willReturn(WireMock.okJson(VALID_HOMEBOX_RESPONSE))); throws Exception {
WireMock.stubFor(WireMock.post(HOMEBOX_LOGIN.getValue())
.willReturn(WireMock.okJson(VALID_HOMEBOX_RESPONSE)));
MvcResult loginResult = mockMvc.perform(post(LOGIN_PATH) MvcResult loginResult = mockMvc
.contentType(MediaType.APPLICATION_JSON) .perform(post(LOGIN_PATH).contentType(MediaType.APPLICATION_JSON)
.content(connectionRequestBody(wm))) .content(connectionRequestBody(wm)))
.andExpect(status().isOk()) .andExpect(status().isOk()).andReturn();
.andReturn();
Cookie sessionCookie = loginResult.getResponse().getCookie("SESSION"); Cookie sessionCookie = loginResult.getResponse().getCookie("SESSION");
mockMvc.perform(get(STATUS_PATH).cookie(sessionCookie)) mockMvc.perform(get(STATUS_PATH).cookie(sessionCookie)).andExpect(status().isOk())
.andExpect(status().isOk()) .andExpect(jsonPath("$.length()").value(1))
.andExpect(jsonPath("$.length()").value(1)) .andExpect(jsonPath("$[0].serviceType").value(HOMEBOX.getValue()))
.andExpect(jsonPath("$[0].serviceType").value(HOMEBOX.getValue())) .andExpect(jsonPath("$[0].username").value(TEST_USER))
.andExpect(jsonPath("$[0].username").value(TEST_USER)) .andExpect(jsonPath("$[0].appUrl").value(wm.getHttpBaseUrl()))
.andExpect(jsonPath("$[0].appUrl").value(wm.getHttpBaseUrl())) .andExpect(jsonPath("$[0].connected").value(true));
.andExpect(jsonPath("$[0].connected").value(true)); }
}
@Test @Test
void shouldReturnConnectedFalseWhenStoredTokenIsExpired(WireMockRuntimeInfo wm) throws Exception { void shouldReturnConnectedFalseWhenStoredTokenIsExpired(WireMockRuntimeInfo wm)
WireMock.stubFor(WireMock.post(HOMEBOX_LOGIN.getValue()).willReturn(WireMock.okJson(EXPIRED_HOMEBOX_RESPONSE))); throws Exception {
WireMock.stubFor(WireMock.post(HOMEBOX_LOGIN.getValue())
.willReturn(WireMock.okJson(EXPIRED_HOMEBOX_RESPONSE)));
MvcResult loginResult = mockMvc.perform(post(LOGIN_PATH) MvcResult loginResult = mockMvc
.contentType(MediaType.APPLICATION_JSON) .perform(post(LOGIN_PATH).contentType(MediaType.APPLICATION_JSON)
.content(connectionRequestBody(wm))) .content(connectionRequestBody(wm)))
.andExpect(status().isOk()) .andExpect(status().isOk()).andReturn();
.andReturn();
Cookie sessionCookie = loginResult.getResponse().getCookie("SESSION"); Cookie sessionCookie = loginResult.getResponse().getCookie("SESSION");
mockMvc.perform(get(STATUS_PATH).cookie(sessionCookie)) mockMvc.perform(get(STATUS_PATH).cookie(sessionCookie)).andExpect(status().isOk())
.andExpect(status().isOk()) .andExpect(jsonPath("$[0].serviceType").value(HOMEBOX.getValue()))
.andExpect(jsonPath("$[0].serviceType").value(HOMEBOX.getValue())) .andExpect(jsonPath("$[0].connected").value(false))
.andExpect(jsonPath("$[0].connected").value(false)) .andExpect(jsonPath("$[0].expiresAt")
.andExpect(jsonPath("$[0].expiresAt").value("2000-01-01T00:00:00Z")); .value("2000-01-01T00:00:00Z"));
} }
@Test @Test
void shouldReturn204NoContentOnLogout(WireMockRuntimeInfo wm) throws Exception { void shouldReturn204NoContentOnLogout(WireMockRuntimeInfo wm) throws Exception {
WireMock.stubFor(WireMock.post(HOMEBOX_LOGIN.getValue()).willReturn(WireMock.okJson(VALID_HOMEBOX_RESPONSE))); WireMock.stubFor(WireMock.post(HOMEBOX_LOGIN.getValue())
.willReturn(WireMock.okJson(VALID_HOMEBOX_RESPONSE)));
MvcResult loginResult = mockMvc.perform(post(LOGIN_PATH) MvcResult loginResult = mockMvc
.contentType(MediaType.APPLICATION_JSON) .perform(post(LOGIN_PATH).contentType(MediaType.APPLICATION_JSON)
.content(connectionRequestBody(wm))) .content(connectionRequestBody(wm)))
.andExpect(status().isOk()) .andExpect(status().isOk()).andReturn();
.andReturn();
Cookie sessionCookie = loginResult.getResponse().getCookie("SESSION"); Cookie sessionCookie = loginResult.getResponse().getCookie("SESSION");
mockMvc.perform(delete(LOGOUT_PATH).cookie(sessionCookie)) mockMvc.perform(delete(LOGOUT_PATH).cookie(sessionCookie))
.andExpect(status().isNoContent()); .andExpect(status().isNoContent());
} }
@Test @Test
void shouldReturnEmptyStatusListAfterLogout(WireMockRuntimeInfo wm) throws Exception { void shouldReturnEmptyStatusListAfterLogout(WireMockRuntimeInfo wm) throws Exception {
WireMock.stubFor(WireMock.post(HOMEBOX_LOGIN.getValue()).willReturn(WireMock.okJson(VALID_HOMEBOX_RESPONSE))); WireMock.stubFor(WireMock.post(HOMEBOX_LOGIN.getValue())
.willReturn(WireMock.okJson(VALID_HOMEBOX_RESPONSE)));
MvcResult loginResult = mockMvc.perform(post(LOGIN_PATH) MvcResult loginResult = mockMvc
.contentType(MediaType.APPLICATION_JSON) .perform(post(LOGIN_PATH).contentType(MediaType.APPLICATION_JSON)
.content(connectionRequestBody(wm))) .content(connectionRequestBody(wm)))
.andExpect(status().isOk()) .andExpect(status().isOk()).andReturn();
.andReturn();
Cookie sessionCookie = loginResult.getResponse().getCookie("SESSION"); Cookie sessionCookie = loginResult.getResponse().getCookie("SESSION");
// Verify connected before logout // Verify connected before logout
mockMvc.perform(get(STATUS_PATH).cookie(sessionCookie)) mockMvc.perform(get(STATUS_PATH).cookie(sessionCookie)).andExpect(status().isOk())
.andExpect(status().isOk()) .andExpect(jsonPath("$.length()").value(1));
.andExpect(jsonPath("$.length()").value(1));
mockMvc.perform(delete(LOGOUT_PATH).cookie(sessionCookie)) mockMvc.perform(delete(LOGOUT_PATH).cookie(sessionCookie))
.andExpect(status().isNoContent()); .andExpect(status().isNoContent());
// A new request (no session cookie, as in a fresh browser) returns no connections // A new request (no session cookie, as in a fresh browser) returns no connections
mockMvc.perform(get(STATUS_PATH)) mockMvc.perform(get(STATUS_PATH)).andExpect(status().isOk())
.andExpect(status().isOk()) .andExpect(content().json("[]"));
.andExpect(content().json("[]")); }
}
@Test @Test
void shouldReturn204WhenLogoutCalledWithNoActiveSession() throws Exception { void shouldReturn204WhenLogoutCalledWithNoActiveSession() throws Exception {
mockMvc.perform(delete(LOGOUT_PATH)) mockMvc.perform(delete(LOGOUT_PATH)).andExpect(status().isNoContent());
.andExpect(status().isNoContent()); }
}
private String connectionRequestBody(WireMockRuntimeInfo wm) { private String connectionRequestBody(WireMockRuntimeInfo wm) {
return """ return """
{ {
"appUrl": "%s", "appUrl": "%s",
"serviceType": "HOMEBOX", "serviceType": "HOMEBOX",
"username": "%s", "username": "%s",
"password": "%s" "password": "%s"
} }
""".formatted(wm.getHttpBaseUrl(), TEST_USER, TEST_PASS); """.formatted(wm.getHttpBaseUrl(), TEST_USER, TEST_PASS);
} }
} }
@@ -37,10 +37,11 @@ class ConnectionServiceTest {
@Test @Test
void login_ShouldAbort_WhenCheckCredentialsThrowsException() { void login_ShouldAbort_WhenCheckCredentialsThrowsException() {
ConnectionRequest request = new ConnectionRequest(MOCK_URL, MOCK_SERVICE_TYPE, null, null, false); ConnectionRequest request =
new ConnectionRequest(MOCK_URL, MOCK_SERVICE_TYPE, null, null, false);
doThrow(new EmptyCredentialsException(List.of("username"))) doThrow(new EmptyCredentialsException(List.of("username"))).when(mockProvider)
.when(mockProvider).checkCredentials(request); .checkCredentials(request);
assertThrows(EmptyCredentialsException.class, () -> connectionService.login(request)); assertThrows(EmptyCredentialsException.class, () -> connectionService.login(request));
@@ -52,11 +52,10 @@ class HomeboxIntegrationTest {
@Test @Test
void shouldReturnStatusOkWhenHomeboxCredentialsAreValid(WireMockRuntimeInfo wm) { void shouldReturnStatusOkWhenHomeboxCredentialsAreValid(WireMockRuntimeInfo wm) {
stubFor(post(HOMEBOX_LOGIN.getValue()) stubFor(post(HOMEBOX_LOGIN.getValue()).willReturn(okJson(okJsonHomeboxResponse)));
.willReturn(okJson(okJsonHomeboxResponse)));
ResponseEntity<String> response = restTemplate.postForEntity(LOGIN.getValue(), connectionRequest(wm), ResponseEntity<String> response =
String.class); restTemplate.postForEntity(LOGIN.getValue(), connectionRequest(wm), String.class);
DocumentContext documentContext = JsonPath.parse(response.getBody()); DocumentContext documentContext = JsonPath.parse(response.getBody());
@@ -78,8 +77,8 @@ class HomeboxIntegrationTest {
stubFor(post(HOMEBOX_LOGIN.getValue()).willReturn(unauthorized())); stubFor(post(HOMEBOX_LOGIN.getValue()).willReturn(unauthorized()));
ResponseEntity<String> response = restTemplate.postForEntity(LOGIN.getValue(), connectionRequest(wm), ResponseEntity<String> response =
String.class); restTemplate.postForEntity(LOGIN.getValue(), connectionRequest(wm), String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
assertThat(response.getBody()).contains(UNAUTHORIZED_WRONG_LOGIN.getMessage()); assertThat(response.getBody()).contains(UNAUTHORIZED_WRONG_LOGIN.getMessage());
@@ -95,8 +94,8 @@ class HomeboxIntegrationTest {
stubFor(post(HOMEBOX_LOGIN.getValue()).willReturn(serviceUnavailable())); stubFor(post(HOMEBOX_LOGIN.getValue()).willReturn(serviceUnavailable()));
ResponseEntity<String> response = restTemplate.postForEntity(LOGIN.getValue(), connectionRequest(wm), ResponseEntity<String> response =
String.class); restTemplate.postForEntity(LOGIN.getValue(), connectionRequest(wm), String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
assertThat(response.getBody()).contains(SERVER_ERROR_GENERAL.getMessage()); assertThat(response.getBody()).contains(SERVER_ERROR_GENERAL.getMessage());
@@ -112,7 +111,8 @@ class HomeboxIntegrationTest {
.willReturn(aResponse().withFault(Fault.CONNECTION_RESET_BY_PEER))); .willReturn(aResponse().withFault(Fault.CONNECTION_RESET_BY_PEER)));
ConnectionRequest badRequest = connectionRequest(wm); ConnectionRequest badRequest = connectionRequest(wm);
ResponseEntity<String> response = restTemplate.postForEntity(LOGIN.getValue(), badRequest, String.class); ResponseEntity<String> response =
restTemplate.postForEntity(LOGIN.getValue(), badRequest, String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
assertThat(response.getBody()).contains(SERVICE_UNAVAILABLE_UNREACHABLE_URL.getMessage()); assertThat(response.getBody()).contains(SERVICE_UNAVAILABLE_UNREACHABLE_URL.getMessage());
@@ -126,34 +126,30 @@ class HomeboxIntegrationTest {
ConnectionRequest emtpyRequest = new ConnectionRequest("", "", "", "", false); ConnectionRequest emtpyRequest = new ConnectionRequest("", "", "", "", false);
ResponseEntity<String> response = restTemplate.postForEntity(LOGIN.getValue(), emtpyRequest, String.class); ResponseEntity<String> response =
restTemplate.postForEntity(LOGIN.getValue(), emtpyRequest, String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(response.getBody()).contains(BAD_REQUEST_EMPTY_FIELDS.getMessage()); assertThat(response.getBody()).contains(BAD_REQUEST_EMPTY_FIELDS.getMessage());
} }
/** /**
* Test the exception when there is an input for serviceType but it's * Test the exception when there is an input for serviceType but it's unsupported.
* unsupported.
*/ */
@Test @Test
void shouldReturnWrongServiceTypeException(WireMockRuntimeInfo wm) { void shouldReturnWrongServiceTypeException(WireMockRuntimeInfo wm) {
ConnectionRequest wrongServiceTypeReq = new ConnectionRequest( ConnectionRequest wrongServiceTypeReq = new ConnectionRequest(wm.getHttpBaseUrl(),
wm.getHttpBaseUrl(), "wrong-service-type", TEST_USER, TEST_PASS, false);
"wrong-service-type",
TEST_USER, TEST_PASS,
false);
ResponseEntity<String> response = restTemplate.postForEntity(LOGIN.getValue(), wrongServiceTypeReq, ResponseEntity<String> response =
String.class); restTemplate.postForEntity(LOGIN.getValue(), wrongServiceTypeReq, String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
assertThat(response.getBody()).contains(WRONG_SERVICE_TYPE.getMessage()); assertThat(response.getBody()).contains(WRONG_SERVICE_TYPE.getMessage());
} }
/** /**
* Tests the succesfull persistance of Homebox credential response to the * Tests the succesfull persistance of Homebox credential response to the database.
* database.
* *
* @param wm the WiremockRuntimeInfo object * @param wm the WiremockRuntimeInfo object
*/ */
@@ -165,10 +161,12 @@ class HomeboxIntegrationTest {
ConnectionRequest request = connectionRequest(wm); ConnectionRequest request = connectionRequest(wm);
ResponseEntity<String> response = restTemplate.postForEntity(LOGIN.getValue(), request, String.class); ResponseEntity<String> response =
restTemplate.postForEntity(LOGIN.getValue(), request, String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
ConnectionEntity dbEntry = cRepository.findByAppUrlAndUsername(request.appUrl(), request.username()); ConnectionEntity dbEntry =
cRepository.findByAppUrlAndUsername(request.appUrl(), request.username());
assertThat(dbEntry).isNotNull(); assertThat(dbEntry).isNotNull();
assertThat(dbEntry.getAppUrl()).isEqualTo(request.appUrl()); assertThat(dbEntry.getAppUrl()).isEqualTo(request.appUrl());
@@ -183,20 +181,18 @@ class HomeboxIntegrationTest {
@Test @Test
void shouldReturnEmptyCredentialsExceptionWhenCredsAreMissing(WireMockRuntimeInfo wm) { void shouldReturnEmptyCredentialsExceptionWhenCredsAreMissing(WireMockRuntimeInfo wm) {
ConnectionRequest missingCredentials = new ConnectionRequest(wm.getHttpBaseUrl(), HOMEBOX.getValue(), TEST_USER, ConnectionRequest missingCredentials = new ConnectionRequest(wm.getHttpBaseUrl(),
null, HOMEBOX.getValue(), TEST_USER, null, false);
false);
ResponseEntity<String> response = restTemplate.postForEntity(LOGIN.getValue(), missingCredentials, ResponseEntity<String> response =
String.class); restTemplate.postForEntity(LOGIN.getValue(), missingCredentials, String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(response.getBody()).contains(BAD_REQUEST_EMPTY_FIELDS.getMessage()); assertThat(response.getBody()).contains(BAD_REQUEST_EMPTY_FIELDS.getMessage());
} }
/** /**
* Creates a valid connection request with a mock Api through * Creates a valid connection request with a mock Api through WireMockRuntimeInfo.
* WireMockRuntimeInfo.
* *
* @param wm the WiremockRuntimeInfo object * @param wm the WiremockRuntimeInfo object
* @return a mock api connection request. * @return a mock api connection request.