/*
 * Copyright 2002-2008 the original author or authors.
 *
 * 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 test.common.util;

import static org.junit.Assert.assertEquals;

import org.springframework.config.java.internal.util.Constants;

import org.springframework.context.ConfigurableApplicationContext;


public class Assert {

    /**
     * Validates the number of beans registered with <var>ctx</var> matches <var>expected</var>.
     * Makes a special exception, however for any bean definitions that have the
     * {@link Constants#JAVA_CONFIG_IGNORE}. These definitions are considered 'internal' and not to
     * be counted.
     *
     * @param  ctx       context to interrogate
     * @param  expected  expected number of beans
     */
    public static void assertBeanDefinitionCount(ConfigurableApplicationContext ctx, int expected) {
        int actual = getNonInternalBeanDefinitionCount(ctx);
        assertEquals(expected, actual);
    }

    /**
     * Returns the number of beans in this <var>ctx</var> that are not JavaConfig-internal bean
     * definitions. Said another way, returns the number of beans that the end user has registered.
     */
    public static int getNonInternalBeanDefinitionCount(ConfigurableApplicationContext ctx) {
        int cx = 0;
        for (String name : ctx.getBeanDefinitionNames())
            if (ctx.getBeanFactory().getBeanDefinition(name).getAttribute(Constants.JAVA_CONFIG_IGNORE) == null)
                cx++;

        return cx;
    }
}
