[jboss-svn-commits] JBL Code SVN: r21032 - in labs/jbossrules/trunk/drools-compiler/src: main/java/org/drools/testframework and 1 other directories.

jboss-svn-commits at lists.jboss.org jboss-svn-commits at lists.jboss.org
Tue Jul 15 02:00:05 EDT 2008


Author: michael.neale at jboss.com
Date: 2008-07-15 02:00:04 -0400 (Tue, 15 Jul 2008)
New Revision: 21032

Modified:
   labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/guvnor/client/modeldriven/testing/Scenario.java
   labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/testframework/ScenarioRunner.java
   labs/jbossrules/trunk/drools-compiler/src/test/java/org/drools/testframework/ScenarioRunnerTest.java
Log:
scenarios can be run outside of guvnor if needed

Modified: labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/guvnor/client/modeldriven/testing/Scenario.java
===================================================================
--- labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/guvnor/client/modeldriven/testing/Scenario.java	2008-07-15 05:58:42 UTC (rev 21031)
+++ labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/guvnor/client/modeldriven/testing/Scenario.java	2008-07-15 06:00:04 UTC (rev 21032)
@@ -226,6 +226,41 @@
 		return new int[] {failures, total};
 	}
 
+	public String printFailureReport() {
+		int total = 0;
+		int failures = 0;
+		StringBuffer buf = new StringBuffer();
+		buf.append("------- Unmet expectations: -------\n");
+		for (Iterator iterator = fixtures.iterator(); iterator.hasNext();) {
+			Fixture f = (Fixture) iterator.next();
+			if (f instanceof VerifyRuleFired) {
+				total++;
+				VerifyRuleFired vr = (VerifyRuleFired) f;
+				if (vr.successResult != null && !vr.successResult.booleanValue()) {
+					failures++;
+					buf.append(vr.explanation);
+					buf.append('\n');
+				}
+			} else if (f instanceof VerifyFact) {
+				VerifyFact vf = (VerifyFact) f;
+				for (Iterator it = vf.fieldValues.iterator(); it
+						.hasNext();) {
+					VerifyField vfl = (VerifyField) it.next();
+					if (vfl.successResult != null && !vfl.successResult.booleanValue()) {
+						failures++;
+						buf.append(vfl.explanation);
+						buf.append('\n');
+
+					}
+					total++;
+				}
+			}
+		}
+		buf.append("\n------- Summary: ------\n");
+		buf.append(failures + " failures out of " + total + " expectations.");
+		return buf.toString();
+	}
+
 }
 
 

Modified: labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/testframework/ScenarioRunner.java
===================================================================
--- labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/testframework/ScenarioRunner.java	2008-07-15 05:58:42 UTC (rev 21031)
+++ labs/jbossrules/trunk/drools-compiler/src/main/java/org/drools/testframework/ScenarioRunner.java	2008-07-15 06:00:04 UTC (rev 21032)
@@ -10,6 +10,8 @@
 import java.util.Map;
 
 import org.drools.FactHandle;
+import org.drools.RuleBase;
+import org.drools.base.ClassTypeResolver;
 import org.drools.base.TypeResolver;
 import org.drools.common.InternalWorkingMemory;
 import org.drools.guvnor.client.modeldriven.testing.ExecutionTrace;
@@ -22,6 +24,8 @@
 import org.drools.guvnor.client.modeldriven.testing.VerifyFact;
 import org.drools.guvnor.client.modeldriven.testing.VerifyField;
 import org.drools.guvnor.client.modeldriven.testing.VerifyRuleFired;
+import org.drools.guvnor.server.util.ScenarioXMLPersistence;
+import org.drools.rule.Package;
 import org.drools.rule.TimeMachine;
 
 /**
@@ -41,6 +45,7 @@
 
 
 	/**
+	 * This constructor is normally used by Guvnor for running tests on a users request.
 	 * @param scenario
 	 *            The scenario to run.
 	 * @param resolver
@@ -58,85 +63,101 @@
 			final InternalWorkingMemory wm) throws ClassNotFoundException {
 		this.scenario = scenario;
 		this.workingMemory = wm;
-		scenario.lastRunResult = new Date();
+		runScenario(scenario, resolver, wm);
+	}
 
+	/**
+	 * Use this constructor if you have a scenario in a file, for instance.
+	 * @throws ClassNotFoundException
+	 */
+	public ScenarioRunner(String xml, RuleBase rb) throws ClassNotFoundException {
+		this.scenario = ScenarioXMLPersistence.getInstance().unmarshal(xml);
+		this.workingMemory = (InternalWorkingMemory) rb.newStatefulSession();
+		Package pk = rb.getPackages()[0];
+        ClassLoader cl = pk.getPackageScopeClassLoader();
+        HashSet<String> imports = new HashSet<String>();
+        imports.add(pk.getName() + ".*");
+        imports.addAll(pk.getImports().keySet());
+        TypeResolver resolver = new ClassTypeResolver( imports, cl );
+        runScenario(scenario, resolver, this.workingMemory);
+	}
 
+	private void runScenario(final Scenario scenario,
+			final TypeResolver resolver, final InternalWorkingMemory wm)
+			throws ClassNotFoundException {
+		scenario.lastRunResult = new Date();
+		//stub out any rules we don't want to have the consequences firing of.
+		HashSet<String> ruleList = new HashSet<String>();
+		ruleList.addAll(scenario.rules);
+		//TestingEventListener.stubOutRules(ruleList, wm.getRuleBase(), scenario.inclusive);
 
-			//stub out any rules we don't want to have the consequences firing of.
-			HashSet<String> ruleList = new HashSet<String>();
-			ruleList.addAll(scenario.rules);
-			//TestingEventListener.stubOutRules(ruleList, wm.getRuleBase(), scenario.inclusive);
+		TestingEventListener listener = null;
 
-			TestingEventListener listener = null;
+		for (Iterator iterator = scenario.globals.iterator(); iterator.hasNext();) {
+			FactData fact = (FactData) iterator.next();
+			Object f = eval("new " + resolver.getFullTypeName(fact.type) + "()");
+			populateFields(fact, globalData, f);
+			globalData.put(fact.name, f);
+			wm.setGlobal(fact.name, f);
+		}
 
-			for (Iterator iterator = scenario.globals.iterator(); iterator.hasNext();) {
-				FactData fact = (FactData) iterator.next();
-				Object f = eval("new " + resolver.getFullTypeName(fact.type) + "()");
-				populateFields(fact, globalData, f);
-				globalData.put(fact.name, f);
-				wm.setGlobal(fact.name, f);
-			}
+		for (Iterator<Fixture> iterator = scenario.fixtures.iterator(); iterator.hasNext();) {
+			Fixture fx = iterator.next();
 
-			for (Iterator<Fixture> iterator = scenario.fixtures.iterator(); iterator.hasNext();) {
-				Fixture fx = iterator.next();
-
-				if (fx instanceof FactData) {
-					//deal with facts and globals
-					FactData fact = (FactData)fx;
-					Object f = (fact.isModify)? this.populatedData.get(fact.name) : eval("new " + resolver.getFullTypeName(fact.type) + "()");
-					if (fact.isModify) {
-						if (!this.factHandles.containsKey(fact.name)) {
-							throw new IllegalArgumentException("Was not a previously inserted fact. [" + fact.name  + "]");
-						}
-						populateFields(fact, populatedData, f);
-						this.workingMemory.update(this.factHandles.get(fact.name), f);
-					} else /* a new one */ {
-						populateFields(fact, populatedData, f);
-						populatedData.put(fact.name, f);
-						this.factHandles.put(fact.name, wm.insert(f));
+			if (fx instanceof FactData) {
+				//deal with facts and globals
+				FactData fact = (FactData)fx;
+				Object f = (fact.isModify)? this.populatedData.get(fact.name) : eval("new " + resolver.getFullTypeName(fact.type) + "()");
+				if (fact.isModify) {
+					if (!this.factHandles.containsKey(fact.name)) {
+						throw new IllegalArgumentException("Was not a previously inserted fact. [" + fact.name  + "]");
 					}
-				} else if (fx instanceof RetractFact) {
-					RetractFact f = (RetractFact)fx;
-					this.workingMemory.retract(this.factHandles.get(f.name));
-					this.populatedData.remove(f.name);
-				} else if (fx instanceof ExecutionTrace) {
-					ExecutionTrace executionTrace = (ExecutionTrace)fx;
-					//create the listener to trace rules
+					populateFields(fact, populatedData, f);
+					this.workingMemory.update(this.factHandles.get(fact.name), f);
+				} else /* a new one */ {
+					populateFields(fact, populatedData, f);
+					populatedData.put(fact.name, f);
+					this.factHandles.put(fact.name, wm.insert(f));
+				}
+			} else if (fx instanceof RetractFact) {
+				RetractFact f = (RetractFact)fx;
+				this.workingMemory.retract(this.factHandles.get(f.name));
+				this.populatedData.remove(f.name);
+			} else if (fx instanceof ExecutionTrace) {
+				ExecutionTrace executionTrace = (ExecutionTrace)fx;
+				//create the listener to trace rules
 
-					if (listener != null) wm.removeEventListener(listener); //remove the old
-					listener = new TestingEventListener();
+				if (listener != null) wm.removeEventListener(listener); //remove the old
+				listener = new TestingEventListener();
 
-					wm.addEventListener(listener);
+				wm.addEventListener(listener);
 
-					//set up the time machine
-					applyTimeMachine(wm, executionTrace);
+				//set up the time machine
+				applyTimeMachine(wm, executionTrace);
 
-					//love you
-					long time = System.currentTimeMillis();
-					wm.fireAllRules(listener.getAgendaFilter(ruleList, scenario.inclusive),scenario.maxRuleFirings);
-					executionTrace.executionTimeResult = System.currentTimeMillis() - time;
-					executionTrace.numberOfRulesFired = listener.totalFires;
-					executionTrace.rulesFired = listener.getRulesFiredSummary();
+				//love you
+				long time = System.currentTimeMillis();
+				wm.fireAllRules(listener.getAgendaFilter(ruleList, scenario.inclusive),scenario.maxRuleFirings);
+				executionTrace.executionTimeResult = System.currentTimeMillis() - time;
+				executionTrace.numberOfRulesFired = listener.totalFires;
+				executionTrace.rulesFired = listener.getRulesFiredSummary();
 
 
-				} else if (fx instanceof Expectation) {
-						Expectation assertion = (Expectation) fx;
-						if (assertion instanceof VerifyFact) {
-							verify((VerifyFact) assertion);
-						} else if (assertion instanceof VerifyRuleFired) {
-							verify((VerifyRuleFired) assertion,
-									(listener.firingCounts != null) ? listener.firingCounts : new HashMap<String, Integer>());
-						}
-				} else {
-					throw new IllegalArgumentException("Not sure what to do with " + fx);
-				}
-
-
-
+			} else if (fx instanceof Expectation) {
+					Expectation assertion = (Expectation) fx;
+					if (assertion instanceof VerifyFact) {
+						verify((VerifyFact) assertion);
+					} else if (assertion instanceof VerifyRuleFired) {
+						verify((VerifyRuleFired) assertion,
+								(listener.firingCounts != null) ? listener.firingCounts : new HashMap<String, Integer>());
+					}
+			} else {
+				throw new IllegalArgumentException("Not sure what to do with " + fx);
 			}
 
 
 
+		}
 	}
 
 	private void applyTimeMachine(final InternalWorkingMemory wm,
@@ -279,6 +300,21 @@
 		return factObject;
 	}
 
+	/**
+	 * True if the scenario was run with 100% success.
+	 */
+	public boolean wasSuccess() {
+		return this.scenario.wasSuccessful();
+	}
 
+	/**
+	 * @return A pretty printed report detailing any failures that occured
+	 * when running the scenario (unmet expectations).
+	 */
+	public String getReport() {
+		return this.scenario.printFailureReport();
+	}
+
+
 }
 

Modified: labs/jbossrules/trunk/drools-compiler/src/test/java/org/drools/testframework/ScenarioRunnerTest.java
===================================================================
--- labs/jbossrules/trunk/drools-compiler/src/test/java/org/drools/testframework/ScenarioRunnerTest.java	2008-07-15 05:58:42 UTC (rev 21031)
+++ labs/jbossrules/trunk/drools-compiler/src/test/java/org/drools/testframework/ScenarioRunnerTest.java	2008-07-15 06:00:04 UTC (rev 21032)
@@ -25,6 +25,7 @@
 import org.drools.guvnor.client.modeldriven.testing.VerifyFact;
 import org.drools.guvnor.client.modeldriven.testing.VerifyField;
 import org.drools.guvnor.client.modeldriven.testing.VerifyRuleFired;
+import org.drools.guvnor.server.util.ScenarioXMLPersistence;
 import org.drools.rule.TimeMachine;
 
 public class ScenarioRunnerTest extends RuleUnit {
@@ -1017,7 +1018,57 @@
 
     public void testIntegrationWithFailure() throws Exception {
         Scenario sc = new Scenario();
-        FactData[] facts = new FactData[]{new FactData( "Cheese",
+        Expectation[] assertions = populateScenarioForFailure(sc);
+
+        TypeResolver resolver = new ClassTypeResolver( new HashSet<String>(),
+                                                       Thread.currentThread().getContextClassLoader() );
+        resolver.addImport( "org.drools.Cheese" );
+        resolver.addImport( "org.drools.Person" );
+
+        WorkingMemory wm = getWorkingMemory( "test_rules2.drl" );
+
+        ScenarioRunner run = new ScenarioRunner( sc,
+                                                 resolver,
+                                                 (InternalWorkingMemory) wm );
+
+        assertSame( run.scenario,
+                    sc );
+
+        assertFalse( sc.wasSuccessful() );
+
+        VerifyFact vf = (VerifyFact) assertions[1];
+        assertFalse( ((VerifyField) vf.fieldValues.get( 0 )).successResult );
+        assertEquals( "XXX",
+                      ((VerifyField) vf.fieldValues.get( 0 )).expected );
+        assertEquals( "rule1",
+                      ((VerifyField) vf.fieldValues.get( 0 )).actualResult );
+        assertNotNull( ((VerifyField) vf.fieldValues.get( 0 )).explanation );
+
+        VerifyRuleFired vr = (VerifyRuleFired) assertions[4];
+        assertFalse( vr.successResult );
+
+        assertEquals( 2,
+                      vr.expectedCount.intValue() );
+        assertEquals( 1,
+                      vr.actualResult.intValue() );
+
+    }
+
+    public void testRunAsString() throws Exception {
+    	Scenario sc = new Scenario();
+    	populateScenarioForFailure(sc);
+    	String xml = ScenarioXMLPersistence.getInstance().marshal(sc);
+    	WorkingMemory wm = getWorkingMemory( "test_rules2.drl" );
+    	ScenarioRunner runner = new ScenarioRunner(xml, wm.getRuleBase());
+    	assertFalse(runner.wasSuccess());
+
+    	String failures = runner.getReport();
+    	assertFalse("".equals(failures));
+    	System.err.println(failures);
+    }
+
+	private Expectation[] populateScenarioForFailure(Scenario sc) {
+		FactData[] facts = new FactData[]{new FactData( "Cheese",
                                                         "c1",
                                                         ls( new FieldData( "type",
                                                                            "cheddar" ),
@@ -1068,41 +1119,9 @@
                                              null );
 
         sc.fixtures.addAll( Arrays.asList( assertions ) );
+		return assertions;
+	}
 
-        TypeResolver resolver = new ClassTypeResolver( new HashSet<String>(),
-                                                       Thread.currentThread().getContextClassLoader() );
-        resolver.addImport( "org.drools.Cheese" );
-        resolver.addImport( "org.drools.Person" );
-
-        WorkingMemory wm = getWorkingMemory( "test_rules2.drl" );
-
-        ScenarioRunner run = new ScenarioRunner( sc,
-                                                 resolver,
-                                                 (InternalWorkingMemory) wm );
-
-        assertSame( run.scenario,
-                    sc );
-
-        assertFalse( sc.wasSuccessful() );
-
-        VerifyFact vf = (VerifyFact) assertions[1];
-        assertFalse( ((VerifyField) vf.fieldValues.get( 0 )).successResult );
-        assertEquals( "XXX",
-                      ((VerifyField) vf.fieldValues.get( 0 )).expected );
-        assertEquals( "rule1",
-                      ((VerifyField) vf.fieldValues.get( 0 )).actualResult );
-        assertNotNull( ((VerifyField) vf.fieldValues.get( 0 )).explanation );
-
-        VerifyRuleFired vr = (VerifyRuleFired) assertions[4];
-        assertFalse( vr.successResult );
-
-        assertEquals( 2,
-                      vr.expectedCount.intValue() );
-        assertEquals( 1,
-                      vr.actualResult.intValue() );
-
-    }
-
     private <T> List<T> ls(T... objects) {
         return Arrays.asList( objects );
     }




More information about the jboss-svn-commits mailing list