01: package org.drools.rule;
02:
03: /*
04: * Copyright 2005 JBoss Inc
05: *
06: * Licensed under the Apache License, Version 2.0 (the "License");
07: * you may not use this file except in compliance with the License.
08: * You may obtain a copy of the License at
09: *
10: * http://www.apache.org/licenses/LICENSE-2.0
11: *
12: * Unless required by applicable law or agreed to in writing, software
13: * distributed under the License is distributed on an "AS IS" BASIS,
14: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15: * See the License for the specific language governing permissions and
16: * limitations under the License.
17: */
18:
19: import java.beans.IntrospectionException;
20: import java.beans.Introspector;
21: import java.beans.PropertyDescriptor;
22:
23: import junit.framework.TestCase;
24:
25: import org.drools.Cheese;
26: import org.drools.base.ClassFieldExtractor;
27: import org.drools.base.ClassFieldExtractorCache;
28: import org.drools.base.ClassObjectType;
29: import org.drools.spi.FieldExtractor;
30:
31: public class DeclarationTest extends TestCase {
32:
33: public void testDeclaration() throws IntrospectionException {
34: final FieldExtractor extractor = ClassFieldExtractorCache
35: .getExtractor(Cheese.class, "type", getClass()
36: .getClassLoader());
37:
38: final Pattern pattern = new Pattern(5, new ClassObjectType(
39: Cheese.class));
40:
41: // Bind the extractor to a decleration
42: // Declarations know the pattern they derive their value from
43: final Declaration declaration = new Declaration("typeOfCheese",
44: extractor, pattern);
45:
46: assertEquals("typeOfCheese", declaration.getIdentifier());
47:
48: assertSame(String.class, declaration.getExtractor()
49: .getExtractToClass());
50:
51: assertSame(extractor, declaration.getExtractor());
52:
53: assertEquals(5, declaration.getPattern().getOffset());
54:
55: }
56:
57: public void testGetFieldValue() throws IntrospectionException {
58: final FieldExtractor extractor = ClassFieldExtractorCache
59: .getExtractor(Cheese.class, "type", getClass()
60: .getClassLoader());
61:
62: final Pattern pattern = new Pattern(5, new ClassObjectType(
63: Cheese.class));
64:
65: // Bind the extractor to a decleration
66: // Declarations know the pattern they derive their value from
67: final Declaration declaration = new Declaration("typeOfCheese",
68: extractor, pattern);
69:
70: // Create some facts
71: final Cheese cheddar = new Cheese("cheddar", 5);
72:
73: // Check we can extract Declarations correctly
74: assertEquals("cheddar", declaration.getValue(null, cheddar));
75: }
76:
77: public static int getIndex(final Class clazz, final String name)
78: throws IntrospectionException {
79: final PropertyDescriptor[] descriptors = Introspector
80: .getBeanInfo(clazz).getPropertyDescriptors();
81: for (int i = 0; i < descriptors.length; i++) {
82: if (descriptors[i].getName().equals(name)) {
83: return i;
84: }
85: }
86: return -1;
87: }
88: }
|