/*
 * 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.dom;

import java.util.HashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;

import woolpack.LoadAllTests;
import woolpack.test.TestUtils;
import woolpack.utils.UtilsConstants;
import junit.framework.TestCase;

public class JoinProcessLoadTest extends TestCase {
	boolean flag;

	private void scenario(final DomExpression expression, final ConcurrentMap<String,Object> session) throws InterruptedException{
		flag = true;
		final CountDownLatch latch = new CountDownLatch(LoadAllTests.MAX_THREAD);
		for(int i=0; i<LoadAllTests.MAX_THREAD; i++){
			LoadAllTests.THREAD_POOL.execute(new Runnable(){
				public void run() {
					try{
						final DomContext context = new DomContext();
						context.setId("id0");
						context.setSession(session);
						expression.interpret(context);
						synchronized(this){
							flag &= TestUtils.equalsForm(context, "<INPUT type=\"text\" name=\"name0\" value=\"value0\" />");
						}
					}finally{
						latch.countDown();
					}
				}
			});
		}
		latch.await();
		assertTrue(flag);
	}
	
	/**
	 * 確率的テスト(確率的に失敗する)
	 * @throws InterruptedException
	 */
	public void testNormal() throws InterruptedException{
		int testCount = 500;//LoadAllTests.TEST_COUNT;
		
		final Count counter0 = new Count(new Sleep(5, 5, TestUtils.getToNodeForm("<INPUT type=\"text\" name=\"name0\" value=\"value0\" />")));
		final DomExpression expression = new JoinProcess(counter0);
		
		for(int i=0; i<testCount; i++){
			final ConcurrentMap<String,Object> session = UtilsConstants.concurrentMap(new HashMap<String,Object>(), new Object());
			scenario(expression, session);
			assertEquals(i+1, counter0.getCount());
		}
	}

}
