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

import java.util.regex.Pattern;

import junit.framework.TestCase;
import woolpack.convert.ConvertUtils;
import woolpack.fn.Fn;
import woolpack.fn.FnUtils;

public class IdUtilsTest extends TestCase {

	public void testConvertId() {
		final Fn<IdContext, Boolean> fn = 
			IdUtils.convertId(ConvertUtils.convertRegExp(Pattern.compile("a(.+)b"), "$1"));
		final SimpleIdContext context = new SimpleIdContext();
		context.setId("accb");
		assertNull(fn.exec(context));
		assertEquals("cc", context.getId());
	}

	public void testGetId() {
		final Fn<IdContext, String> fn = IdUtils.GET_ID;
		final SimpleIdContext context = new SimpleIdContext();
		assertNull(fn.exec(context));
		context.setId("id0");
		assertEquals("id0", fn.exec(context));
	}
	
	public void testLocalId() {
		final Fn<SimpleIdContext, Object> expression =
			IdUtils.localId(IdUtils.convertId(FnUtils.fix("id0")));
		final SimpleIdContext context = new SimpleIdContext();
		context.setId("id1");
		expression.exec(context);
		assertEquals("id1", context.getId());
	}
	
	public void testLocalIdException() {
		final Fn<SimpleIdContext, Object> expression =
			IdUtils.localId(FnUtils.join(
					IdUtils.convertId(FnUtils.fix("id0")),
					FnUtils.throwing(new IllegalStateException())));
		final SimpleIdContext context = new SimpleIdContext();
		context.setId("id1");
		try {
			expression.exec(context);
			fail();
		} catch (final IllegalStateException e) {
		}
		assertEquals("id1", context.getId());
	}
}
