You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@commons.apache.org by mo...@apache.org on 2002/05/03 00:25:45 UTC
cvs commit: jakarta-commons/latka/src/java/org/apache/commons/latka/validators BaseConditionalValidator.java CookieHandler.java CookieValidator.java RegexpValidator.java ResponseHeaderHandler.java ResponseHeaderValidator.java XPathValidator.java
morgand 02/05/02 15:25:44
Modified: latka/src/java/org/apache/commons/latka/validators
CookieHandler.java CookieValidator.java
RegexpValidator.java ResponseHeaderHandler.java
ResponseHeaderValidator.java XPathValidator.java
Added: latka/src/java/org/apache/commons/latka/validators
BaseConditionalValidator.java
Log:
adding new base class BaseConditionalValidator
Revision Changes Path
1.6 +22 -21 jakarta-commons/latka/src/java/org/apache/commons/latka/validators/CookieHandler.java
Index: CookieHandler.java
===================================================================
RCS file: /home/cvs/jakarta-commons/latka/src/java/org/apache/commons/latka/validators/CookieHandler.java,v
retrieving revision 1.5
retrieving revision 1.6
diff -u -r1.5 -r1.6
--- CookieHandler.java 11 Apr 2002 13:46:25 -0000 1.5
+++ CookieHandler.java 2 May 2002 22:25:44 -0000 1.6
@@ -1,8 +1,4 @@
/*
- *
- *
- *
- *
* ====================================================================
*
* The Apache Software License, Version 1.1
@@ -68,24 +64,29 @@
public class CookieHandler extends ValidationHandler {
- public void startElement(String uri, String localName,
- String qName, Attributes atts)
- throws SAXException {
-
- CookieValidator validator =
- new CookieValidator(atts.getValue("label"));
-
- String cookieName = atts.getValue("name");
- if (cookieName != null) {
- validator.setCookieName(cookieName);
- }
- String cookieValue = atts.getValue("value");
- if (cookieValue != null) {
- validator.setCookieValue(cookieValue);
- }
+ public void startElement(String uri, String localName,
+ String qName, Attributes atts)
+ throws SAXException {
+
+ CookieValidator validator =
+ new CookieValidator(atts.getValue("label"));
+
+ String cookieName = atts.getValue("name");
+ if (cookieName != null) {
+ validator.setCookieName(cookieName);
+ }
+ String cookieValue = atts.getValue("value");
+ if (cookieValue != null) {
+ validator.setCookieValue(cookieValue);
+ }
+
+ String condition = atts.getValue("cond");
+ if (condition != null) {
+ validator.setCondition(Boolean.valueOf(condition).booleanValue());
+ }
- validate(validator);
+ validate(validator);
- }
+ }
}
1.7 +95 -83 jakarta-commons/latka/src/java/org/apache/commons/latka/validators/CookieValidator.java
Index: CookieValidator.java
===================================================================
RCS file: /home/cvs/jakarta-commons/latka/src/java/org/apache/commons/latka/validators/CookieValidator.java,v
retrieving revision 1.6
retrieving revision 1.7
diff -u -r1.6 -r1.7
--- CookieValidator.java 11 Apr 2002 13:46:25 -0000 1.6
+++ CookieValidator.java 2 May 2002 22:25:44 -0000 1.7
@@ -1,8 +1,4 @@
/*
- *
- *
- *
- *
* ====================================================================
*
* The Apache Software License, Version 1.1
@@ -72,91 +68,107 @@
*
* @author <a href="mailto:dsale@us.britannica.com">Doug Sale</a>
* @author dIon Gillard
- * @version $Id: CookieValidator.java,v 1.6 2002/04/11 13:46:25 dion Exp $
+ * @version $Id: CookieValidator.java,v 1.7 2002/05/02 22:25:44 morgand Exp $
*/
-public class CookieValidator extends BaseValidator implements Validator {
+public class CookieValidator extends BaseConditionalValidator {
+
+ // --------------------------------------------------------------- Attributes
+
+ protected String _cookieValue = null;
+ protected String _cookieName = null;
+
+ protected static final String MESSAGE_INVALID_TEST = "INVALID TEST: COOKIE NAME NOT SET";
+ protected static final String BARE_MESSAGE_EXISTENT_COOKIE = " TO FIND COOKIE IN SESSION";
+ protected static final String BARE_MESSAGE_EQUAL_VALUES = " THAT COOKIE VALUES EQUAL:";
+
+ // needed to generate the correct exception
+ protected String _lastTestedCookieValue = null;
+
+ // ------------------------------------------------------------- Constructors
+
+ public CookieValidator() {
+ this(null,null,null,true);
+ }
+
+ public CookieValidator(String label) {
+ this(label,null,null,true);
+ }
- // --------------------------------------------------------------- Attributes
+ public CookieValidator(String name, String value) {
+ this(null,name,value,true);
+ }
+
+ public CookieValidator(String label, String name, String value, boolean condition) {
+ super(label, condition);
+ _cookieName = name;
+ _cookieValue = value;
+ }
+
+ // ------------------------------------------------------------------ Methods
- protected String _cookieValue = null;
- protected String _cookieName = null;
+ /**
+ * If cookie value is set, this <code>Validator</code> tests for cookie value equivalency, in addition to cookie existence
+ *
+ * @param value the value of the cookie
+ */
+ public void setCookieValue(String value) {
+ _cookieValue = value;
+ }
+
+ /**
+ * The cookie name must be set for this <code>Validator</code> to function properly.
+ *
+ * @param name the name of the cookie
+ */
+ public void setCookieName(String name) {
+ _cookieName = name;
+ }
- protected static final String MESSAGE_INVALID_TEST = "INVALID TEST: COOKIE NAME NOT SET";
- protected static final String MESSAGE_NONEXISTENT_COOKIE = "COOKIE NOT IN SESSION";
- protected static final String MESSAGE_UNEQUAL_VALUES = "COOKIE VALUES UNEQUAL:";
-
- // ------------------------------------------------------------- Constructors
-
- public CookieValidator() {
- this(null,null,null);
- }
-
- public CookieValidator(String label) {
- this(label,null,null);
- }
-
- public CookieValidator(String name, String value) {
- this(null,name,value);
- }
-
- public CookieValidator(String label, String name, String value) {
- super(label);
- _cookieName = name;
- _cookieValue = value;
- }
-
- // ------------------------------------------------------------------ Methods
-
- /**
- * If cookie value is set, this <code>Validator</code> tests for cookie value equivalency, in addition to cookie existence
- *
- * @param value the value of the cookie
- */
- public void setCookieValue(String value) {
- _cookieValue = value;
- }
-
- /**
- * The cookie name must be set for this <code>Validator</code> to function properly.
- *
- * @param name the name of the cookie
- */
- public void setCookieName(String name) {
- _cookieName = name;
- }
-
- /**
- * @throws org.apache.commons.latka.ValidationException
- * if cookie name hasn't been set, the cookie doesn't exist in the session, or if cookie value has been set and the cookie values don't match
- */
- public void validate(Response response)
- throws ValidationException {
-
- if(_cookieName != null) {
- Session session = response.getRequest().getSession();
-
- String value = session.getCookieValue(_cookieName);
-
- // existence test
- if(value == null) {
- fail(MESSAGE_NONEXISTENT_COOKIE);
- }
- // value test
- else if(_cookieValue != null) {
- if(!_cookieValue.equals(value)) {
- StringBuffer buffer = new StringBuffer(MESSAGE_UNEQUAL_VALUES);
- buffer.append(" EXPECTED: ");
- buffer.append(_cookieValue);
- buffer.append(" RECEIVED: ");
- buffer.append(value);
- fail(buffer.toString());
+ /**
+ * @throws org.apache.commons.latka.ValidationException
+ * if cookie name hasn't been set, the cookie doesn't exist in the session, or if cookie value has been set and the cookie values don't match
+ */
+ public boolean assertTrue(Response response)
+ throws ValidationException {
+
+ if (_cookieName != null) {
+ Session session = response.getRequest().getSession();
+
+ _lastTestedCookieValue = session.getCookieValue(_cookieName);
+
+ // existence test
+ if (_lastTestedCookieValue == null) {
+ return false;
+ }
+ // value test
+ else if (_cookieValue != null) {
+ if (!_cookieValue.equals(_lastTestedCookieValue)) {
+ return false;
+ }
+ }
}
- }
+ // invalid test
+ else {
+ fail(MESSAGE_INVALID_TEST);
+ }
+
+ return true;
}
- // invalid test
- else {
- fail(MESSAGE_INVALID_TEST);
+
+ public String generateBareExceptionMessage() {
+
+ if (_lastTestedCookieValue == null) {
+ return BARE_MESSAGE_EXISTENT_COOKIE;
+ }
+ // value test
+ else {
+ StringBuffer buffer = new StringBuffer(BARE_MESSAGE_EQUAL_VALUES);
+ buffer.append(" EXPECTED: ");
+ buffer.append(_cookieValue);
+ buffer.append(" RECEIVED: ");
+ buffer.append(_lastTestedCookieValue);
+ return buffer.toString();
+ }
}
- }
}
1.8 +42 -54 jakarta-commons/latka/src/java/org/apache/commons/latka/validators/RegexpValidator.java
Index: RegexpValidator.java
===================================================================
RCS file: /home/cvs/jakarta-commons/latka/src/java/org/apache/commons/latka/validators/RegexpValidator.java,v
retrieving revision 1.7
retrieving revision 1.8
diff -u -r1.7 -r1.8
--- RegexpValidator.java 11 Apr 2002 13:46:25 -0000 1.7
+++ RegexpValidator.java 2 May 2002 22:25:44 -0000 1.8
@@ -74,78 +74,66 @@
*
* @author Morgan Delagrange
* @author dIon Gillard
- * @version $Id: RegexpValidator.java,v 1.7 2002/04/11 13:46:25 dion Exp $
+ * @version $Id: RegexpValidator.java,v 1.8 2002/05/02 22:25:44 morgand Exp $
*/
-public class RegexpValidator extends BaseValidator implements Validator {
+public class RegexpValidator extends BaseConditionalValidator implements Validator {
- // --------------------------------------------------------------- Attributes
+ // --------------------------------------------------------------- Attributes
- protected String _pattern = null;
- protected boolean _cond = true;
- protected boolean _ignoreCase = false;
+ protected String _pattern = null;
+ protected boolean _ignoreCase = false;
- protected static final String TRUE_MESSAGE = "EXPECTED TO MATCH PATTERN: ";
- protected static final String FALSE_MESSAGE = "DID NOT EXPECT TO MATCH PATTERN: ";
+ protected static final String BARE_EXCEPTION_MESSAGE = " TO MATCH PATTERN: ";
- // ------------------------------------------------------------- Constructors
+ // ------------------------------------------------------------- Constructors
- public RegexpValidator() {
- this(null,null,true,false);
- }
-
- public RegexpValidator(String label) {
- this(label,null,true,false);
- }
+ public RegexpValidator() {
+ this(null,null,true,false);
+ }
- public RegexpValidator(String label, String pattern, boolean cond, boolean ignoreCase) {
- super(label);
- _pattern = pattern;
- _cond = cond;
- _ignoreCase = ignoreCase;
- }
+ public RegexpValidator(String label) {
+ this(label,null,true,false);
+ }
- // ------------------------------------------------------------------ Methods
+ public RegexpValidator(String label, String pattern, boolean cond, boolean ignoreCase) {
+ super(label, cond);
+ _pattern = pattern;
+ _ignoreCase = ignoreCase;
+ }
- public void setPattern(String pattern) {
- _pattern = pattern;
- }
+ // ------------------------------------------------------------------ Methods
- public void setCondition(boolean cond) {
- _cond = cond;
- }
+ public void setPattern(String pattern) {
+ _pattern = pattern;
+ }
- public void setIgnoreCase(boolean ignoreCase) {
- _ignoreCase = ignoreCase;
- }
+ public void setIgnoreCase(boolean ignoreCase) {
+ _ignoreCase = ignoreCase;
+ }
- public void validate(Response response)
+ public boolean assertTrue(Response response)
throws ValidationException {
- RE r = null;
- try {
- r = new RE(_pattern); // Compile expression
- } catch (RESyntaxException e) {
- fail(e.toString());
- }
+ RE r = null;
+ try {
+ r = new RE(_pattern); // Compile expression
+ } catch (RESyntaxException e) {
+ fail(e.toString());
+ }
+
+ if (_ignoreCase == true) {
+ r.setMatchFlags(RE.MATCH_CASEINDEPENDENT);
+ }
- if (_ignoreCase == true) {
- r.setMatchFlags(RE.MATCH_CASEINDEPENDENT);
- }
+ boolean matched =
+ r.match(response.getResource()); // Match against expression
- boolean matched =
- r.match(response.getResource()); // Match against expression
- if (!(matched == _cond)) {
- StringBuffer buf = new StringBuffer();
- if (_cond == true) {
- buf.append(TRUE_MESSAGE);
- } else {
- buf.append(FALSE_MESSAGE);
- }
+ return matched;
- buf.append(_pattern);
- fail(buf.toString());
}
- }
+ public String generateBareExceptionMessage() {
+ return BARE_EXCEPTION_MESSAGE + _pattern;
+ }
}
1.6 +18 -13 jakarta-commons/latka/src/java/org/apache/commons/latka/validators/Attic/ResponseHeaderHandler.java
Index: ResponseHeaderHandler.java
===================================================================
RCS file: /home/cvs/jakarta-commons/latka/src/java/org/apache/commons/latka/validators/Attic/ResponseHeaderHandler.java,v
retrieving revision 1.5
retrieving revision 1.6
diff -u -r1.5 -r1.6
--- ResponseHeaderHandler.java 9 Sep 2001 04:35:21 -0000 1.5
+++ ResponseHeaderHandler.java 2 May 2002 22:25:44 -0000 1.6
@@ -66,20 +66,25 @@
public class ResponseHeaderHandler extends ValidationHandler {
- public void startElement(String uri, String localName,
- String qName, Attributes atts)
- throws SAXException {
+ public void startElement(String uri, String localName,
+ String qName, Attributes atts)
+ throws SAXException {
- ResponseHeaderValidator validator =
- new ResponseHeaderValidator(atts.getValue("label"),atts.getValue("headerName"));
-
- String headerValue = atts.getValue("headerValue");
- if (headerValue != null) {
- validator.setHeaderValue(headerValue);
- }
-
- validate(validator);
+ ResponseHeaderValidator validator =
+ new ResponseHeaderValidator(atts.getValue("label"),atts.getValue("headerName"));
+
+ String headerValue = atts.getValue("headerValue");
+ if (headerValue != null) {
+ validator.setHeaderValue(headerValue);
+ }
+
+ String condition = atts.getValue("cond");
+ if (condition != null) {
+ validator.setCondition(Boolean.valueOf(condition).booleanValue());
+ }
- }
+ validate(validator);
+
+ }
}
1.6 +106 -81 jakarta-commons/latka/src/java/org/apache/commons/latka/validators/Attic/ResponseHeaderValidator.java
Index: ResponseHeaderValidator.java
===================================================================
RCS file: /home/cvs/jakarta-commons/latka/src/java/org/apache/commons/latka/validators/Attic/ResponseHeaderValidator.java,v
retrieving revision 1.5
retrieving revision 1.6
diff -u -r1.5 -r1.6
--- ResponseHeaderValidator.java 9 Sep 2001 04:35:21 -0000 1.5
+++ ResponseHeaderValidator.java 2 May 2002 22:25:44 -0000 1.6
@@ -69,92 +69,117 @@
*
* @author Morgan Delagrange
*/
-public class ResponseHeaderValidator extends BaseValidator implements Validator {
+public class ResponseHeaderValidator extends BaseConditionalValidator {
- // --------------------------------------------------------------- Attributes
+ // --------------------------------------------------------------- Attributes
- protected String _headerName = null;
- protected String _headerValue = null;
+ protected String _headerName = null;
+ protected String _headerValue = null;
- protected boolean _checkValue = false;
+ protected boolean _checkValue = false;
- protected static final String MESSAGE_NONEXISTENT_HEADER = "HEADER NOT IN RESPONSE";
- protected static final String MESSAGE_UNEQUAL_VALUES = "HEADER VALUES UNEQUAL:";
-
- // ------------------------------------------------------------- Constructors
-
- /**
- * Constructs a validator for the given header with no label.
- *
- * @param headerName Name of the header to validate
- */
- public ResponseHeaderValidator(String headerName) {
- this(null,headerName);
- }
-
- /**
- * Constructs a labeled validator for the given
- * header
- *
- * @param label name of the header to validate
- * @param headerName
- */
- public ResponseHeaderValidator(String label, String headerName) {
- super(label);
- _headerName = headerName;
- }
-
- /**
- * Sets the desired value of the header to be validated.
- * If this method is not called, then the validator will
- * only check for the existence of the header and
- * disregard its value.
- *
- * @param headerValue
- * desired value of the header, or null to look for a
- * header with the String value "null"
- */
- public void setHeaderValue(String headerValue) {
- _checkValue = true;
-
- if (headerValue == null) {
- headerValue = "null";
- }
- _headerValue = headerValue;
- }
-
-
- /**
- * Checks to see that the header exists, and also checks
- * its value if setHeaderValue(String) has been called
- *
- * @param response The HTTP response to validate
- * @exception ValidationException
- * if the header does not meet the criteria of the test
- */
- public void validate(Response response)
- throws ValidationException {
-
- String actualValue = response.getHeader(_headerName);
-
- if (actualValue == null) {
- fail(MESSAGE_NONEXISTENT_HEADER);
- }
-
- // if checkValue == false, we only care if the header exists
- if (_checkValue == false) {
- return;
- }
-
- if (!actualValue.equals(_headerValue)) {
- StringBuffer buffer = new StringBuffer(MESSAGE_UNEQUAL_VALUES);
- buffer.append(" EXPECTED: ");
- buffer.append(_headerValue);
- buffer.append(" RECEIVED: ");
- buffer.append(actualValue);
- fail(buffer.toString());
+ protected static final String BARE_MESSAGE_EXISTENT_HEADER = " TO FIND HEADER IN RESPONSE";
+ protected static final String BARE_MESSAGE_EQUAL_VALUES = " THAT HEADER VALUES EQUAL:";
+
+ // need to store the value of the tested header, in order
+ // to generate the right exception
+ protected String _actualValue = null;
+
+ // ------------------------------------------------------------- Constructors
+
+ /**
+ * Constructs a validator for the given header with no label.
+ *
+ * @param headerName Name of the header to validate
+ */
+ public ResponseHeaderValidator(String headerName) {
+ this(null,headerName,true);
+ }
+
+ /**
+ * Constructs a labeled validator for the given
+ * header
+ *
+ * @param label name of the header to validate
+ * @param headerName
+ */
+ public ResponseHeaderValidator(String label, String headerName) {
+ this(label,headerName,true);
+ }
+
+ /**
+ * Constructs a labeled validator for the given
+ * header
+ *
+ * @param label name of the header to validate
+ * @param headerName
+ */
+ public ResponseHeaderValidator(String label, String headerName, boolean condition) {
+ super(label,condition);
+ _headerName = headerName;
}
- }
+ /**
+ * Sets the desired value of the header to be validated.
+ * If this method is not called, then the validator will
+ * only check for the existence of the header and
+ * disregard its value.
+ *
+ * @param headerValue
+ * desired value of the header, or null to look for a
+ * header with the String value "null"
+ */
+ public void setHeaderValue(String headerValue) {
+ _checkValue = true;
+
+ if (headerValue == null) {
+ headerValue = "null";
+ }
+ _headerValue = headerValue;
+ }
+
+
+ /**
+ * Checks to see that the header exists, and also checks
+ * its value if setHeaderValue(String) has been called
+ *
+ * @param response The HTTP response to validate
+ * @exception ValidationException
+ * if the header does not meet the criteria of the test
+ */
+ public boolean assertTrue(Response response)
+ throws ValidationException {
+
+ _actualValue = response.getHeader(_headerName);
+
+ if (_actualValue == null) {
+ return false;
+ }
+
+ // if checkValue == false, we only care if the header exists
+ if (_checkValue == false) {
+ return true;
+ }
+
+ if (!_actualValue.equals(_headerValue)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ public String generateBareExceptionMessage() {
+
+ if (_actualValue == null) {
+ return BARE_MESSAGE_EXISTENT_HEADER;
+ } else {
+ StringBuffer buffer = new StringBuffer(BARE_MESSAGE_EQUAL_VALUES);
+ buffer.append(" EXPECTED: ");
+ buffer.append(_headerValue);
+ buffer.append(" RECEIVED: ");
+ buffer.append(_actualValue);
+ return buffer.toString();
+ }
+ }
}
1.4 +254 -250 jakarta-commons/latka/src/java/org/apache/commons/latka/validators/XPathValidator.java
Index: XPathValidator.java
===================================================================
RCS file: /home/cvs/jakarta-commons/latka/src/java/org/apache/commons/latka/validators/XPathValidator.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -r1.3 -r1.4
--- XPathValidator.java 11 Apr 2002 13:46:25 -0000 1.3
+++ XPathValidator.java 2 May 2002 22:25:44 -0000 1.4
@@ -1,8 +1,4 @@
/*
- *
- *
- *
- *
* ====================================================================
*
* The Apache Software License, Version 1.1
@@ -70,7 +66,7 @@
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
-import org.jaxen.jdom.XPath;
+import org.jaxen.jdom.JDOMXPath;
import org.jaxen.JaxenException;
/**
@@ -116,252 +112,260 @@
* @author <a href="mailto:jefft@apache.org">Jeff Turner</a>
* @author dIon Gillard
* @since 6 January, 2001
- * @version $Id: XPathValidator.java,v 1.3 2002/04/11 13:46:25 dion Exp $
+ * @version $Id: XPathValidator.java,v 1.4 2002/05/02 22:25:44 morgand Exp $
*/
-public class XPathValidator extends BaseValidator implements Validator {
+public class XPathValidator extends BaseConditionalValidator {
+
+ // General notes:
+ // - It started out simple, honest.. =)
+ // --------------------------------------------------------------- Attributes
+
+ protected String _select = null;
+ protected String _value = null;
+ // need the last XPath result for exception generation
+ protected Object _lastSelected = null;
+
+ // ------------------------------------------------------------- Constructors
+
+ public XPathValidator() {
+ this(null,null,true,null);
+ }
+
+ public XPathValidator(String label) {
+ this(label,null,true,null);
+ }
+
+ public XPathValidator(String label, String select, boolean cond, String value) {
+ super(label,cond);
+ _select = select;
+ _value = value;
+ }
+
+ // ------------------------------------------------------------------ Public Methods
+
+ public void setSelect(String select) {
+ _select = select;
+ }
+
+ public void setValue(String value) {
+ _value = value;
+ }
+
+ public boolean assertTrue(Response response)
+ throws ValidationException {
+
+ JDOMXPath xpath = getJDOMXPath(_select); // compile the XPath expression
+ Document doc = getDocument(response); // retrieve the XML Document to process
+ Object selected = getSelectedNode(xpath, doc); // Apply the XPath to retrieve a node
+ _lastSelected = selected;
+
+ if (selected == null) {
+ return false;
+ }
+
+ // Now the fun begins, where we see if our selected node meets the criteria.
+ // There are two factors:
+ //
+ // 1) What type of object did the XPath expression return?
+ // 2) If _value is specified, ie if we're testing for _value_ or _existence_
+
+ if (selected instanceof Boolean) {
+ // Eg, we had an expression /foo = 'bar'
+ _log.debug("Boolean XPath expression evaluated to "+selected);
+ if (_value != null) {
+ _log.warn("Ignoring unused value '"+_value+"'.");
+ }
+ boolean matched = ((Boolean)selected).booleanValue();
+
+ return matched;
+
+ } else if (selected instanceof String) {
+ _log.debug("XPath selected string '"+selected+"'.");
+ if (_value != null) {
+ boolean matched = selected.equals(_value);
+
+ return matched;
+ } else {
+ // otherwise we only test if the node is meant to exist
+ return true;
+ }
+ } else if (selected instanceof Element) {
+ if (_log.isDebugEnabled()) {
+ _log.debug("XPath matched element: ");
+ _log.debug(printElement((Element)selected));
+ }
+ if (_value != null) {
+ _log.warn("Ignoring unused value '"+_value+"'.");
+ }
+
+ // otherwise we only test if the node is meant to exist
+ return true;
+ } else {
+ // Otherwise Jaxen is returning something odd
+ if (_value != null) {
+ // Hope that .equals() does a sensible comparison
+ boolean matched = selected.equals(_value);
+
+ return matched;
+
+ } else {
+ _log.warn("Selected unknown type "+selected.getClass().getName());
+ // only test if the node (whatever it is) is meant to exist
+ return true;
+ }
+ }
+ }
+
+ public String generateBareExceptionMessage() {
- // General notes:
- // - It started out simple, honest.. =)
- // - We really need to separate out the negation logic into a separate <not>
- // tag. It's silly having xpath, regexp and whathaveyou all doing their own
- // negation tests..
- // - Need some unit tests, with a mock object for the Response.
-
- // --------------------------------------------------------------- Attributes
-
- protected String _select = null;
- protected boolean _cond = true;
- protected String _value = null;
-
- protected static final String TRUE_MESSAGE = "EXPECTED TO MATCH XPATH: ";
- protected static final String FALSE_MESSAGE = "DID NOT EXPECT TO MATCH XPATH: ";
-
- // ------------------------------------------------------------- Constructors
-
- public XPathValidator() {
- this(null,null,true,null);
- }
-
- public XPathValidator(String label) {
- this(label,null,true,null);
- }
-
- public XPathValidator(String label, String select, boolean cond, String value) {
- super(label);
- _select = select;
- _cond = cond;
- _value = value;
- }
-
- // ------------------------------------------------------------------ Public Methods
-
- public void setSelect(String select) {
- _select = select;
- }
-
- public void setCondition(boolean cond) {
- _cond = cond;
- }
-
- public void setValue(String value) {
- _value = value;
- }
-
- public void validate(Response response)
- throws ValidationException {
-
- XPath xpath = getXPath(_select); // compile the XPath expression
- Document doc = getDocument(response); // retrieve the XML Document to process
- Object selected = getSelectedNode(xpath, doc); // Apply the XPath to retrieve a node
-
-
- // Now the fun begins, where we see if our selected node meets the criteria.
- // There are three factors:
- //
- // 1) What type of object did the XPath expression return?
- // 2) If _value is specified, ie if we're testing for _value_ or _existence_
- // 3) If _cond is true/false, ie do we WANT the value to match/node to exist?
-
-
- if (selected instanceof Boolean) {
- // Eg, we had an expression /foo = 'bar'
- _log.debug("Boolean XPath expression evaluated to "+selected);
- if (_value != null) {
- _log.warn("Ignoring unused value '"+_value+"'.");
- }
- boolean matched = ((Boolean)selected).booleanValue();
- if (_cond != matched) {
- fail("Boolean XPath '"+_select+"' didn't match.");
- }
- } else if (selected instanceof String) {
- _log.debug("XPath selected string '"+selected+"'.");
- if (_value != null) {
- boolean matched = selected.equals(_value);
- if (_cond != matched) {
- StringBuffer buf = new StringBuffer();
- if (_cond == true) {
- buf.append(TRUE_MESSAGE);
- } else {
- buf.append(FALSE_MESSAGE);
- }
- buf.append(_select);
- fail(buf.toString());
- }
- } else {
- // otherwise we only test if the node is meant to exist
- if (!_cond) {
- fail("XPath '"+_select+"' selected string '"+selected+
- "' when specified not to.");
- }
- }
- } else if (selected instanceof Element) {
- if (_log.isDebugEnabled()) {
- _log.debug("XPath matched element: ");
- _log.debug(printElement((Element)selected));
- }
- if (_value != null) {
- _log.warn("Ignoring unused value '"+_value+"'.");
- }
- if (!_cond) {
- fail("XPath '"+_select+"' selected element '"+selected+
- "' when specified not to.");
- }
- } else {
- // Otherwise Jaxen is returning something odd
- if (_value != null) {
- // Hope that .equals() does a sensible comparison
- boolean matched = selected.equals(_value);
- if (_cond != matched) {
- fail("XPath expression '"+_value+"' returned '"+selected+
- "' of unknown type "+selected.getClass().getName()+
- ". This did "+(_cond?"not ":"")+"match the specified value '"+_value+"'."
- );
- }
- } else {
- // only test if the node (whatever it is) is meant to exist
- if (!_cond) {
- fail("XPath '"+_select+"' selected node '"+selected+
- "' when specified not to.");
- }
- _log.warn("Selected unknown type "+selected.getClass().getName());
- }
- }
- }
-
- // ------------------------------------------------------------------ Private Methods
-
- /**
- * Creates a Jaxen <code>XPath</code> for a given XPath expression.
- * @param xpathExpr The XPath expression
- * @return A non-null Jaxen <code>XPath</code> object.
- * @throws ValidationException if <code>xpathExpr</code> was invalid.
- */
- private XPath getXPath(final String xpathExpr)
- throws ValidationException
- {
- XPath xpath = null;
- try {
- xpath = new XPath(xpathExpr);
- } catch (JaxenException e) {
- fail("Couldn't compile XPath xpathExpr "+xpathExpr+": "+e.toString());
- }
-
- if (xpath == null) { // this should never happen
- fail("Null compiled XPath object");
- }
-
- if (_log.isDebugEnabled()) {
- _log.debug("Using XPath expression: "+xpathExpr);
- }
- return xpath;
- }
-
- /**
- * Creates a <code>Document</code> from the Response.
- * @param response The (usu. HTTP) Reponse object presumably containing an XML
- * response body.
- * @return A non-null <code>Document</code> representing the response body.
- * @throws ValidationException if the Response object's body did not contain
- * well-formed XML.
- */
- private Document getDocument(Response response)
- throws ValidationException
- {
- Document doc = null;
- SAXBuilder builder = new SAXBuilder();
- try {
- doc = builder.build(response.getStream());
- } catch (JDOMException e) {
- fail(e.toString());
- }
- if (doc == null) { // this should never happen
- fail("Null document");
- }
- if (_log.isDebugEnabled()) {
- _log.debug("Processing doc: "+printDoc(doc));
- }
- return doc;
- }
-
- /**
- * Apply a compiled XPath expression to an XML Document, and return the
- * selected node.
- * @param xpath The compiled Jaxen <code>XPath</code> object
- * @param doc The <code>Document</code> object containing the XML.
- * @return A non-null object returned from Jaxen. This may be:
- * <ul>
- * <li>A String, if the expression selected an element with a text node child</li>
- * <li>An <code>Element</code></li>
- * <li>A <code>java.lang.Boolean</code>, if the XPath expression is a
- * statement (eg /foo/bar='content')</li>
- * <li>Anything else the Jaxen author deemed useful; ie don't assume anything</li>
- * </ul>
- */
- private Object getSelectedNode(XPath xpath, Document doc)
- throws ValidationException
- {
- Object selected = null;
- try {
- selected = xpath.selectSingleNode(doc);
- } catch (JaxenException e) {
- fail("XPath expression '"+_select+"' didn't match any node. "+e.toString());
- }
- if (selected == null) {
- fail("Couldn't find node '"+_select+"' in document");
- }
-
- return selected;
- }
-
- /**
- * Utility method for returning an XML rendition of a <code>Document</code>.
- * @param doc The Document to print
- * @return A String of XML representing the document.
- */
- private String printDoc(final Document doc) {
- java.io.StringWriter sw = new java.io.StringWriter();
- try {
- new org.jdom.output.XMLOutputter().output(doc, sw);
- } catch (java.io.IOException ioe) {
- _log.error("Could not print XML document.", ioe);
- }
- return sw.toString();
- }
-
- /**
- * Utility method for returning an XML rendition of a <code>Element</code>.
- * @param elem an <code>Element</code> to print.
- * @return A String of XML representing the element.
- */
- private String printElement(final Element elem) {
- java.io.StringWriter sw = new java.io.StringWriter();
- Element clone = (Element)((Element)elem).clone();
- org.jdom.output.XMLOutputter xmlOut = new org.jdom.output.XMLOutputter();
- try {
- xmlOut.output(new org.jdom.Document(clone), sw);
- } catch (java.io.IOException ioe) {
- _log.error("Could not print XML element.", ioe);
+ if (_lastSelected == null) {
+ return " THAT BOOLEAN XPATH '"+_select+"' WOULD SELECT SOME NODE.";
+ }
+
+ if (_lastSelected instanceof Boolean) {
+ return " THAT BOOLEAN XPATH '"+_select+"' WOULD RETURN '" + getCondition() + "'.";
+ } else if (_lastSelected instanceof String) {
+ if (_value != null) {
+ StringBuffer buf = new StringBuffer();
+ buf.append(" THAT XPATH '");
+ buf.append(_select);
+ buf.append("' WOULD SELECT '");
+ buf.append(_value);
+ buf.append("', RECEIVED '");
+ buf.append(_lastSelected);
+ buf.append("'.");
+ return buf.toString();
+ } else {
+ // otherwise we only test if the node is meant to exist
+ return " THAT XPATH '" + _select + "' WOULD SELECT SOMETHING.";
+ }
+ } else if (_lastSelected instanceof Element) {
+ // otherwise we only test if the node is meant to exist
+ return " THAT XPATH '" + _select + "' WOULD SELECT SOMETHING.";
+ } else {
+ // Otherwise Jaxen is returning something odd
+ if (_value != null) {
+ return " THAT XPATH EXPRESSION '"+_select+"' WOULD RETURN '" + _value +
+ "', RETURNED UNKNOWN TYPE "+_lastSelected.getClass().getName()+ ".";
+ } else {
+ _log.warn("Selected unknown type "+_lastSelected.getClass().getName());
+ // only test if the node (whatever it is) is meant to exist
+ return " THAT XPATH '" + _select + "' WOULD SELECT SOMETHING.";
+ }
+ }
+ }
+
+ // ------------------------------------------------------------------ Private Methods
+
+ /**
+ * Creates a Jaxen <code>JDOMXPath</code> for a given XPath expression.
+ * @param xpathExpr The XPath expression
+ * @return A non-null Jaxen <code>JDOMXPath</code> object.
+ * @throws ValidationException if <code>xpathExpr</code> was invalid.
+ */
+ private JDOMXPath getJDOMXPath(final String xpathExpr)
+ throws ValidationException
+ {
+ JDOMXPath xpath = null;
+ try {
+ xpath = new JDOMXPath(xpathExpr);
+ } catch (JaxenException e) {
+ fail("Couldn't compile JDOMXPath xpathExpr "+xpathExpr+": "+e.toString());
+ }
+
+ if (xpath == null) { // this should never happen
+ fail("Null compiled XPath object");
+ }
+
+ if (_log.isDebugEnabled()) {
+ _log.debug("Using XPath expression: "+xpathExpr);
+ }
+ return xpath;
+ }
+
+ /**
+ * Creates a <code>Document</code> from the Response.
+ * @param response The (usu. HTTP) Reponse object presumably containing an XML
+ * response body.
+ * @return A non-null <code>Document</code> representing the response body.
+ * @throws ValidationException if the Response object's body did not contain
+ * well-formed XML.
+ */
+ private Document getDocument(Response response)
+ throws ValidationException
+ {
+ Document doc = null;
+ SAXBuilder builder = new SAXBuilder();
+ try {
+ doc = builder.build(response.getStream());
+ } catch (JDOMException e) {
+ fail(e.toString());
+ }
+ if (doc == null) { // this should never happen
+ fail("Null document");
+ }
+ if (_log.isDebugEnabled()) {
+ _log.debug("Processing doc: "+printDoc(doc));
+ }
+ return doc;
+ }
+
+ /**
+ * Apply a compiled XPath expression to an XML Document, and return the
+ * selected node.
+ * @param xpath The compiled Jaxen <code>XPath</code> object
+ * @param doc The <code>Document</code> object containing the XML.
+ * @return An object returned from Jaxen, or null if there was no match. This may be:
+ * <ul>
+ * <li>A String, if the expression selected an element with a text node child</li>
+ * <li>An <code>Element</code></li>
+ * <li>A <code>java.lang.Boolean</code>, if the XPath expression is a
+ * statement (eg /foo/bar='content')</li>
+ * <li>Anything else the Jaxen author deemed useful; ie don't assume anything</li>
+ * </ul>
+ */
+ private Object getSelectedNode(JDOMXPath xpath, Document doc)
+ throws ValidationException
+ {
+ Object selected = null;
+ try {
+ selected = xpath.selectSingleNode(doc);
+ } catch (JaxenException e) {
+ fail("XPath expression '"+_select+"' didn't match any node. "+e.toString());
+ }
+
+ return selected;
+ }
+
+ /**
+ * Utility method for returning an XML rendition of a <code>Document</code>.
+ * @param doc The Document to print
+ * @return A String of XML representing the document.
+ */
+ private String printDoc(final Document doc) {
+ java.io.StringWriter sw = new java.io.StringWriter();
+ try {
+ new org.jdom.output.XMLOutputter().output(doc, sw);
+ } catch (java.io.IOException ioe) {
+ _log.error("Could not print XML document.", ioe);
+ }
+ return sw.toString();
+ }
+
+ /**
+ * Utility method for returning an XML rendition of a <code>Element</code>.
+ * @param elem an <code>Element</code> to print.
+ * @return A String of XML representing the element.
+ */
+ private String printElement(final Element elem) {
+ java.io.StringWriter sw = new java.io.StringWriter();
+ Element clone = (Element)((Element)elem).clone();
+ org.jdom.output.XMLOutputter xmlOut = new org.jdom.output.XMLOutputter();
+ try {
+ xmlOut.output(new org.jdom.Document(clone), sw);
+ } catch (java.io.IOException ioe) {
+ _log.error("Could not print XML element.", ioe);
+ }
+ return sw.toString();
}
- return sw.toString();
- }
}
1.1 jakarta-commons/latka/src/java/org/apache/commons/latka/validators/BaseConditionalValidator.java
Index: BaseConditionalValidator.java
===================================================================
/*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.latka.validators;
import org.apache.commons.latka.Validator;
import org.apache.commons.latka.ValidationException;
import org.apache.commons.latka.http.Response;
import org.apache.log4j.Category;
/**
* This subclass of BaseValidator largely removes the need of
* a validator to know whether a particular test is supposed
* to succeed or fail. The validate(Response) method
* becomes final, and the logic is moved into two
* abstract methods (see Javadocs): assertTrue(Response)
* and generateBareExceptionMessage().
*
* @author MorganDelagrange
* @version $Id: BaseConditionalValidator.java,v 1.1 2002/05/02 22:25:44 morgand Exp $
*/
public abstract class BaseConditionalValidator extends BaseValidator {
// ------------------------------------------------------- Instance Variables
protected final Category _log = Category.getInstance(BaseConditionalValidator.class);
protected boolean _condition = true;
// ----------------------------------------------------------- Constructors
/**
* A test without a label
*
* @param condition Whether the test should evaluate to true or false
*/
public BaseConditionalValidator(boolean condition) {
this(null,condition);
}
/**
* A test with a label
*
* @param label test label
* @param condition whether the test should evaluate to true or false
*/
public BaseConditionalValidator(String label, boolean condition) {
super(label);
_condition = condition;
}
// ---------------------------------------------------------------- Methods
/**
* Set whether or not this test is supposed to succeed
*
* @param condition true if the test should succeed
*/
public void setCondition(boolean condition) {
_condition = condition;
}
/**
* Returns whether or not this test is supposed to succeed
*
* @return true if the test is supposed to succeed
*/
public boolean getCondition() {
return _condition;
}
/**
* Final method. Implement the assertion logic for
* the test in assertTrue(Response), and the exception generation
* in generateBareExceptionMessage()
*
* @param response Response from the HTTP server
* @exception ValidationException
*/
public final void validate(Response response) throws ValidationException {
boolean assertion = assertTrue(response);
if ((assertion == true) && (_condition == false)) {
throwValidationException();
} else if ((assertion == false) && (_condition == true)) {
throwValidationException();
}
}
/**
* Return true or false, depending on whether or not
* the test conditions were met. This
* is <i>regardless</i> of the value of getCondition(),
* which is handled elsewhere.
*
* Note: this method
* should _only_ throw ValidationExceptions under
* exceptional circumstances (e.g. invalid regular
* expressions, IOExceptions, etc). A successful test
* should only return true or false.
*
* @param response HTTP response
* @return true if the test conditions were met, false otherwise
* @exception ValidationException
*/
public abstract boolean assertTrue(Response response) throws ValidationException;
/**
* The BASE exception message for a subclass of
* BaseConditionalValidator. Expect that the String
* "EXPECTED" or "DID NOT EXPECT" will be prepended to
* this message, depending on the value of getCondition().
* For example, if you are validator attempts to match
* regular expression <i>x</i>, this methods should
* generate something like " TO MATCH REGULAR EXPRESSION
* <i>x</i>.".
*
* @return bare exception message, to which will be prepended
* "EXPECTED" or "DID NOT EXPECT"
*/
public abstract String generateBareExceptionMessage();
/**
* Automatically generated exception messages, based
* on the value of getCondition() and
* generateBareExceptionMessage().
*
* @exception ValidationException
* generated Exception
*/
protected void throwValidationException() throws ValidationException {
if (_condition == true) {
fail("EXPECTED" + generateBareExceptionMessage());
} else {
fail("DID NOT EXPECT" + generateBareExceptionMessage());
}
}
}
--
To unsubscribe, e-mail: <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>