Revision: 626
          http://svn.sourceforge.net/jwebunit/?rev=626&view=rev
Author:   henryju
Date:     2006-11-24 06:11:31 -0800 (Fri, 24 Nov 2006)

Log Message:
-----------
Add methods to test binary response (for non html content).
Fix getPageSource() to return HTTP Body as String for non HTML content.

Modified Paths:
--------------
    
branches/1.x/jwebunit-commons-tests/src/main/java/net/sourceforge/jwebunit/tests/util/JettySetup.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-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/NonHtmlContentTest.java
    
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/NonHtmlContentTest/
    
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/NonHtmlContentTest/image.png
    
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/NonHtmlContentTest/text.bin
    
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/NonHtmlContentTest/text.txt

Added: 
branches/1.x/jwebunit-commons-tests/src/main/java/net/sourceforge/jwebunit/tests/NonHtmlContentTest.java
===================================================================
--- 
branches/1.x/jwebunit-commons-tests/src/main/java/net/sourceforge/jwebunit/tests/NonHtmlContentTest.java
                            (rev 0)
+++ 
branches/1.x/jwebunit-commons-tests/src/main/java/net/sourceforge/jwebunit/tests/NonHtmlContentTest.java
    2006-11-24 14:11:31 UTC (rev 626)
@@ -0,0 +1,50 @@
+/******************************************************************************
+ * jWebUnit project (http://jwebunit.sourceforge.net)                         *
+ * Distributed open-source, see full license under LICENCE.txt                *
+ 
******************************************************************************/
+package net.sourceforge.jwebunit.tests;
+
+import java.io.File;
+import java.net.URL;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import net.sourceforge.jwebunit.tests.util.JettySetup;
+
+/**
+ * Test that non-html content is well handled.
+ * 
+ * @author Julien Henry
+ */
+public class NonHtmlContentTest extends JWebUnitAPITestCase {
+
+    public static Test suite() {
+        Test suite = new TestSuite(NonHtmlContentTest.class);
+        return new JettySetup(suite);
+    }
+
+    public void setUp() throws Exception {
+        super.setUp();
+        getTestContext().setBaseUrl(HOST_PATH + "/NonHtmlContentTest");
+    }
+
+    public void testTextContent() {
+        beginAt("/text.txt");
+        assertTextPresent("Hello\r\nWorld");
+    }
+
+    public void testBinaryContent() {
+        beginAt("/text.bin");
+        assertTextPresent("Hello\r\nWorld");
+    }
+
+    public void testImageContent() {
+        beginAt("/image.png");
+        saveAs(new File("C:\\test.png"));
+        URL url = this.getClass().getResource(
+                "/testcases/NonHtmlContentTest/image.png");
+        File img = new File(url.getPath());
+        assertDownloadedFileEquals(img);
+    }
+}
\ No newline at end of file

Modified: 
branches/1.x/jwebunit-commons-tests/src/main/java/net/sourceforge/jwebunit/tests/util/JettySetup.java
===================================================================
--- 
branches/1.x/jwebunit-commons-tests/src/main/java/net/sourceforge/jwebunit/tests/util/JettySetup.java
       2006-11-23 10:01:43 UTC (rev 625)
+++ 
branches/1.x/jwebunit-commons-tests/src/main/java/net/sourceforge/jwebunit/tests/util/JettySetup.java
       2006-11-24 14:11:31 UTC (rev 626)
@@ -69,6 +69,8 @@
                        // Handle files encoded in UTF-8
                        MimeTypes mimeTypes = new MimeTypes();
                        mimeTypes.addMimeMapping("html_utf-8", "text/html; 
charset=UTF-8");
+            mimeTypes.addMimeMapping("txt", "text/plain");
+            mimeTypes.addMimeMapping("bin", "application/octet-stream");
                        wah.setMimeTypes(mimeTypes);
                        
                        

Added: 
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/NonHtmlContentTest/image.png
===================================================================
(Binary files differ)


Property changes on: 
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/NonHtmlContentTest/image.png
___________________________________________________________________
Name: svn:mime-type
   + application/octet-stream

Added: 
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/NonHtmlContentTest/text.bin
===================================================================
--- 
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/NonHtmlContentTest/text.bin
                                (rev 0)
+++ 
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/NonHtmlContentTest/text.bin
        2006-11-24 14:11:31 UTC (rev 626)
@@ -0,0 +1,2 @@
+Hello
+World
\ No newline at end of file

Added: 
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/NonHtmlContentTest/text.txt
===================================================================
--- 
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/NonHtmlContentTest/text.txt
                                (rev 0)
+++ 
branches/1.x/jwebunit-commons-tests/src/main/resources/testcases/NonHtmlContentTest/text.txt
        2006-11-24 14:11:31 UTC (rev 626)
@@ -0,0 +1,2 @@
+Hello
+World
\ No newline at end of file

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
  2006-11-23 10:01:43 UTC (rev 625)
+++ 
branches/1.x/jwebunit-core/src/main/java/net/sourceforge/jwebunit/api/IJWebUnitDialog.java
  2006-11-24 14:11:31 UTC (rev 626)
@@ -4,6 +4,7 @@
  
******************************************************************************/
 package net.sourceforge.jwebunit.api;
 
+import java.io.File;
 import java.util.List;
 
 import net.sourceforge.jwebunit.exception.ExpectedJavascriptAlertException;
@@ -499,31 +500,41 @@
      * <li>button type=button
      * </ul>
      * 
-     * @param text the text of the button (contents of the value attribute).
+     * @param buttonValueText the text of the button (contents of the value 
attribute).
      */
     void clickButtonWithText(String buttonValueText);
 
     /**
      * Return the string representation of the current page, encoded as 
specified by the current
      * [EMAIL PROTECTED] net.sourceforge.jwebunit.util.TestContext}.
+     * @return Visible text in the page.
      */
     String getPageText();
 
     /**
      * Return the source of the current page (like in a browser).
+     * @return Source of the page (or HTTP Body as String)
      */
     String getPageSource();
 
     /**
      * Return the page title of the current response page, encoded as 
specified by the current
      * [EMAIL PROTECTED] net.sourceforge.jwebunit.util.TestContext}.
+     * @return Title of the page.
      */
     String getPageTitle();
 
     /**
-     * Return the response of the server.
+     * Return the response of the server for the current page.
+     * @return HTTP header & body
      */
     String getServerResponse();
+    
+    /**
+     * Save the last server response as file to the disk.
+     * @param f The file name.
+     */
+    void saveAs(File f);
 
     /**
      * Check if the Table object representing a specified table exists.

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
      2006-11-23 10:01:43 UTC (rev 625)
+++ 
branches/1.x/jwebunit-core/src/main/java/net/sourceforge/jwebunit/junit/WebTester.java
      2006-11-24 14:11:31 UTC (rev 626)
@@ -4,6 +4,10 @@
  
******************************************************************************/
 package net.sourceforge.jwebunit.junit;
 
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
 import java.io.PrintStream;
 import java.util.Iterator;
 import java.util.List;
@@ -175,7 +179,8 @@
     }
 
     private String createUrl(String url) {
-        if (url.startsWith("http://";) || url.startsWith("https://";) || 
url.startsWith("file://")) {
+        if (url.startsWith("http://";) || url.startsWith("https://";)
+                || url.startsWith("file://")) {
             return url;
         } else if (url.startsWith("www.")) {
             return "http://"; + url;
@@ -260,7 +265,8 @@
     public void assertTextPresent(String text) {
         if (!(getDialog().getPageText().indexOf(text) >= 0))
             Assert.fail("Expected text not found in current page: [" + text
-                    + "]\n Page content was: " + getDialog().getPageText());
+                    + "]\n Page content was: [" + getDialog().getPageText()
+                    + "]");
     }
 
     /**
@@ -1657,6 +1663,7 @@
     public void setWorkingForm(int index) {
         getDialog().setWorkingForm(index);
     }
+
     /**
      * Begin interaction with a specified form. If form interaction methods 
are called without explicitly calling this
      * method first, jWebUnit will attempt to determine itself which form is 
being manipulated.
@@ -2015,12 +2022,53 @@
         }
     }
 
+    /**
+     * Get the source of the HTML page (like in a real browser), or HTTP body 
for a non HTML content.
+     * 
+     * @return The HTML content.
+     */
+    public String getPageSource() {
+        return getDialog().getPageSource();
+    }
+
+    /**
+     * Get the last data sent by the server.
+     * 
+     * @return HTTP server response.
+     */
+    public String getServeurResponse() {
+        return getDialog().getServerResponse();
+    }
+
+    /**
+     * Save the last downloaded page (or file) to the disk.
+     * 
+     * @param f The file name.
+     */
+    public void saveAs(File f) {
+        getDialog().saveAs(f);
+    }
+
+    public void assertDownloadedFileEquals(File expected) {
+        try {
+            File tmp = File.createTempFile("jwebunit", null);
+            tmp.deleteOnExit();
+            saveAs(tmp);
+            Assert.assertTrue("Files are not binary equals.", areFilesEqual(
+                    expected, tmp));
+        } catch (IOException e) {
+            e.printStackTrace();
+            Assert.fail(e.toString());
+        }
+    }
+
     // Debug methods
 
     /**
      * Dump html of current response to System.out - for debugging purposes.
      * 
      * @param stream
+     * @deprecated Use [EMAIL PROTECTED] WebTester#getPageSource()}
      */
     public void dumpHtml() {
         dumpHtml(System.out);
@@ -2030,6 +2078,7 @@
      * Dump html of current response to a specified stream - for debugging 
purposes.
      * 
      * @param stream
+     * @deprecated Use [EMAIL PROTECTED] WebTester#getPageSource()}
      */
     public void dumpHtml(PrintStream stream) {
         stream.println(getDialog().getPageSource());
@@ -2122,18 +2171,18 @@
      * Exemple: <br/>
      * 
      * <pre>
-     *                                     &lt;FORM 
action=&quot;http://my_host/doit&quot; method=&quot;post&quot;&gt;
-     *                                       &lt;P&gt;
-     *                                         &lt;SELECT multiple 
size=&quot;4&quot; name=&quot;component-select&quot;&gt;
-     *                                           &lt;OPTION selected 
value=&quot;Component_1_a&quot;&gt;Component_1&lt;/OPTION&gt;
-     *                                           &lt;OPTION selected 
value=&quot;Component_1_b&quot;&gt;Component_2&lt;/OPTION&gt;
-     *                                           
&lt;OPTION&gt;Component_3&lt;/OPTION&gt;
-     *                                           
&lt;OPTION&gt;Component_4&lt;/OPTION&gt;
-     *                                           
&lt;OPTION&gt;Component_5&lt;/OPTION&gt;
-     *                                         &lt;/SELECT&gt;
-     *                                         &lt;INPUT 
type=&quot;submit&quot; value=&quot;Send&quot;&gt;&lt;INPUT 
type=&quot;reset&quot;&gt;
-     *                                       &lt;/P&gt;
-     *                                     &lt;/FORM&gt;
+     *                                        &lt;FORM 
action=&quot;http://my_host/doit&quot; method=&quot;post&quot;&gt;
+     *                                          &lt;P&gt;
+     *                                            &lt;SELECT multiple 
size=&quot;4&quot; name=&quot;component-select&quot;&gt;
+     *                                              &lt;OPTION selected 
value=&quot;Component_1_a&quot;&gt;Component_1&lt;/OPTION&gt;
+     *                                              &lt;OPTION selected 
value=&quot;Component_1_b&quot;&gt;Component_2&lt;/OPTION&gt;
+     *                                              
&lt;OPTION&gt;Component_3&lt;/OPTION&gt;
+     *                                              
&lt;OPTION&gt;Component_4&lt;/OPTION&gt;
+     *                                              
&lt;OPTION&gt;Component_5&lt;/OPTION&gt;
+     *                                            &lt;/SELECT&gt;
+     *                                            &lt;INPUT 
type=&quot;submit&quot; value=&quot;Send&quot;&gt;&lt;INPUT 
type=&quot;reset&quot;&gt;
+     *                                          &lt;/P&gt;
+     *                                        &lt;/FORM&gt;
      * </pre>
      * 
      * Should return [Component_1, Component_2, Component_3, Component_4, 
Component_5]
@@ -2305,4 +2354,23 @@
         }
     }
 
+    protected boolean areFilesEqual(File f1, File f2) throws IOException {
+        // compare file sizes
+        if (f1.length() != f2.length())
+            return false;
+
+        // read and compare bytes pair-wise
+        InputStream i1 = new FileInputStream(f1);
+        InputStream i2 = new FileInputStream(f2);
+        int b1, b2;
+        do {
+            b1 = i1.read();
+            b2 = i2.read();
+        } while (b1 == b2 && b1 != -1);
+        i1.close();
+        i2.close();
+        // true only if end of file is reached
+        return b1 == -1;
+    }
+
 }

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
   2006-11-23 10:01:43 UTC (rev 625)
+++ 
branches/1.x/jwebunit-htmlunit-plugin/src/main/java/net/sourceforge/jwebunit/htmlunit/HtmlUnitDialog.java
   2006-11-24 14:11:31 UTC (rev 626)
@@ -6,9 +6,14 @@
 
 import org.apache.commons.httpclient.Cookie;
 import org.apache.commons.httpclient.HttpState;
+import org.apache.commons.httpclient.NameValuePair;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
 import java.io.IOException;
 import java.net.ConnectException;
 import java.net.InetAddress;
@@ -48,10 +53,13 @@
 import com.gargoylesoftware.htmlunit.ConfirmHandler;
 import com.gargoylesoftware.htmlunit.DefaultCredentialsProvider;
 import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
+import com.gargoylesoftware.htmlunit.JavaScriptPage;
 import com.gargoylesoftware.htmlunit.Page;
 import com.gargoylesoftware.htmlunit.PromptHandler;
+import com.gargoylesoftware.htmlunit.TextPage;
 import com.gargoylesoftware.htmlunit.UnexpectedPage;
 import com.gargoylesoftware.htmlunit.WebClient;
+import com.gargoylesoftware.htmlunit.WebResponse;
 import com.gargoylesoftware.htmlunit.WebWindow;
 import com.gargoylesoftware.htmlunit.WebWindowEvent;
 import com.gargoylesoftware.htmlunit.WebWindowListener;
@@ -82,6 +90,7 @@
 import com.gargoylesoftware.htmlunit.ElementNotFoundException;
 import com.gargoylesoftware.htmlunit.html.HtmlTableRow.CellIterator;
 import com.gargoylesoftware.htmlunit.html.xpath.HtmlUnitXPath;
+import com.gargoylesoftware.htmlunit.xml.XmlPage;
 
 /**
  * Acts as the wrapper for HtmlUnit access. A dialog is initialized with a 
given URL, and maintains conversational state
@@ -296,7 +305,6 @@
         win = getFrame(frameName);
     }
 
-    
     /**
      * [EMAIL PROTECTED]
      */
@@ -532,7 +540,7 @@
     }
 
     public String getPageSource() {
-        return getCurrentPage().getWebResponse().getContentAsString();
+        return 
wc.getCurrentWindow().getEnclosedPage().getWebResponse().getContentAsString();
     }
 
     public String getPageTitle() {
@@ -540,13 +548,45 @@
     }
 
     public String getPageText() {
-        return ((HtmlPage) getCurrentPage()).asText();
+        Page page = win.getEnclosedPage();
+        if (page instanceof HtmlPage)
+            return ((HtmlPage) page).asText();
+        if (page instanceof TextPage)
+            return ((TextPage) page).getContent();
+        if (page instanceof JavaScriptPage)
+            return ((JavaScriptPage) page).getContent();
+        if (page instanceof XmlPage)
+            return ((XmlPage) page).getContent();
+        if (page instanceof UnexpectedPage)
+            return ((UnexpectedPage) 
page).getWebResponse().getContentAsString();
+        throw new RuntimeException("Unexpected error in getPageText(). This 
method need to be updated.");
     }
 
     public String getServerResponse() {
-        return wc.getCurrentWindow().getEnclosedPage().getWebResponse()
-                .getContentAsString();
+        StringBuffer result = new StringBuffer();
+        WebResponse wr = 
wc.getCurrentWindow().getEnclosedPage().getWebResponse();
+        result.append(wr.getStatusCode()).append(" 
").append(wr.getStatusMessage()).append("\n");
+        result.append("Location: ").append(wr.getUrl()).append("\n");
+        List headers = wr.getResponseHeaders();
+        for (Iterator i=headers.iterator(); i.hasNext();) {
+            NameValuePair h = (NameValuePair)i.next();
+            result.append(h.getName()).append(": 
").append(h.getValue()).append("\n");
+        }
+        result.append("\n");
+        result.append(wr.getContentAsString());
+        return result.toString();
     }
+    
+    public void saveAs(File f) {
+        try {
+            f.createNewFile();
+            FileOutputStream out = new FileOutputStream(f);
+            
out.write(wc.getCurrentWindow().getEnclosedPage().getWebResponse().getResponseBody());
+            out.close();
+        } catch (IOException e) {
+            throw new RuntimeException("Error when writing to file",e);
+        }
+    }
 
     private void initWebClient() {
         wc = new WebClient(new BrowserVersion(BrowserVersion.INTERNET_EXPLORER,
@@ -871,9 +911,7 @@
         Page page = win.getEnclosedPage();
         if (page instanceof HtmlPage)
             return (HtmlPage) page;
-        if (page instanceof UnexpectedPage)
-            throw new RuntimeException("Unexpected content");
-        return (HtmlPage) page;
+        throw new RuntimeException("Non HTML content");
     }
 
     private void setWorkingForm(HtmlForm newForm) {
@@ -1077,8 +1115,7 @@
     public boolean hasResetButton() {
         List l = null;
         try {
-            final HtmlUnitXPath xp = new HtmlUnitXPath(
-                    "//[EMAIL PROTECTED]'reset']");
+            final HtmlUnitXPath xp = new HtmlUnitXPath("//[EMAIL 
PROTECTED]'reset']");
             l = xp.selectNodes(getForm());
         } catch (JaxenException e) {
             throw new RuntimeException(e);
@@ -1592,7 +1629,7 @@
 
     public String getElementAttributByXPath(String xpath, String attribut) {
         HtmlElement e = getElementByXPath(xpath);
-        if (e==null)
+        if (e == null)
             return null;
         return e.getAttributeValue(attribut);
     }

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
     2006-11-23 10:01:43 UTC (rev 625)
+++ 
branches/1.x/jwebunit-htmlunit-plugin/src/test/java/net/sourceforge/jwebunit/htmlunit/JWebUnitTest.java
     2006-11-24 14:11:31 UTC (rev 626)
@@ -48,8 +48,9 @@
         suite.addTestSuite(XPathTest.class);
         suite.addTestSuite(CharsetTest.class);
         suite.addTestSuite(ButtonAssertionsTest.class);
+        suite.addTestSuite(NonHtmlContentTest.class);
         //$JUnit-END$
         return new JettySetup(suite);
     }
 
-}
\ No newline at end of file
+}

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      
2006-11-23 10:01:43 UTC (rev 625)
+++ branches/1.x/jwebunit-webtestcase-generator/src/main/javacc/Java1.5.jj      
2006-11-24 14:11:31 UTC (rev 626)
@@ -487,7 +487,8 @@
   {sb.append(getToken(1).specialToken.image).append("\n");}
   [ PackageDeclaration(sb) ]
 
-  {sb.append("import java.io.PrintStream;\n\n");
+  {sb.append("import java.io.File;\n");
+  sb.append("import java.io.PrintStream;\n\n");
   sb.append("import net.sourceforge.jwebunit.api.IJWebUnitDialog;\n");
   sb.append("import net.sourceforge.jwebunit.html.Table;\n");
   sb.append("import net.sourceforge.jwebunit.util.TestContext;\n\n");

Modified: branches/1.x/src/changes/changes.xml
===================================================================
--- branches/1.x/src/changes/changes.xml        2006-11-23 10:01:43 UTC (rev 
625)
+++ branches/1.x/src/changes/changes.xml        2006-11-24 14:11:31 UTC (rev 
626)
@@ -7,6 +7,15 @@
         </author>
     </properties>
     <body>
+        <release version="1.4-RC2" date="UNKNOW">
+            <action type="add" dev="Julien Henry">
+                Add saveAs(File f) and assertDownloadedFileEquals(File 
expected) methods
+                to check downloaded response as a binary File.
+            </action>
+            <action type="add" dev="Julien Henry">
+                Add getServeurResponse() method to debug HTTP response.
+            </action>
+        </release>
         <release version="1.4-RC1" date="november 20, 2006">
             <action type="fix" dev="Julien Henry">
                 submit([...]) methods now detect image input elements.


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

Reply via email to