@Test void testConstructor1() throws Exception { //given Object validatedObject = new Object(); Object invalidValue = new Object(); //when Violation violation = new Violation("niceViolation", validatedObject, invalidValue); //then assertEquals(validatedObject, violation.getValidatedObject(), "validatedObject must be equal to a validatedObject which was given to constructor"); assertEquals(invalidValue, violation.getInvalidValue(), "invalidValue must be equal to a invalidValue which was given to constructor"); assertNull(violation.getCheck()); assertNull(violation.getConstraint()); }
/** * Prepares validation messages. * Key is either validation constraint class name or violation name. */ public static String resolveValidationMessage(final HttpServletRequest request, final Violation violation) { ValidationConstraint vc = violation.getConstraint(); String key = vc != null ? vc.getClass().getName() : violation.getName(); String msg = LocalizationUtil.findMessage(request, key); if (msg != null) { return beanTemplateParser.parseWithBean(msg, violation); } return null; }
/** * Adds action violation. */ protected void addViolation(final String name, final Object invalidValue) { prepareValidator(); vtor.addViolation(new Violation(name, this, invalidValue)); }
@Test void testToString() throws Exception { //given Object validatedObject = new Object(); Object invalidValue = new Object(); Violation violation = new Violation("niceViolation", validatedObject, invalidValue, new Check("niceCheck", new TestValidationConstraint())); //when String toString = violation.toString(); //then assertEquals(toString, "Violation{niceViolation:jodd.vtor.ViolationTest$TestValidationConstraint}"); }
/** * Returns JSON violations string. Contains javascript array with elements that contain: * <ul> * <li>name - violation name</li> * <li>msg - message code i.e. constraint class name</li> * </ul> */ public static String createViolationsJsonString(final HttpServletRequest request, final List<Violation> violations) { if (violations == null) { return StringPool.EMPTY; } StringBuilder sb = new StringBuilder().append('['); for (int i = 0, violationsSize = violations.size(); i < violationsSize; i++) { Violation violation = violations.get(i); if (i != 0) { sb.append(','); } sb.append('{'); sb.append("\"name\":\"").append(violation.getName()).append('"').append(','); sb.append("\"msg\":\"").append(resolveValidationMessage(request, violation)).append('"'); sb.append('}'); } sb.append(']'); return sb.toString(); }
@Test void testTime() { Vtor vtor = new Vtor(); vtor.validate(new Tad()); assertTrue(vtor.hasViolations()); List<Violation> v = vtor.getViolations(); assertEquals(3, v.size()); assertEquals(TimeAfterConstraint.class, v.get(0).getConstraint().getClass()); } }
@Test void testValidateCheckForDifferentProfile() throws Exception { //given a list of constraints with different profiles, one check has same profile as Vtor Vtor vtor = new Vtor(); vtor.useProfile("profil1"); Map<String, List<Check>> constraints = new HashMap<>(); ValidationConstraint testCheck1Constraint = mock(ValidationConstraint.class); ValidationConstraint testCheck2Constraint = mock(ValidationConstraint.class); Check ch1 = createCheckWithProfile("check1", "profil1", testCheck1Constraint); Check ch2 = createCheckWithProfile("check2", "profil2", testCheck2Constraint); List<Check> checks = new ArrayList<>(); checks.add(ch1); checks.add(ch2); constraints.put("testField", checks); //when List<Violation> violations = vtor.validate(mockValidationContext(constraints), new ValidateTestObject("testValue"), "testField"); //then assertEquals(1, violations.size()); assertEquals("profil1", violations.get(0).getCheck().getProfiles()[0]); verify(testCheck1Constraint).isValid(any(ValidationConstraintContext.class), eq("testValue")); verify(testCheck2Constraint, never()).isValid(any(ValidationConstraintContext.class), eq("testValue")); }
/** * Performs validation of provided validation context and appends violations. */ public List<Violation> validate(final ValidationContext ctx, final Object target, final String targetName) { for (Map.Entry<String, List<Check>> entry : ctx.map.entrySet()) { String name = entry.getKey(); Object value = BeanUtil.declaredSilent.getProperty(target, name); String valueName = targetName != null ? (targetName + '.' + name) : name; // move up ValidationConstraintContext vcc = new ValidationConstraintContext(this, target, valueName); for (Check check : entry.getValue()) { String[] checkProfiles = check.getProfiles(); if (!matchProfiles(checkProfiles)) { continue; } if (check.getSeverity() < severity) { continue; } ValidationConstraint constraint = check.getConstraint(); if (!constraint.isValid(vcc, value)) { addViolation(new Violation(valueName, target, value, check)); } } } return getViolations(); }
@Test void testDefaultProfiles() { Vtor vtor = new Vtor(); vtor.setValidateAllProfilesByDefault(false); Zoo zoo = new Zoo(); vtor.validate(zoo); List<Violation> vlist = vtor.getViolations(); assertEquals(1, vlist.size()); vtor.resetViolations(); vtor.useProfile("default"); vtor.validate(zoo); vlist = vtor.getViolations(); assertEquals(1, vlist.size()); assertEquals("ccc", vlist.get(0).getName()); vtor.resetViolations(); vtor.resetProfiles(); vtor.useProfile("p2"); vtor.validate(zoo); vlist = vtor.getViolations(); assertEquals(1, vlist.size()); assertEquals("bbb", vlist.get(0).getName()); }
assertEquals(1, vlist.size()); Violation v = vlist.get(0); assertEquals(MinLengthConstraint.class, v.getConstraint().getClass());
@Test void testValidateCheckSeverity() throws Exception { //given Vtor vtor = new Vtor(); vtor.setSeverity(10); Map<String, List<Check>> constraints = new HashMap<>(); ValidationConstraint testCheck1Constraint = mock(ValidationConstraint.class); ValidationConstraint testCheck2Constraint = mock(ValidationConstraint.class); Check ch1 = new Check("check1", testCheck1Constraint); ch1.setSeverity(15); Check ch2 = new Check("check2", testCheck2Constraint); ch2.setSeverity(5); List<Check> checks = new ArrayList<>(); checks.add(ch1); checks.add(ch2); constraints.put("testField", checks); //when List<Violation> violations = vtor.validate(mockValidationContext(constraints), new ValidateTestObject("testValue"), "testField"); //then assertEquals(1, violations.size()); assertEquals(ch1, violations.get(0).getCheck()); verify(testCheck1Constraint).isValid(any(ValidationConstraintContext.class), eq("testValue")); verify(testCheck2Constraint, never()).isValid(any(ValidationConstraintContext.class), eq("testValue")); }
@Test void testConstructor2() throws Exception { //given Object validatedObject = new Object(); Object invalidValue = new Object(); ValidationConstraint constr = mock(ValidationConstraint.class); Check niceCheck = new Check("niceCheck", constr); //when Violation violation = new Violation("niceViolation", validatedObject, invalidValue, niceCheck); //then assertEquals("niceViolation", violation.getName()); assertEquals(validatedObject, violation.getValidatedObject()); assertEquals(invalidValue, violation.getInvalidValue()); assertEquals(niceCheck, violation.getCheck()); assertEquals(constr, violation.getConstraint()); }
/** * Adds action violation. */ protected void addViolation(final String name, final Object invalidValue) { prepareValidator(); vtor.addViolation(new Violation(name, this, invalidValue)); }
/** * Prepares validation messages. * Key is either validation constraint class name or violation name. */ public static String resolveValidationMessage(final HttpServletRequest request, final Violation violation) { ValidationConstraint vc = violation.getConstraint(); String key = vc != null ? vc.getClass().getName() : violation.getName(); String msg = LocalizationUtil.findMessage(request, key); if (msg != null) { return beanTemplateParser.parseWithBean(msg, violation); } return null; }
/** * Returns JSON violations string. Contains javascript array with elements that contain: * <ul> * <li>name - violation name</li> * <li>msg - message code i.e. constraint class name</li> * </ul> */ public static String createViolationsJsonString(final HttpServletRequest request, final List<Violation> violations) { if (violations == null) { return StringPool.EMPTY; } StringBuilder sb = new StringBuilder().append('['); for (int i = 0, violationsSize = violations.size(); i < violationsSize; i++) { Violation violation = violations.get(i); if (i != 0) { sb.append(','); } sb.append('{'); sb.append("\"name\":\"").append(violation.getName()).append('"').append(','); sb.append("\"msg\":\"").append(resolveValidationMessage(request, violation)).append('"'); sb.append('}'); } sb.append(']'); return sb.toString(); }
@Test void testManualAddViolation() { ValidationContext vctx = new ValidationContext(); vctx.add(new Check("string", new MinLengthConstraint(2))); Vtor vtor = new Vtor(); Foo foo = new Foo(); vtor.validate(vctx, foo); vtor.addViolation(new Violation("number", foo, null)); List<Violation> vlist = vtor.getViolations(); assertFalse(vlist.isEmpty()); assertEquals(2, vlist.size()); Violation v = vlist.get(0); assertEquals("string", v.getName()); assertEquals("1", v.getInvalidValue()); assertEquals("string", v.getCheck().getName()); assertEquals(MinLengthConstraint.class, v.getConstraint().getClass()); v = vlist.get(1); assertEquals("number", v.getName()); assertNull(v.getInvalidValue()); assertNull(v.getCheck()); assertNull(v.getConstraint()); } }
/** * Performs validation of provided validation context and appends violations. */ public void validate(ValidationContext ctx, Object target, String targetName) { for (Map.Entry<String, List<Check>> entry : ctx.map.entrySet()) { String name = entry.getKey(); Object value = BeanUtil.getDeclaredPropertySilently(target, name); String valueName = targetName != null ? (targetName + '.' + name) : name; // move up ValidationConstraintContext vcc = new ValidationConstraintContext(this, target, valueName); for (Check check : entry.getValue()) { String[] checkProfiles = check.getProfiles(); if (matchProfiles(checkProfiles) == false) { continue; } if (check.getSeverity() < severity) { continue; } ValidationConstraint constraint = check.getConstraint(); if (constraint.isValid(vcc, value) == false) { addViolation(new Violation(valueName, target, value, check)); } } } }
@Test void testManualConfig() { ValidationContext vctx = new ValidationContext(); vctx.add(new Check("string", new MinLengthConstraint(2))); Vtor vtor = new Vtor(); vtor.validate(vctx, new Foo()); assertTrue(vtor.hasViolations()); List<Violation> vlist = vtor.getViolations(); assertFalse(vlist.isEmpty()); assertEquals(1, vlist.size()); Violation v = vlist.get(0); assertEquals("string", v.getName()); assertEquals("1", v.getInvalidValue()); assertEquals("string", v.getCheck().getName()); assertNull(v.getCheck().getMessage()); assertEquals(MinLengthConstraint.class, v.getConstraint().getClass()); // new context that contains previous ValidationContext vctx2 = new ValidationContext(); vctx2.add(new Check("foo", new AssertValidConstraint(vctx))); vtor = new Vtor(); vtor.validate(vctx2, new Boo()); vlist = vtor.getViolations(); assertFalse(vlist.isEmpty()); assertEquals(1, vlist.size()); v = vlist.get(0); assertEquals("foo.string", v.getName()); assertEquals("1", v.getInvalidValue()); assertEquals("string", v.getCheck().getName()); assertEquals(MinLengthConstraint.class, v.getConstraint().getClass()); }