/*
 * Copyright 2010 Proofpoint, Inc.
 *
 * Licensed 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 com.proofpoint.testing;

import com.google.common.annotations.Beta;
import org.apache.bval.jsr303.ApacheValidationProvider;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.lang.annotation.Annotation;
import java.util.Set;

import static java.lang.String.format;
import static org.testng.Assert.fail;

@Beta
public class ValidationAssertions
{
    private static final Validator VALIDATOR = Validation.byProvider(ApacheValidationProvider.class).configure().buildValidatorFactory().getValidator();

    public static <T> T assertValidates(T object)
    {
        return assertValidates(object, null);
    }

    public static <T> T assertValidates(T object, String message)
    {
        Set<ConstraintViolation<T>> violations = VALIDATOR.validate(object);
        if (violations.isEmpty()) {
            return object;
        }
        StringBuilder builder = new StringBuilder(toMessageString(message));
        builder.append("expected:<").append(object).append("> to pass validation:");
        for (ConstraintViolation<T> violation : violations) {
            builder.append("\n\t")
                    .append(violation.getPropertyPath().toString())
                    .append(" failed validation for ")
                    .append(violation.getConstraintDescriptor().getAnnotation().annotationType().getName())
                    .append(" with message '")
                    .append(violation.getMessage())
                    .append("'");
        }
        fail(builder.toString());
        return object;
    }

    public static <T> void assertFailsValidation(T object, String field, String expectedErrorMessage, Class<? extends Annotation> annotation, String message)
    {
        Set<ConstraintViolation<T>> violations = VALIDATOR.validate(object);

        for (ConstraintViolation<T> violation : violations) {
            if (annotation.isInstance(violation.getConstraintDescriptor().getAnnotation()) &&
                    violation.getPropertyPath().toString().equals(field)) {

                if (!violation.getMessage().equals(expectedErrorMessage)) {
                    fail(format("%sexpected %s.%s for <%s> to fail validation for %s with message '%s', but message was '%s'",
                                toMessageString(message),
                                object.getClass().getName(),
                                field,
                                message,
                                annotation.getName(),
                                expectedErrorMessage,
                                violation.getMessage()));

                }
                return;
            }
        }

        fail(format("%sexpected %s.%s for <%s> to fail validation for %s with message '%s'",
                    toMessageString(message),
                    object.getClass().getName(),
                    field,
                    object,
                    annotation.getName(),
                    expectedErrorMessage));
    }

    public static <T> void assertFailsValidation(T object, String field, String expectedErrorMessage, Class<? extends Annotation> annotation)
    {
        assertFailsValidation(object, field, expectedErrorMessage, annotation, null);
    }

    private static String toMessageString(String message)
    {
        return message == null ? "" : message + " ";
    }
}

@@ -1668,24 +1668,249 @@
 idation:%22);%0A
+        appendViolations(builder, violations);%0A        fail(builder.toString());%0A        return object;%0A    %7D%0A%0A    private static %3CT%3E void appendViolations(StringBuilder builder, Set%3CConstraintViolation%3CT%3E%3E violations)%0A    %7B%0A
         for 
@@ -1951,32 +1951,32 @@
 : violations) %7B%0A
-
             buil
@@ -2372,65 +2372,8 @@
   %7D%0A
-        fail(builder.toString());%0A        return object;%0A
     
@@ -3486,36 +3486,73 @@
      %7D%0A%0A        
-fail
+StringBuilder builder = new StringBuilder
 (format(%22%25sexpec
@@ -3624,36 +3624,32 @@
                 
-    
 toMessageString(
@@ -3650,36 +3650,32 @@
 tring(message),%0A
-    
                 
@@ -3715,39 +3715,31 @@
             
-  
-  
 field,%0A
-    
             
@@ -3750,20 +3750,16 @@
 object,%0A
-    
         
@@ -3796,36 +3796,32 @@
                 
-    
 expectedErrorMes
@@ -3824,24 +3824,282 @@
 rMessage));%0A
+        if (violations.isEmpty()) %7B%0A            builder.append(%22 but it passed%22);%0A        %7D else %7B%0A            builder.append(%22 but it failed for other fields:%22);%0A            appendViolations(builder, violations);%0A        %7D%0A        fail(builder.toString());%0A
     %7D%0A%0A    p

Improve assertion message when validation doesn't fail as expected