package net.hillsdon.svnwiki.webtests;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.UnexpectedPage;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;


public class TestAttachments extends WebTestSupport {

  public void testGetAttachmentThatDoesntExistGives404() throws Exception {
    try {
      getWebPage(getUrl("FrontPage/attachments/DoesntExist.txt"));
      fail();
    }
    catch (FailingHttpStatusCodeException ex) {
      assertEquals(404, ex.getStatusCode());
    }
  }
  
  public void testUploadAndDownloadAttachment() throws Exception {
    String name = uniqueWikiPageName("AttachmentsTest");
    HtmlPage page = editWikiPage(name, "", "", true);
    HtmlAnchor attachmentsLink = page.getAnchorByHref(name + "/attachments/");
    assertEquals("Attachments", attachmentsLink.asText());
    HtmlPage attachments = (HtmlPage) attachmentsLink.click();
    HtmlForm form = attachments.getFormByName("attachmentUpload");
    form.getInputByName("file").setValueAttribute("build.xml");
    attachments = (HtmlPage) form.getInputByValue("Upload").click();
    UnexpectedPage attachment = (UnexpectedPage) attachments.getAnchorByHref("build.xml").click();
    BufferedReader in = new BufferedReader(new InputStreamReader(attachment.getInputStream()));
    try {
      assertTrue(in.readLine().startsWith("<project name="));
    }
    finally {
      in.close();
    }
  }
  
}

@@ -64,16 +64,44 @@
 Reader;%0A
+import java.io.IOException;%0A
 import j
@@ -1330,93 +1330,400 @@
     
-UnexpectedPage attachment = (UnexpectedPage) attachments.getAnchorByHref(%22build.xml%22)
+checkAttachmentIsAtEndOfLink(attachments.getAnchorByHref(%22build.xml%22));%0A    %0A    page = editWikiPage(name, %22%7Battached:build.xml%7D%22, %22Linked to attachment%22, false);%0A    checkAttachmentIsAtEndOfLink(page.getAnchorByHref(name + %22/attachments/build.xml%22));%0A  %7D%0A%0A  private void checkAttachmentIsAtEndOfLink(HtmlAnchor link) throws IOException %7B%0A    UnexpectedPage attachment = (UnexpectedPage) link
 .cli

Create an {attached:foo} link to our new attachment and check we can use that to download it too.