KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > idaremedia > antx > capture > AssertLoggedTask


1 /**
2  * $Id: AssertLoggedTask.java 180 2007-03-15 12:56:38Z ssmc $
3  * Copyright 2002-2005 iDare Media, Inc. All rights reserved.
4  *
5  * Originally written by iDare Media, Inc. for release into the public domain. This
6  * library, source form and binary form, is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public License as published by the
8  * Free Software Foundation; either version 2.1 of the License, or (at your option) any
9  * later version.<p>
10  *
11  * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
12  * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13  * See the GNU LGPL (GNU Lesser General Public License) for more details.<p>
14  *
15  * You should have received a copy of the GNU Lesser General Public License along with this
16  * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite
17  * 330, Boston, MA 02111-1307 USA. The LGPL can be found online at
18  * http://www.fsf.org/copyleft/lesser.html<p>
19  *
20  * This product has been influenced by several projects within the open-source community.
21  * The JWare developers wish to acknowledge the open-source community's support. For more
22  * information regarding the open-source products used within JWare, please visit the
23  * JWare website.
24  *----------------------------------------------------------------------------------------*
25  * WEBSITE- http://www.jware.info EMAIL- inquiries@jware.info
26  *----------------------------------------------------------------------------------------*
27  **/

28
29 package com.idaremedia.antx.capture;
30
31 import java.util.ArrayList JavaDoc;
32
33 import org.apache.tools.ant.BuildException;
34 import org.apache.tools.ant.Project;
35 import org.apache.tools.ant.taskdefs.condition.Condition;
36 import org.apache.tools.ant.types.RegularExpression;
37 import org.apache.tools.ant.util.regexp.RegexpMatcher;
38
39 import com.idaremedia.antx.AntX;
40 import com.idaremedia.antx.apis.BuildAssertionException;
41 import com.idaremedia.antx.apis.TestScriptComponent;
42 import com.idaremedia.antx.helpers.InnerString;
43 import com.idaremedia.antx.helpers.Empties;
44 import com.idaremedia.antx.helpers.Strings;
45
46 /**
47  * Assertion task whose conditions all involve checking contents of captured feedback
48  * messages. No real use outside of testing other task implementations.
49  * <p>
50  * <b>Example Usage:</b><pre>
51  * &lt;capturelogs&gt;
52  * &lt;echo level="warning" message="((Warning))"/&gt;
53  * &lt;assertlogged value="((Warning))" trueproperty="Was.warned"/&gt;
54  * &lt;assert issettrue="Was.warned"/&gt;
55  * &lt;echo level="verbose" message="((Verbose))"/&gt;
56  * &lt;assertlogged value="((Verbose))" occurances="0" msg="Broken importance check"/&gt;
57  * &lt;assertlogged important="no" value="((Verbose))" occurances="1"/&gt;
58  * &lt;assertlogged important="no"&gt;
59  * &lt;string value="((Warning))"/&gt;
60  * &lt;string value="((Verbose))"/&gt;
61  * &lt;/assertlogged&gt;
62  * &lt;/capturelogs&gt;
63  * </pre>
64  * If a regular expression is defined for the assertion (using
65  * &lt;assertlogged like="&#46;&#46;&#46;"/&gt;) then no other match parameter or
66  * nested element is allowed. The regular expression must contain any occurances specifiers.
67  *
68  * @since JWare/AntX 0.2
69  * @author ssmc, &copy;2002-2005 <a HREF="http://www.jware.info">iDare&nbsp;Media,&nbsp;Inc.</a>
70  * @version 0.5
71  * @.safety single
72  * @.group api,test,helper
73  * @see CaptureLogsTask
74  * @see CaptureStreamsTask
75  **/

76
77 public final class AssertLoggedTask extends LogsUsingTask
78     implements Condition, TestScriptComponent
79 {
80     /**
81      * Initializes a new AssertLoggedTask instance.
82      **/

83     public AssertLoggedTask()
84     {
85         super(AntX.capture+"AssertLoggedTask:");
86     }
87
88
89 // ---------------------------------------------------------------------------------------
90
// Parameters, Nested Elements:
91
// ---------------------------------------------------------------------------------------
92

93     /**
94      * Sets an inlined message to be displayed if assertion
95      * fails.
96      **/

97     public final void setMsg(String JavaDoc msg)
98     {
99         m_defaultMsg = msg;
100     }
101
102
103     /**
104      * Returns this task's inlined default message. Returns
105      * <i>null</i> if never set.
106      */

107     public final String JavaDoc getDefaultMsg()
108     {
109         return m_defaultMsg;
110     }
111
112
113     /**
114      * Defines the single value to look for in recorded logs. If
115      * defined no other match parameter or nested elements are allowed.
116      * @throws BuildException if this task already setup to look for an
117      * order list of values
118      * @see #setLike
119      **/

120     public void setValue(String JavaDoc value)
121     {
122         require_(value!=null,"setValu- nonzro valu");
123         checkLookupMechanism("value");
124         m_requiredValue = value;
125     }
126
127
128     /**
129      * Returns the single value to look for in recorded logs.
130      * Will return <i>null</i> if never set.
131      **/

132     public final String JavaDoc getValue()
133     {
134         return m_requiredValue;
135     }
136
137
138     /**
139      * Sets the expected number of occurances of the value under
140      * test. Set to zero to indicate the value should <em>not</em>
141      * exist in logs. Set to a negative value to indicate the value
142      * can occur any number of times (will just check that exists).
143      * @param Ntimes number of occurances
144      **/

145     public void setOccurances(int Ntimes)
146     {
147         m_Ntimes = Ntimes;
148     }
149
150     /**
151      * Typo-friendly synonym for {@linkplain #setOccurances
152      * setOccurances}.
153      **/

154     public final void setOccurance(int Ntimes)
155     {
156         setOccurances(Ntimes);
157     }
158
159
160     /**
161      * Returns the expected number of occurances of the value
162      * under test. Will return a negative number if never set (which
163      * means the value can exist one or more times). Will return
164      * zero if the value should <em>not</em> exist; otherwise
165      * returns the number of expected occurance.
166      **/

167     public final int getOccurances()
168     {
169         return m_Ntimes;
170     }
171
172
173     /**
174      * Defines the regular expression to look for in recorded logs.
175      * If defined no other match parameter or nested elements are allowed.
176      * @param pattern regular expression to match in logs (non-null)
177      * @throws BuildException if this task already setup with any
178      * other type of lookup mechanim
179      * @since JWare/AntX 0.3
180      **/

181     public void setLike(String JavaDoc pattern)
182     {
183         require_(pattern!=null,"setLike- nonzro pattern");
184         checkLookupMechanism("like");
185         m_RE = new RegularExpression();
186         m_RE.setPattern(pattern);
187     }
188
189
190     /**
191      * Returns the regular expression used to search recored logs.
192      * Returns <i>null</i> if regular expression never defined.
193      * @since JWare/AntX 0.3
194      **/

195     public final String JavaDoc getLike()
196     {
197         return (m_RE==null) ? null : m_RE.getPattern(getProject());
198     }
199
200
201     /**
202      * Sets the property to be created on a positive evaluation.
203      * Property will be set to the string "<i>true</i>."
204      * @param property the property to create (non-null)
205      **/

206     public void setTrueProperty(String JavaDoc property)
207     {
208         require_(property!=null,"setTrueP- nonzro nam");
209         m_trueProperty = property;
210     }
211
212
213     /**
214      * Returns the property to be created/set on a positive
215      * evaluation. Returns <i>null</i> if never set.
216      **/

217     public final String JavaDoc getTrueProperty()
218     {
219         return m_trueProperty;
220     }
221
222
223     /**
224      * Adds next value item to this task's expected ordered value
225      * sequence.
226      * @throws BuildException if this task already setup to look for
227      * a single value
228      * @see #setValue
229      **/

230     public void addConfiguredString(InnerString valueN)
231     {
232         require_(valueN!=null,"addString- nonzro valu");
233
234         if (m_orderedValues.isEmpty()) {
235             checkLookupMechanism("orderset");
236         }
237         m_orderedValues.add(valueN.toString(getProject()));
238     }
239
240
241     /**
242      * Returns <i>true</i> if this task is already configured to
243      * check an ordered sequence of values.
244      **/

245     public final boolean willCheckOrder()
246     {
247         return !m_orderedValues.isEmpty();
248     }
249
250
251 // ---------------------------------------------------------------------------------------
252
// Evaluation:
253
// ---------------------------------------------------------------------------------------
254

255     /**
256      * Verifies that a value either exists or not within the given
257      * log set.
258      * @param log the logs against which value under test checked (non-null)
259      * @param string value under test (non-null)
260      * @param Nwant zero if the value should not exist otherwise value
261      * should exist at least once
262      * @throws BuildAssertionException if value check fails
263      **/

264     protected final void verifyExists(String JavaDoc log, final String JavaDoc string, int Nwant)
265     {
266         String JavaDoc ermsg = null;
267         int Nfound= -1;
268         int i = log.indexOf(string);
269         if (Nwant>0) {
270             if (i == -1) {
271                 ermsg = "brul.logs.missing.value";
272                 Nfound = 0;
273                 Nwant = 1;
274             }
275         } else if (i != -1) {
276             ermsg = "brul.logs.found.value";
277             Nfound = 1;
278             Nwant = 0;
279         }
280         if (ermsg!=null) {//NB:true means boo-boo found
281
if (getDefaultMsg()!=null) {
282                 ermsg = getDefaultMsg();
283             } else {
284                 ermsg = getAntXMsg(ermsg,String.valueOf(Nwant),
285                                    String.valueOf(Nfound),string);
286             }
287             log(ermsg,Project.MSG_ERR);
288             throw new BuildAssertionException(ermsg,getLocation());
289         }
290     }
291
292
293     /**
294      * Verifies that a value exists <i>N</i>-times in the given log set.
295      * @param log the logs against which value under test checked (non-null)
296      * @param string value under test (non-null)
297      * @param Nwant number of times the 'string' should exist in the log
298      * @throws BuildAssertionException if value check fails
299      **/

300     protected final void verifyOccurances(String JavaDoc log, String JavaDoc string, int Nwant)
301     {
302         int Nfound= 0;
303         int i, from=0;
304         while ((i=log.indexOf(string,from))>=0) {
305             Nfound++;
306             from = i+string.length();
307         }
308         if (Nfound!=Nwant) {
309             String JavaDoc ermsg;
310             if (getDefaultMsg()!=null) {
311                 ermsg = getDefaultMsg();
312             } else {
313                 ermsg = getAntXMsg("brul.logs.mismatch.occurs",
314                                    String.valueOf(Nwant),String.valueOf(Nfound),
315                                    string);
316             }
317             log(ermsg,Project.MSG_ERR);
318             throw new BuildAssertionException(ermsg,getLocation());
319         }
320     }
321
322
323     /**
324      * Verify the order in which certain marker strings were sent to the
325      * captured logs.
326      * @param log the logs against which string will be checked (non-null)
327      * @param strings the sequence of strings as expected in log
328      * @throws BuildAssertionException if value check fails
329      **/

330     protected final void verifyOutputInOrder(String JavaDoc log, String JavaDoc[] strings)
331     {
332         String JavaDoc ermsg=null;
333         final int Nmax = log.length();
334         int ilast=0;
335         for (int i=0;i<strings.length;i++) {
336             int at = log.indexOf(strings[i], ilast);
337             if (at<0) {
338                 ermsg = getAntXMsg("brul.logs.outofplace",strings[i],String.valueOf(i));
339                 break;
340             }
341             ilast = at+strings[i].length();
342             if ((ilast==Nmax) && (i!=strings.length-1)) {
343                 ermsg = getAntXMsg("brul.logs.eof",strings[i+1],strings[i],String.valueOf(i));
344                 break;
345             }
346         }
347         if (ermsg!=null) {
348             if (getDefaultMsg()!=null) {
349                 ermsg = getDefaultMsg();
350             }
351             log(ermsg,Project.MSG_ERR);
352             throw new BuildAssertionException(ermsg,getLocation());
353         }
354     }
355
356
357     /**
358      * Verify that a regular expression matches against the given log set.
359      * @param log the logs against which string will be checked (non-null)
360      * @param re the Ant regular expression matches (non-null)
361      * @throws BuildAssertionException if nothing matches
362      * @since JWare/AntX 0.3
363      **/

364     protected final void verifyMatches(String JavaDoc log, RegexpMatcher re)
365     {
366         if (!re.matches(log)) {
367             String JavaDoc ermsg = getAntXMsg("brul.logs.no.match",re.getPattern());
368             log(ermsg,Project.MSG_ERR);
369             throw new BuildAssertionException(ermsg,getLocation());
370         }
371     }
372
373
374     /**
375      * Evaluates this assertion as a condition. Will throw an assertion
376      * exception if <i>false</i>.
377      **/

378     public boolean eval()
379     {
380         verifyCanExecute_("eval");
381
382         boolean evaluated = false;
383
384         String JavaDoc vutLog = getVUTLog();
385
386         if (getLike()!=null) {
387             verifyMatches(vutLog, m_RE.getRegexp(getProject()));
388             evaluated = true;
389         }
390         else if (getValue()!=null) {
391             int N = getOccurances();
392             if (N>0) {
393                 verifyOccurances(vutLog,getValue(),N);
394             } else {
395                 verifyExists(vutLog,getValue(),N==0 ? 0 : 1);
396             }
397             evaluated = true;
398         }
399         else if (!m_orderedValues.isEmpty()) {
400             String JavaDoc[] strings = (String JavaDoc[])m_orderedValues.toArray(Empties.EMPTY_STRING_ARRAY);
401             verifyOutputInOrder(vutLog,strings);
402             strings = null;
403             evaluated = true;
404         }
405
406         if (evaluated) {
407             if (getTrueProperty()!=null) {
408                 String JavaDoc prop = getTrueProperty();
409                 log("AssertLogged was true; setting true-property '"+prop+"' property",
410                     Project.MSG_DEBUG);
411                 getProject().setNewProperty(prop,Strings.TRUE);
412             }
413             if (willReset()) {
414                 LogsRecorder r = getRecorder(true);
415                 if (r!=null) {
416                     r.clearLogs();
417                 }
418             }
419         }
420
421         return true;
422     }
423
424
425     /**
426      * Same as {@linkplain #eval evaluation} only ignoring
427      * the result.
428      **/

429     public void execute()
430     {
431         eval();
432     }
433
434
435     /**
436      * Verify this task is enclosed by at least one {@linkplain LogsRecorder
437      * logs recording} taskset and has a fully defined condition.
438      * @throws BuildException if neither a value or a sequence of values defined
439      **/

440     protected void verifyCanExecute_(String JavaDoc calr)
441     {
442         super.verifyCanExecute_(calr);
443
444         if (m_numMechanisms==0) {
445             String JavaDoc ermsg = getAntXMsg("brul.logs.nothing.to.check");
446             log(ermsg,Project.MSG_ERR);
447             throw new BuildException(ermsg,getLocation());
448         }
449     }
450
451
452     /**
453      * Ensure there are no other lookup mechanisms defined.
454      * @param from [optional] calling setter's name
455      **/

456     private void checkLookupMechanism(String JavaDoc from)
457     {
458         if (m_numMechanisms>0) {
459             String JavaDoc ermsg = getAntXMsg("brul.logs.one.lookup.kind");
460             log(ermsg,Project.MSG_ERR);
461             throw new BuildException(ermsg,getLocation());
462         }
463         m_numMechanisms++;
464     }
465
466
467     /** Flag to indicate looking just for existence. **/
468     private static final int ATLEAST_ONCE= -1;
469
470     private String JavaDoc m_requiredValue;//NB:this or nested ordered entries
471
private int m_Ntimes= ATLEAST_ONCE;//NB:by default look any number
472
private RegularExpression m_RE;//NB:cache the RE for 'like' lookups
473
private String JavaDoc m_defaultMsg;//NB:inlined error message
474
private String JavaDoc m_trueProperty;//NB:
475
private ArrayList JavaDoc m_orderedValues= new ArrayList JavaDoc(5);
476     private int m_numMechanisms;//NB:ensure only one defined
477
}
478
479 /* end-of-AssertLoggedTask.java */
480
Popular Tags