You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@bval.apache.org by rm...@apache.org on 2013/08/26 15:59:20 UTC
svn commit: r1517540 [12/15] - in /bval/branches/bval-11/bval-jsr: ./ src/
src/main/ src/main/appended-resources/
src/main/appended-resources/META-INF/ src/main/java/ src/main/java/org/
src/main/java/org/apache/ src/main/java/org/apache/bval/ src/main/...
Added: bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/ComposedConstraintsTest.java
URL: http://svn.apache.org/viewvc/bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/ComposedConstraintsTest.java?rev=1517540&view=auto
==============================================================================
--- bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/ComposedConstraintsTest.java (added)
+++ bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/ComposedConstraintsTest.java Mon Aug 26 13:59:15 2013
@@ -0,0 +1,131 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.apache.bval.jsr;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
+import org.apache.bval.jsr.example.CompanyAddress;
+import org.apache.bval.jsr.example.FrenchAddress;
+import org.apache.bval.jsr.util.TestUtils;
+
+import javax.validation.ConstraintViolation;
+import javax.validation.Validation;
+import javax.validation.Validator;
+import javax.validation.ValidatorFactory;
+import javax.validation.constraints.Size;
+import javax.validation.metadata.ConstraintDescriptor;
+import javax.validation.metadata.ElementDescriptor;
+import java.util.Locale;
+import java.util.Set;
+
+/**
+ * Description: <br/>
+ */
+public class ComposedConstraintsTest extends TestCase {
+ static ValidatorFactory factory;
+
+ static {
+ factory = Validation.buildDefaultValidatorFactory();
+ ((DefaultMessageInterpolator) factory.getMessageInterpolator()).setLocale(Locale.ENGLISH);
+ }
+
+ /**
+ * Validator instance to test
+ */
+ protected Validator validator;
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ validator = createValidator();
+ }
+
+ /**
+ * Create the validator instance.
+ *
+ * @return Validator
+ */
+ protected Validator createValidator() {
+ return factory.getValidator();
+ }
+
+ public void testMetaDataAPI_ComposedConstraints() {
+ ElementDescriptor ed =
+ validator.getConstraintsForClass(FrenchAddress.class)
+ .getConstraintsForProperty("zipCode");
+ Assert.assertEquals(1, ed.getConstraintDescriptors().size());
+ for (ConstraintDescriptor<?> cd : ed.getConstraintDescriptors()) {
+ Assert.assertTrue(cd.isReportAsSingleViolation());
+ Assert.assertEquals(3, cd.getComposingConstraints().size());
+ Assert.assertTrue("no composing constraints found!!",
+ !cd.getComposingConstraints().isEmpty());
+ processConstraintDescriptor(cd); //check all constraints on zip code
+ }
+ }
+
+ public void processConstraintDescriptor(ConstraintDescriptor<?> cd) {
+ //Size.class is understood by the tool
+ if (cd.getAnnotation().annotationType().equals(Size.class)) {
+ @SuppressWarnings("unused")
+ Size m = (Size) cd.getAnnotation();//what for?
+ }
+ for (ConstraintDescriptor<?> composingCd : cd.getComposingConstraints()) {
+ //check composing constraints recursively
+ processConstraintDescriptor(composingCd);
+ }
+ }
+
+ public void testValidateComposed() {
+ FrenchAddress adr = new FrenchAddress();
+ Set<ConstraintViolation<FrenchAddress>> findings = validator.validate(adr);
+ Assert.assertEquals(1, findings.size()); // with @ReportAsSingleConstraintViolation
+
+ ConstraintViolation<FrenchAddress> finding = findings.iterator().next();
+ Assert.assertEquals("Wrong zipcode", finding.getMessage());
+
+ adr.setZipCode("1234567");
+ findings = validator.validate(adr);
+ Assert.assertEquals(0, findings.size());
+
+ adr.setZipCode("1234567234567");
+ findings = validator.validate(adr);
+ Assert.assertTrue(findings.size() > 0); // too long
+ }
+
+ public void testOverridesAttributeConstraintIndex() {
+ CompanyAddress adr = new CompanyAddress("invalid-string");
+ Set<ConstraintViolation<CompanyAddress>> findings = validator.validate(adr);
+ assertEquals(2, findings.size()); // without @ReportAsSingleConstraintViolation
+ assertNotNull(TestUtils.getViolationWithMessage(findings, "Not COMPANY"));
+ assertNotNull(TestUtils.getViolationWithMessage(findings, "Not an email"));
+
+ adr = new CompanyAddress("JOHN_DO@WEB.DE");
+ findings = validator.validate(adr);
+ assertEquals(1, findings.size());
+ assertNotNull(TestUtils.getViolationWithMessage(findings, "Not COMPANY"));
+
+ adr = new CompanyAddress("JOHN_DO@COMPANY.DE");
+ findings = validator.validate(adr);
+ Assert.assertTrue(findings.isEmpty());
+ }
+
+}
Added: bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/ConstraintCompositionTest.java
URL: http://svn.apache.org/viewvc/bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/ConstraintCompositionTest.java?rev=1517540&view=auto
==============================================================================
--- bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/ConstraintCompositionTest.java (added)
+++ bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/ConstraintCompositionTest.java Mon Aug 26 13:59:15 2013
@@ -0,0 +1,305 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.apache.bval.jsr;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
+
+import javax.validation.Constraint;
+import javax.validation.ConstraintViolation;
+import javax.validation.OverridesAttribute;
+import javax.validation.Payload;
+import javax.validation.ReportAsSingleViolation;
+import javax.validation.Validation;
+import javax.validation.Validator;
+import javax.validation.ValidatorFactory;
+import javax.validation.constraints.NotNull;
+import javax.validation.constraints.Pattern;
+import javax.validation.constraints.Size;
+import javax.validation.metadata.ConstraintDescriptor;
+import java.lang.annotation.Annotation;
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+import java.util.Locale;
+import java.util.Set;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+/**
+ * Checks that groups are correctly inherited from the root constraint to its
+ * compositing constraints.
+ *
+ * @author Carlos Vara
+ */
+public class ConstraintCompositionTest extends TestCase {
+ static ValidatorFactory factory;
+
+ static {
+ factory = Validation.buildDefaultValidatorFactory();
+ ((DefaultMessageInterpolator) factory.getMessageInterpolator()).setLocale(Locale.ENGLISH);
+ }
+
+ /**
+ * Validator instance to test
+ */
+ protected Validator validator;
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ validator = createValidator();
+ }
+
+ /**
+ * Create the validator instance.
+ *
+ * @return Validator
+ */
+ protected Validator createValidator() {
+ return factory.getValidator();
+ }
+
+ /**
+ * Check correct group inheritance on constraint composition on a 1 level
+ * hierarchy.
+ */
+ public void test1LevelInheritance() {
+ Set<ConstraintViolation<Person>> violations = validator.validate(new Person());
+
+ Assert.assertEquals("Wrong number of violations detected", 1, violations.size());
+ String msg = violations.iterator().next().getMessage();
+ Assert.assertEquals("Incorrect violation message", "A person needs a non null name", msg);
+
+ violations = validator.validate(new Person(), Group1.class);
+ Assert.assertEquals("Wrong number of violations detected", 0, violations.size());
+ }
+
+ /**
+ * Check correct group inheritance on constraint composition on a 2 level
+ * hierarchy.
+ */
+ public void test2LevelInheritance() {
+ Set<ConstraintViolation<Man>> violations = validator.validate(new Man());
+
+ Assert.assertEquals("Wrong number of violations detected", 0, violations.size());
+
+ violations = validator.validate(new Man(), Group1.class);
+ Assert.assertEquals("Wrong number of violations detected", 1, violations.size());
+ String msg = violations.iterator().next().getMessage();
+ Assert.assertEquals("Incorrect violation message", "A person needs a non null name", msg);
+ }
+
+ /**
+ * Checks that the groups() value of the constraint annotations are
+ * correctly set to the inherited ones.
+ */
+ public void testAnnotationGroupsAreInherited() {
+ // Check that the groups() value is right when querying the metadata
+ ConstraintDescriptor<?> manNameDesc =
+ validator.getConstraintsForClass(Man.class).getConstraintsForProperty("name").getConstraintDescriptors()
+ .iterator().next();
+ ConstraintDescriptor<?> personNameDesc = manNameDesc.getComposingConstraints().iterator().next();
+ ConstraintDescriptor<?> notNullDesc = personNameDesc.getComposingConstraints().iterator().next();
+ Assert.assertEquals("There should only be 1 group", 1, manNameDesc.getGroups().size());
+ Assert.assertTrue("Group1 should be present", manNameDesc.getGroups().contains(Group1.class));
+ Assert.assertEquals("There should only be 1 group", 1, personNameDesc.getGroups().size());
+ Assert.assertTrue("Group1 should be present", personNameDesc.getGroups().contains(Group1.class));
+ Assert.assertEquals("There should only be 1 group", 1, personNameDesc.getGroups().size());
+ Assert.assertTrue("Group1 should be present", notNullDesc.getGroups().contains(Group1.class));
+
+ // Check that the groups() value is right when accessing it from an
+ // error
+ Set<ConstraintViolation<Man>> violations = validator.validate(new Man(), Group1.class);
+ Set<Class<?>> notNullGroups = violations.iterator().next().getConstraintDescriptor().getGroups();
+ Assert.assertEquals("There should only be 1 group", 1, notNullGroups.size());
+ Assert.assertTrue("Group1 should be the only group", notNullGroups.contains(Group1.class));
+ }
+
+ /**
+ * Checks that the payload() value of the constraint annotations are
+ * correctly set to the inherited ones.
+ */
+ public void testAnnotationPayloadsAreInherited() {
+ // Check that the payload() value is right when querying the metadata
+ ConstraintDescriptor<?> manNameDesc =
+ validator.getConstraintsForClass(Man.class).getConstraintsForProperty("name").getConstraintDescriptors()
+ .iterator().next();
+ ConstraintDescriptor<?> personNameDesc = manNameDesc.getComposingConstraints().iterator().next();
+ ConstraintDescriptor<?> notNullDesc = personNameDesc.getComposingConstraints().iterator().next();
+ Assert.assertEquals("There should only be 1 payload class", 1, manNameDesc.getPayload().size());
+ Assert.assertTrue("Payload1 should be present", manNameDesc.getPayload().contains(Payload1.class));
+ Assert.assertEquals("There should only be 1 payload class", 1, personNameDesc.getPayload().size());
+ Assert.assertTrue("Payload1 should be present", personNameDesc.getPayload().contains(Payload1.class));
+ Assert.assertEquals("There should only be 1 payload class", 1, personNameDesc.getPayload().size());
+ Assert.assertTrue("Payload1 should be present", notNullDesc.getPayload().contains(Payload1.class));
+
+ // Check that the payload() value is right when accessing it from an
+ // error
+ Set<ConstraintViolation<Man>> violations = validator.validate(new Man(), Group1.class);
+ Set<Class<? extends Payload>> notNullPayload =
+ violations.iterator().next().getConstraintDescriptor().getPayload();
+ Assert.assertEquals("There should only be 1 payload class", 1, notNullPayload.size());
+ Assert.assertTrue("Payload1 should be the only payload", notNullPayload.contains(Payload1.class));
+ }
+
+ /**
+ * Checks that {@link OverridesAttribute#constraintIndex()} parsing and
+ * applying works.
+ */
+ public void testIndexedOverridesAttributes() {
+ Person p = new Person();
+ p.name = "valid";
+
+ // With a valid id, no errors expected
+ p.id = "1234";
+ Set<ConstraintViolation<Person>> constraintViolations = validator.validate(p);
+ Assert.assertTrue("No violations should be reported on valid id", constraintViolations.isEmpty());
+
+ // With a short id, only 1 error expected
+ p.id = "1";
+ constraintViolations = validator.validate(p);
+ Assert.assertEquals("Only 1 violation expected", 1, constraintViolations.size());
+ ConstraintViolation<Person> violation = constraintViolations.iterator().next();
+ Assert.assertEquals("Wrong violation", "Id is too short", violation.getMessage());
+
+ // With a long id, only 1 error expected
+ p.id = "loooooong id";
+ constraintViolations = validator.validate(p);
+ Assert.assertEquals("Only 1 violation expected", 1, constraintViolations.size());
+ violation = constraintViolations.iterator().next();
+ Assert.assertEquals("Wrong violation", "Id is too long", violation.getMessage());
+ }
+
+ /**
+ * Checks that errors are reported correctly when using
+ * {@link ReportAsSingleViolation}.
+ */
+ public void testReportAsAsingleViolation() {
+ Code c = new Code();
+ c.code = "very invalid code";
+ Set<ConstraintViolation<Code>> constraintViolations = validator.validate(c);
+
+ // Only 1 error expected
+ Assert.assertEquals("Only 1 violation expected", 1, constraintViolations.size());
+ ConstraintViolation<Code> violation = constraintViolations.iterator().next();
+ Assert.assertEquals("Wrong violation message", "Invalid code", violation.getMessage());
+ Assert.assertEquals("Wrong violation type", ElevenDigitsCode.class, ((Annotation) violation
+ .getConstraintDescriptor().getAnnotation()).annotationType());
+ }
+
+ public static class Person {
+ @PersonName
+ String name;
+
+ @PersonId
+ String id;
+ }
+
+ public static class Man {
+ @ManName(groups = { Group1.class }, payload = { Payload1.class })
+ String name;
+ }
+
+ public static class Code {
+ @ElevenDigitsCode
+ String code;
+ }
+
+ @NotNull(message = "A person needs a non null name", groups = { Group1.class }, payload = {})
+ @Constraint(validatedBy = {})
+ @Documented
+ @Target( { METHOD, FIELD, TYPE })
+ @Retention(RUNTIME)
+ public static @interface PersonName {
+ String message() default "Wrong person name";
+
+ Class<?>[] groups() default {};
+
+ Class<? extends Payload>[] payload() default {};
+ }
+
+ @PersonName(groups = { Group2.class }, payload = { Payload1.class, Payload2.class })
+ @Constraint(validatedBy = {})
+ @Documented
+ @Target( { METHOD, FIELD, TYPE })
+ @Retention(RUNTIME)
+ public static @interface ManName {
+ String message() default "Wrong man name";
+
+ Class<?>[] groups() default {};
+
+ Class<? extends Payload>[] payload() default {};
+ }
+
+ @Size.List( { @Size(min = 3, max = 3, message = "Id is too short"),
+ @Size(min = 5, max = 5, message = "Id is too long") })
+ @Constraint(validatedBy = {})
+ @Documented
+ @Target( { METHOD, FIELD, TYPE })
+ @Retention(RUNTIME)
+ public static @interface PersonId {
+ String message() default "Wrong person id";
+
+ Class<?>[] groups() default {};
+
+ Class<? extends Payload>[] payload() default {};
+
+ @OverridesAttribute(constraint = Size.class, constraintIndex = 0, name = "max")
+ int maxSize() default 1000;
+
+ @OverridesAttribute(constraint = Size.class, constraintIndex = 1, name = "min")
+ int minSize() default 0;
+ }
+
+ @Size(min = 11, max = 11)
+ @Pattern(regexp = "\\d*")
+ @Constraint(validatedBy = {})
+ @ReportAsSingleViolation
+ @Documented
+ @Target( { METHOD, FIELD, TYPE })
+ @Retention(RUNTIME)
+ public static @interface ElevenDigitsCode {
+ String message() default "Invalid code";
+
+ Class<?>[] groups() default {};
+
+ Class<? extends Payload>[] payload() default {};
+ }
+
+ public static interface Group1 {
+ }
+
+ public static interface Group2 {
+ }
+
+ public static class Payload1 implements Payload {
+ }
+
+ public static class Payload2 implements Payload {
+ }
+
+}
Added: bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/ConstraintDefinitionsTest.java
URL: http://svn.apache.org/viewvc/bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/ConstraintDefinitionsTest.java?rev=1517540&view=auto
==============================================================================
--- bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/ConstraintDefinitionsTest.java (added)
+++ bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/ConstraintDefinitionsTest.java Mon Aug 26 13:59:15 2013
@@ -0,0 +1,320 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.apache.bval.jsr;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
+import org.apache.bval.constraints.NotNullValidator;
+
+import javax.validation.Constraint;
+import javax.validation.ConstraintDefinitionException;
+import javax.validation.Payload;
+import javax.validation.Validation;
+import javax.validation.Validator;
+import javax.validation.ValidatorFactory;
+import javax.validation.constraints.Min;
+import javax.validation.metadata.BeanDescriptor;
+import javax.validation.metadata.ConstraintDescriptor;
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+import java.util.Locale;
+import java.util.Set;
+
+import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+/**
+ * Checks the correct parsing of constraint definitions.
+ *
+ * @author Carlos Vara
+ */
+public class ConstraintDefinitionsTest extends TestCase {
+ static ValidatorFactory factory;
+
+ static {
+ factory = Validation.buildDefaultValidatorFactory();
+ ((DefaultMessageInterpolator) factory.getMessageInterpolator()).setLocale(Locale.ENGLISH);
+ }
+
+ /**
+ * Validator instance to test
+ */
+ protected Validator validator;
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ validator = createValidator();
+ }
+
+ /**
+ * Create the validator instance.
+ *
+ * @return Validator
+ */
+ protected Validator createValidator() {
+ return factory.getValidator();
+ }
+
+ /**
+ * Checks the correct parsing of a constraint with an array of constraints
+ * as attributes.
+ */
+ public void testCustomAttributes() {
+ BeanDescriptor constraints = validator.getConstraintsForClass(Person.class);
+ Set<ConstraintDescriptor<?>> ageConstraints =
+ constraints.getConstraintsForProperty("age").getConstraintDescriptors();
+
+ Assert.assertEquals("There should be 2 constraints in 'age'", ageConstraints.size(), 2);
+ for (ConstraintDescriptor<?> cd : ageConstraints) {
+ Assert.assertEquals("Annotation should be @Min", cd.getAnnotation().annotationType().getName(), Min.class
+ .getName());
+ }
+ }
+
+ /**
+ * Checks that a {@link ConstraintDefinitionException} is thrown when
+ * parsing a constraint definition with no <code>groups()</code> method.
+ */
+ public void testNoGroupsConstraint() {
+ try {
+ validator.validate(new NoGroups());
+ fail("No exception thrown when parsing a constraint definition with no groups() method");
+ } catch (ConstraintDefinitionException e) {
+ // correct
+ }
+ }
+
+ /**
+ * Checks that a {@link ConstraintDefinitionException} is thrown when
+ * parsing a constraint definition with an invalid <code>groups()</code>
+ * method.
+ */
+ public void testInvalidDefaultGroupsConstraint() {
+ try {
+ validator.validate(new InvalidGroups());
+ fail("No exception thrown when parsing a constraint definition with a groups() method does not return Class[]");
+ } catch (ConstraintDefinitionException e) {
+ // correct
+ }
+ }
+
+ /**
+ * Checks that a {@link ConstraintDefinitionException} is thrown when
+ * parsing a constraint definition with no <code>payload()</code> method.
+ */
+ public void testNoPayloadConstraint() {
+ try {
+ validator.validate(new NoPayload());
+ fail("No exception thrown when parsing a constraint definition with no payload() method");
+ } catch (ConstraintDefinitionException e) {
+ // correct
+ }
+ }
+
+ /**
+ * Checks that a {@link ConstraintDefinitionException} is thrown when
+ * parsing a constraint definition with an invalid <code>payload()</code>
+ * method.
+ */
+ public void testInvalidDefaultPayloadConstraint() {
+ try {
+ validator.validate(new InvalidPayload());
+ fail("No exception thrown when parsing a constraint definition with a payload() method does not return an empty array");
+ } catch (ConstraintDefinitionException e) {
+ // correct
+ }
+ }
+
+ /**
+ * Checks that a {@link ConstraintDefinitionException} is thrown when
+ * parsing a constraint definition with no <code>message()</code> method.
+ */
+ public void testNoMessageConstraint() {
+ try {
+ validator.validate(new NoMessage());
+ fail("No exception thrown when parsing a constraint definition with no payload() method");
+ } catch (ConstraintDefinitionException e) {
+ // correct
+ }
+ }
+
+ /**
+ * Checks that a {@link ConstraintDefinitionException} is thrown when
+ * parsing a constraint definition with an invalid <code>message()</code>
+ * method.
+ */
+ public void testInvalidDefaultMessageConstraint() {
+ try {
+ validator.validate(new InvalidMessage());
+ fail("No exception thrown when parsing a constraint definition with a message() method does not return a String");
+ } catch (ConstraintDefinitionException e) {
+ // correct
+ }
+ }
+
+ /**
+ * Checks that a {@link ConstraintDefinitionException} is thrown when
+ * parsing a constraint definition with a method starting with 'valid'.
+ */
+ public void testInvalidAttributeConstraint() {
+ try {
+ validator.validate(new InvalidAttribute());
+ fail("No exception thrown when parsing a constraint definition with a method starting with 'valid'");
+ } catch (ConstraintDefinitionException e) {
+ // correct
+ }
+ }
+
+ public static class Person {
+ @MinList( { @Min(value = 20), @Min(value = 30) })
+ public Integer age;
+ }
+
+ @Target( { METHOD, FIELD, ANNOTATION_TYPE })
+ @Retention(RUNTIME)
+ @Documented
+ public static @interface MinList {
+ Min[] value();
+ }
+
+ public static class NoGroups {
+ @NoGroupsConstraint
+ public String prop;
+ }
+
+ @Target( { METHOD, FIELD, ANNOTATION_TYPE })
+ @Retention(RUNTIME)
+ @Documented
+ @Constraint(validatedBy = { NotNullValidator.class })
+ public static @interface NoGroupsConstraint {
+ String message() default "def msg";
+
+ Class<? extends Payload>[] payload() default {};
+ }
+
+ public static class InvalidGroups {
+ @InvalidGroupsConstraint
+ public String prop;
+ }
+
+ @Target( { METHOD, FIELD, ANNOTATION_TYPE })
+ @Retention(RUNTIME)
+ @Documented
+ @Constraint(validatedBy = { NotNullValidator.class })
+ public static @interface InvalidGroupsConstraint {
+ String message() default "def msg";
+
+ String[] groups() default { "Group1" };
+
+ Class<? extends Payload>[] payload() default {};
+ }
+
+ public static class NoPayload {
+ @NoPayloadConstraint
+ public String prop;
+ }
+
+ @Target( { METHOD, FIELD, ANNOTATION_TYPE })
+ @Retention(RUNTIME)
+ @Documented
+ @Constraint(validatedBy = { NotNullValidator.class })
+ public static @interface NoPayloadConstraint {
+ String message() default "def msg";
+
+ String[] groups() default {};
+ }
+
+ public static class InvalidPayload {
+ @InvalidPayloadConstraint
+ public String prop;
+ }
+
+ @Target( { METHOD, FIELD, ANNOTATION_TYPE })
+ @Retention(RUNTIME)
+ @Documented
+ @Constraint(validatedBy = { NotNullValidator.class })
+ public static @interface InvalidPayloadConstraint {
+ String message() default "def msg";
+
+ String[] groups() default {};
+
+ Class<? extends Payload>[] payload() default { Payload1.class };
+
+ public static class Payload1 implements Payload {
+ }
+ }
+
+ public static class NoMessage {
+ @NoMessageConstraint
+ public String prop;
+ }
+
+ @Target( { METHOD, FIELD, ANNOTATION_TYPE })
+ @Retention(RUNTIME)
+ @Documented
+ @Constraint(validatedBy = { NotNullValidator.class })
+ public static @interface NoMessageConstraint {
+ String[] groups() default {};
+
+ Class<? extends Payload>[] payload() default {};
+ }
+
+ public static class InvalidMessage {
+ @InvalidMessageConstraint(message = 2)
+ public String prop;
+ }
+
+ @Target( { METHOD, FIELD, ANNOTATION_TYPE })
+ @Retention(RUNTIME)
+ @Documented
+ @Constraint(validatedBy = { NotNullValidator.class })
+ public static @interface InvalidMessageConstraint {
+ int message();
+
+ String[] groups() default {};
+
+ Class<? extends Payload>[] payload() default {};
+ }
+
+ public static class InvalidAttribute {
+ @InvalidAttributeConstraint
+ public String prop;
+ }
+
+ @Target( { METHOD, FIELD, ANNOTATION_TYPE })
+ @Retention(RUNTIME)
+ @Documented
+ @Constraint(validatedBy = { NotNullValidator.class })
+ public static @interface InvalidAttributeConstraint {
+ String message() default "def msg";
+
+ String[] groups() default {};
+
+ Class<? extends Payload>[] payload() default {};
+
+ String validValue() default "1";
+ }
+}
Added: bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/ConstraintValidatorContextTest.java
URL: http://svn.apache.org/viewvc/bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/ConstraintValidatorContextTest.java?rev=1517540&view=auto
==============================================================================
--- bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/ConstraintValidatorContextTest.java (added)
+++ bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/ConstraintValidatorContextTest.java Mon Aug 26 13:59:15 2013
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.apache.bval.jsr;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
+import org.apache.bval.jsr.util.PathImpl;
+import org.apache.bval.model.ValidationListener;
+import org.apache.bval.model.ValidationListener.Error;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+import javax.validation.ConstraintValidatorContext;
+import javax.validation.ConstraintValidatorContext.ConstraintViolationBuilder;
+
+/**
+ * Checks to validate the correct implementation of
+ * {@link ConstraintValidatorContext} and its sub-interfaces.
+ *
+ * @author Carlos Vara
+ */
+public class ConstraintValidatorContextTest extends TestCase {
+
+ private ConstraintValidatorContextImpl cvc;
+ private ConstraintViolationBuilder cvb;
+
+ @Mock
+ private GroupValidationContext<ValidationListener> groupValidationContext;
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ MockitoAnnotations.initMocks(this);
+ Mockito.when(groupValidationContext.getPropertyPath()).thenAnswer(new Answer<PathImpl>() {
+
+ public PathImpl answer(InvocationOnMock invocation) throws Throwable {
+ return PathImpl.createPathFromString("");
+ }
+ });
+ this.cvc = new ConstraintValidatorContextImpl(groupValidationContext,
+ null);
+ this.cvc.disableDefaultConstraintViolation();
+ this.cvb = cvc.buildConstraintViolationWithTemplate("dummy.msg.tpl");
+ }
+
+ public void testPerson1() {
+ cvb.addNode("person").addNode(null).inIterable().atIndex(1).addConstraintViolation();
+ final Error error = cvc.getErrorMessages().iterator().next();
+ final PathImpl errorPath = (PathImpl) error.getOwner();
+ Assert.assertEquals("Incorrect path created", "person[1]", errorPath.toString());
+ }
+
+ public void testPersonLawyerName() {
+ cvb.addNode("person").addNode("name").inIterable().atKey("john")
+ .addConstraintViolation();
+ Error error = cvc.getErrorMessages().iterator().next();
+ PathImpl errorPath = (PathImpl) error.getOwner();
+ Assert.assertEquals("Incorrect path created", "person[john].name",
+ errorPath.toString());
+ }
+
+ public void test0Name() {
+ cvb.addNode(null).addNode("name").inIterable().atIndex(0).addNode(null)
+ .inIterable().addConstraintViolation();
+ Error error = cvc.getErrorMessages().iterator().next();
+ PathImpl errorPath = (PathImpl) error.getOwner();
+ Assert.assertEquals("Incorrect path created", "[0].name[]", errorPath
+ .toString());
+ }
+
+ public void testEmptyIndex() {
+ cvb.addNode(null).addNode(null).inIterable().addConstraintViolation();
+ Error error = cvc.getErrorMessages().iterator().next();
+ PathImpl errorPath = (PathImpl) error.getOwner();
+ Assert.assertEquals("Incorrect path created", "[]", errorPath
+ .toString());
+ }
+
+ public void testRootPath() {
+ // Adding only nulls should still give a root path
+ cvb.addNode(null).addNode(null).addNode(null).addNode(null)
+ .addConstraintViolation();
+ Error error = cvc.getErrorMessages().iterator().next();
+ PathImpl errorPath = (PathImpl) error.getOwner();
+ Assert.assertTrue("Created path must be a root path", errorPath
+ .isRootPath());
+
+ }
+
+}
Added: bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/ContextConstraintValidatorFactoryTest.java
URL: http://svn.apache.org/viewvc/bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/ContextConstraintValidatorFactoryTest.java?rev=1517540&view=auto
==============================================================================
--- bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/ContextConstraintValidatorFactoryTest.java (added)
+++ bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/ContextConstraintValidatorFactoryTest.java Mon Aug 26 13:59:15 2013
@@ -0,0 +1,113 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.apache.bval.jsr;
+
+import junit.framework.TestCase;
+
+import javax.validation.Constraint;
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+import javax.validation.ConstraintValidatorFactory;
+import javax.validation.ConstraintViolation;
+import javax.validation.Payload;
+import javax.validation.Validation;
+import javax.validation.ValidatorFactory;
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.util.Locale;
+import java.util.Set;
+
+/**
+ * <a href="https://issues.apache.org/jira/browse/BVAL-111">https://issues.apache.org/jira/browse/BVAL-111</a>
+ * was a serious regression that resulted in BVal's bypassing the context-specific {@link ConstraintValidatorFactory},
+ * rather using the instance available from the {@link ValidatorFactory}. Thus any solutions to e.g. inject
+ * collaborators into {@link ConstraintValidator} implementations would fail.
+ */
+public class ContextConstraintValidatorFactoryTest extends TestCase {
+ static ValidatorFactory factory;
+
+ static {
+ factory = Validation.buildDefaultValidatorFactory();
+ ((DefaultMessageInterpolator) factory.getMessageInterpolator()).setLocale(Locale.ENGLISH);
+ }
+
+ @Documented
+ @Retention(RetentionPolicy.RUNTIME)
+ @Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD })
+ @Constraint(validatedBy = { Contrived.Validator.class })
+ public @interface Contrived {
+ String message() default "{org.apache.bval.constraints.Contrived.message}";
+
+ Class<?>[] groups() default {};
+
+ Class<? extends Payload>[] payload() default {};
+
+ public static class Validator implements ConstraintValidator<Contrived, Object> {
+ private Object requiredCollaborator;
+
+ public Object getRequiredCollaborator() {
+ return requiredCollaborator;
+ }
+
+ public void setRequiredCollaborator(Object requiredCollaborator) {
+ this.requiredCollaborator = requiredCollaborator;
+ }
+
+ public void initialize(Contrived constraintAnnotation) {
+ }
+
+ public boolean isValid(Object value, ConstraintValidatorContext context) {
+ getRequiredCollaborator().toString();
+ return true;
+ }
+
+ }
+
+ }
+
+ @Contrived
+ public static class Example {
+ }
+
+ public void testContextBoundConstraintValidatorFactory() {
+ final ConstraintValidatorFactory constraintValidatorFactory = new ConstraintValidatorFactory() {
+
+ public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
+ if (key.equals(Contrived.Validator.class)) {
+ final Contrived.Validator result = new Contrived.Validator();
+ result.setRequiredCollaborator(new Object());
+ @SuppressWarnings("unchecked")
+ final T t = (T) result;
+ return t;
+ }
+ return null;
+ }
+
+ public void releaseInstance(ConstraintValidator<?, ?> instance) {
+ // no-op
+ }
+ };
+ final Set<ConstraintViolation<Example>> violations = factory.usingContext().constraintValidatorFactory(constraintValidatorFactory)
+ .getValidator().validate(new Example());
+ assertTrue(violations.isEmpty());
+ }
+}
Added: bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/CustomConstraintValidatorFactoryTest.java
URL: http://svn.apache.org/viewvc/bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/CustomConstraintValidatorFactoryTest.java?rev=1517540&view=auto
==============================================================================
--- bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/CustomConstraintValidatorFactoryTest.java (added)
+++ bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/CustomConstraintValidatorFactoryTest.java Mon Aug 26 13:59:15 2013
@@ -0,0 +1,108 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.apache.bval.jsr;
+
+import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+import javax.validation.Constraint;
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+import javax.validation.ConstraintValidatorFactory;
+import javax.validation.Payload;
+import javax.validation.Validation;
+import javax.validation.ValidationException;
+import javax.validation.Validator;
+
+import org.apache.bval.jsr.CustomConstraintValidatorFactoryTest.GoodPerson.GoodPersonValidator;
+
+import junit.framework.TestCase;
+
+/**
+ * Checks that overriding the default {@link ConstraintValidatorFactory} works
+ * as expected.
+ *
+ * @author Carlos Vara
+ */
+public class CustomConstraintValidatorFactoryTest extends TestCase {
+
+ /**
+ * If the custom ConstraintValidatorFactory returns <code>null</code> for a
+ * valid {@link ConstraintValidatorFactory#getInstance(Class)} call, a
+ * validation exception should be thrown.
+ */
+ public void testValidationExceptionWhenFactoryReturnsNullValidator() {
+
+ ConstraintValidatorFactory customFactory = new ConstraintValidatorFactory() {
+ // @Override - not allowed in 1.5 for Interface methods
+ public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
+ return null; // always return null
+ }
+
+ public void releaseInstance(ConstraintValidator<?, ?> instance) {
+ // no-op
+ }
+ };
+
+ // Create a validator with this factory
+ ApacheValidatorConfiguration customConfig = Validation.byProvider(ApacheValidationProvider.class).configure().constraintValidatorFactory(customFactory);
+ Validator validator = customConfig.buildValidatorFactory().getValidator();
+
+ try {
+ validator.validate(new Person());
+ fail("ValidationException must be thrown when factory returns a null constraint validator.");
+ } catch (ValidationException e) {
+ // correct
+ }
+ }
+
+ @GoodPerson
+ public static class Person {
+ }
+
+ @Constraint(validatedBy = { GoodPersonValidator.class })
+ @Target({ METHOD, FIELD, ANNOTATION_TYPE, TYPE })
+ @Retention(RUNTIME)
+ @Documented
+ public static @interface GoodPerson {
+
+ String message() default "Not a good person";
+ Class<?>[] groups() default { };
+ Class<? extends Payload>[] payload() default {};
+
+ public static class GoodPersonValidator implements ConstraintValidator<GoodPerson, Person> {
+ // @Override - not allowed in 1.5 for Interface methods
+ public void initialize(GoodPerson constraintAnnotation) {
+ }
+
+ // @Override - not allowed in 1.5 for Interface methods
+ public boolean isValid(Person value, ConstraintValidatorContext context) {
+ return true;
+ }
+ }
+ }
+
+}
Added: bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/CustomValidatorFactoryTest.java
URL: http://svn.apache.org/viewvc/bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/CustomValidatorFactoryTest.java?rev=1517540&view=auto
==============================================================================
--- bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/CustomValidatorFactoryTest.java (added)
+++ bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/CustomValidatorFactoryTest.java Mon Aug 26 13:59:15 2013
@@ -0,0 +1,134 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.apache.bval.jsr;
+
+import junit.framework.TestCase;
+
+import javax.validation.ConstraintValidatorFactory;
+import javax.validation.MessageInterpolator;
+import javax.validation.ParameterNameProvider;
+import javax.validation.TraversableResolver;
+import javax.validation.Validation;
+import javax.validation.ValidationException;
+import javax.validation.Validator;
+import javax.validation.ValidatorContext;
+import javax.validation.ValidatorFactory;
+import javax.validation.spi.ConfigurationState;
+
+/**
+ * Test the ability to force a particular {@link ValidatorFactory}
+ * implementation class.
+ *
+ * @version $Rev$ $Date$
+ */
+public class CustomValidatorFactoryTest extends TestCase {
+
+ public static class CustomValidatorFactory extends ApacheValidatorFactory {
+
+ /**
+ * Create a new CustomValidatorFactory instance.
+ *
+ * @param configurationState
+ */
+ public CustomValidatorFactory(ConfigurationState configurationState) {
+ super(configurationState);
+ }
+ }
+
+ public static class IncompatibleValidatorFactory implements ValidatorFactory {
+
+ public ConstraintValidatorFactory getConstraintValidatorFactory() {
+ return null;
+ }
+
+ public ParameterNameProvider getParameterNameProvider() {
+ return null;
+ }
+
+ public MessageInterpolator getMessageInterpolator() {
+ return null;
+ }
+
+ public TraversableResolver getTraversableResolver() {
+ return null;
+ }
+
+ public Validator getValidator() {
+ return null;
+ }
+
+ public <T> T unwrap(Class<T> type) {
+ return null;
+ }
+
+ public void close() {
+
+ }
+
+ public ValidatorContext usingContext() {
+ return null;
+ }
+
+ }
+
+ public static class NotAValidatorFactory {
+ public NotAValidatorFactory(ConfigurationState configurationState) {
+ }
+ }
+
+ public void testDefaultValidatorFactory() {
+ Validation.byProvider(ApacheValidationProvider.class).configure().buildValidatorFactory().unwrap(
+ ApacheValidatorFactory.class);
+ }
+
+ public void testNoSuchType() {
+ try {
+ Validation.byProvider(ApacheValidationProvider.class).configure().addProperty(
+ ApacheValidatorConfiguration.Properties.VALIDATOR_FACTORY_CLASSNAME, "no.such.type")
+ .buildValidatorFactory();
+ fail();
+ } catch (ValidationException ex) {
+ assertTrue(ex.getCause() instanceof ClassNotFoundException);
+ }
+ }
+
+ public void testCustomValidatorFactory() {
+ doTest(CustomValidatorFactory.class, null);
+ }
+
+ public void testInvalidType() {
+ doTest(NotAValidatorFactory.class, ClassCastException.class);
+ }
+
+ public void testUnsupportedValidatorFactoryType() {
+ doTest(IncompatibleValidatorFactory.class, NoSuchMethodException.class);
+ }
+
+ private void doTest(Class<?> validatorFactoryType, Class<? extends Exception> expectedFailureCause) {
+ try {
+ Validation.byProvider(ApacheValidationProvider.class).configure().addProperty(
+ ApacheValidatorConfiguration.Properties.VALIDATOR_FACTORY_CLASSNAME, validatorFactoryType.getName())
+ .buildValidatorFactory().unwrap(validatorFactoryType);
+ assertNull(expectedFailureCause);
+ } catch (ValidationException ex) {
+ assertNotNull(expectedFailureCause);
+ assertTrue(expectedFailureCause.isInstance(ex.getCause()));
+ }
+ }
+}
Added: bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/DefaultMessageInterpolatorTest.java
URL: http://svn.apache.org/viewvc/bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/DefaultMessageInterpolatorTest.java?rev=1517540&view=auto
==============================================================================
--- bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/DefaultMessageInterpolatorTest.java (added)
+++ bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/DefaultMessageInterpolatorTest.java Mon Aug 26 13:59:15 2013
@@ -0,0 +1,164 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with this
+ * work for additional information regarding copyright ownership. The ASF
+ * licenses this file to you 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
+ *
+ * http://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.apache.bval.jsr;
+
+import junit.framework.Assert;
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+import org.apache.bval.jsr.example.Author;
+import org.apache.bval.jsr.example.PreferredGuest;
+
+import javax.validation.MessageInterpolator;
+import javax.validation.Validator;
+import javax.validation.constraints.Pattern;
+import javax.validation.metadata.ConstraintDescriptor;
+import java.util.Locale;
+
+/**
+ * MessageResolverImpl Tester.
+ */
+public class DefaultMessageInterpolatorTest extends TestCase {
+
+ private DefaultMessageInterpolator interpolator;
+
+ public DefaultMessageInterpolatorTest(String name) {
+ super(name);
+ }
+
+ public static Test suite() {
+ return new TestSuite(DefaultMessageInterpolatorTest.class);
+ }
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp(); // call super!
+ interpolator = new DefaultMessageInterpolator();
+ interpolator.setLocale(Locale.ENGLISH);
+ }
+
+ public void testCreateResolver() {
+
+ final Validator gvalidator = getValidator();
+
+ assertTrue(!gvalidator.getConstraintsForClass(PreferredGuest.class).getConstraintsForProperty(
+ "guestCreditCardNumber").getConstraintDescriptors().isEmpty());
+
+ MessageInterpolator.Context ctx = new MessageInterpolator.Context() {
+
+ public ConstraintDescriptor<?> getConstraintDescriptor() {
+ return (ConstraintDescriptor<?>) gvalidator.getConstraintsForClass(PreferredGuest.class)
+ .getConstraintsForProperty("guestCreditCardNumber").getConstraintDescriptors().iterator().next();
+ }
+
+ public Object getValidatedValue() {
+ return "12345678";
+ }
+
+ public <T> T unwrap(Class<T> type) {
+ return null;
+ }
+ };
+ String msg = interpolator.interpolate("{validator.creditcard}", ctx);
+ Assert.assertEquals("credit card is not valid", msg);
+
+ ctx = new MessageInterpolator.Context() {
+ public ConstraintDescriptor<?> getConstraintDescriptor() {
+ return gvalidator.getConstraintsForClass(Author.class).getConstraintsForProperty("lastName")
+ .getConstraintDescriptors().iterator().next();
+ }
+
+ public Object getValidatedValue() {
+ return "";
+ }
+
+ public <T> T unwrap(Class<T> type) {
+ return null;
+ }
+ };
+
+ msg = interpolator.interpolate("{org.apache.bval.constraints.NotEmpty.message}", ctx);
+ Assert.assertEquals("may not be empty", msg);
+ }
+
+ /**
+ * Checks that strings containing special characters are correctly
+ * substituted when interpolating.
+ */
+ public void testReplacementWithSpecialChars() {
+
+ final Validator validator = getValidator();
+ MessageInterpolator.Context ctx;
+
+ // Try to interpolate an annotation attribute containing $
+ ctx = new MessageInterpolator.Context() {
+
+ public ConstraintDescriptor<?> getConstraintDescriptor() {
+ return (ConstraintDescriptor<?>) validator.getConstraintsForClass(Person.class)
+ .getConstraintsForProperty("idNumber").getConstraintDescriptors().iterator().next();
+ }
+
+ public Object getValidatedValue() {
+ return "12345678";
+ }
+
+ public <T> T unwrap(Class<T> type) {
+ return null;
+ }
+ };
+
+ String result = this.interpolator.interpolate("Id number should match {regexp}", ctx);
+ Assert.assertEquals("Incorrect message interpolation when $ is in an attribute",
+ "Id number should match ....$", result);
+
+ // Try to interpolate an annotation attribute containing \
+ ctx = new MessageInterpolator.Context() {
+
+ public ConstraintDescriptor<?> getConstraintDescriptor() {
+ return (ConstraintDescriptor<?>) validator.getConstraintsForClass(Person.class)
+ .getConstraintsForProperty("otherId").getConstraintDescriptors().iterator().next();
+ }
+
+ public Object getValidatedValue() {
+ return "12345678";
+ }
+
+ public <T> T unwrap(Class<T> type) {
+ return null;
+ }
+ };
+
+ result = this.interpolator.interpolate("Other id should match {regexp}", ctx);
+ Assert.assertEquals("Incorrect message interpolation when \\ is in an attribute value",
+ "Other id should match .\\n", result);
+
+ }
+
+ public static class Person {
+
+ @Pattern(message = "Id number should match {regexp}", regexp = "....$")
+ public String idNumber;
+
+ @Pattern(message = "Other id should match {regexp}", regexp = ".\\n")
+ public String otherId;
+
+ }
+
+ private Validator getValidator() {
+ return ApacheValidatorFactory.getDefault().getValidator();
+ }
+}
Added: bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/ExceptionsContractTest.java
URL: http://svn.apache.org/viewvc/bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/ExceptionsContractTest.java?rev=1517540&view=auto
==============================================================================
--- bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/ExceptionsContractTest.java (added)
+++ bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/ExceptionsContractTest.java Mon Aug 26 13:59:15 2013
@@ -0,0 +1,270 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.apache.bval.jsr;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
+
+import javax.validation.Validation;
+import javax.validation.ValidationException;
+import javax.validation.Validator;
+import javax.validation.ValidatorFactory;
+import javax.validation.constraints.Min;
+import javax.validation.constraints.NotNull;
+import javax.validation.metadata.BeanDescriptor;
+import java.util.Locale;
+
+/**
+ * Several checks to validate that the implementations of {@link Validator} and
+ * {@link BeanDescriptor} throw the correct exceptions as per the spec.
+ *
+ * @author Carlos Vara
+ */
+public class ExceptionsContractTest extends TestCase {
+ static ValidatorFactory factory;
+
+ static {
+ factory = Validation.buildDefaultValidatorFactory();
+ ((DefaultMessageInterpolator) factory.getMessageInterpolator()).setLocale(Locale.ENGLISH);
+ }
+
+ /**
+ * Validator instance to test
+ */
+ protected Validator validator;
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ validator = createValidator();
+ }
+
+ /**
+ * Create the validator instance.
+ *
+ * @return Validator
+ */
+ protected Validator createValidator() {
+ return factory.getValidator();
+ }
+
+ /**
+ * Checks that the correct exception is thrown when validating a bean whose
+ * getter throws an exception.
+ */
+ public void testExceptionThrowingBean() {
+ try {
+ validator.validate(new ExceptionThrowingBean());
+ Assert.fail("No exception thrown when validating a bean whose getter throws a RTE");
+ } catch (ValidationException e) {
+ // Correct
+ }
+ }
+
+ /**
+ * Checks that an {@link IllegalArgumentException} is thrown when passing
+ * <code>null</code> as group array.
+ */
+ public void testValidateNullGroup() {
+ try {
+ Class<?>[] groups = null;
+ validator.validate(new String(), groups);
+ Assert.fail("No exception thrown when passing null as group array");
+ } catch (IllegalArgumentException e) {
+ // Correct
+ }
+ }
+
+ /**
+ * Checks that an {@link IllegalArgumentException} is thrown when passing an
+ * invalid property name.
+ */
+ public void testValidateInvalidPropertyName() {
+
+ // Null propertyName
+ try {
+ validator.validateProperty(new Person(), null);
+ } catch (IllegalArgumentException e) {
+ // Correct
+ }
+
+ // Empty propertyName
+ try {
+ validator.validateProperty(new Person(), "");
+ } catch (IllegalArgumentException e) {
+ // Correct
+ }
+
+ // Invalid propertyName
+ try {
+ validator.validateProperty(new Person(), "surname");
+ } catch (IllegalArgumentException e) {
+ // Correct
+ }
+
+ }
+
+ /**
+ * Checks that an {@link IllegalArgumentException} is thrown when trying to
+ * validate a property on a null object.
+ */
+ public void testValidatePropertyOnNullBean() {
+ try {
+ validator.validateProperty(null, "class");
+ } catch (IllegalArgumentException e) {
+ // Correct
+ }
+ }
+
+ /**
+ * Checks that an {@link IllegalArgumentException} is thrown when passing
+ * <code>null</code> as group array in a
+ * {@link Validator#validateProperty(Object, String, Class...)} call.
+ */
+ public void testValidatePropertyNullGroup() {
+ try {
+ Class<?>[] groups = null;
+ validator.validateProperty(new Person(), "name", groups);
+ Assert.fail("No exception thrown when passing null as group array");
+ } catch (IllegalArgumentException e) {
+ // Correct
+ }
+ }
+
+ /**
+ * Checks that an {@link IllegalArgumentException} is thrown when calling
+ * {@link Validator#validateValue(Class, String, Object, Class...)} with a
+ * <code>null</code> class.
+ */
+ public void testValidateValueOnNullClass() {
+ try {
+ validator.validateValue(null, "class", Object.class);
+ Assert.fail("No exception thrown when passing null as group array");
+ } catch (IllegalArgumentException e) {
+ // Correct
+ }
+ }
+
+ /**
+ * Checks that an {@link IllegalArgumentException} is thrown when passing an
+ * invalid property name to
+ * {@link Validator#validateValue(Class, String, Object, Class...)}.
+ */
+ public void testValidateValueInvalidPropertyName() {
+ // Null propertyName
+ try {
+ validator.validateValue(Person.class, null, "John");
+ } catch (IllegalArgumentException e) {
+ // Correct
+ }
+
+ // Empty propertyName
+ try {
+ validator.validateValue(Person.class, "", "John");
+ } catch (IllegalArgumentException e) {
+ // Correct
+ }
+
+ // Invalid propertyName
+ try {
+ validator.validateValue(Person.class, "unexistant", "John");
+ } catch (IllegalArgumentException e) {
+ // Correct
+ }
+ }
+
+ /**
+ * Checks that an {@link IllegalArgumentException} is thrown when calling
+ * {@link Validator#validateValue(Class, String, Object, Class...)} with a
+ * <code>null</code> group array.
+ */
+ public void testValidateValueNullGroup() {
+ try {
+ Class<?>[] groups = null;
+ validator.validateValue(Person.class, "name", "John", groups);
+ Assert.fail("No exception thrown when passing null as group array");
+ } catch (IllegalArgumentException e) {
+ // Correct
+ }
+ }
+
+ /**
+ * Enforces the "not a valid object property" part of the {@link IllegalArgumentException}
+ * declaration on {@link Validator#validateValue(Class, String, Object, Class...)}
+ */
+ public void testValidateIncompatibleValue() {
+ try {
+ validator.validateValue(Person.class, "name", 666);
+ Assert.fail("No exception thrown when passing Integer for string value");
+ } catch (IllegalArgumentException e) {
+ // Correct
+ }
+ try {
+ validator.validateValue(Person.class, "age", null);
+ Assert.fail("No exception thrown when passing null for primitive value");
+ } catch (IllegalArgumentException e) {
+ // Correct
+ }
+ }
+
+ /**
+ * Checks that an {@link IllegalArgumentException} is thrown when calling
+ * {@link BeanDescriptor#getConstraintsForProperty(String)} with an invalid
+ * property name.
+ */
+ public void testGetConstraintsForInvalidProperty() {
+ BeanDescriptor personDescriptor = validator.getConstraintsForClass(Person.class);
+
+ try {
+ personDescriptor.getConstraintsForProperty(null);
+ fail("No exception thrown when calling getConstraintsForProperty with null property");
+ } catch (IllegalArgumentException e) {
+ // Correct
+ }
+
+ try {
+ personDescriptor.getConstraintsForProperty("");
+ fail("No exception thrown when calling getConstraintsForProperty with empty property");
+ } catch (IllegalArgumentException e) {
+ // Correct
+ }
+ }
+
+ public static class ExceptionThrowingBean {
+
+ @NotNull
+ public String getValue() {
+ throw new IllegalStateException();
+ }
+
+ }
+
+ public static class Person {
+
+ @NotNull
+ public String name;
+
+ @Min(0)
+ public int age;
+ }
+
+}
Added: bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/FooTest.java
URL: http://svn.apache.org/viewvc/bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/FooTest.java?rev=1517540&view=auto
==============================================================================
--- bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/FooTest.java (added)
+++ bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/FooTest.java Mon Aug 26 13:59:15 2013
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.apache.bval.jsr;
+
+import junit.framework.TestCase;
+
+import javax.validation.ConstraintViolation;
+import javax.validation.Valid;
+import javax.validation.Validator;
+import javax.validation.constraints.NotNull;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Set;
+
+/**
+ * Description: <br/>
+ */
+public class FooTest extends TestCase {
+
+ @Valid
+ private Collection<Foo> foos = new ArrayList<Foo>();
+
+ public FooTest() {
+ foos.add(new Foo("foo1"));
+ foos.add(null);
+ foos.add(new Foo("foo3"));
+ }
+
+
+ public class Foo {
+ @NotNull
+ public String bar;
+
+ public Foo(String bar) {
+ this.bar = bar;
+ }
+
+ }
+
+ public void testValidation() {
+ FooTest t = new FooTest();
+
+ Validator v = ApacheValidatorFactory.getDefault().getValidator();
+ Set<ConstraintViolation<FooTest>> errors = v.validate(t);
+ System.out.println("got errors:");
+ for (ConstraintViolation<?> error : errors) {
+ System.out.println(error.getPropertyPath());
+ }
+ }
+}
\ No newline at end of file
Added: bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/Jsr303Test.java
URL: http://svn.apache.org/viewvc/bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/Jsr303Test.java?rev=1517540&view=auto
==============================================================================
--- bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/Jsr303Test.java (added)
+++ bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/Jsr303Test.java Mon Aug 26 13:59:15 2013
@@ -0,0 +1,271 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.apache.bval.jsr;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
+import org.apache.bval.constraints.SizeValidatorForCharSequence;
+import org.apache.bval.jsr.example.Address;
+import org.apache.bval.jsr.example.Book;
+import org.apache.bval.jsr.example.Engine;
+import org.apache.bval.jsr.example.IllustratedBook;
+import org.apache.bval.jsr.example.MaxTestEntity;
+import org.apache.bval.jsr.example.NoValidatorTestEntity;
+import org.apache.bval.jsr.example.Second;
+import org.apache.bval.jsr.example.SizeTestEntity;
+import org.apache.bval.jsr.util.TestUtils;
+
+import javax.validation.ConstraintViolation;
+import javax.validation.UnexpectedTypeException;
+import javax.validation.Validation;
+import javax.validation.Validator;
+import javax.validation.ValidatorFactory;
+import javax.validation.metadata.BeanDescriptor;
+import javax.validation.metadata.ConstraintDescriptor;
+import javax.validation.metadata.ElementDescriptor;
+import javax.validation.metadata.PropertyDescriptor;
+import java.math.BigDecimal;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Locale;
+import java.util.Set;
+
+/**
+ * Description: <br/>
+ */
+public class Jsr303Test extends TestCase {
+ /*
+ * static { ApacheValidatorFactory.getDefault().getMetaBeanManager()
+ * .addResourceLoader("org/apache/bval/example/test-beanInfos.xml"); }
+ */
+
+ /*
+ * public void testUseCoreXmlMetaData() { Validator validator =
+ * getValidator();
+ *
+ * BusinessObject object = new BusinessObject();
+ * object.setTitle("1234567834567 too long title ");
+ * Set<ConstraintViolation<BusinessObject>> violations =
+ * validator.validate(object); Assert.assertNotNull(violations);
+ * Assert.assertTrue(!violations.isEmpty());
+ *
+ * Assert.assertTrue(!validator.validateProperty(object,
+ * "title").isEmpty()); }
+ */
+
+ static ValidatorFactory factory;
+
+ static {
+ factory = Validation.buildDefaultValidatorFactory();
+ ((DefaultMessageInterpolator) factory.getMessageInterpolator()).setLocale(Locale.ENGLISH);
+ }
+
+ /**
+ * Validator instance to test
+ */
+ protected Validator validator;
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ validator = createValidator();
+ }
+
+ /**
+ * Create the validator instance.
+ *
+ * @return Validator
+ */
+ protected Validator createValidator() {
+ return factory.getValidator();
+ }
+
+ public void testPropertyDescriptorHasConstraints() {
+ BeanDescriptor cons = validator.getConstraintsForClass(Book.class);
+ assertTrue(cons.getConstraintsForProperty("author").hasConstraints());
+ assertTrue(cons.getConstraintsForProperty("title").hasConstraints());
+ assertTrue(cons.getConstraintsForProperty("uselessField").hasConstraints());
+ // cons.getConstraintsForProperty("unconstraintField") == null without
+ // Introspector
+ // cons.getConstraintsForProperty("unconstraintField") != null with
+ // Introspector
+ assertTrue(cons.getConstraintsForProperty("unconstraintField") == null
+ || !cons.getConstraintsForProperty("unconstraintField").hasConstraints());
+ assertNull(cons.getConstraintsForProperty("unknownField"));
+ }
+
+ public void testValidateValue() {
+ assertTrue(validator.validateValue(Book.class, "subtitle", "123456789098765432").isEmpty());
+ assertFalse(validator.validateValue(Book.class, "subtitle",
+ "123456789098765432123412345678909876543212341234564567890987654321234", Second.class).isEmpty());
+ // tests for issue 22: validation of a field without any constraints
+ assertEquals(0, validator.validateValue(Book.class, "unconstraintField", 4).size());
+ // tests for issue 22: validation of unknown field cause
+ // ValidationException
+ try {
+ validator.validateValue(Book.class, "unknownProperty", 4);
+ fail("unknownProperty not detected");
+ } catch (IllegalArgumentException ex) {
+ // OK
+ assertEquals("unknown property 'unknownProperty' in org.apache.bval.jsr.example.Book", ex.getMessage());
+ }
+ }
+
+ public void testValidateNonCascadedRealNestedProperty() {
+ try {
+ validator.validateValue(IllustratedBook.class, "illustrator.firstName", "Edgar");
+ fail("unknownProperty not detected");
+ } catch (IllegalArgumentException ex) {
+ // OK
+ assertEquals("Property org.apache.bval.jsr.example.IllustratedBook.illustrator is not cascaded", ex.getMessage());
+ }
+ }
+
+ public void testMetadataAPI_Book() {
+ Assert.assertNotNull(validator.getConstraintsForClass(Book.class));
+ // not necessary for implementation correctness, but we'll test
+ // nevertheless:
+ Assert.assertSame(validator.getConstraintsForClass(Book.class), validator.getConstraintsForClass(Book.class));
+ BeanDescriptor bc = validator.getConstraintsForClass(Book.class);
+ // assertEquals(ElementType.TYPE, bc.getElementType());
+ Assert.assertEquals(Book.class, bc.getElementClass());
+ // assertEquals(false, bc.isCascaded());
+ // assertEquals("", bc.getPropertyPath());
+ Assert.assertTrue(bc.getConstraintDescriptors() != null);
+ TestUtils.failOnModifiable(bc.getConstraintDescriptors(), "beanDescriptor constraintDescriptors");
+ }
+
+ public void testMetadataAPI_Engine() {
+ ElementDescriptor desc =
+ validator.getConstraintsForClass(Engine.class).getConstraintsForProperty("serialNumber");
+ assertNotNull(desc);
+ // assertEquals(ElementType.FIELD, desc.getElementType());
+ Assert.assertEquals(String.class, desc.getElementClass());
+ }
+
+ public void testMetadataAPI_Address() {
+ Assert.assertFalse(validator.getConstraintsForClass(Address.class).getConstraintDescriptors().isEmpty());
+
+ Set<PropertyDescriptor> props = validator.getConstraintsForClass(Address.class).getConstrainedProperties();
+ TestUtils.failOnModifiable(props, "beanDescriptor constrainedProperties");
+ Set<String> propNames = new HashSet<String>(props.size());
+ for (PropertyDescriptor each : props) {
+ TestUtils.failOnModifiable(each.getConstraintDescriptors(), "propertyDescriptor constraintDescriptors");
+ propNames.add(each.getPropertyName());
+ }
+ Assert.assertTrue(propNames.contains("addressline1")); // annotated at
+ // field level
+ Assert.assertTrue(propNames.contains("addressline2"));
+ Assert.assertTrue(propNames.contains("zipCode"));
+ Assert.assertTrue(propNames.contains("country"));
+ Assert.assertTrue(propNames.contains("city")); // annotated at method
+ // level
+ Assert.assertEquals(5, props.size());
+
+ ElementDescriptor desc =
+ validator.getConstraintsForClass(Address.class).getConstraintsForProperty("addressline1");
+ Assert.assertNotNull(desc);
+ boolean found = false;
+ for (ConstraintDescriptor<?> each : desc.getConstraintDescriptors()) {
+ if (each.getConstraintValidatorClasses().get(0).equals(SizeValidatorForCharSequence.class)) {
+ Assert.assertTrue(each.getAttributes().containsKey("max"));
+ assertEquals(30, each.getAttributes().get("max"));
+ found = true;
+ }
+ }
+ Assert.assertTrue(found);
+
+ }
+
+ public void testValidateMultiValuedConstraints() {
+ Engine engine = new Engine();
+ engine.serialNumber = "abcd-defg-0123";
+ Set<ConstraintViolation<Engine>> violations;
+ violations = validator.validate(engine);
+ assertEquals(0, violations.size());
+
+ engine.serialNumber = "!)/(/()";
+ violations = validator.validate(engine);
+ assertEquals(2, violations.size());
+ for (String msg : new String[] { "must contain alphabetical characters only", "must match ....-....-...." }) {
+ assertNotNull(TestUtils.getViolationWithMessage(violations, msg));
+ }
+ }
+
+ public void testConstraintValidatorResolutionAlgorithm() {
+ MaxTestEntity entity = new MaxTestEntity();
+ entity.setText("101");
+ entity.setProperty("201");
+ entity.setLongValue(301);
+ entity.setDecimalValue(new BigDecimal(401));
+ Set<ConstraintViolation<MaxTestEntity>> violations = validator.validate(entity);
+ assertEquals(4, violations.size());
+
+ NoValidatorTestEntity entity2 = new NoValidatorTestEntity();
+ try {
+ validator.validate(entity2);
+ fail("UnexpectedTypeException expected but not thrown");
+ } catch (UnexpectedTypeException ex) {
+ // we expected this
+ assertEquals("No validator could be found for type java.lang.Object. "
+ + "See: @Max at private java.lang.Object " + "org.apache.bval.jsr.example."
+ + "NoValidatorTestEntity.anything", ex.getMessage());
+ }
+ }
+
+ public void testSizeValidation() {
+ SizeTestEntity en = new SizeTestEntity();
+ en.ba = new byte[3];
+ en.ca = new char[3];
+ en.boa = new boolean[3];
+ en.coll = Arrays.asList("1", "2", "3");
+ en.da = new double[3];
+ en.fa = new float[3];
+ en.it = new int[3];
+ en.la = new long[3];
+ en.map = new HashMap<String, String>();
+ en.map.put("1", "1");
+ en.map.put("3", "3");
+ en.map.put("2", "2");
+ en.oa = new Integer[3];
+ en.oa2 = new Integer[3];
+ en.sa = new short[3];
+ en.text = "123";
+ Set<ConstraintViolation<SizeTestEntity>> vi = validator.validate(en);
+ assertEquals(13, vi.size());
+ }
+
+ /**
+ * JSR-303 Section 5.1.c, IllegalArgumentException should be thrown
+ */
+ public void testGetConstraintsForNullClass() {
+ try {
+ validator.getConstraintsForClass(null);
+ Assert.fail("No exception thrown on Validator.getConstraintsForClass(null)");
+ } catch (IllegalArgumentException e) {
+ // Correct
+ return;
+ }
+ }
+
+}
Added: bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/PayloadTest.java
URL: http://svn.apache.org/viewvc/bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/PayloadTest.java?rev=1517540&view=auto
==============================================================================
--- bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/PayloadTest.java (added)
+++ bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/PayloadTest.java Mon Aug 26 13:59:15 2013
@@ -0,0 +1,115 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.apache.bval.jsr;
+
+import junit.framework.TestCase;
+import org.apache.bval.jsr.util.TestUtils;
+
+import javax.validation.ConstraintViolation;
+import javax.validation.Payload;
+import javax.validation.Validation;
+import javax.validation.Validator;
+import javax.validation.ValidatorFactory;
+import javax.validation.constraints.NotNull;
+import java.util.Locale;
+import java.util.Set;
+
+/**
+ * Description: test that payload information can be retrieved
+ * from error reports via the ConstraintDescriptor either accessed
+ * through the ConstraintViolation objects<br/>
+ */
+public class PayloadTest extends TestCase {
+ static ValidatorFactory factory;
+
+ static {
+ factory = Validation.buildDefaultValidatorFactory();
+ ((DefaultMessageInterpolator) factory.getMessageInterpolator()).setLocale(Locale.ENGLISH);
+ }
+
+ /**
+ * Validator instance to test
+ */
+ protected Validator validator;
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ validator = createValidator();
+ }
+
+ /**
+ * Create the validator instance.
+ *
+ * @return Validator
+ */
+ protected Validator createValidator() {
+ return factory.getValidator();
+ }
+
+ static class Severity {
+ static class Info implements Payload {
+ }
+
+ static class Error implements Payload {
+ }
+ }
+
+ static class Address {
+ private String zipCode;
+ private String city;
+
+ Address(String zipCode, String city) {
+ this.zipCode = zipCode;
+ this.city = city;
+ }
+
+ @NotNull(message = "would be nice if we had one", payload = Severity.Info.class)
+ public String getZipCode() {
+ return zipCode;
+ }
+
+ @NotNull(message = "the city is mandatory", payload = Severity.Error.class)
+ public String getCity() {
+ return city;
+ }
+ }
+
+ public void testPayload() {
+ Set<ConstraintViolation<Address>> violations;
+ Address address = new Address(null, null);
+ violations = validator.validate(address);
+ assertEquals(2, violations.size());
+ ConstraintViolation<?> vio;
+ vio = TestUtils.getViolation(violations, "zipCode");
+ assertNotNull(vio);
+ assertEquals(1, vio.getConstraintDescriptor().getPayload().size());
+ assertTrue(
+ vio.getConstraintDescriptor().getPayload().contains(Severity.Info.class));
+
+ vio = TestUtils.getViolation(violations, "city");
+ assertNotNull(vio);
+ assertEquals(1, vio.getConstraintDescriptor().getPayload().size());
+ assertTrue(
+ vio.getConstraintDescriptor().getPayload().contains(Severity.Error.class));
+ }
+}
Added: bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/TckReproducerTest.java
URL: http://svn.apache.org/viewvc/bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/TckReproducerTest.java?rev=1517540&view=auto
==============================================================================
--- bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/TckReproducerTest.java (added)
+++ bval/branches/bval-11/bval-jsr/src/test/java/org/apache/bval/jsr/TckReproducerTest.java Mon Aug 26 13:59:15 2013
@@ -0,0 +1,114 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * http://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.apache.bval.jsr;
+
+import junit.framework.TestCase;
+import org.apache.bval.util.PropertyAccess;
+
+import javax.validation.ConstraintViolation;
+import javax.validation.Validation;
+import javax.validation.Validator;
+import javax.validation.ValidatorFactory;
+import javax.validation.constraints.Pattern;
+import java.util.Locale;
+import java.util.Set;
+
+/**
+ * Description: <br>
+ * User: roman.stumm<br>
+ * Date: 21.04.2010<br>
+ * Time: 14:21:45<br>
+ */
+public class TckReproducerTest extends TestCase {
+ static ValidatorFactory factory;
+
+ static {
+ factory = Validation.buildDefaultValidatorFactory();
+ ((DefaultMessageInterpolator) factory.getMessageInterpolator()).setLocale(Locale.ENGLISH);
+ }
+
+ /**
+ * Validator instance to test
+ */
+ protected Validator validator;
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ validator = createValidator();
+ }
+
+ /**
+ * Create the validator instance.
+ *
+ * @return Validator
+ */
+ protected Validator createValidator() {
+ return factory.getValidator();
+ }
+
+ public static <T> void assertCorrectNumberOfViolations(Set<ConstraintViolation<T>> violations,
+ int expectedViolations) {
+ assertEquals("Wrong number of constraint violations. Expected: " + expectedViolations + " Actual: "
+ + violations.size(), expectedViolations, violations.size());
+ }
+
+ public void testPropertyAccessOnNonPublicClass() throws Exception {
+ Car car = new Car("USd-298");
+ assertEquals(car.getLicensePlateNumber(), PropertyAccess.getProperty(car, "licensePlateNumber"));
+
+ Set<ConstraintViolation<Car>> violations =
+ validator.validateProperty(car, "licensePlateNumber", First.class,
+ org.apache.bval.jsr.example.Second.class);
+ assertCorrectNumberOfViolations(violations, 1);
+
+ car.setLicensePlateNumber("USD-298");
+ violations =
+ validator.validateProperty(car, "licensePlateNumber", First.class,
+ org.apache.bval.jsr.example.Second.class);
+ assertCorrectNumberOfViolations(violations, 0);
+ }
+
+ class Car {
+ @Pattern(regexp = "[A-Z][A-Z][A-Z]-[0-9][0-9][0-9]", groups = { First.class, Second.class })
+ private String licensePlateNumber;
+
+ Car(String licensePlateNumber) {
+ this.licensePlateNumber = licensePlateNumber;
+ }
+
+ public String getLicensePlateNumber() {
+ return licensePlateNumber;
+ }
+
+ public void setLicensePlateNumber(String licensePlateNumber) {
+ this.licensePlateNumber = licensePlateNumber;
+ }
+ }
+
+ interface First {
+ }
+
+ interface Second {
+ }
+}