KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > blandware > atleap > webapp > webtest > BaseWebTestCase


1 /*
2  * Copyright 2004 Blandware (http://www.blandware.com)
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package com.blandware.atleap.webapp.webtest;
17
18 import com.blandware.atleap.common.util.ConvertUtil;
19 import com.blandware.atleap.common.util.StringUtil;
20 import com.gargoylesoftware.htmlunit.ElementNotFoundException;
21 import com.gargoylesoftware.htmlunit.Page;
22 import com.gargoylesoftware.htmlunit.WebClient;
23 import com.gargoylesoftware.htmlunit.html.*;
24 import com.gargoylesoftware.htmlunit.html.xpath.HtmlUnitXPath;
25 import junit.framework.TestCase;
26 import org.apache.commons.logging.Log;
27 import org.apache.commons.logging.LogFactory;
28 import org.apache.oro.text.regex.MalformedPatternException;
29 import org.apache.oro.text.regex.Pattern;
30 import org.apache.oro.text.regex.PatternCompiler;
31 import org.apache.oro.text.regex.PatternMatcher;
32 import org.apache.oro.text.regex.Perl5Compiler;
33 import org.apache.oro.text.regex.Perl5Matcher;
34 import org.jaxen.JaxenException;
35 import org.jaxen.XPath;
36
37 import java.io.File JavaDoc;
38 import java.io.FileOutputStream JavaDoc;
39 import java.io.IOException JavaDoc;
40 import java.io.InputStream JavaDoc;
41 import java.net.URL JavaDoc;
42 import java.text.MessageFormat JavaDoc;
43 import java.util.Calendar JavaDoc;
44 import java.util.Date JavaDoc;
45 import java.util.HashMap JavaDoc;
46 import java.util.Iterator JavaDoc;
47 import java.util.List JavaDoc;
48 import java.util.Map JavaDoc;
49 import java.util.Properties JavaDoc;
50 import java.util.ResourceBundle JavaDoc;
51
52 /**
53  * <p>Describes test case in terms of web application interface. Provides some methods, which can be used in sublasses</p>
54  * <p><a HREF="BaseWebTestCase.java.htm"><i>View Source</i></a></p>
55  *
56  * @author Sergey Zubtcovskii <a HREF="mailto:sergey.zubtcovskii@blandware.com">&lt;sergey.zubtcovskii@blandware.com&gt;</a>
57  * @version $Revision: 1.3 $ $Date: 2005/11/13 08:27:05 $
58  */

59 public abstract class BaseWebTestCase extends TestCase {
60
61     /**
62      * Type of HTML text input
63      */

64     protected static final String JavaDoc INPUT_TYPE_TEXT = "text";
65
66     /**
67      * Type of HTML password input
68      */

69     protected static final String JavaDoc INPUT_TYPE_PASSWORD = "password";
70
71     /**
72      * Type of HTML submit button input
73      */

74     protected static final String JavaDoc INPUT_TYPE_SUBMIT = "submit";
75
76
77     /**
78      * Type of HTML button input
79      */

80     protected static final String JavaDoc INPUT_TYPE_BUTTON = "button";
81
82     /**
83      * Type of HTML reset button input
84      */

85     protected static final String JavaDoc INPUT_TYPE_RESET = "reset";
86
87     /**
88      * Type of HTML checkbox input
89      */

90     protected static final String JavaDoc INPUT_TYPE_CHECKBOX = "checkbox";
91
92     /**
93      * Type of HTML radio button input
94      */

95     protected static final String JavaDoc INPUT_TYPE_RADIO = "radio";
96
97     /**
98      * Type of HTML file upload input
99      */

100     protected static final String JavaDoc INPUT_TYPE_FILE = "file";
101
102     /**
103      * Type of HTML hidden input
104      */

105     protected static final String JavaDoc INPUT_TYPE_HIDDEN = "hidden";
106
107     /**
108      * Type of HTML image button input
109      */

110     protected static final String JavaDoc INPUT_TYPE_IMAGE = "image";
111
112     /**
113      * MessageFormat instance, which is used to produce error message, when some input field is of unexpected type
114      */

115     protected static final MessageFormat JavaDoc UNEXPECTED_INPUT_TYPE = new MessageFormat JavaDoc("Input with name '{0}' in form '{1}' does not seem to be of type '{2}', though expected");
116
117     /**
118      * Name of user, which has been granted administrator privileges
119      */

120     protected static final String JavaDoc ADMIN_USER_NAME = "admin";
121
122     /**
123      * Password of user, which has been granted administrator privileges
124      */

125     protected static final String JavaDoc ADMIN_PASSWORD = "password";
126
127     /**
128      * Commons-loggin instance for this class
129      */

130     protected transient final Log log = LogFactory.getLog(getClass());
131
132     /**
133      * Prefix of file, where to save response
134      */

135     protected String JavaDoc responseFilePrefix = "response-";
136
137     /**
138      * Base URL of our application
139      */

140     protected String JavaDoc baseUrl = null;
141
142     /**
143      * Whether or not to save each response into file
144      */

145     protected Boolean JavaDoc saveResponse = null;
146
147     /**
148      * Message bundle, used to get localized messages in order to compare
149      * some text with keys rather than values
150      */

151     protected static Properties JavaDoc messageBundle = new Properties JavaDoc();
152
153     /**
154      * Web client, which is used to talk with server
155      */

156     protected WebClient webClient;
157
158     /**
159      * Last response, received from server
160      */

161     protected HtmlPage lastResponse;
162
163     /**
164      * Configuration options
165      */

166     protected static Map JavaDoc config = new HashMap JavaDoc();
167
168     // initializes configuration
169
static {
170         // get WebTest resource bundle, which must be always present
171
String JavaDoc bundleName = BaseWebTestCase.class.getPackage().getName();
172         bundleName += ".WebTest";
173
174         ResourceBundle JavaDoc rb = ResourceBundle.getBundle(bundleName);
175         config = ConvertUtil.convertBundleToMap(rb);
176
177
178         String JavaDoc messageBundleFileName = (String JavaDoc) config.get("messageBundle");
179         if ( messageBundleFileName != null && messageBundleFileName.length() > 0 ) {
180             InputStream JavaDoc in = null;
181             try {
182                 in = BaseWebTestCase.class.getClassLoader().getResourceAsStream("ApplicationResources_en.properties");
183                 if ( in != null ) {
184                     messageBundle.load(in);
185                 } else {
186                     throw new ExceptionInInitializerError JavaDoc("Message bundle file (" + messageBundleFileName + ") could not be found in classpath");
187                 }
188             } catch ( IOException JavaDoc e ) {
189                 throw new ExceptionInInitializerError JavaDoc(e);
190             } finally {
191                 try {
192                     if ( in != null ) {
193                         in.close();
194                     }
195                 } catch ( Exception JavaDoc e ) {
196                 }
197             }
198         }
199     }
200
201     /**
202      * Creates new instance of BaseWebTestCase
203      */

204     public BaseWebTestCase() {
205         super();
206         init();
207     }
208
209     /**
210      * Creates new instance of BaseWebTestCase
211      *
212      * @param name Name of method to invoke on test run
213      */

214     public BaseWebTestCase(String JavaDoc name) {
215         super(name);
216         init();
217     }
218
219     /**
220      * Performs initalization of this class
221      */

222     protected final void init() {
223         webClient = new WebClient();
224         webClient.setJavaScriptEnabled(false);
225         webClient.addRequestHeader("Accept-Language", "en");
226     }
227
228
229     /**
230      * Returns message from message bundle, associated with specified key
231      *
232      * @param key Key to look up message for
233      * @return Message, associated with specified key, or <code>null</code>, if there is no such key in bundle
234      */

235     protected String JavaDoc getMessage(String JavaDoc key) {
236         return messageBundle.getProperty(key);
237     }
238
239     /**
240      * Creates base URL, according to protocol, host, port and context path settings
241      *
242      * @return Base URL for our application
243      */

244     protected String JavaDoc createBaseUrl() {
245
246         if ( baseUrl != null ) {
247             return baseUrl;
248         }
249
250         // construct base URL
251
String JavaDoc protocol = (String JavaDoc) config.get("protocol");
252         if ( protocol == null || !"http".equalsIgnoreCase(protocol) && !"https".equalsIgnoreCase(protocol) ) {
253             // unknown protocol
254
if ( log.isWarnEnabled() ) {
255                 log.warn("Protocol does not specified or is unsupported. Using http instead");
256             }
257             protocol = "http";
258         } else {
259             protocol = protocol.toLowerCase();
260         }
261
262         String JavaDoc host = (String JavaDoc) config.get("host");
263
264         if ( host == null || host.length() == 0 ) {
265             if ( log.isWarnEnabled() ) {
266                 log.warn("Host does not specified, assume localhost");
267             }
268             host = "localhost";
269         }
270
271         String JavaDoc portString = (String JavaDoc) config.get("port");
272         int port;
273         try {
274             port = Integer.parseInt(portString);
275         } catch ( RuntimeException JavaDoc e ) {
276             if ( log.isWarnEnabled() ) {
277                 log.warn(e.getClass().getName() + ": No port specified, or value is incorrect. Using default, according to protocol");
278             }
279             if ( "http".equals(protocol) ) {
280                 port = 80;
281             } else {
282                 // https
283
port = 443;
284             }
285         }
286
287         String JavaDoc contextPath = (String JavaDoc) config.get("contextPath");
288         if ( contextPath == null ) {
289             contextPath = "";
290         }
291
292         if ( !contextPath.startsWith("/") ) {
293             contextPath = "/" + contextPath;
294         }
295
296         baseUrl = protocol + "://" + host + ":" + port + contextPath;
297         return baseUrl;
298     }
299
300     /**
301      * Returns <code>true</code> if each response should be saved
302      *
303      * @return <code>True</code> if each response should be saved
304      */

305     protected boolean isSaveResponse() {
306         if ( saveResponse != null ) {
307             return saveResponse.booleanValue();
308         }
309
310         saveResponse = Boolean.TRUE;
311         Object JavaDoc saveReponseParam = config.get("saveResponse");
312         if ( saveReponseParam != null ) {
313             if ( saveReponseParam instanceof Boolean JavaDoc ) {
314                 saveResponse = (Boolean JavaDoc) saveReponseParam;
315             } else if ( saveReponseParam instanceof String JavaDoc ) {
316                 saveResponse = Boolean.valueOf((String JavaDoc) saveReponseParam);
317             }
318         }
319         return saveResponse.booleanValue();
320     }
321
322     /**
323      * Returns path, where to save responses
324      *
325      * @return Path, where to save responses
326      */

327     protected String JavaDoc getResultPath() {
328         return (String JavaDoc) config.get("resultPath");
329     }
330
331     /**
332      * Creates file, where to save response. File name will be constructed from
333      * respone prefix, current date in format YYYY-MM-dd, time in format HH-mm-ss and number of milliseconds,
334      * separated by underscores
335      *
336      * @return Instance of <code>java.io.File</code>, representing file, which will be used for saving response
337      */

338     protected File JavaDoc createResponseFile() {
339         Calendar JavaDoc cal = Calendar.getInstance();
340         cal.setTime(new Date JavaDoc());
341
342         // create file name
343
StringBuffer JavaDoc fileName = new StringBuffer JavaDoc();
344         String JavaDoc resultPath = getResultPath();
345         if ( resultPath != null && resultPath.length() > 0 ) {
346             if ( !resultPath.endsWith(File.separator) ) {
347                 resultPath += File.separator;
348             }
349             fileName.append(resultPath);
350         }
351
352         // append prefix
353
fileName.append(responseFilePrefix);
354
355         // append date in format YYYY-MM-dd
356
fileName.append(cal.get(Calendar.YEAR)).append("-");
357         fileName.append(StringUtil.completeNumber(cal.get(Calendar.MONTH) + 1, 2)).append("-");
358         fileName.append(StringUtil.completeNumber(cal.get(Calendar.DATE), 2));
359
360         // separator
361
fileName.append("_");
362
363         // append time in format HH-mm-ss
364
fileName.append(StringUtil.completeNumber(cal.get(Calendar.HOUR_OF_DAY), 2)).append("-");
365         fileName.append(StringUtil.completeNumber(cal.get(Calendar.MINUTE), 2)).append("-");
366         fileName.append(StringUtil.completeNumber(cal.get(Calendar.SECOND), 2));
367
368         // separator
369
fileName.append("_");
370
371         // append milliseconds
372
fileName.append(StringUtil.completeNumber(cal.get(Calendar.MILLISECOND), 3));
373
374         // append extension
375
fileName.append(".html");
376         return new File JavaDoc(fileName.toString());
377     }
378
379     /**
380      * Saves response to specified file
381      *
382      * @param responseFile File to save response into
383      * @param response Response to save
384      * @throws IOException if any I/O error occurs
385      */

386     protected void saveResponse(File JavaDoc responseFile, Page response) throws IOException JavaDoc {
387         FileOutputStream JavaDoc out = new FileOutputStream JavaDoc(responseFile);
388         out.write(response.getWebResponse().getResponseBody());
389         out.close();
390     }
391
392     /**
393      * Invoces specified URL and returns page, which was returned by server
394      *
395      * @param relativeUrl URL, relative to base URL of our application
396      * @throws IOException if any I/O error occurs
397      */

398     protected void invoke(String JavaDoc relativeUrl) throws IOException JavaDoc {
399         String JavaDoc absoluteUrl = createBaseUrl();
400         if ( !absoluteUrl.endsWith("/") ) {
401             absoluteUrl += "/";
402         }
403
404         if ( relativeUrl.startsWith("/") ) {
405             relativeUrl = relativeUrl.substring(1);
406         }
407
408         absoluteUrl += relativeUrl;
409
410         setLastResponse((HtmlPage) webClient.getPage(new URL JavaDoc(absoluteUrl)));
411     }
412
413     /**
414      * Logs into application with specified user name and password, using form authentication.
415      * First of all verifies, that login form is present and contains all needed elements, then logins and verifies,
416      * that logout form has appeared
417      *
418      * @param userName User name to log in with
419      * @param password Password to log in with
420      * @throws IOException if any I/O error occurs
421      */

422     protected void login(String JavaDoc userName, String JavaDoc password) throws IOException JavaDoc {
423
424         // request restricted resource
425
invoke("/admin.do");
426
427         // look for login form
428
HtmlForm loginForm = getFormByName("loginForm");
429
430         // look for j_username and j_password fields
431
HtmlTextInput userNameField = (HtmlTextInput) getInputByName(loginForm, "j_username", INPUT_TYPE_TEXT);
432         HtmlPasswordInput passwordField = (HtmlPasswordInput) getInputByName(loginForm, "j_password", INPUT_TYPE_PASSWORD);
433
434         userNameField.setValueAttribute(userName);
435         passwordField.setValueAttribute(password);
436
437         // perform login
438
clickButtonWithLabel(loginForm, getMessage("core.commons.buttons.login"));
439
440         // verify, that logout form exists on the received page
441
getFormByName("logoutForm");
442
443         // login successfull
444
if ( log.isInfoEnabled() ) {
445             log.info("User '" + userName + "' has successfully logged in");
446         }
447     }
448
449     /**
450      * Overloaded method, which logs in user with name "admin" and
451      * password "password"
452      *
453      * @throws IOException if any I/O error occurs
454      */

455     protected void login() throws IOException JavaDoc {
456         login(ADMIN_USER_NAME, ADMIN_PASSWORD);
457     }
458
459     /**
460      * Logs out from the application
461      *
462      * @throws IOException if any I/O error occurs
463      */

464     protected void logout() throws IOException JavaDoc {
465         if ( lastResponse == null ) {
466             fail("No request has been done yet, no response received. Could not log out from application");
467         }
468
469         HtmlForm logoutForm = getFormByName("logoutForm");
470
471         clickButtonWithLabel(logoutForm, getMessage("core.commons.buttons.logout"));
472
473         // verify, that login form has appeared
474
getFormByName("loginForm");
475
476         // login successfull
477
if ( log.isInfoEnabled() ) {
478             log.info("Logout has been successfully performed");
479         }
480     }
481
482     /**
483      * Sets last response and saves it into file, if needed
484      *
485      * @param response Response to set as last
486      * @throws IOException if any I/O error occurs
487      */

488     protected void setLastResponse(HtmlPage response) throws IOException JavaDoc {
489         lastResponse = response;
490         if ( isSaveResponse() ) {
491             saveResponse(createResponseFile(), lastResponse);
492         }
493     }
494
495     /**
496      * Searches for the HTML form with given name in the last response. The main purpose
497      * of this method is to catch <code>com.gargoylesoftware.htmlunit.ElementNotFoundException</code> and throw
498      * <code>junit.framework.AssertionFailedError</code> with detail message instead.
499      *
500      * @param name Name of HTML form to search
501      * @return Instance of <code>com.gargoylesoftware.htmlunit.html.HtmlForm</code>,
502      * which represents HTML form with given name
503      * @see com.gargoylesoftware.htmlunit.html.HtmlForm
504      * @see com.gargoylesoftware.htmlunit.ElementNotFoundException
505      * @see junit.framework.AssertionFailedError
506      */

507     protected HtmlForm getFormByName(String JavaDoc name) {
508         HtmlForm form = null;
509         try {
510             form = lastResponse.getFormByName(name);
511         } catch ( ElementNotFoundException e ) {
512             fail("No form with name '" + name + "' could be found in the last response");
513         }
514         return form;
515     }
516
517     /**
518      * Searches for input with specified name in given HTML form and asserts, that it is of expected type
519      *
520      * @param form HTML form to look for input in
521      * @param name Name of input field to look up
522      * @param expectedType Expected type of input. If <code>null</code>, no check is performed; input is returned as is.
523      * @return Input field with specified name
524      */

525     protected HtmlInput getInputByName(HtmlForm form, String JavaDoc name, String JavaDoc expectedType) {
526         HtmlInput input = null;
527         try {
528             input = form.getInputByName(name);
529             boolean error = false;
530             if ( expectedType != null ) {
531                 error = expectedType.equalsIgnoreCase(INPUT_TYPE_BUTTON) && !(input instanceof HtmlButtonInput) ||
532                         expectedType.equalsIgnoreCase(INPUT_TYPE_CHECKBOX) && !(input instanceof HtmlCheckBoxInput) ||
533                         expectedType.equalsIgnoreCase(INPUT_TYPE_FILE) && !(input instanceof HtmlFileInput) ||
534                         expectedType.equalsIgnoreCase(INPUT_TYPE_HIDDEN) && !(input instanceof HtmlHiddenInput) ||
535                         expectedType.equalsIgnoreCase(INPUT_TYPE_IMAGE) && !(input instanceof HtmlImageInput) ||
536                         expectedType.equalsIgnoreCase(INPUT_TYPE_PASSWORD) && !(input instanceof HtmlPasswordInput) ||
537                         expectedType.equalsIgnoreCase(INPUT_TYPE_RADIO) && !(input instanceof HtmlRadioButtonInput) ||
538                         expectedType.equalsIgnoreCase(INPUT_TYPE_RESET) && !(input instanceof HtmlResetInput) ||
539                         expectedType.equalsIgnoreCase(INPUT_TYPE_SUBMIT) && !(input instanceof HtmlSubmitInput) ||
540                         expectedType.equalsIgnoreCase(INPUT_TYPE_TEXT) && !(input instanceof HtmlTextInput);
541             }
542             if ( error ) {
543                 fail(UNEXPECTED_INPUT_TYPE.format(new Object JavaDoc[]{name, form.getNameAttribute(), expectedType}));
544             }
545         } catch ( ElementNotFoundException e ) {
546             fail("No input field with name '" + name + "' is available in form with name '" + form.getNameAttribute() + "'");
547         }
548         return input;
549     }
550
551     /**
552      * Searches for select element with specified name in given form. The main purpose
553      * of this method is to catch <code>com.gargoylesoftware.htmlunit.ElementNotFoundException</code> and throw
554      * <code>junit.framework.AssertionFailedError</code> with detail message instead.
555      *
556      * @param form HTML form to search for select element in
557      * @param name Name of select element
558      * @return Instance of <code>com.gargoylesoftware.htmlunit.html.HtmlSelect</code>, representing select element
559      * with specified name
560      * @see com.gargoylesoftware.htmlunit.html.HtmlSelect
561      */

562     protected HtmlSelect getSelectByName(HtmlForm form, String JavaDoc name) {
563         HtmlSelect select = null;
564         try {
565             select = form.getSelectByName(name);
566         } catch ( ElementNotFoundException e ) {
567             fail("Select with name '" + name + "' could not be found in form '" + form.getNameAttribute() + "'");
568         }
569         return select;
570     }
571
572     /**
573      * Searches for button with specified label in the specified form and clicks it.
574      * <code>lastResponse</code> field will be set to the page, which is returned after button click
575      *
576      * @param form HTML form to search button in. If <code>null</code>, button will be searched in all forms,
577      * which are present on the page, returned in last response
578      * @param label Label on button to search
579      * @throws IOException if any I/O error occurs
580      */

581     protected void clickButtonWithLabel(HtmlForm form, String JavaDoc label) throws IOException JavaDoc {
582         HtmlSubmitInput button = null;
583         HtmlInput tmp = null;
584         if ( form != null ) {
585             try {
586                 tmp = form.getInputByValue(label);
587             } catch ( ElementNotFoundException e ) {
588                 fail("No button with label=" + label + " could be found in form '" + form.getNameAttribute() + "'");
589             }
590         } else {
591             List JavaDoc forms = lastResponse.getForms();
592             if ( forms == null || forms.isEmpty() ) {
593                 fail("No form could be found on the page, returned in last response");
594             }
595             Iterator JavaDoc formsIterator = forms.iterator();
596             while ( formsIterator.hasNext() ) {
597                 form = (HtmlForm) formsIterator.next();
598                 try {
599                     tmp = form.getInputByValue(label);
600                 } catch ( ElementNotFoundException e ) {
601                     // not found, continue the loop
602
continue;
603                 }
604             }
605             if ( tmp == null ) {
606                 // button not found
607
fail("No button with label '" + label + "' could be found on the page, returned in last response");
608             }
609         }
610         if ( !(tmp instanceof HtmlSubmitInput) ) {
611             fail("Input with value=" + label + " should be submit button but it does not");
612         } else {
613             button = (HtmlSubmitInput) tmp;
614         }
615
616         setLastResponse((HtmlPage) button.click());
617     }
618
619
620     /**
621      * Selects and returns single node, which matches specified XPath expression
622      *
623      * @param xpathExpr XPath expression to evaluate
624      * @param page Page to evaluate XPath expression on
625      * @return Single node, which matches given expression or <code>null</code> if there is no such node
626      * @throws JaxenException if any error occurs, while XPath is being evaluated
627      */

628     protected Object JavaDoc evaluateXPath(String JavaDoc xpathExpr, HtmlPage page) throws JaxenException {
629         return evaluateXPath(xpathExpr, page, true);
630     }
631
632     /**
633      * Selects and returns single node or list of nodes, which match specified XPath expression
634      *
635      * @param xpathExpr XPath expression to evaluate
636      * @param page Page to evaluate XPath expression on
637      * @return Single node or list of nodes, which match given expression or <code>null</code> if there is no such node
638      * @throws JaxenException if any error occurs, while XPath is being evaluated
639      */

640     protected Object JavaDoc evaluateXPath(String JavaDoc xpathExpr, HtmlPage page, boolean singleNode) throws JaxenException {
641         XPath xpath = new HtmlUnitXPath(xpathExpr);
642         if ( singleNode ) {
643             return xpath.selectSingleNode(page);
644         } else {
645             return xpath.selectNodes(page);
646         }
647     }
648
649     // ~ General assertions ===========================================================================================
650

651     /**
652      * Verifies, that specified XPath expression does not evaluate to <code>null</code> in context
653      * of page, returned with last response
654      *
655      * @param xpathExpr XPath expression to evaluate
656      * @throws JaxenException if there is an error during evaluation of XPath expression
657      */

658     protected void assertXPathResultNotNull(String JavaDoc xpathExpr) throws JaxenException {
659         Object JavaDoc result = evaluateXPath(xpathExpr, lastResponse);
660         assertNotNull(result);
661     }
662
663     /**
664      * Asserts, that given XPath expression evaluates to expected value in context of page,
665      * returned in last response
666      *
667      * @param xpathExpr XPath expression to evaluate
668      * @param expectedValue Expected value, to which result of evaluation of XPath expression must be equal
669      * @throws JaxenException if any expection occurs, while XPath expression is being evaluated
670      */

671     protected void assertXPathResultEquals(String JavaDoc xpathExpr, String JavaDoc expectedValue) throws JaxenException {
672         String JavaDoc actual = (String JavaDoc) evaluateXPath(xpathExpr, lastResponse);
673         assertEquals(expectedValue, actual);
674     }
675
676     /**
677      * Asserts, that given XPath expression evaluates to string, which matches given regular expression
678      *
679      * @param xpathExpr XPath expression to evaluate
680      * @param regex Regular expression, to which result of evaluation of XPath epression must match
681      * @throws JaxenException if any excpetion occurs, while XPath expression is being evaluated
682      * @throws MalformedPatternException if specified regular expression is malformed
683      */

684     protected void assertXPathResultMatches(String JavaDoc xpathExpr, String JavaDoc regex) throws JaxenException, MalformedPatternException {
685         String JavaDoc actual = (String JavaDoc) evaluateXPath(xpathExpr, lastResponse);
686         assertMatches(actual, regex);
687     }
688
689     /**
690      * Asserts, that actual comparable instance is greater than specified value
691      *
692      * @param actual Actual object to compare
693      * @param compareTo Value to compare with
694      */

695     protected void assertGreaterThan(Comparable JavaDoc actual, Comparable JavaDoc compareTo) {
696         assertTrue(actual.compareTo(compareTo) > 0);
697     }
698
699     /**
700      * Asserts, that given string matches given regular expression
701      *
702      * @param input String, that should match regular expression
703      * @param regex Regular expression, to which input string should match
704      * @throws MalformedPatternException if regular expression pattern is malformed
705      */

706     protected void assertMatches(String JavaDoc input, String JavaDoc regex) throws MalformedPatternException {
707         PatternCompiler compiler = new Perl5Compiler();
708         PatternMatcher matcher = new Perl5Matcher();
709         Pattern pattern = compiler.compile(regex);
710         assertTrue(matcher.matches(input, pattern));
711     }
712
713     // ~ Common test methods ==========================================================================================
714

715     public void testLoginAndLogout() throws IOException JavaDoc {
716         login();
717         logout();
718     }
719
720 }
721
Popular Tags