/*
 * Copyright 2006 Takahiro Nakamura.
 *
 * 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 woolpack.validator;

import java.util.ArrayList;
import java.util.List;

import junit.framework.TestCase;

public class IfValidatorTest extends TestCase {

	public void testConstructor(){
		try{
			new IfValidator(null, ValidatorConstants.FALSE, ValidatorConstants.FALSE);
			fail();
		}catch(final NullPointerException expected){
		}
		try{
			new IfValidator(ValidatorConstants.FALSE, null, ValidatorConstants.FALSE);
			fail();
		}catch(final NullPointerException expected){
		}
		try{
			new IfValidator(ValidatorConstants.FALSE, ValidatorConstants.FALSE, null);
			fail();
		}catch(final NullPointerException expected){
		}
	}
	
	private void scenario(final boolean[] input, final boolean expectedResult, final int[] expectedCount){
		final List<CountValidator> list = new ArrayList<CountValidator>();
		for(final boolean flag:input){
			list.add(new CountValidator(flag?ValidatorConstants.TRUE:ValidatorConstants.FALSE));
		}
		final ValidatorExpression expression;
		if(input.length == 3){
			expression = new IfValidator(list.get(0), list.get(1), list.get(2));
		}else{
			expression = new IfValidator(list.get(0), list.get(1));
		}
		final ValidatorContext context = new ValidatorContext();
		assertEquals(expectedResult, expression.interpret(context));
		for(int i=0; i<expectedCount.length; i++){
			assertEquals(expectedCount[i], list.get(i).getCount());
			for(int j=0; j<expectedCount[i]; j++){
				assertTrue(context == list.get(i).getContextList().removeLast());
			}
		}
	}
	
	public void testNormal(){
		scenario(new boolean[]{true, true}, true, new int[]{1,1});
		scenario(new boolean[]{true, false}, false, new int[]{1,1});
		scenario(new boolean[]{false, true}, true, new int[]{1,0});
		scenario(new boolean[]{false, false}, true, new int[]{1,0});
		scenario(new boolean[]{true, true, true}, true, new int[]{1,1,0});
		scenario(new boolean[]{true, true, false}, true, new int[]{1,1,0});
		scenario(new boolean[]{true, false, true}, false, new int[]{1,1,0});
		scenario(new boolean[]{true, false, false}, false, new int[]{1,1,0});
		scenario(new boolean[]{false, true, true}, true, new int[]{1,0,1});
		scenario(new boolean[]{false, true, false}, false, new int[]{1,0,1});
		scenario(new boolean[]{false, false, true}, true, new int[]{1,0,1});
		scenario(new boolean[]{false, false, false}, false, new int[]{1,0,1});
	}
}
