org.openqa.selenium.logging.LogType Java Examples

The following examples show how to use org.openqa.selenium.logging.LogType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ConsoleTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@BuggyWebDriver
public void assertObject() throws Exception {
    final String html
        = "<html>\n"
        + "<body>\n"
        + "<script>\n"
        + "  number = 1;\n"
        + "  console.assert(number % 2 === 0, {number: number, errorMsg: 'the # is not even'});\n"
        + "</script>\n"
        + "</body></html>";

    final WebDriver driver = loadPage2(html);

    final Logs logs = driver.manage().logs();
    final LogEntries logEntries = logs.get(LogType.BROWSER);
    final List<LogEntry> logEntryList = logEntries.getAll();

    assertEquals(1, logEntryList.size());

    final LogEntry logEntry = logEntryList.get(0);
    assertTrue(logEntry.getMessage(), logEntry.getMessage()
            .contains("Assertion failed: ({number: 1.0, errorMsg: \"the # is not even\"})"));
}
 
Example #2
Source File: JsonOutputTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void convertLoggingPreferencesToJson() {
  LoggingPreferences prefs = new LoggingPreferences();
  prefs.enable(LogType.BROWSER, Level.WARNING);
  prefs.enable(LogType.CLIENT, Level.FINE);
  prefs.enable(LogType.DRIVER, Level.ALL);
  prefs.enable(LogType.SERVER, Level.OFF);

  String json = convert(prefs);

  JsonObject converted = new JsonParser().parse(json).getAsJsonObject();

  assertThat(converted.get(BROWSER).getAsString()).isEqualTo("WARNING");
  assertThat(converted.get(CLIENT).getAsString()).isEqualTo("DEBUG");
  assertThat(converted.get(DRIVER).getAsString()).isEqualTo("ALL");
  assertThat(converted.get(SERVER).getAsString()).isEqualTo("OFF");
}
 
Example #3
Source File: RemoteLogsTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void canGetProfilerLogs() {
  List<LogEntry> entries = new ArrayList<>();
  entries.add(new LogEntry(Level.INFO, 0, "hello"));
  when(localLogs.get(LogType.PROFILER)).thenReturn(new LogEntries(entries));

  when(
      executeMethod.execute(
          DriverCommand.GET_LOG, ImmutableMap.of(RemoteLogs.TYPE_KEY, LogType.PROFILER)))
      .thenReturn(singletonList(
          ImmutableMap.of("level", Level.INFO.getName(), "timestamp", 1L, "message", "world")));

  LogEntries logEntries = remoteLogs.get(LogType.PROFILER);
  List<LogEntry> allLogEntries = logEntries.getAll();
  assertThat(allLogEntries).hasSize(2);
  assertThat(allLogEntries.get(0).getMessage()).isEqualTo("hello");
  assertThat(allLogEntries.get(1).getMessage()).isEqualTo("world");
}
 
Example #4
Source File: DragAndDropTest.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
public void dndWithCopy() throws Throwable {
    DesiredCapabilities caps = new DesiredCapabilities();
    // caps.setCapability("nativeEvents", true);
    driver = new JavaDriver(caps, caps);
    WebElement list = driver.findElement(By.cssSelector("list"));
    assertEquals(
            "[[\"List Item 0\",\"List Item 1\",\"List Item 2\",\"List Item 3\",\"List Item 4\",\"List Item 5\",\"List Item 6\",\"List Item 7\",\"List Item 8\",\"List Item 9\"]]",
            list.getAttribute("content"));
    WebElement listitem1 = driver.findElement(By.cssSelector("list::nth-item(1)"));
    WebElement listitem5 = driver.findElement(By.cssSelector("list::nth-item(5)"));
    listitem1.click();
    driver.clearlogs(LogType.DRIVER);
    Keys copyKey = Keys.ALT;
    if (Platform.getCurrent().is(Platform.WINDOWS)) {
        copyKey = Keys.CONTROL;
    }
    new Actions(driver).keyDown(copyKey).dragAndDrop(listitem1, listitem5).keyUp(copyKey).perform();
    waitTillDropCompletes(
            "[[\"List Item 0\",\"List Item 1\",\"List Item 2\",\"List Item 3\",\"List Item 0(1)\",\"List Item 5\",\"List Item 6\",\"List Item 7\",\"List Item 8\",\"List Item 9\"]]",
            list);
    assertEquals(
            "[[\"List Item 0\",\"List Item 1\",\"List Item 2\",\"List Item 3\",\"List Item 0(1)\",\"List Item 5\",\"List Item 6\",\"List Item 7\",\"List Item 8\",\"List Item 9\"]]",
            list.getAttribute("content"));
}
 
Example #5
Source File: DragAndDropTest.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
public void dndWithMove() throws Throwable {
    DesiredCapabilities caps = new DesiredCapabilities();
    // caps.setCapability("nativeEvents", true);
    driver = new JavaDriver(caps, caps);
    WebElement list = driver.findElement(By.cssSelector("list"));
    assertEquals(
            "[[\"List Item 0\",\"List Item 1\",\"List Item 2\",\"List Item 3\",\"List Item 4\",\"List Item 5\",\"List Item 6\",\"List Item 7\",\"List Item 8\",\"List Item 9\"]]",
            list.getAttribute("content"));
    WebElement listitem1 = driver.findElement(By.cssSelector("list::nth-item(1)"));
    WebElement listitem5 = driver.findElement(By.cssSelector("list::nth-item(5)"));
    driver.clearlogs(LogType.DRIVER);
    System.err.println("About to sleep");
    new Actions(driver).dragAndDrop(listitem1, listitem5).perform();
    waitTillDropCompletes(
            "[[\"List Item 1\",\"List Item 2\",\"List Item 3\",\"List Item 0\",\"List Item 5\",\"List Item 6\",\"List Item 7\",\"List Item 8\",\"List Item 9\"]]",
            list);
    assertEquals(
            "[[\"List Item 1\",\"List Item 2\",\"List Item 3\",\"List Item 0\",\"List Item 5\",\"List Item 6\",\"List Item 7\",\"List Item 8\",\"List Item 9\"]]",
            list.getAttribute("content"));
}
 
Example #6
Source File: RemoteLogsTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void canGetLocalProfilerLogsIfNoRemoteProfilerLogSupport() {
  List<LogEntry> entries = new ArrayList<>();
  entries.add(new LogEntry(Level.INFO, 0, "hello"));
  when(localLogs.get(LogType.PROFILER)).thenReturn(new LogEntries(entries));

  when(
      executeMethod.execute(
          DriverCommand.GET_LOG, ImmutableMap.of(RemoteLogs.TYPE_KEY, LogType.PROFILER)))
      .thenThrow(
          new WebDriverException("IGNORE THIS LOG MESSAGE AND STACKTRACE; IT IS EXPECTED."));

  LogEntries logEntries = remoteLogs.get(LogType.PROFILER);
  List<LogEntry> allLogEntries = logEntries.getAll();
  assertThat(allLogEntries).hasSize(1);
  assertThat(allLogEntries.get(0).getMessage()).isEqualTo("hello");
}
 
Example #7
Source File: RemoteLogs.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
public LogEntries get(String logType) {
  if (LogType.PROFILER.equals(logType)) {
    LogEntries remoteEntries = new LogEntries(new ArrayList<>());
    try {
      remoteEntries = getRemoteEntries(logType);
    } catch (WebDriverException e) {
      // An exception may be thrown if the WebDriver server does not recognize profiler logs.
      // In this case, the user should be able to see the local profiler logs.
      logger.log(Level.WARNING,
          "Remote profiler logs are not available and have been omitted.", e);
    }

    return LogCombiner.combine(remoteEntries, getLocalEntries(logType));
  }
  if (LogType.CLIENT.equals(logType)) {
    return getLocalEntries(logType);
  }
  return getRemoteEntries(logType);
}
 
Example #8
Source File: JsUtility.java    From Selenium-Foundation with Apache License 2.0 6 votes vote down vote up
/**
 * Propagate the specified web driver exception, extracting encoded JavaScript exception if present
 * 
 * @param driver A handle to the currently running Selenium test window.
 * @param exception web driver exception to propagate
 * @return nothing (this method always throws the specified exception)
 * @since 17.4.0 
 */
public static RuntimeException propagate(final WebDriver driver, final WebDriverException exception) {
    Throwable thrown = exception;
    // if exception is a WebDriverException (not a sub-class)
    if (JS_EXCEPTIONS.contains(exception.getClass().getName())) {
        // extract serialized exception object from message
        thrown = extractException(exception, exception.getMessage());
        
        // if driver spec'd and no serialized exception found
        if ((driver != null) && (thrown.equals(exception))) {
            // get browser log entries
            LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);

            // for each log entry
            for (LogEntry logEntry : logEntries.filter(Level.WARNING)) {
                // extract serialized exception object from message
                thrown = extractException(exception, logEntry.getMessage());
                // done if serialized exception found
                if (!thrown.equals(exception)) break;
            }
        }
    }
    // throw resolved exception as unchecked
    throw UncheckedThrow.throwUnchecked(thrown);
}
 
Example #9
Source File: ChromeDriverClient.java    From AndroidRobot with Apache License 2.0 6 votes vote down vote up
public void createDriver(String pkg_name, String sn) {
    	if(this.driver == null) {
	        ChromeOptions chromeOptions = new ChromeOptions();
	        chromeOptions.setExperimentalOption("androidPackage", pkg_name);
	//        chromeOptions.setExperimentalOption("androidActivity", "com.eg.android.AlipayGphone.AlipayLogin");
	//        chromeOptions.setExperimentalOption("debuggerAddress", "127.0.0.1:9222");
	        chromeOptions.setExperimentalOption("androidUseRunningApp", true);
	        chromeOptions.setExperimentalOption("androidDeviceSerial", sn);
	//        Map<String, Object> chromeOptions = new HashMap<String, Object>();
	//        chromeOptions.put("androidPackage", "com.eg.android.AlipayGphoneRC");
	//        chromeOptions.put("androidActivity", "com.eg.android.AlipayGphone.AlipayLogin");
	        DesiredCapabilities capabilities = DesiredCapabilities.chrome();
	        LoggingPreferences logPrefs = new LoggingPreferences();
	        logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
	        capabilities.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
	        capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
//	        capabilities.setCapability(CapabilityType., value);
	        if(ChromeService.getService() != null)
	        	driver = new RobotRemoteWebDriver(ChromeService.getService().getUrl(), capabilities);
    	}
    }
 
Example #10
Source File: ConsoleTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@BuggyWebDriver
public void assertParams() throws Exception {
    final String html
        = "<html>\n"
        + "<body>\n"
        + "<script>\n"
        + "  console.assert(false, 'the word is %s', 'foo');\n"
        + "</script>\n"
        + "</body></html>";

    final WebDriver driver = loadPage2(html);

    final Logs logs = driver.manage().logs();
    final LogEntries logEntries = logs.get(LogType.BROWSER);
    final List<LogEntry> logEntryList = logEntries.getAll();

    assertEquals(1, logEntryList.size());

    final LogEntry logEntry = logEntryList.get(0);
    assertTrue(logEntry.getMessage(), logEntry.getMessage()
            .contains("Assertion failed: the word is foo"));
}
 
Example #11
Source File: ConsoleTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@BuggyWebDriver
public void assertObjects() throws Exception {
    final String html
        = "<html>\n"
        + "<body>\n"
        + "<script>\n"
        + "  number = 1;\n"
        + "  console.assert(number % 2 === 0, {number: number}, {errorMsg: 'the # is not even'});\n"
        + "</script>\n"
        + "</body></html>";

    final WebDriver driver = loadPage2(html);

    final Logs logs = driver.manage().logs();
    final LogEntries logEntries = logs.get(LogType.BROWSER);
    final List<LogEntry> logEntryList = logEntries.getAll();

    assertEquals(1, logEntryList.size());

    final LogEntry logEntry = logEntryList.get(0);
    assertTrue(logEntry.getMessage(), logEntry.getMessage()
            .contains("Assertion failed: ({number: 1.0}) ({errorMsg: \"the # is not even\"})"));
}
 
Example #12
Source File: ConsoleTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@BuggyWebDriver
public void assertString() throws Exception {
    final String html
        = "<html>\n"
        + "<body>\n"
        + "<script>\n"
        + "  number = 1;\n"
        + "  console.assert(number % 2 === 0, 'the # is not even');\n"
        + "</script>\n"
        + "</body></html>";

    final WebDriver driver = loadPage2(html);

    final Logs logs = driver.manage().logs();
    final LogEntries logEntries = logs.get(LogType.BROWSER);
    final List<LogEntry> logEntryList = logEntries.getAll();

    assertEquals(1, logEntryList.size());

    final LogEntry logEntry = logEntryList.get(0);
    assertTrue(logEntry.getMessage(), logEntry.getMessage().contains("Assertion failed: the # is not even"));
}
 
Example #13
Source File: ConsoleTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@BuggyWebDriver
public void assertOnly() throws Exception {
    final String html
        = "<html>\n"
        + "<body>\n"
        + "<script>\n"
        + "  number = 1;\n"
        + "  console.assert(number % 2 === 0);\n"
        + "</script>\n"
        + "</body></html>";

    final WebDriver driver = loadPage2(html);

    final Logs logs = driver.manage().logs();
    final LogEntries logEntries = logs.get(LogType.BROWSER);
    final List<LogEntry> logEntryList = logEntries.getAll();

    assertEquals(1, logEntryList.size());

    final LogEntry logEntry = logEntryList.get(0);
    assertTrue(logEntry.getMessage(), logEntry.getMessage().contains("Assertion failed"));
}
 
Example #14
Source File: RemoteLogsTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void canGetAvailableLogTypes() {
  List<String> remoteAvailableLogTypes = new ArrayList<>();
  remoteAvailableLogTypes.add(LogType.PROFILER);
  remoteAvailableLogTypes.add(LogType.SERVER);

  when(executeMethod.execute(DriverCommand.GET_AVAILABLE_LOG_TYPES, null))
      .thenReturn(remoteAvailableLogTypes);

  Set<String> localAvailableLogTypes = new HashSet<>();
  localAvailableLogTypes.add(LogType.PROFILER);
  localAvailableLogTypes.add(LogType.CLIENT);

  when(localLogs.getAvailableLogTypes()).thenReturn(localAvailableLogTypes);

  Set<String> expected = new HashSet<>();
  expected.add(LogType.CLIENT);
  expected.add(LogType.PROFILER);
  expected.add(LogType.SERVER);

  Set<String> availableLogTypes = remoteLogs.getAvailableLogTypes();

  assertThat(availableLogTypes).isEqualTo(expected);
}
 
Example #15
Source File: Edition038_Android_Web_Console.java    From appiumpro with Apache License 2.0 6 votes vote down vote up
@Test
public void testLogging_Hybrid() throws MalformedURLException {
    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setCapability("platformName", "Android");
    capabilities.setCapability("automationName", "UiAutomator2");
    capabilities.setCapability("deviceName", "Android Emulator");
    capabilities.setCapability("app", APP_ANDROID);
    LoggingPreferences logPrefs = new LoggingPreferences();
    logPrefs.enable(LogType.BROWSER, Level.ALL);
    capabilities.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);

    driver = new AndroidDriver<>(new URL("http://localhost:4723/wd/hub"), capabilities);
    WebDriverWait wait = new WebDriverWait(driver, 10);

    // get to webview screen and enter webview mode
    wait.until(ExpectedConditions.presenceOfElementLocated(hybridScreen)).click();
    wait.until(ExpectedConditions.presenceOfElementLocated(urlInput));
    driver.context(getWebContext(driver));

    // now we can run the same routine as for the browser
    loggingRoutine(driver);
}
 
Example #16
Source File: BROWSERSTACKCloudActionProvider.java    From xframium-java with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String getLog( DeviceWebDriver webDriver )
{
    try
       {
           LogEntries logEntries = webDriver.manage().logs().get( LogType.BROWSER );
           if ( logEntries != null )
           {
               StringBuilder logBuilder = new StringBuilder();
               for ( LogEntry logEntry : logEntries )
                   logBuilder.append( dateFormat.format( new Date( logEntry.getTimestamp() ) ) ).append( ": " ).append( logEntry.getMessage() ).append( "\r\n" );

               logBuilder.toString();
           }
           return null;
       }
       catch ( Exception e )
       {
           log.info( "Could not generate device logs" );
           return null;
       }
    
}
 
Example #17
Source File: SELENIUMCloudActionProvider.java    From xframium-java with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String getLog( DeviceWebDriver webDriver )
{
    try
       {
           LogEntries logEntries = webDriver.manage().logs().get( LogType.BROWSER );
           if ( logEntries != null )
           {
               StringBuilder logBuilder = new StringBuilder();
               for ( LogEntry logEntry : logEntries )
                   logBuilder.append( dateFormat.format( new Date( logEntry.getTimestamp() ) ) ).append( ": " ).append( logEntry.getMessage() ).append( "\r\n" );

               return logBuilder.toString();
           }
           return null;
       }
       catch ( Exception e )
       {
           log.info( "Could not generate device logs" );
           return null;
       }
    
}
 
Example #18
Source File: BrowserLogCleanningListenerTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@TestFactory
Stream<DynamicTest> testCleanBeforeNavigate()
{
    WebDriver driver = mock(WebDriver.class, withSettings().extraInterfaces(HasCapabilities.class));
    Consumer<Runnable> test = methodUnderTest ->
    {
        Options options = mock(Options.class);
        when(driver.manage()).thenReturn(options);
        Logs logs = mock(Logs.class);
        when(options.logs()).thenReturn(logs);
        when(logs.get(LogType.BROWSER)).thenReturn(mock(LogEntries.class));
        methodUnderTest.run();
    };
    return Stream.of(
            dynamicTest("beforeNavigateBack", () -> test.accept(() -> listener.beforeNavigateBack(driver))),
            dynamicTest("beforeNavigateForward", () -> test.accept(() -> listener.beforeNavigateForward(driver))),
            dynamicTest("beforeNavigateRefresh", () -> test.accept(() -> listener.beforeNavigateRefresh(driver))),
            dynamicTest("beforeNavigateTo", () -> test.accept(() -> listener.beforeNavigateTo("url", driver))));
}
 
Example #19
Source File: GetLogTypes.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
public HttpResponse execute(HttpRequest req) throws UncheckedIOException {
  // Try going upstream first. It's okay if this fails.
  HttpRequest upReq = new HttpRequest(GET, String.format("/session/%s/log/types", session.getId()));
  HttpResponse upRes = session.execute(upReq);

  ImmutableSet.Builder<String> types = ImmutableSet.builder();
  types.add(LogType.SERVER);

  if (upRes.getStatus() == HTTP_OK) {
    Map<String, Object> upstream = json.toType(string(upRes), Json.MAP_TYPE);
    Object raw = upstream.get("value");
    if (raw instanceof Collection) {
      ((Collection<?>) raw).stream().map(String::valueOf).forEach(types::add);
    }
  }

  Response response = new Response(session.getId());
  response.setValue(types.build());
  response.setStatus(ErrorCodes.SUCCESS);

  HttpResponse resp = new HttpResponse();
  session.getDownstreamDialect().getResponseCodec().encode(() -> resp, response);
  return resp;
}
 
Example #20
Source File: SAUCELABSCloudActionProvider.java    From xframium-java with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String getLog( DeviceWebDriver webDriver )
{
    try
    {
        LogEntries logEntries = webDriver.manage().logs().get( LogType.BROWSER );
        if ( logEntries != null )
        {
            StringBuilder logBuilder = new StringBuilder();
            for ( LogEntry logEntry : logEntries )
                logBuilder.append( dateFormat.format( new Date( logEntry.getTimestamp() ) ) ).append( ": " ).append( logEntry.getMessage() ).append( "\r\n" );

            logBuilder.toString();
        }
        return null;
    }
    catch ( Exception e )
    {
        log.info( "Could not generate device logs" );
        return null;
    }
    
}
 
Example #21
Source File: RemoteLogsTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void canGetServerLogs() {
  when(
      executeMethod.execute(
          DriverCommand.GET_LOG, ImmutableMap.of(RemoteLogs.TYPE_KEY, LogType.SERVER)))
      .thenReturn(singletonList(
          ImmutableMap.of("level", Level.INFO.getName(), "timestamp", 0L, "message", "world")));

  LogEntries logEntries = remoteLogs.get(LogType.SERVER);
  assertThat(logEntries.getAll()).hasSize(1);
  assertThat(logEntries.getAll().get(0).getMessage()).isEqualTo("world");

  // Server logs should not retrieve local logs.
  verifyNoMoreInteractions(localLogs);
}
 
Example #22
Source File: RemoteWebDriver.java    From selenium with Apache License 2.0 5 votes vote down vote up
private void init(Capabilities capabilities) {
  capabilities = capabilities == null ? new ImmutableCapabilities() : capabilities;

  logger.addHandler(LoggingHandler.getInstance());

  converter = new JsonToWebElementConverter(this);
  executeMethod = new RemoteExecuteMethod(this);
  keyboard = new RemoteKeyboard(executeMethod);
  mouse = new RemoteMouse(executeMethod);

  ImmutableSet.Builder<String> builder = new ImmutableSet.Builder<>();

  boolean isProfilingEnabled = capabilities.is(CapabilityType.ENABLE_PROFILING_CAPABILITY);
  if (isProfilingEnabled) {
    builder.add(LogType.PROFILER);
  }

  LoggingPreferences mergedLoggingPrefs = new LoggingPreferences();
  mergedLoggingPrefs.addPreferences((LoggingPreferences) capabilities.getCapability(LOGGING_PREFS));

  if (!mergedLoggingPrefs.getEnabledLogTypes().contains(LogType.CLIENT) ||
      mergedLoggingPrefs.getLevel(LogType.CLIENT) != Level.OFF) {
    builder.add(LogType.CLIENT);
  }

  Set<String> logTypesToInclude = builder.build();

  LocalLogs performanceLogger = LocalLogs.getStoringLoggerInstance(logTypesToInclude);
  LocalLogs clientLogs = LocalLogs.getHandlerBasedLoggerInstance(LoggingHandler.getInstance(),
      logTypesToInclude);
  localLogs = LocalLogs.getCombinedLogsHolder(clientLogs, performanceLogger);
  remoteLogs = new RemoteLogs(executeMethod, localLogs);
}
 
Example #23
Source File: TestBenchHelpers.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the log entries from the browser that have the given logging level
 * or higher.
 *
 * @param level
 *            the minimum severity of logs included
 * @return log entries from the browser
 */
protected List<LogEntry> getLogEntries(Level level) {
    // https://github.com/vaadin/testbench/issues/1233
    getCommandExecutor().waitForVaadin();

    return driver.manage().logs().get(LogType.BROWSER).getAll().stream()
            .filter(logEntry -> logEntry.getLevel().intValue() >= level
                    .intValue())
            // we always have this error
            .filter(logEntry -> !logEntry.getMessage()
                    .contains("favicon.ico"))
            .collect(Collectors.toList());
}
 
Example #24
Source File: PERFECTOCloudActionProvider.java    From xframium-java with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String getLog( DeviceWebDriver webDriver )
{
	
	if ( webDriver.getDevice().getOs().equalsIgnoreCase( "IOS" ) || webDriver.getDevice().getOs().equalsIgnoreCase( "ANDROID" ) )
	{
		Map<String, Object> pars = new HashMap<>();
		pars.put("tail", 1000);
		return (String) webDriver.executeScript("mobile:device:log", pars); 
	}
	else
	{
		try
        {
            LogEntries logEntries = webDriver.manage().logs().get( LogType.BROWSER );
            if ( logEntries != null )
            {
                StringBuilder logBuilder = new StringBuilder();
                for ( LogEntry logEntry : logEntries )
                    logBuilder.append( dateFormat.format( new Date( logEntry.getTimestamp() ) ) ).append( ": " ).append( logEntry.getMessage() ).append( "\r\n" );

                return logBuilder.toString();
            }
            return null;
        }
        catch ( Exception e )
        {
            log.info( "Could not generate device logs", e );
            return null;
        }
	}
	
	
}
 
Example #25
Source File: RemoteLogsTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void canGetClientLogs() {
  List<LogEntry> entries = new ArrayList<>();
  entries.add(new LogEntry(Level.SEVERE, 0, "hello"));
  when(localLogs.get(LogType.CLIENT)).thenReturn(new LogEntries(entries));

  LogEntries logEntries = remoteLogs.get(LogType.CLIENT);
  assertThat(logEntries.getAll()).hasSize(1);
  assertThat(logEntries.getAll().get(0).getMessage()).isEqualTo("hello");

  // Client logs should not retrieve remote logs.
  verifyNoMoreInteractions(executeMethod);
}
 
Example #26
Source File: ReportingWebDriverEventListener.java    From dropwizard-experiment with MIT License 5 votes vote down vote up
private static void saveLogs(String filename, WebDriver driver) {
    StringBuffer logs = new StringBuffer();
    for (LogEntry entry : driver.manage().logs().get(LogType.BROWSER)) {
        logs.append(Instant.ofEpochMilli(entry.getTimestamp()))
                .append(": ")
                .append(entry.getMessage())
                .append("\n");
    }
    try {
        Files.write(logs, new File(filename + ".txt"), Charsets.UTF_8);
    } catch (IOException e) {
        log.error("Unable to save logs from test failure.", e);
    }
}
 
Example #27
Source File: RemoteLogsTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void throwsOnBogusRemoteLogsResponse() {
  when(
      executeMethod.execute(
          DriverCommand.GET_LOG, ImmutableMap.of(RemoteLogs.TYPE_KEY, LogType.BROWSER)))
      .thenReturn(ImmutableMap.of(
          "error", "unknown method",
          "message", "Command not found: POST /session/11037/log",
          "stacktrace", ""));

  assertThatExceptionOfType(WebDriverException.class)
      .isThrownBy(() -> remoteLogs.get(LogType.BROWSER));

  verifyNoMoreInteractions(localLogs);
}
 
Example #28
Source File: PerSessionLogHandler.java    From selenium with Apache License 2.0 5 votes vote down vote up
/**
 * Fetches and stores available logs from the given session and driver.
 *
 *  @param sessionId The id of the session.
 *  @param driver The driver to get the logs from.
 *  @throws IOException If there was a problem reading from file.
 */
public synchronized void fetchAndStoreLogsFromDriver(SessionId sessionId, WebDriver driver)
  throws IOException {
  if (!perSessionDriverEntries.containsKey(sessionId)) {
    perSessionDriverEntries.put(sessionId, new HashMap<>());
  }
  Map<String, LogEntries> typeToEntriesMap = perSessionDriverEntries.get(sessionId);
  if (storeLogsOnSessionQuit) {
    typeToEntriesMap.put(LogType.SERVER, getSessionLog(sessionId));
    Set<String> logTypeSet = driver.manage().logs().getAvailableLogTypes();
    for (String logType : logTypeSet) {
      typeToEntriesMap.put(logType, driver.manage().logs().get(logType));
    }
  }
}
 
Example #29
Source File: PerSessionLogHandler.java    From selenium with Apache License 2.0 5 votes vote down vote up
/**
 * Configures logging using a logging preferences object.
 *
 * @param prefs The logging preferences object.
 */
// TODO(simons): Of course, this effects all loggers, not just the one for the session.
public void configureLogging(LoggingPreferences prefs) {
  if (prefs == null) {
    return;
  }
  if (prefs.getEnabledLogTypes().contains(LogType.SERVER)) {
    serverLogLevel = prefs.getLevel(LogType.SERVER);
  }
}
 
Example #30
Source File: GetLogHandler.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public LogEntries call() throws Exception {
  if (LogType.SERVER.equals(type)) {
    return LoggingManager.perSessionLogHandler().getSessionLog(getSessionId());
  }
  return getDriver().manage().logs().get(type);
}