@Test
  public void testExceptionPhaseListener() throws Exception {
    WebClient client = new WebClient();
    client.setThrowExceptionOnFailingStatusCode(false);

    // First, try a transient conversation

    // Access a page that throws an exception
    client.getPage(getPath("/thunderstorm.jsf"));

    // Then access another page that doesn't and check the contexts are ok
    HtmlPage cloud = client.getPage(getPath("/cloud.jsf"));
    String cloudName = getFirstMatchingElement(cloud, HtmlSpan.class, "cloudName").getTextContent();
    assertEquals(Cloud.NAME, cloudName);

    // Now start a conversation and access the page that throws an exception again
    HtmlPage thunderstorm =
        getFirstMatchingElement(cloud, HtmlSubmitInput.class, "beginConversation").click();
    // This page will error

    String cid = getCid(thunderstorm);

    cloud = client.getPage(getPath("/cloud.jsf", cid));

    // And navigate to another page, checking the conversation exists by verifying that state is
    // maintained
    cloudName = getFirstMatchingElement(cloud, HtmlSpan.class, "cloudName").getTextContent();
    assertEquals("gavin", cloudName);
  }
  /**
   * The request context is destroyed at the end of the servlet request, after the service() method
   * and all doFilter() methods, and all requestDestroyed() notifications return.
   */
  @Test
  @SpecAssertions({
    @SpecAssertion(section = REQUEST_CONTEXT_EE, id = "ba"),
    @SpecAssertion(section = REQUEST_CONTEXT_EE, id = "bb"),
    @SpecAssertion(section = REQUEST_CONTEXT_EE, id = "bc")
  })
  public void testRequestScopeIsDestroyedAfterServletRequest() throws Exception {

    WebClient webClient = new WebClient();
    webClient.setThrowExceptionOnFailingStatusCode(true);

    // First request - response content contains SimpleRequestBean id
    TextPage firstRequestResult = webClient.getPage(contextPath + "introspect");
    assertNotNull(firstRequestResult.getContent());
    // Make a second request and make sure the same context is not there (compare SimpleRequestBean
    // ids)
    TextPage secondRequestResult = webClient.getPage(contextPath + "introspect");
    assertNotNull(secondRequestResult.getContent());
    assertNotEquals(
        secondRequestResult.getContent().trim(), firstRequestResult.getContent().trim());

    // Make sure request context is destroyed after service(), doFilter(), requestDestroyed()
    webClient.getPage(contextPath + "introspect?mode=collect");
    ActionSequence correctSequence =
        new ActionSequence()
            .add(IntrospectServlet.class.getName())
            .add(IntrospectFilter.class.getName())
            .add(TestServletRequestListener.class.getName())
            .add(ContextDestructionObserver.class.getName());
    TextPage destroyRequestResult = webClient.getPage(contextPath + "introspect?mode=verify");
    assertNotNull(destroyRequestResult.getContent());
    assertEquals(destroyRequestResult.getContent(), correctSequence.toString());
  }
 private void assertComponentInstancesNotEqual(String mode) throws Exception {
   WebClient webClient = new WebClient();
   webClient.setThrowExceptionOnFailingStatusCode(true);
   TextPage page = webClient.getPage(contextPath + "test?mode=" + mode);
   String[] ids = page.getContent().split(":");
   System.out.println(Arrays.toString(ids));
   assertEquals(ids.length, 2);
   assertNotEquals(ids[0], ids[1]);
 }
Example #4
0
 @Test(groups = {"contexts"})
 public void testConversationPropagationToNonExistentConversationLeadsException()
     throws Exception {
   WebClient client = new WebClient();
   client.setThrowExceptionOnFailingStatusCode(false);
   Page page = client.getPage(getPath("/index.jsp"));
   assert page.getWebResponse().getStatusCode() == 200;
   assert page.getWebResponse().getRequestUrl().toString().contains("home.jsf");
 }
 /**
  * The request scope is active during the doFilter() method of any Filter in the web application.
  */
 @Test
 @SpecAssertions({
   @SpecAssertion(section = REQUEST_CONTEXT_EE, id = "ab"),
   @SpecAssertion(section = REQUEST_CONTEXT_EE, id = "ac")
 })
 public void testRequestScopeActiveDuringServletFilter() throws Exception {
   WebClient webClient = new WebClient();
   webClient.setThrowExceptionOnFailingStatusCode(true);
   webClient.getPage(contextPath + "SimplePage.html");
 }
 @Before
 public void beforeTest() {
   webClient.setThrowExceptionOnFailingStatusCode(true);
 }
Example #7
0
  public static void main(String[] args) {
    try {
      System.out.println("Starting application...");
      java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);

      wc = new WebClient(BrowserVersion.FIREFOX_10);
      // wc = new WebClient(BrowserVersion.FIREFOX_10, "50.117.67.126", 3131);
      final DefaultCredentialsProvider scp = new DefaultCredentialsProvider();
      scp.addCredentials("754d539bc6ade1ad", "454585f105747a76");
      // wc.setCredentialsProvider(scp);
      wc.setJavaScriptEnabled(false);
      wc.setThrowExceptionOnScriptError(false);
      wc.setThrowExceptionOnFailingStatusCode(false);

      // Get the first page
      HtmlPage page = wc.getPage("http://torn.com/index.php");
      if (page.asText().contains("You are no longer logged in."))
        page = login(page, "tempaccount", "temp123");
      else System.out.println("Already logged in.");

      System.out.println("Index.php loaded.");
      int loop = 0;
      int errors = 0;
      while (true) {

        System.out.println("Beginning loop " + loop + "...");
        loop++;
        try {
          if (inHospital(page) || inJail(page)) {
            System.out.println("Sleeping 5 minutes...");
            Thread.sleep(1000 * 5 * 60);
          } else {
            System.out.println("Loading page...");
            wc.setJavaScriptEnabled(true);
            page = wc.getPage("http://torn.com/gym.php");
            // page = wc.getPage("http://torn.com/crimes.php");
            while (onCaptcha(page)) {
              wc.setJavaScriptEnabled(true);
              System.out.println("Captcha encountered.");
              page = solveCaptcha(page);
              wc.setJavaScriptEnabled(false);
            }
            // System.out.println(page.getWebResponse().getContentAsString());
            trainStrength(page, 20);
            // doCrime(page, 5);
            System.out.println("Sleeping 30 minutes...");
            Thread.sleep(1000 * 15);
          }
          page = loadIndex();
        } catch (Exception e) {
          System.out.println(e.toString());
          errors++;
          page = loadIndex();
          if (errors > 3) System.exit(1);
        }
      }

    } catch (Exception e) {
      wc.closeAllWindows();
      e.printStackTrace();
    }
  }
Example #8
0
  public static void main(String[] args) throws Exception {

    Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);

    String app = System.getProperty("application.url", "http://*****:*****@tests.list").openStream(), "utf-8"));
      String marker = in.readLine();
      if (!marker.equals("---")) {
        throw new RuntimeException("Oops");
      }
      root = new File(in.readLine());
      selenium = in.readLine();
      tests = new ArrayList<String>();
      String line;
      while ((line = in.readLine()) != null) {
        tests.add(line);
      }
      in.close();
    } catch (Exception e) {
      System.out.println("~ The application does not start. There are errors: " + e);
      System.exit(-1);
    }

    // Let's tweak WebClient
    WebClient firephoque = new WebClient(BrowserVersion.INTERNET_EXPLORER_8);
    firephoque.setPageCreator(
        new DefaultPageCreator() {

          @Override
          public Page createPage(WebResponse wr, WebWindow ww) throws IOException {
            Page page = createHtmlPage(wr, ww);
            return page;
          }
        });
    firephoque.setThrowExceptionOnFailingStatusCode(false);
    firephoque.setAlertHandler(
        new AlertHandler() {
          public void handleAlert(Page page, String string) {
            try {
              Window window = (Window) page.getEnclosingWindow().getScriptObject();
              window.custom_eval(
                  "parent.selenium.browserbot.recordedAlerts.push('"
                      + string.replace("'", "\\'")
                      + "');");
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        });
    firephoque.setConfirmHandler(
        new ConfirmHandler() {
          public boolean handleConfirm(Page page, String string) {
            try {
              Window window = (Window) page.getEnclosingWindow().getScriptObject();
              Object result =
                  window.custom_eval(
                      "parent.selenium.browserbot.recordedConfirmations.push('"
                          + string.replace("'", "\\'")
                          + "');"
                          + "var result = parent.selenium.browserbot.nextConfirmResult;"
                          + "parent.selenium.browserbot.nextConfirmResult = true;"
                          + "result");
              return (Boolean) result;
            } catch (Exception e) {
              e.printStackTrace();
              return false;
            }
          }
        });
    firephoque.setPromptHandler(
        new PromptHandler() {
          public String handlePrompt(Page page, String string) {
            try {
              Window window = (Window) page.getEnclosingWindow().getScriptObject();
              Object result =
                  window.custom_eval(
                      "parent.selenium.browserbot.recordedPrompts.push('"
                          + string.replace("'", "\\'")
                          + "');"
                          + "var result = !parent.selenium.browserbot.nextConfirmResult ? null : parent.selenium.browserbot.nextPromptResult;"
                          + "parent.selenium.browserbot.nextConfirmResult = true;"
                          + "parent.selenium.browserbot.nextPromptResult = '';"
                          + "result");
              return (String) result;
            } catch (Exception e) {
              e.printStackTrace();
              return "";
            }
          }
        });
    firephoque.setThrowExceptionOnScriptError(false);

    // Go!
    int maxLength = 0;
    for (String test : tests) {
      String testName =
          test.replace(".class", "").replace(".test.html", "").replace(".", "/").replace("$", "/");
      if (testName.length() > maxLength) {
        maxLength = testName.length();
      }
    }
    System.out.println("~ " + tests.size() + " test" + (tests.size() != 1 ? "s" : "") + " to run:");
    System.out.println("~");
    firephoque.openWindow(new URL(app + "/@tests/init"), "headless");
    boolean ok = true;
    for (String test : tests) {
      long start = System.currentTimeMillis();
      String testName =
          test.replace(".class", "").replace(".test.html", "").replace(".", "/").replace("$", "/");
      System.out.print("~ " + testName + "... ");
      for (int i = 0; i < maxLength - testName.length(); i++) {
        System.out.print(" ");
      }
      System.out.print("    ");
      URL url;
      if (test.endsWith(".class")) {
        url = new URL(app + "/@tests/" + test);
      } else {
        url =
            new URL(
                app
                    + ""
                    + selenium
                    + "?baseUrl="
                    + app
                    + "&test=/@tests/"
                    + test
                    + ".suite&auto=true&resultsUrl=/@tests/"
                    + test);
      }
      firephoque.openWindow(url, "headless");
      firephoque.waitForBackgroundJavaScript(5 * 60 * 1000);
      int retry = 0;
      while (retry < 5) {
        if (new File(root, test.replace("/", ".") + ".passed.html").exists()) {
          System.out.print("PASSED     ");
          break;
        } else if (new File(root, test.replace("/", ".") + ".failed.html").exists()) {
          System.out.print("FAILED  !  ");
          ok = false;
          break;
        } else {
          if (retry++ == 4) {
            System.out.print("ERROR   ?  ");
            ok = false;
            break;
          } else {
            Thread.sleep(1000);
          }
        }
      }

      //
      int duration = (int) (System.currentTimeMillis() - start);
      int seconds = (duration / 1000) % 60;
      int minutes = (duration / (1000 * 60)) % 60;

      if (minutes > 0) {
        System.out.println(minutes + " min " + seconds + "s");
      } else {
        System.out.println(seconds + "s");
      }
    }
    firephoque.openWindow(
        new URL(app + "/@tests/end?result=" + (ok ? "passed" : "failed")), "headless");
  }