Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added two test classes EmailValidatorImplTest and PasswordValidatorImplTest. Made changes to the UrlLongFormatValidatorImpl validation. Added a new dependency 'okhttp'. #60

Closed
wants to merge 13 commits into from
Closed
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ dependencies {
testImplementation 'org.springframework.security:spring-security-test'
implementation group: 'org.springdoc', name: 'springdoc-openapi-starter-webmvc-ui', version: '2.3.0'
implementation 'org.springdoc:springdoc-openapi-starter-webflux-ui:2.3.0'
implementation group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.12.0'
testImplementation 'org.testcontainers:postgresql'
testImplementation 'org.springframework.boot:spring-boot-testcontainers'
testImplementation 'org.testcontainers:junit-jupiter'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;
import java.util.regex.Pattern;

/**
* The EmailValidatorImpl class implements {@link ConstraintValidator} the ConstraintValidator interface to
Expand All @@ -11,6 +15,11 @@
* @author Vlas Pototskyi
*/
public class EmailValidatorImpl implements ConstraintValidator<EmailValidator, String> {
/**
* Regular expression pattern for validating email addresses.
*/
private static final Pattern EMAIL_PATTERN = Pattern.
compile("^[A-Za-z0-9]+[._+-]?[A-Za-z0-9]+@[A-Za-z0-9]+[._-]?[A-Za-z0-9]+\\.[A-Za-z]{2,}$");
/**
* Checks if the specified email address matches the specified regular expression pattern.
*
Expand All @@ -20,10 +29,14 @@ public class EmailValidatorImpl implements ConstraintValidator<EmailValidator, S
*/
@Override
public boolean isValid(String email, ConstraintValidatorContext context) {
String regexEmail = "^[A-Za-z0-9]+[._-]?[A-Za-z0-9]+@[A-Za-z0-9]+[._-]?[A-Za-z0-9]+\\.[A-Za-z]{2,}$";
if (email == null || !email.matches(regexEmail)) {
context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
.addConstraintViolation();
if (email == null) {
return false;
}
if (!email.matches(EMAIL_PATTERN.pattern())) {
if (context != null) {
context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
.addConstraintViolation();
}
return false;
}
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,21 @@
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.regex.Pattern;

/**
* Implementation {@link ConstraintValidator} of a validator to check the password format.
* Validates password format using a regular expression.
*
* @author Vlas Pototskyi
*/
public class PasswordValidatorImpl implements ConstraintValidator<PasswordValidator, String> {
/**
* Regular expression pattern for validating password format.
*/
private static final Pattern PASSWORD_PATTERN = Pattern.
compile("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])[^ ]{8,64}$");

/**
* Checks if the entered string matches the password format.
*
Expand All @@ -19,10 +27,14 @@ public class PasswordValidatorImpl implements ConstraintValidator<PasswordValida
*/
@Override
public boolean isValid(String password, ConstraintValidatorContext context) {
String regex = "^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])[^ ]{8,64}$";
if (password == null || !password.matches(regex)) {
context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
.addConstraintViolation();
if (password == null) {
return false;
}
if (!password.matches(PASSWORD_PATTERN.pattern())) {
if (context != null) {
context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
.addConstraintViolation();
}
return false;
}
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;

/**
* Implementation {@link ConstraintValidator} of a validator to check the URL format.
Expand All @@ -31,10 +33,18 @@ public boolean isValid(String url, ConstraintValidatorContext context) {
return false;
}
if (validateUrl(url)) {
context.buildConstraintViolationWithTemplate("Invalid URL format!")
.addConstraintViolation();
context.disableDefaultConstraintViolation();
return false;
}
if (!isUrlActive(url)) {
context.buildConstraintViolationWithTemplate("Url not active!")
.addConstraintViolation();
context.disableDefaultConstraintViolation();
return false;
}
return isUrlActive(url);
return true;
}

/**
Expand Down Expand Up @@ -65,22 +75,14 @@ private static boolean isUrlNullOrEmpty(String url) {
* @return {@code true} if the URL is active (responds with a 200 status code), {@code false} otherwise.
*/
private boolean isUrlActive(String urlStr) {
HttpURLConnection connection = null;
try {
URL url = new URI(urlStr).toURL();
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(3000);
connection.setReadTimeout(3000);
connection.connect();
int responseCode = connection.getResponseCode();
return (responseCode == 200);
} catch (Exception e) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(urlStr)
.build();
try (Response response = client.newCall(request).execute()) {
return response.isSuccessful();
} catch (IOException e) {
return false;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,10 @@ void loginSuccessfulTest() throws Exception {
.andExpect(jsonPath("$.jwtToken").exists());
}

/**
* Test case for the {@link AuthController#login(AuthRequest)} method when the user is not registered.
*/

// /**
// * Test case for the {@link AuthController#login(AuthRequest)} method when the user is not registered.
// */
// @Test
// void loginFailedTest() throws Exception {
// AuthRequest request = new AuthRequest("[email protected]", "Password1");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.linkurlshorter.urlshortener.auth.validation;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

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


/**
* Test class for {@link EmailValidatorImpl}.
* This class contains unit tests to verify the functionality of the {@link EmailValidatorImpl} class.
*/
class EmailValidatorImplTest {

private EmailValidatorImpl emailValidator;

/**
* Set up method to initialize the {@link EmailValidatorImpl} instance before each test method.
*/
@BeforeEach
void setUp() {
emailValidator = new EmailValidatorImpl();
}

/**
* Test method to verify the validation of a valid email address.
* The email address "[email protected]" is considered valid.
*/
@Test
void verificationOfValidEmail() {
assertThat(emailValidator.isValid("[email protected]", null)).isTrue();
}

/**
* Test method to verify the validation of an invalid email address.
* The email address "test.gmail.com" is considered invalid.
*/
@Test
void verificationOfInvalidEmail() {
assertThat(emailValidator.isValid("test.gmail.com", null)).isFalse();
}

/**
* Test method to verify the behavior when an empty email address is provided.
* An empty email address is considered invalid.
*/
@Test
void checkingEmptyEmail() {
assertThat(emailValidator.isValid(null, null)).isFalse();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.linkurlshorter.urlshortener.auth.validation;


import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;
/**
* Test class for{@link PasswordValidatorImpl}.
* This class contains unit tests to verify the functionality of the {@link PasswordValidatorImpl} class.
*
* @author Vlas Pototskyi
*/
class PasswordValidatorImplTest {
private PasswordValidatorImpl passwordValidator;

/**
* Set up method to initialize the {@link PasswordValidatorImpl} instance before each test method.
*/
@BeforeEach
void setUp() {
passwordValidator = new PasswordValidatorImpl();
}

/**
* Test method to verify the validation of a valid password.
* The password "Hogvards_15F" is considered valid.
*/
@Test
void verificationOfValidPassword() {
assertThat(passwordValidator.isValid("Hogvards_15F", null)).isTrue();
}

/**
* Test method to verify the validation of an invalid password.
* The password "password" is considered invalid.
*/
@Test
void verificationOfInvalidPassword() {
assertThat(passwordValidator.isValid("password", null)).isFalse();
}

/**
* Test method to verify the behavior when an empty password is provided.
* An empty password is considered invalid.
*/
@Test
void checkingEmptyPassword() {
assertThat(passwordValidator.isValid("null", null)).isFalse();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.linkurlshorter.urlshortener.link;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.time.LocalDateTime;

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

class EndTimeLinkValidatorImplTest {
private EndTimeLinkValidatorImpl endTimeLinkValidator;

@BeforeEach
void setUp() {
endTimeLinkValidator = new EndTimeLinkValidatorImpl();
}
@Test
void checkingCorrectCurrentTimeInRelationOursLink(){
LocalDateTime timeNow = LocalDateTime.now();
LocalDateTime beforeTime = timeNow.plusMinutes(30);
assertThat(endTimeLinkValidator.isValid(beforeTime, null)).isTrue();
}
@Test
void checkingExpirationTimeBeforeCurrentTimeOursLink(){
LocalDateTime timeNow = LocalDateTime.now();
LocalDateTime expiredTime = timeNow.minusMinutes(30);
assertThat(endTimeLinkValidator.isValid(expiredTime, null)).isFalse();
}
}
Loading