Revision: 648
http://svn.sourceforge.net/jwebunit/?rev=648&view=rev
Author: henryju
Date: 2007-01-02 08:57:57 -0800 (Tue, 02 Jan 2007)
Log Message:
-----------
Apply patch from Gr?\195?\169gory Joseph concerning image testing.
Modified Paths:
--------------
branches/1.x/jwebunit-commons-tests/src/main/java/net/sourceforge/jwebunit/tests/TestContextTest.java
branches/1.x/jwebunit-core/src/main/java/net/sourceforge/jwebunit/api/IJWebUnitDialog.java
branches/1.x/jwebunit-core/src/main/java/net/sourceforge/jwebunit/junit/WebTester.java
branches/1.x/jwebunit-core/src/main/java/net/sourceforge/jwebunit/util/TestContext.java
branches/1.x/jwebunit-htmlunit-plugin/src/main/java/net/sourceforge/jwebunit/htmlunit/HtmlUnitDialog.java
branches/1.x/jwebunit-htmlunit-plugin/src/test/java/net/sourceforge/jwebunit/htmlunit/JWebUnitTest.java
branches/1.x/jwebunit-webtestcase-generator/src/main/javacc/Java1.5.jj
branches/1.x/src/changes/changes.xml
Added Paths:
-----------
branches/1.x/jwebunit-commons-tests/src/main/java/net/sourceforge/jwebunit/tests/ImageTest.java
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/PageWithImages.html
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/images/
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/images/Image1.gif
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/images/Image2.png
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/images/InvalidImage.gif
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/images/photos/
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/images/photos/Image3.jpg
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/somedir/
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/somedir/AnotherPageWithImages.html
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/somedir/Image4.gif
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/somedir/images/
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/somedir/images/Image5.png
Added:
branches/1.x/jwebunit-commons-tests/src/main/java/net/sourceforge/jwebunit/tests/ImageTest.java
===================================================================
---
branches/1.x/jwebunit-commons-tests/src/main/java/net/sourceforge/jwebunit/tests/ImageTest.java
(rev 0)
+++
branches/1.x/jwebunit-commons-tests/src/main/java/net/sourceforge/jwebunit/tests/ImageTest.java
2007-01-02 16:57:57 UTC (rev 648)
@@ -0,0 +1,82 @@
+/******************************************************************************
+ * jWebUnit project (http://jwebunit.sourceforge.net) *
+ * Distributed open-source, see full license under LICENCE.txt *
+
******************************************************************************/
+package net.sourceforge.jwebunit.tests;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+import net.sourceforge.jwebunit.tests.util.JettySetup;
+
+import javax.imageio.ImageIO;
+import java.awt.Image;
+import java.awt.image.BufferedImage;
+import java.io.File;
+
+/**
+ *
+ * @author gjoseph
+ */
+public class ImageTest extends JWebUnitAPITestCase {
+
+ public static Test suite() {
+ Test suite = new TestSuite(ImageTest.class);
+ return new JettySetup(suite);
+ }
+
+ public void setUp() throws Exception {
+ super.setUp();
+ getTestContext().setBaseUrl(HOST_PATH + "/ImageTest");
+ beginAt("/PageWithImages.html");
+ }
+
+ public void testSimpleImagePresenceAssertion() throws Throwable {
+ assertImagePresent("images/Image1.gif", "image 1");
+ assertImagePresent("images/Image2.png", "image 2");
+ assertImagePresent("images/photos/Image3.jpg", "image 3");
+ assertImagePresent("somedir/Image4.gif", null);
+ assertImagePresent("images/InvalidImage.gif", "invalid image");
+
+ assertFail("assertImagePresent", new Object[]{"images/Image4.jpg",
"image 4"});
+ assertFail("assertImagePresent", new Object[]{"images/wrongUrl.jpg",
"image 3"});
+ assertFail("assertImagePresent", new Object[]{"images/Image2.png",
"wrong alt"});
+ }
+
+ public void testGifCanBeLoaded() throws Throwable {
+ assertPass("assertImageValid", new Object[]{"images/Image1.gif",
"image 1"});
+ }
+
+ public void testPngCanBeLoaded() throws Throwable {
+ assertPass("assertImageValid", new Object[]{"images/Image2.png",
"image 2"});
+ }
+
+ public void testJpgCanBeLoaded() throws Throwable {
+ assertPass("assertImageValid", new
Object[]{"images/photos/Image3.jpg", "image 3"});
+ }
+
+ public void testFailsOnInvalidImages() throws Throwable {
+ assertFail("assertImageValid", new Object[]{"images/InvalidImage.gif",
"invalid image"});
+ }
+
+ public void testSavesImage() throws Throwable {
+ File testOut = File.createTempFile("jwebunit-test-", ".png");
+ testOut.deleteOnExit();
+ assertImageValidAndStore("images/Image2.png", "image 2", testOut);
+ BufferedImage testImg = ImageIO.read(testOut);
+ // let's just assume it's ok if the image was loaded from the
filesystem
+ assertNotNull(testImg);
+ }
+
+ public void testImagesAreExposed() throws Throwable {
+ Image image = getImage("images/Image1.gif", "image 1");
+ // let's just assume it's ok if the image is there
+ assertNotNull(image);
+ }
+
+ public void testRelativePathsAreCorrectlyResolved() {
+ beginAt("/somedir/AnotherPageWithImages.html");
+ assertImageValid("Image4.gif", "image 4 - same dir");
+ assertImageValid("images/Image5.png", "image 5 - subdir");
+ assertImageValid("../images/photos/Image3.jpg", "image 3 again -
topdir");
+ }
+}
Modified:
branches/1.x/jwebunit-commons-tests/src/main/java/net/sourceforge/jwebunit/tests/TestContextTest.java
===================================================================
---
branches/1.x/jwebunit-commons-tests/src/main/java/net/sourceforge/jwebunit/tests/TestContextTest.java
2007-01-02 14:59:26 UTC (rev 647)
+++
branches/1.x/jwebunit-commons-tests/src/main/java/net/sourceforge/jwebunit/tests/TestContextTest.java
2007-01-02 16:57:57 UTC (rev 648)
@@ -38,7 +38,7 @@
assertEquals(c.getValue(), "val");
assertEquals(c.getDomain(), "www.foo.bar");
assertEquals(Locale.CANADA_FRENCH, context.getLocale());
- assertEquals("http://localhost:8080", context.getBaseUrl());
+ assertEquals("http://localhost:8080", context.getBaseUrl().toString());
assertNull(context.getResourceBundleName());
}
Added:
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/PageWithImages.html
===================================================================
---
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/PageWithImages.html
(rev 0)
+++
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/PageWithImages.html
2007-01-02 16:57:57 UTC (rev 648)
@@ -0,0 +1,17 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+ <title>Image Test</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-15"/>
+</head>
+<body>
+<div id="test">
+ <img src="images/Image1.gif" alt="image 1" />
+ <img src="images/Image2.png" alt="image 2" />
+ <img src="images/photos/Image3.jpg" alt="image 3" />
+ <img src="somedir/Image4.gif" />
+ <img src="images/InvalidImage.gif" alt="invalid image" />
+</div>
+</body>
+</html>
+
Added:
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/images/Image1.gif
===================================================================
(Binary files differ)
Property changes on:
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/images/Image1.gif
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added:
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/images/Image2.png
===================================================================
(Binary files differ)
Property changes on:
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/images/Image2.png
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added:
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/images/InvalidImage.gif
===================================================================
---
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/images/InvalidImage.gif
(rev 0)
+++
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/images/InvalidImage.gif
2007-01-02 16:57:57 UTC (rev 648)
@@ -0,0 +1,2 @@
+this is not an image
+
Added:
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/images/photos/Image3.jpg
===================================================================
(Binary files differ)
Property changes on:
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/images/photos/Image3.jpg
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added:
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/somedir/AnotherPageWithImages.html
===================================================================
---
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/somedir/AnotherPageWithImages.html
(rev 0)
+++
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/somedir/AnotherPageWithImages.html
2007-01-02 16:57:57 UTC (rev 648)
@@ -0,0 +1,15 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+ <title>Image Test</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-15"/>
+</head>
+<body>
+<div id="test">
+ <img src="Image4.gif" alt="image 4 - same dir" />
+ <img src="images/Image5.png" alt="image 5 - subdir" />
+ <img src="../images/photos/Image3.jpg" alt="image 3 again - topdir" />
+</div>
+</body>
+</html>
+
Added:
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/somedir/Image4.gif
===================================================================
(Binary files differ)
Property changes on:
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/somedir/Image4.gif
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added:
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/somedir/images/Image5.png
===================================================================
(Binary files differ)
Property changes on:
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/ImageTest/somedir/images/Image5.png
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Modified:
branches/1.x/jwebunit-core/src/main/java/net/sourceforge/jwebunit/api/IJWebUnitDialog.java
===================================================================
---
branches/1.x/jwebunit-core/src/main/java/net/sourceforge/jwebunit/api/IJWebUnitDialog.java
2007-01-02 14:59:26 UTC (rev 647)
+++
branches/1.x/jwebunit-core/src/main/java/net/sourceforge/jwebunit/api/IJWebUnitDialog.java
2007-01-02 16:57:57 UTC (rev 648)
@@ -5,6 +5,8 @@
package net.sourceforge.jwebunit.api;
import java.io.File;
+import java.io.InputStream;
+import java.net.URL;
import java.util.List;
import net.sourceforge.jwebunit.exception.ExpectedJavascriptAlertException;
@@ -32,7 +34,7 @@
* @param aTestContext Test context
* @throws TestingEngineResponseException If something bad happend (404)
*/
- void beginAt(String aInitialURL, TestContext aTestContext)
+ void beginAt(URL aInitialURL, TestContext aTestContext)
throws TestingEngineResponseException;
/**
@@ -55,8 +57,8 @@
* @param url Full URL of the page.
* @throws TestingEngineResponseException If something bad happend (404)
*/
- void gotoPage(String url) throws TestingEngineResponseException;
-
+ void gotoPage(URL url) throws TestingEngineResponseException;
+
/**
* Enable or disable Javascript support.
*
@@ -505,6 +507,12 @@
void clickButtonWithText(String buttonValueText);
/**
+ * Get the location of the current page.
+ * @return an URL.
+ */
+ URL getPageURL();
+
+ /**
* Return the string representation of the current page, encoded as
specified by the current
* [EMAIL PROTECTED] net.sourceforge.jwebunit.util.TestContext}.
*
@@ -535,13 +543,21 @@
String getServerResponse();
/**
- * Save the last server response as file to the disk.
+ * Gets the last server response as input stream.
*
- * @param f The file name.
*/
- void saveAs(File f);
+ InputStream getInputStream();
/**
+ * Gets the input stream for a given URL - can be used to test images or
other resources without changing the current
+ * navigation context.
+ *
+ * @param url the url to the resource
+ */
+ InputStream getInputStream(URL url)
+ throws TestingEngineResponseException;
+
+ /**
* Check if the Table object representing a specified table exists.
*
* @param tableSummaryNameOrId summary, name or id of the table.
Modified:
branches/1.x/jwebunit-core/src/main/java/net/sourceforge/jwebunit/junit/WebTester.java
===================================================================
---
branches/1.x/jwebunit-core/src/main/java/net/sourceforge/jwebunit/junit/WebTester.java
2007-01-02 14:59:26 UTC (rev 647)
+++
branches/1.x/jwebunit-core/src/main/java/net/sourceforge/jwebunit/junit/WebTester.java
2007-01-02 16:57:57 UTC (rev 648)
@@ -4,16 +4,21 @@
******************************************************************************/
package net.sourceforge.jwebunit.junit;
+import java.awt.Image;
+import java.awt.image.BufferedImage;
import java.io.File;
+import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
+import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
+import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import junit.framework.Assert;
@@ -54,8 +59,7 @@
private String testingEngineKey = null;
/**
- * Provides access to the testing engine for subclasses - in case
functionality not yet wrappered required
- * by test.
+ * Provides access to the testing engine for subclasses - in case
functionality not yet wrappered required by test.
*
* If the dialog is not explicitly set the jWebUnit framework will default
to using the orignal testing engine,
* which is, htmlunit.
@@ -66,9 +70,10 @@
public IJWebUnitDialog getDialog() {
return getTestingEngine();
}
-
+
/**
* Protected version of deprecated getDialog(). Not deprecated for
internal use.
+ *
* @return IJWebUnitDialog instance.
*/
protected IJWebUnitDialog getTestingEngine() {
@@ -139,6 +144,7 @@
/**
* Set the testing engine.
+ *
* @param aIJWebUnitDialog Testing engine.
*/
public void setDialog(IJWebUnitDialog aIJWebUnitDialog) {
@@ -179,22 +185,25 @@
*/
public void beginAt(String aRelativeURL) {
try {
- getTestingEngine().beginAt(createUrl(aRelativeURL), testContext);
+ getTestingEngine().beginAt(createUrl(aRelativeURL,
getTestContext().getBaseUrl()), testContext);
} catch (TestingEngineResponseException e) {
- Assert.fail("The server returns the code " + e.getHttpStatusCode()
+ "\n" + e.getCause().getMessage());
+ Assert.fail("The server returns the code " + e.getHttpStatusCode()
+ + "\n" + e.getCause().getMessage());
+ } catch (MalformedURLException e) {
+ Assert.fail(e.getLocalizedMessage());
}
}
- private String createUrl(String url) {
+ private URL createUrl(String url, URL baseURL) throws
MalformedURLException {
if (url.startsWith("http://") || url.startsWith("https://")
|| url.startsWith("file://")) {
- return url;
+ return new URL(url);
} else if (url.startsWith("www.")) {
- return "http://" + url;
+ return new URL("http://" + url);
} else {
url = url.startsWith("/") ? url.substring(1) : url;
- return getTestContext().getBaseUrl() + url;
+ return new URL(baseURL, url);
}
}
@@ -253,7 +262,8 @@
* @param titleKey web resource key for title
*/
public void assertTitleEqualsKey(String titleKey) {
- Assert.assertEquals(getMessage(titleKey),
getTestingEngine().getPageTitle());
+ Assert.assertEquals(getMessage(titleKey), getTestingEngine()
+ .getPageTitle());
}
/**
@@ -273,8 +283,8 @@
public void assertTextPresent(String text) {
if (!(getTestingEngine().getPageText().indexOf(text) >= 0))
Assert.fail("Expected text not found in current page: [" + text
- + "]\n Page content was: [" +
getTestingEngine().getPageText()
- + "]");
+ + "]\n Page content was: ["
+ + getTestingEngine().getPageText() + "]");
}
/**
@@ -492,7 +502,8 @@
*/
public void assertTableEquals(String tableSummaryNameOrId,
Table expectedTable) {
-
getTestingEngine().getTable(tableSummaryNameOrId).assertEquals(expectedTable);
+ getTestingEngine().getTable(tableSummaryNameOrId).assertEquals(
+ expectedTable);
}
/**
@@ -556,7 +567,8 @@
* @param expectedTable represents expected regexps (colspan supported).
*/
public void assertTableMatch(String tableSummaryOrId, Table expectedTable)
{
-
getTestingEngine().getTable(tableSummaryOrId).assertMatch(expectedTable);
+ getTestingEngine().getTable(tableSummaryOrId)
+ .assertMatch(expectedTable);
}
/**
@@ -580,8 +592,8 @@
*/
public void assertTableRowsMatch(String tableSummaryOrId, int startRow,
Table expectedTable) {
-
getTestingEngine().getTable(tableSummaryOrId).assertSubTableMatch(startRow,
- expectedTable);
+ getTestingEngine().getTable(tableSummaryOrId).assertSubTableMatch(
+ startRow, expectedTable);
}
/**
@@ -593,8 +605,8 @@
*/
public void assertTableRowsMatch(String tableSummaryOrId, int startRow,
String[][] expectedTable) {
-
getTestingEngine().getTable(tableSummaryOrId).assertSubTableMatch(startRow,
- new Table(expectedTable));
+ getTestingEngine().getTable(tableSummaryOrId).assertSubTableMatch(
+ startRow, new Table(expectedTable));
}
/**
@@ -605,8 +617,8 @@
public void assertFormElementPresent(String formElementName) {
assertFormPresent();
Assert.assertTrue("Did not find form element with name ["
- + formElementName + "].",
getTestingEngine().hasFormParameterNamed(
- formElementName));
+ + formElementName + "].", getTestingEngine()
+ .hasFormParameterNamed(formElementName));
}
/**
@@ -774,8 +786,8 @@
public void assertTextFieldEquals(String formElementName,
String expectedValue) {
assertFormElementPresent(formElementName);
- Assert.assertEquals(expectedValue,
getTestingEngine().getTextFieldValue(
- formElementName));
+ Assert.assertEquals(expectedValue, getTestingEngine()
+ .getTextFieldValue(formElementName));
}
/**
@@ -788,8 +800,8 @@
public void assertHiddenFieldPresent(String formElementName,
String expectedValue) {
assertFormElementPresent(formElementName);
- Assert.assertEquals(expectedValue,
getTestingEngine().getHiddenFieldValue(
- formElementName));
+ Assert.assertEquals(expectedValue, getTestingEngine()
+ .getHiddenFieldValue(formElementName));
}
/**
@@ -882,8 +894,10 @@
*/
public void assertRadioOptionSelected(String name, String radioOption) {
assertRadioOptionPresent(name, radioOption);
- Assert.assertEquals(radioOption,
getTestingEngine().getElementAttributByXPath(
- "//[EMAIL PROTECTED]'radio' and @name='" + name + "']",
"value"));
+ Assert.assertEquals(radioOption, getTestingEngine()
+ .getElementAttributByXPath(
+ "//[EMAIL PROTECTED]'radio' and @name='" + name + "']",
+ "value"));
}
/**
@@ -895,9 +909,10 @@
public void assertRadioOptionNotSelected(String name, String radioOption) {
assertRadioOptionPresent(name, radioOption);
Assert.assertFalse("Radio option [" + radioOption + "] is selected.",
-
radioOption.equals(getTestingEngine().getElementAttributByXPath(
- "//[EMAIL PROTECTED]'radio' and @name='" + name + "']",
- "value")));
+ radioOption.equals(getTestingEngine()
+ .getElementAttributByXPath(
+ "//[EMAIL PROTECTED]'radio' and @name='" + name
+ + "']", "value")));
}
/**
@@ -912,7 +927,8 @@
for (int i = 0; i < optionLabels.length; i++)
Assert.assertTrue("Option [" + optionLabels[i]
+ "] not found in select element " + selectName,
- getTestingEngine().hasSelectOption(selectName,
optionLabels[i]));
+ getTestingEngine().hasSelectOption(selectName,
+ optionLabels[i]));
}
/**
@@ -1019,8 +1035,8 @@
public void assertSelectOptionValuesEqual(String selectName,
String[] expectedValues) {
assertFormElementPresent(selectName);
- assertArraysEqual(expectedValues,
getTestingEngine().getSelectOptionValues(
- selectName));
+ assertArraysEqual(expectedValues, getTestingEngine()
+ .getSelectOptionValues(selectName));
}
@@ -1049,12 +1065,15 @@
*/
public void assertSelectedOptionsEqual(String selectName, String[] labels)
{
assertFormElementPresent(selectName);
- Assert.assertEquals(labels.length,
getTestingEngine().getSelectedOptions(
- selectName).length);
+ Assert.assertEquals(labels.length, getTestingEngine()
+ .getSelectedOptions(selectName).length);
for (int i = 0; i < labels.length; i++)
- Assert.assertEquals(labels[i], getDialog()
- .getSelectOptionLabelForValue(selectName,
-
getTestingEngine().getSelectedOptions(selectName)[i]));
+ Assert.assertEquals(labels[i],
+ getDialog()
+ .getSelectOptionLabelForValue(
+ selectName,
+ getTestingEngine().getSelectedOptions(
+ selectName)[i]));
}
public void assertSelectedOptionEquals(String selectName, String option) {
@@ -1070,11 +1089,11 @@
public void assertSelectedOptionValuesEqual(String selectName,
String[] values) {
assertFormElementPresent(selectName);
- Assert.assertEquals(values.length,
getTestingEngine().getSelectedOptions(
- selectName).length);
+ Assert.assertEquals(values.length, getTestingEngine()
+ .getSelectedOptions(selectName).length);
for (int i = 0; i < values.length; i++)
- Assert.assertEquals(values[i],
getTestingEngine().getSelectedOptions(
- selectName)[i]);
+ Assert.assertEquals(values[i], getTestingEngine()
+ .getSelectedOptions(selectName)[i]);
}
/**
@@ -1095,14 +1114,15 @@
*/
public void assertSelectedOptionsMatch(String selectName, String[]
regexps) {
assertFormElementPresent(selectName);
- Assert.assertEquals(regexps.length,
getTestingEngine().getSelectedOptions(
- selectName).length);
+ Assert.assertEquals(regexps.length, getTestingEngine()
+ .getSelectedOptions(selectName).length);
for (int i = 0; i < regexps.length; i++) {
RE re = getRE(regexps[i]);
Assert.assertTrue("Unable to match [" + regexps[i]
+ "] in option \""
- + getTestingEngine().getSelectedOptions(selectName)[i] +
"\"", re
-
.match(getTestingEngine().getSelectedOptions(selectName)[i]));
+ + getTestingEngine().getSelectedOptions(selectName)[i]
+ + "\"", re.match(getTestingEngine().getSelectedOptions(
+ selectName)[i]));
}
}
@@ -1191,8 +1211,8 @@
public void assertSubmitButtonPresent(String buttonName, String
buttonValue) {
assertFormPresent();
Assert.assertTrue("Submit Button [" + buttonName + "] with value ["
- + buttonValue + "] not found.",
getTestingEngine().hasSubmitButton(
- buttonName, buttonValue));
+ + buttonValue + "] not found.", getTestingEngine()
+ .hasSubmitButton(buttonName, buttonValue));
}
/**
@@ -1236,7 +1256,8 @@
*/
public void assertResetButtonNotPresent() {
assertFormPresent();
- Assert.assertFalse("Reset Button found.",
getTestingEngine().hasResetButton());
+ Assert.assertFalse("Reset Button found.", getTestingEngine()
+ .hasResetButton());
}
/**
@@ -1330,8 +1351,8 @@
*/
public void assertLinkPresentWithText(String linkText) {
Assert.assertTrue("Link with text [" + linkText
- + "] not found in response.",
getTestingEngine().hasLinkWithText(
- linkText, 0));
+ + "] not found in response.", getTestingEngine()
+ .hasLinkWithText(linkText, 0));
}
/**
@@ -1365,8 +1386,8 @@
*/
public void assertLinkNotPresentWithText(String linkText, int index) {
Assert.assertTrue("Link with text [" + linkText + "] and index "
- + index + " found in response.",
!getTestingEngine().hasLinkWithText(
- linkText, index));
+ + index + " found in response.", !getTestingEngine()
+ .hasLinkWithText(linkText, index));
}
// BEGIN RFE 996031...
@@ -1378,8 +1399,8 @@
*/
public void assertLinkPresentWithExactText(String linkText) {
Assert.assertTrue("Link with Exact text [" + linkText
- + "] not found in response.",
getTestingEngine().hasLinkWithExactText(
- linkText, 0));
+ + "] not found in response.", getTestingEngine()
+ .hasLinkWithExactText(linkText, 0));
}
/**
@@ -1389,8 +1410,8 @@
*/
public void assertLinkNotPresentWithExactText(String linkText) {
Assert.assertTrue("Link with Exact text [" + linkText
- + "] found in response.",
!getTestingEngine().hasLinkWithExactText(
- linkText, 0));
+ + "] found in response.", !getTestingEngine()
+ .hasLinkWithExactText(linkText, 0));
}
/**
@@ -1427,8 +1448,8 @@
*/
public void assertLinkPresentWithImage(String imageFileName) {
Assert.assertTrue("Link with image file [" + imageFileName
- + "] not found in response.",
getTestingEngine().hasLinkWithImage(
- imageFileName, 0));
+ + "] not found in response.", getTestingEngine()
+ .hasLinkWithImage(imageFileName, 0));
}
/**
@@ -1502,8 +1523,8 @@
Assert.assertTrue("Unable to locate element with id \"" + elementID
+ "\"", getTestingEngine().hasElement(elementID));
Assert.assertFalse("Text [" + text + "] found in element [" + elementID
- + "] when not expected",
getTestingEngine().isTextInElement(elementID,
- text));
+ + "] when not expected", getTestingEngine().isTextInElement(
+ elementID, text));
}
/**
@@ -1516,8 +1537,8 @@
Assert.assertTrue("Unable to locate element with id \"" + elementID
+ "\"", getTestingEngine().hasElement(elementID));
Assert.assertTrue("Unable to match [" + regexp + "] in element \""
- + elementID + "\"",
getTestingEngine().isMatchInElement(elementID,
- regexp));
+ + elementID + "\"", getTestingEngine().isMatchInElement(
+ elementID, regexp));
}
/**
@@ -1572,9 +1593,11 @@
* @param windowCount Window count
*/
public void assertWindowCountEquals(int windowCount) {
- Assert.assertTrue("Window count is " +
getTestingEngine().getWindowCount()
- + " but " + windowCount + " was expected.", getDialog()
- .getWindowCount() == windowCount);
+ Assert
+ .assertTrue("Window count is "
+ + getTestingEngine().getWindowCount() + " but "
+ + windowCount + " was expected.", getDialog()
+ .getWindowCount() == windowCount);
}
/**
@@ -1584,7 +1607,8 @@
*/
public void assertFramePresent(String frameNameOrId) {
Assert.assertTrue("Unable to locate frame with name or ID ["
- + frameNameOrId + "].",
getTestingEngine().hasFrame(frameNameOrId));
+ + frameNameOrId + "].", getTestingEngine().hasFrame(
+ frameNameOrId));
}
/**
@@ -2009,9 +2033,11 @@
*/
public void gotoPage(String url) {
try {
- getTestingEngine().gotoPage(createUrl(url));
+ getTestingEngine().gotoPage(createUrl(url,
getTestContext().getBaseUrl()));
} catch (TestingEngineResponseException e) {
Assert.fail("The server returns the code " +
e.getHttpStatusCode());
+ } catch (MalformedURLException e) {
+ Assert.fail(e.getLocalizedMessage());
}
}
@@ -2054,7 +2080,18 @@
* @param f The file name.
*/
public void saveAs(File f) {
- getTestingEngine().saveAs(f);
+ InputStream in = getTestingEngine().getInputStream();
+ int c=0;
+ try {
+ f.createNewFile();
+ FileOutputStream out = new FileOutputStream(f);
+ while ((c=in.read()) != -1) out.write(c);
+ in.close();
+ out.close();
+ } catch (IOException e) {
+ throw new RuntimeException("Error when writing to file", e);
+ }
+
}
/**
@@ -2184,18 +2221,18 @@
* Exemple: <br/>
*
* <pre>
- * <FORM action="http://my_host/doit"
method="post">
- * <P>
- * <SELECT multiple size="4"
name="component-select">
- * <OPTION selected
value="Component_1_a">Component_1</OPTION>
- * <OPTION selected
value="Component_1_b">Component_2</OPTION>
- * <OPTION>Component_3</OPTION>
- * <OPTION>Component_4</OPTION>
- * <OPTION>Component_5</OPTION>
- * </SELECT>
- * <INPUT type="submit"
value="Send"><INPUT type="reset">
- * </P>
- * </FORM>
+ * <FORM action="http://my_host/doit"
method="post">
+ * <P>
+ * <SELECT multiple size="4"
name="component-select">
+ * <OPTION selected
value="Component_1_a">Component_1</OPTION>
+ * <OPTION selected
value="Component_1_b">Component_2</OPTION>
+ * <OPTION>Component_3</OPTION>
+ * <OPTION>Component_4</OPTION>
+ * <OPTION>Component_5</OPTION>
+ * </SELECT>
+ * <INPUT type="submit"
value="Send"><INPUT type="reset">
+ * </P>
+ * </FORM>
* </pre>
*
* Should return [Component_1, Component_2, Component_3, Component_4,
Component_5]
@@ -2207,8 +2244,8 @@
String[] values = getTestingEngine().getSelectOptionValues(selectName);
String[] result = new String[values.length];
for (int i = 0; i < values.length; i++) {
- result[i] =
getTestingEngine().getSelectOptionLabelForValue(selectName,
- values[i]);
+ result[i] = getTestingEngine().getSelectOptionLabelForValue(
+ selectName, values[i]);
}
return result;
}
@@ -2222,8 +2259,8 @@
private void selectOptionsByLabel(String selectName, String[] labels) {
String[] values = new String[labels.length];
for (int i = 0; i < values.length; i++) {
- values[i] =
getTestingEngine().getSelectOptionValueForLabel(selectName,
- labels[i]);
+ values[i] = getTestingEngine().getSelectOptionValueForLabel(
+ selectName, labels[i]);
}
getTestingEngine().selectOptions(selectName, values);
}
@@ -2258,7 +2295,7 @@
public void setExpectedJavaScriptAlert(String message) {
try {
getTestingEngine().setExpectedJavaScriptAlert(
- new JavascriptAlert[] {new JavascriptAlert(message)});
+ new JavascriptAlert[] { new JavascriptAlert(message) });
} catch (ExpectedJavascriptAlertException e) {
Assert.fail("You previously tell that alert with message ["
+ e.getAlertMessage()
@@ -2368,6 +2405,66 @@
}
}
+ public void assertImagePresent(String imageSrc, String imageAlt) {
+ String xpath = "//[EMAIL PROTECTED]"" + imageSrc + "\"";
+ if (imageAlt!= null) {
+ xpath += " and @alt=\"" + imageAlt + "\"";
+ }
+ xpath += "]";
+ assertElementPresentByXPath(xpath);
+ }
+
+ /**
+ * @see #assertImageValidAndStore(String, String, java.io.File)
+ */
+ public void assertImageValid(String imageSrc, String imageAlt) {
+ validateImage(imageSrc, imageAlt, null);
+ }
+
+ /**
+ * Asserts that the image with the given src and alt attribute values
exist in the page and is an actual reachable
+ * image, then saves it as png with the given file name.
+ *
+ * @param imageSrc as it appears in the html page, i.e. relative to the
current page.
+ */
+ public void assertImageValidAndStore(String imageSrc, String imageAlt,
+ File out) {
+ validateImage(imageSrc, imageAlt, out);
+ }
+
+ /**
+ * @see #assertImageValidAndStore(String, String, java.io.File)
+ */
+ public Image getImage(String imageSrc, String imageAlt) {
+ return validateImage(imageSrc, imageAlt, null);
+ }
+
+ private Image validateImage(String imageSrc, String imageAlt, File out) {
+ assertImagePresent(imageSrc, imageAlt);
+ URL imageUrl = null;
+ try {
+ imageUrl = createUrl(imageSrc, getTestingEngine().getPageURL());
+ } catch (MalformedURLException e1) {
+ Assert.fail(e1.getLocalizedMessage());
+ }
+ try {
+ final InputStream imgStream =
getTestingEngine().getInputStream(imageUrl);
+ final BufferedImage img = ImageIO.read(imgStream);
+ if (img == null) {
+ Assert.fail("Could not load image from " + imageUrl);
+ }
+ if (out != null) {
+ ImageIO.write(img, "png", out);
+ }
+ return img;
+ } catch (IOException e) {
+ Assert.fail("Could not load or save image from " + imageUrl);
+ } catch (TestingEngineResponseException e) {
+ Assert.fail("The server returns the code " +
e.getHttpStatusCode());
+ }
+ throw new IllegalStateException();
+ }
+
protected boolean areFilesEqual(URL f1, URL f2) throws IOException {
// read and compare bytes pair-wise
InputStream i1 = f1.openStream();
Modified:
branches/1.x/jwebunit-core/src/main/java/net/sourceforge/jwebunit/util/TestContext.java
===================================================================
---
branches/1.x/jwebunit-core/src/main/java/net/sourceforge/jwebunit/util/TestContext.java
2007-01-02 14:59:26 UTC (rev 647)
+++
branches/1.x/jwebunit-core/src/main/java/net/sourceforge/jwebunit/util/TestContext.java
2007-01-02 16:57:57 UTC (rev 648)
@@ -6,6 +6,8 @@
import javax.servlet.http.Cookie;
+import java.net.MalformedURLException;
+import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -38,7 +40,7 @@
private String resourceBundleName;
- private String baseUrl = "http://localhost:8080";
+ private URL baseUrl;
private String userAgent;
@@ -59,6 +61,12 @@
*/
public TestContext() {
cookies = new ArrayList();
+ try {
+ baseUrl = new URL("http://localhost:8080");
+ } catch (MalformedURLException e) {
+ // Should not be invalid
+ e.printStackTrace();
+ }
}
/**
@@ -265,7 +273,7 @@
/**
* Return the base URL for the test context. The default base URL is port
8080 on localhost.
*/
- public String getBaseUrl() {
+ public URL getBaseUrl() {
return baseUrl;
}
@@ -275,10 +283,23 @@
* @param url Base url value - A trailing "/" is appended if not provided.
*/
public void setBaseUrl(String url) {
- baseUrl = url.endsWith("/") ? url : url + "/";
+ try {
+ baseUrl = new URL(url.endsWith("/") ? url : url + "/");
+ } catch (MalformedURLException e) {
+ throw new RuntimeException(e);
+ }
}
/**
+ * Set the base url for the test context.
+ *
+ * @param url Base url value. Anything after trailing "/" will be skipped.
+ */
+ public void setBaseUrl(URL url) {
+ baseUrl = url;
+ }
+
+ /**
* Add a custom request header.
* @param name header name.
* @param value header value.
Modified:
branches/1.x/jwebunit-htmlunit-plugin/src/main/java/net/sourceforge/jwebunit/htmlunit/HtmlUnitDialog.java
===================================================================
---
branches/1.x/jwebunit-htmlunit-plugin/src/main/java/net/sourceforge/jwebunit/htmlunit/HtmlUnitDialog.java
2007-01-02 14:59:26 UTC (rev 647)
+++
branches/1.x/jwebunit-htmlunit-plugin/src/main/java/net/sourceforge/jwebunit/htmlunit/HtmlUnitDialog.java
2007-01-02 16:57:57 UTC (rev 648)
@@ -50,9 +50,11 @@
import com.gargoylesoftware.htmlunit.html.xpath.HtmlUnitXPath;
import com.gargoylesoftware.htmlunit.xml.XmlPage;
+import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
+import java.io.InputStream;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
@@ -155,12 +157,12 @@
* @param context contains context information for the test client.
* @throws TestingEngineResponseException
*/
- public void beginAt(String initialURL, TestContext context)
+ public void beginAt(URL initialURL, TestContext context)
throws TestingEngineResponseException {
this.setTestContext(context);
initWebClient();
try {
- wc.getPage(new URL(initialURL));
+ wc.getPage(initialURL);
win = wc.getCurrentWindow();
form = null;
} catch (FailingHttpStatusCodeException aException) {
@@ -194,10 +196,9 @@
}
- public void gotoPage(String initialURL)
- throws TestingEngineResponseException {
+ public void gotoPage(URL initialURL) throws TestingEngineResponseException
{
try {
- wc.getPage(new URL(initialURL));
+ wc.getPage(initialURL);
win = wc.getCurrentWindow();
form = null;
} catch (FailingHttpStatusCodeException aException) {
@@ -544,6 +545,10 @@
+ selectName);
}
+ public URL getPageURL() {
+ return win.getEnclosedPage().getWebResponse().getUrl();
+ }
+
public String getPageSource() {
return wc.getCurrentWindow().getEnclosedPage().getWebResponse()
.getContentAsString();
@@ -588,18 +593,37 @@
return result.toString();
}
- public void saveAs(File f) {
+ public InputStream getInputStream() {
try {
- f.createNewFile();
- FileOutputStream out = new FileOutputStream(f);
- out.write(wc.getCurrentWindow().getEnclosedPage().getWebResponse()
- .getResponseBody());
- out.close();
+ return wc.getCurrentWindow().getEnclosedPage().getWebResponse()
+ .getContentAsStream();
} catch (IOException e) {
- throw new RuntimeException("Error when writing to file", e);
+ throw new RuntimeException(e);
}
}
+ public InputStream getInputStream(URL resourceUrl)
+ throws TestingEngineResponseException {
+ WebWindow imageWindow = null;
+ try {
+ // as far as I can tell, there is no such thing as an
iframe/object kind of "window" in htmlunit, so I'm
+ // opening a fake new window here
+ imageWindow = wc.openWindow(resourceUrl, "for_stream");
+ Page page = imageWindow.getEnclosedPage();
+ return page.getWebResponse().getContentAsStream();
+ } catch (FailingHttpStatusCodeException aException) {
+ throw new TestingEngineResponseException(
+ aException.getStatusCode(), aException);
+
+ } catch (IOException aException) {
+ throw new RuntimeException(aException);
+ } finally {
+ if (imageWindow != null) {
+ wc.deregisterWebWindow(imageWindow);
+ }
+ }
+ }
+
private void initWebClient() {
wc = new WebClient(new BrowserVersion(BrowserVersion.INTERNET_EXPLORER,
"4.0", testContext.getUserAgent(), "1.2", 6));
@@ -639,8 +663,11 @@
}
String win = event.getWebWindow().getName();
Page oldPage = event.getOldPage();
- LOGGER.info("Window " + win + " closed : "
- + ((HtmlPage) oldPage).getTitleText());
+ String oldPageTitle = "no_html";
+ if (oldPage instanceof HtmlPage) {
+ oldPageTitle = ((HtmlPage) oldPage).getTitleText();
+ }
+ LOGGER.info("Window " + win + " closed : " + oldPageTitle);
}
public void webWindowContentChanged(WebWindowEvent event) {
@@ -661,7 +688,7 @@
public void webWindowOpened(WebWindowEvent event) {
String win = event.getWebWindow().getName();
Page newPage = event.getNewPage();
- if (newPage != null) {
+ if (newPage != null && newPage instanceof HtmlPage) {
LOGGER.info("Window " + win + " openend : "
+ ((HtmlPage) newPage).getTitleText());
} else {
Modified:
branches/1.x/jwebunit-htmlunit-plugin/src/test/java/net/sourceforge/jwebunit/htmlunit/JWebUnitTest.java
===================================================================
---
branches/1.x/jwebunit-htmlunit-plugin/src/test/java/net/sourceforge/jwebunit/htmlunit/JWebUnitTest.java
2007-01-02 14:59:26 UTC (rev 647)
+++
branches/1.x/jwebunit-htmlunit-plugin/src/test/java/net/sourceforge/jwebunit/htmlunit/JWebUnitTest.java
2007-01-02 16:57:57 UTC (rev 648)
@@ -49,6 +49,7 @@
suite.addTestSuite(ButtonAssertionsTest.class);
suite.addTestSuite(NonHtmlContentTest.class);
suite.addTestSuite(RedirectionTest.class);
+ suite.addTestSuite(ImageTest.class);
// $JUnit-END$
return new JettySetup(suite);
}
Modified: branches/1.x/jwebunit-webtestcase-generator/src/main/javacc/Java1.5.jj
===================================================================
--- branches/1.x/jwebunit-webtestcase-generator/src/main/javacc/Java1.5.jj
2007-01-02 14:59:26 UTC (rev 647)
+++ branches/1.x/jwebunit-webtestcase-generator/src/main/javacc/Java1.5.jj
2007-01-02 16:57:57 UTC (rev 648)
@@ -487,7 +487,8 @@
{sb.append(getToken(1).specialToken.image).append("\n");}
[ PackageDeclaration(sb) ]
- {sb.append("import java.io.File;\n");
+ {sb.append("import java.awt.Image;\n");
+ sb.append("import java.io.File;\n");
sb.append("import java.io.PrintStream;\n");
sb.append("import java.net.URL;\n\n");
sb.append("import net.sourceforge.jwebunit.api.IJWebUnitDialog;\n");
Modified: branches/1.x/src/changes/changes.xml
===================================================================
--- branches/1.x/src/changes/changes.xml 2007-01-02 14:59:26 UTC (rev
647)
+++ branches/1.x/src/changes/changes.xml 2007-01-02 16:57:57 UTC (rev
648)
@@ -8,6 +8,11 @@
</properties>
<body>
<release version="1.4-RC3" date="unknow">
+ <action type="add" dev="Julien Henry" due-to="Gr\xE9gory Joseph"
issue="1531873">
+ Add methods to test images in a web page:
assertImagePresent(String imageSrc, String imageAlt),
+ assertImageValid(String imageSrc, String imageAlt),
+ assertImageValidAndStore(String imageSrc, String imageAlt,
File out)
+ </action>
<action type="add" dev="Julien Henry" due-to="Jeff Grimshaw"
issue="1563168">
Add methods in TestContext to specify custom request headers.
</action>
This was sent by the SourceForge.net collaborative development platform, the
world's largest Open Source development site.
-------------------------------------------------------------------------
Take Surveys. Earn Cash. Influence the Future of IT
Join SourceForge.net's Techsay panel and you'll get the chance to share your
opinions on IT & business topics through brief surveys - and earn cash
http://www.techsay.com/default.php?page=join.php&p=sourceforge&CID=DEVDEV
_______________________________________________
Jwebunit-development mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/jwebunit-development