Skip to content

Commit

Permalink
Improved tests
Browse files Browse the repository at this point in the history
  • Loading branch information
dearrudam committed Mar 23, 2022
1 parent 2c15c26 commit 930656e
Show file tree
Hide file tree
Showing 9 changed files with 160 additions and 29 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,5 @@ nb-configuration.xml

# Local environment
.env

*.pem
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import io.github.arrudalabs.mizudo.model.Usuario;
import io.github.arrudalabs.mizudo.services.GeradorDeHash;
import io.github.arrudalabs.mizudo.validation.DeveSerIdValido;
import io.github.arrudalabs.mizudo.validation.SuportaValidacao;
import io.github.arrudalabs.mizudo.validation.Validacao;

import javax.inject.Inject;
import javax.transaction.Transactional;
Expand All @@ -12,6 +14,7 @@
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import java.util.Objects;

@Path("/membros/{membroId}/user")
public class UsuarioDoMembroResource {
Expand All @@ -29,15 +32,30 @@ public UsuarioRegistrado definirUsuario(
@PathParam("membroId") final Long membroId,
@Valid final NovoUsuario novoUsuario) {

return new UsuarioRegistrado(Usuario.definirUsuario(Membro.findById(membroId),novoUsuario.username,novoUsuario.senha,geradorDeHash));
return new UsuarioRegistrado(Usuario.definirUsuario(Membro.findById(membroId), novoUsuario.username, novoUsuario.senha, geradorDeHash));
}

@SuportaValidacao(
message = "senhas não conferem",
classeValidadora = NovoUsuario.NovoUsuarioValidation.class
)
public record NovoUsuario(@NotBlank
String username,
@NotBlank
String senha,
@NotBlank
String confirmacaoSenha) {
public static class NovoUsuarioValidation implements Validacao {
@Override
public boolean estahValido(Object object) {
if (object instanceof NovoUsuario novoUsuario) {
return Objects.nonNull(novoUsuario)
&& Objects.nonNull(novoUsuario.senha)
&& novoUsuario.senha.equals(novoUsuario.confirmacaoSenha);
}
return false;
}
}
}

public record UsuarioRegistrado(String username, String senha) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,19 @@

import io.quarkus.hibernate.orm.panache.runtime.JpaOperations;

import javax.enterprise.context.ApplicationScoped;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.io.Serializable;
import java.util.Optional;

@ApplicationScoped
public class DeveSerIdValidoValidator implements ConstraintValidator<DeveSerIdValido, Serializable> {

private DeveSerIdValido constraintAnnotation ;
private DeveSerIdValido constraintAnnotation;

@Override
public void initialize(DeveSerIdValido constraintAnnotation) {
ConstraintValidator.super.initialize(constraintAnnotation);
this.constraintAnnotation=(constraintAnnotation);
this.constraintAnnotation = constraintAnnotation;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,14 @@
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.function.Predicate;

@Constraint(validatedBy = SuportaValidacaoValidator.class)
@Target({ElementType.TYPE,ElementType.FIELD,ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface SuportaValidacao {
String message();

Class<? extends Predicate> classeValidadora();
Class<? extends Validacao> classeValidadora();

Class<? extends Payload>[] payload() default {};

Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
package io.github.arrudalabs.mizudo.validation;

import javax.enterprise.context.ApplicationScoped;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.InvocationTargetException;

@ApplicationScoped
public class SuportaValidacaoValidator implements ConstraintValidator<SuportaValidacao, Object> {

private SuportaValidacao constraintAnnotation;

@Override
public void initialize(SuportaValidacao constraintAnnotation) {
ConstraintValidator.super.initialize(constraintAnnotation);
this.constraintAnnotation = constraintAnnotation;
this.constraintAnnotation=constraintAnnotation;
}

@Override
Expand All @@ -22,7 +20,7 @@ public boolean isValid(Object value, ConstraintValidatorContext context) {
return this.constraintAnnotation
.classeValidadora()
.getConstructor(new Class[0])
.newInstance(new Object[0]).test(value);
.newInstance(new Object[0]).estahValido(value);
} catch (IllegalAccessException
| NoSuchMethodException
| InstantiationException
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package io.github.arrudalabs.mizudo.validation;

public interface Validacao {

boolean estahValido(Object object);

}
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,20 @@
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import javax.inject.Inject;
import javax.json.Json;
import javax.ws.rs.core.Response;

import java.util.Map;
import java.util.UUID;
import java.util.stream.Stream;

import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.params.provider.Arguments.arguments;

@QuarkusTest
public class UsuarioDoMembroResourceTest {
Expand Down Expand Up @@ -48,7 +52,7 @@ void deveDefinirUsuarioParaUmMembroValido() {
{
"username": "%s",
"senha": "%s",
"confirmacaoSenha": "%s"
"confirmacaoSenha": "%s"
}
""".formatted(username, senha, senha))
.put("/resources/membros/{id}/user", Map.of("id", membro.id))
Expand All @@ -62,4 +66,97 @@ void deveDefinirUsuarioParaUmMembroValido() {
assertThat("Não foi persistido o usuário do membro com o username informado.", Usuario.buscarPorUsername(username), notNullValue());
}

@ParameterizedTest(name = "{index} - deve retornar HTTP Status 400 - {0}")
@MethodSource("invalidInputs")
void naoDeveDefinirUsuarioParaUmMembroValido(String cenario, String payload) {

var membro = apiTestSupport.executeAndGet(() -> Membro.novoMembro(UUID.randomUUID().toString()));

apiTestSupport
.newAuthenticatedRequest()
.log().everything()
.contentType(ContentType.JSON)
.body(payload)
.put("/resources/membros/{id}/user", Map.of("id", membro.id))
.then()
.log().everything()
.statusCode(Response.Status.BAD_REQUEST.getStatusCode());


}

static Stream<Arguments> invalidInputs(){
return Stream.of(
arguments(
"quando username for omitido",
"""
{
"senha": "abcd",
"confirmacaoSenha": "abcd"
}
"""
),
arguments(
"quando username for vazio",
"""
{
"username": "",
"senha": "abcd",
"confirmacaoSenha": "abcd"
}
"""
),
arguments(
"quando username estiver em branco",
"""
{
"username": " ",
"senha": "abcd",
"confirmacaoSenha": "abcd"
}
"""
),
arguments(
"quando senha for omitida",
"""
{
"username": "ze"
"senha": "abcd",
"confirmacaoSenha": "abcd"
}
"""
),
arguments(
"quando senha estiver vazia",
"""
{
"username": "ze"
"senha": "",
"confirmacaoSenha": ""
}
"""
),
arguments(
"quando senha estiver em branco",
"""
{
"username": " ",
"senha": " ",
"confirmacaoSenha": " "
}
"""
),
arguments(
"quando a senha e confirmacaoSenha não forem iguais",
"""
{
"username": "ze",
"senha": "234234",
"confirmacaoSenha": "fjvdfvfdn"
}
"""
)
);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

import javax.inject.Inject;
import javax.transaction.SystemException;
import javax.validation.Validator;

import java.util.UUID;
import java.util.stream.Stream;
Expand All @@ -26,7 +27,7 @@ class DeveSerIdValidoValidatorTest {
TestSupport testSupport;

@Inject
DeveSerIdValidoValidator validator;
Validator validator;

@Test
@DisplayName("testando isValid() quando o membroId for válido")
Expand All @@ -36,7 +37,7 @@ public void testIsValidWhenMembroIdIsValid() {
}

@AfterEach
public void apagarMembrosCriadosNesteTeste(){
public void apagarMembrosCriadosNesteTeste() {
testSupport.execute(Membro::removerTodosMembros);
}

Expand All @@ -49,7 +50,10 @@ public void testIsValidWhenMembroIdIsInvalid(String cenario,
}

private void testIsValid(Long membroId, boolean ehValido) {
assertThat(validator.isValid(membroId, null), is(ehValido));
assertThat(validator.validate(new DTO(membroId)), ehValido ? empty() : not(empty()));
}

record DTO(@DeveSerIdValido(entityClass = Membro.class, message = "membro inválido") Long membroId) {
}

static Stream<Arguments> testIsValidWhenMembroIdIsInvalidArgs() throws SystemException {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
package io.github.arrudalabs.mizudo.validation;

import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import javax.inject.Inject;
import javax.validation.Validator;
import javax.validation.constraints.NotBlank;

import java.util.Objects;
import java.util.function.Predicate;

import static org.junit.jupiter.api.Assertions.*;

Expand All @@ -19,24 +19,32 @@ class SuportaValidacaoValidatorTest {
Validator validator;

@Test
void test() {
assertFalse(validator.validate(new Pojo(null,"ewrw")).isEmpty());
@DisplayName("o TipoA deveria estar inválido")
void test1() {
assertFalse(validator.validate(new TipoA(null, "ewrw")).isEmpty());
}

@Test
@DisplayName("o TipoA deveria estar válido")
void test2() {
assertTrue(validator.validate(new TipoA("ewrw", "ewrw")).isEmpty());
}


@SuportaValidacao(
message = "Pojo invalido - atributos diferentes",
classeValidadora = Pojo.PojoValidator.class
classeValidadora = TipoA.PojoValidator.class
)
static record Pojo(@NotBlank String atributo1,
@NotBlank String atributo2) {
static record TipoA(@NotBlank String atributo1,
@NotBlank String atributo2) {

public static class PojoValidator implements Predicate<Pojo> {
public static class PojoValidator implements Validacao {

@Override
public boolean test(Pojo o) {
return Objects.nonNull(o)
&& Objects.equals(o.atributo1, o.atributo2);
public boolean estahValido(Object object) {
if(object instanceof TipoA o)
return Objects.equals(o.atributo1, o.atributo2);
return false;
}
}

Expand Down

0 comments on commit 930656e

Please sign in to comment.