Java 类org.openqa.selenium.logging.LogEntry 实例源码

项目:elpi    文件:WebdriverTestCase.java   
public boolean getTestLogs(String videoFileName) throws Exception {
    HTMLFormatter f = new HTMLFormatter();
    File logFile = new File(OUTPUT_DIR + videoFileName + ".html");
    if (!logFile.exists()) {
        logFile.createNewFile();
    }
    FileOutputStream fos = new FileOutputStream(logFile);
    PrintStream ps = new PrintStream(fos);

    ps.print(f.getHead(null));
    ps.println();

    LogEntries entries =  driver.manage().logs().get(LogType.CLIENT);
    for(LogEntry entry : entries.getAll()) {
        if (entry.getMessage().contains("Executing:") || entry.getMessage().contains("Executed:")) {
            ps.print(f.format(entry));
            ps.println();
        }
    }
    ps.print(f.getTail(null));
    ps.println();
    ps.close();
    return true;
}
项目:xframium-java    文件:SELENIUMCloudActionProvider.java   
@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;
       }

}
项目:xframium-java    文件:SAUCELABSCloudActionProvider.java   
@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;
    }

}
项目:jwebrobot    文件:ReporterTest.java   
@Test
public void shouldConvertLogEntries() {
    LogEntries logEntries = mock(LogEntries.class);
    when(logs.get(LogType.BROWSER)).thenReturn(logEntries);
    LogEntry logEntry = mock(LogEntry.class);
    when(logEntries.getAll()).thenReturn(asList(logEntry));

    when(logEntry.getLevel()).thenReturn(Level.FINEST);
    when(executorOptions.getBrowserLogLevel()).thenReturn(website.automate.waml.report.io.model.LogEntry.LogLevel.DEBUG);

    reporter.processLogEntries(context, actionReport);

    verify(logEntries).getAll();

    verify(actionReport).setLogEntries(logEntryListCaptor.capture());
    List<website.automate.waml.report.io.model.LogEntry> logEntryList = logEntryListCaptor.getValue();
    assertThat(logEntryList, hasSize(1));
}
项目:spa-perf    文件:SPAPerfChromeDriver.java   
public List<JsonObject> readPerfLog() throws Exception {
    List<LogEntry> entries = this.manage().logs().get(LogType.PERFORMANCE).getAll();

    List<JsonObject> events = new ArrayList<>();

    for (LogEntry entry : entries) {
        JsonObject message = JsonObject.readFrom(entry.getMessage()).get("message").asObject();

        if (message.get("method").asString() == "Tracing.dataCollected") {
            events.add(message.get("params").asObject());
        }
        if (message.get("method").asString() == "Tracing.bufferUsage") {
            throw new Exception("The DevTools trace buffer filled during the test!");
        }
    }

    return convertPerfRecordsToEvents(events);
}
项目:crowdsource    文件:BrowserLogFetchHook.java   
@cucumber.api.java.After
public void after(Scenario result) {
    if (webDriverProvider.hasActiveWebDriver()) {
        WebDriver webDriver = webDriverProvider.provideDriver();

        if (result != null) {
            LogEntries logs = webDriver.manage().logs().get(LogType.BROWSER);

            if (LOG.isInfoEnabled()) {
                String logOutput = logs.getAll().stream()
                        .map(LogEntry::toString)
                        .collect(joining("\n"));

                LOG.info("Browser console.log output: {}", "\n" + logOutput);
            }
        }
    }
}
项目:ScriptDriver    文件:RunTests.java   
private void dumpLog() throws Exception {
    Logs log = driver.manage().logs();
    LogEntries entries = log.get(LogType.BROWSER);
    // System.out.println(entries);
    List<LogEntry> list = entries.getAll();
    boolean fail = false;
    for (int i = 0; i < list.size(); i++) {
        LogEntry e = list.get(i);
        System.out.println(e);
        if (e.getLevel().getName().equals("SEVERE") 
                && e.getMessage().indexOf("Uncaught ") != -1
                && e.getMessage().indexOf(" Error:") != -1) {
            System.out.println("*** Uncaught Error ***");
            fail = true;
        }                       
    }
    if (fail) throw new Exception("Unhandled Exception! Check console log for details");        
}
项目:kurento-java    文件:BrowserTest.java   
@FailedTest
public static void storeBrowsersLogs() {
  List<String> lines = new ArrayList<>();
  for (String browserKey : browserLogs.keySet()) {
    for (LogEntry logEntry : browserLogs.get(browserKey)) {
      lines.add(logEntry.toString());
    }

    File file = new File(getDefaultOutputTestPath() + browserKey + ".log");

    try {
      FileUtils.writeLines(file, lines);
    } catch (IOException e) {
      log.error("Error while writing browser log to a file", e);
    }
  }
}
项目:testing-tools    文件:AbstractWebDriverTest.java   
protected void dumpBrowserLogs(String testName) {
    try {
        Logs logs = webdriver.manage().logs();

        for(String type : logs.getAvailableLogTypes()) {
            String fileName = testName + "_" + type;
            List<LogEntry> allLogs = logs.get(type).getAll();
            if (allLogs.size() > 0) {
                WEBDRIVER_LOGS_DIR_PATH.mkdirs();
                writeLines(new File(WEBDRIVER_LOGS_DIR_PATH, fileName), allLogs);
            }
        }
    } catch (Exception e) {
        logger.error("Cannot dumpBrowserLogs('" + testName + "')", e);
    }
}
项目:gatf    文件:SeleniumTest.java   
public SeleniumTestResult(WebDriver d, SeleniumTest test, Throwable cause, LoggingPreferences ___lp___) {
    this.status = false;
    this.internalTestRes = test.internalTestRs;
    Logs logs = d.manage().logs();
    for (String s : LOG_TYPES_SET) {
        if(!logs.getAvailableLogTypes().contains(s))continue;
        LogEntries logEntries = logs.get(s);
        if(logEntries!=null && !logEntries.getAll().isEmpty()) {
            this.logs.put(s, new SerializableLogEntries(logEntries.getAll())); 
        }
    }
    List<LogEntry> entries = new ArrayList<LogEntry>();
    entries.add(new LogEntry(Level.ALL, new Date().getTime(), cause.getMessage()));
    entries.add(new LogEntry(Level.ALL, new Date().getTime(), ExceptionUtils.getStackTrace(cause)));
    this.logs.put("gatf", new SerializableLogEntries(entries));
}
项目:seletest    文件:TestListener.java   
@Override
public void onTestFailure(ITestResult testResult) {
    log.debug("Test "+ testResult.getName()+" failed!!!");
    try {
        log.debug("Collect client logs after failure of the @Test {}", testResult.getMethod());
        LogEntries entries=ApplicationContextProvider.getApplicationContext().getBean(StrategyFactory.class).getControllerStrategy(SessionContext.getSession().getControllerStrategy()).logs(LogType.BROWSER);
        StringBuilder list=new StringBuilder();
        for (LogEntry entry : entries) {
            list.append(entry.getMessage()).append("\n");
        }
        ApplicationContextProvider.getApplicationContext().getBean(FilesUtils.class).createHTML("Logs for Client", list.toString(), "Logs_"+testResult.getName());
        Reporter.log("<p class=\"testOutput\"><a href=\"Logs/Logs_"+testResult.getName()+".html\">Client Logs<a/></p>");
    }
    catch(Exception ex) {
        log.error("Exception trying to collect client logs: {}",ex.getMessage());
    }

    if(System.getProperty("email")!=null) {
        log.debug("Send email notification with failure of the @Test to address {} ", System.getProperty("email"));
        ApplicationContextProvider.getApplicationContext().getBean(MailUtils.class).sendMail(System.getProperty("email"),"Failure on test: "+testResult.getName(),"Exception occured is: "+testResult.getThrowable().getMessage());
    }
}
项目:selendroid    文件:AbstractDevice.java   
@Override
public List<LogEntry> getLogs() {
  List<LogEntry> logs = Lists.newArrayList();
  String result = logoutput != null ? logoutput.toString() : "";
  String[] lines = result.split("\\r?\\n");
  log.fine("getting logcat");
  for (String line : lines) {
    Level l;
    if (line.startsWith("I")) {
      l = Level.INFO;
    } else if (line.startsWith("W")) {
      l = Level.WARNING;
    } else if (line.startsWith("S")) {
      l = Level.SEVERE;
    } else {
      l = Level.FINE;
    }
    logs.add(new LogEntry(l, System.currentTimeMillis(), line));
    log.fine(line);
  }
  return logs;
}
项目:marathonv5    文件:JavaDriverLogsTest.java   
public void loggingWorks() {
    LoggingPreferences prefs = new LoggingPreferences();
    prefs.enable(LogType.DRIVER, Level.INFO);
    DesiredCapabilities caps = JavaDriver.defaultCapabilities();
    caps.setCapability(CapabilityType.LOGGING_PREFS, prefs);
    driver = new JavaDriver(caps, caps);
    LogEntries logEntries = driver.manage().logs().get(LogType.DRIVER);
    List<LogEntry> all = logEntries.getAll();
    AssertJUnit.assertEquals(2, all.size());
    AssertJUnit.assertTrue(all.get(0).getMessage().contains("A new session created. sessionID = "));
}
项目:marathonv5    文件:JavaDriverLogsTest.java   
public void loglevelsAreRespected() {
    LoggingPreferences prefs = new LoggingPreferences();
    prefs.enable(LogType.DRIVER, Level.WARNING);
    DesiredCapabilities caps = JavaDriver.defaultCapabilities();
    caps.setCapability(CapabilityType.LOGGING_PREFS, prefs);
    driver = new JavaDriver(caps, caps);
    LogEntries logEntries = driver.manage().logs().get(LogType.DRIVER);
    List<LogEntry> all = logEntries.getAll();
    AssertJUnit.assertEquals(0, all.size());
}
项目:NoraUi    文件:Step.java   
/**
 * CAUTION: This check do not work with IE: https://github.com/SeleniumHQ/selenium/issues/468
 * CAUTION: This feature is not supported by HtmlUnit web driver
 *
 * @return a String with the message of Alert, return null if no alert message.
 */
protected String getLastConsoleAlertMessage() {
    String msg;
    List<LogEntry> l = getDriver().manage().logs().get(LogType.BROWSER).getAll();
    for (int i = l.size() - 1; i >= 0; i--) {
        if (l.get(i).getMessage().contains(ALERT_KEY)) {
            msg = l.get(i).getMessage();
            return msg.substring(msg.indexOf('"') + 1, msg.length() - 1).replace(ALERT_KEY, "").replace(" (:", "");
        }
    }
    return null;
}
项目:devtools-driver    文件:LogHandler.java   
@Override
public Response handle() throws Exception {
  ServerSideSession session = getSession();
  JsonObject payload = getRequest().getPayload();
  String type = payload.getString("type");
  List<LogEntry> entries = session.getLogManager().getLog(type);
  return createResponse(entries);
}
项目:ja11y    文件:AccessibilitySniffer.java   
public void runCodeSniffer() throws IOException {
    String jquery_content = Jsoup.connect("http://squizlabs.github.io/HTML_CodeSniffer/build/HTMLCS.js").ignoreContentType(true).execute().body();
    js.executeScript(jquery_content);
    js.executeScript("window.HTMLCS_RUNNER.run('WCAG2AA');");
    LogEntries logs = driver.manage().logs().get("browser");
    for (LogEntry entry : logs) {
        System.out.println(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());
    }
}
项目:spa-perf    文件:ConsolePrinter.java   
public void printLogToConsole(WebDriver driver, String type) {
    // Get the logs
    // ChromeDriver - format: message: "[{method:'Tracing.dataCollected', params:{cat:...,pid:...}}]"
    List<LogEntry> entries = driver.manage().logs().get(type).getAll();

    System.out.println(entries.size() + " " + type + " log entries found");
    for (LogEntry entry : entries) {
        System.out.println(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());
    }
}
项目:grid-refactor-remote-server    文件:DefaultPerSessionLogHandler.java   
/**
 * Returns the server log for the given session id.
 * 
 * @param sessionId The session id.
 * @return The available server log entries for the session.
 * @throws IOException If there was a problem reading from file.
 */
@Override
public synchronized LogEntries getSessionLog(SessionId sessionId) throws IOException {
  List<LogEntry> entries = Lists.<LogEntry>newLinkedList();
  LogRecord[] records = records(sessionId);
  if (records != null) {
    for (LogRecord record : records) {
      if (record.getLevel().intValue() >= serverLogLevel.intValue())
        entries.add(new LogEntry(record.getLevel(), record.getMillis(), record.getMessage()));
    }
  }
  return new LogEntries(entries);
}
项目:elpi    文件:WebdriverTestCase.java   
public String format(LogEntry entry) {
  String message = "<tr><td>" + format.format(entry.getTimestamp()) + "</td><td>";
  if (entry.getMessage().contains("Executing:")) {
      message = message + entry.getMessage().substring(entry.getMessage().indexOf("Executing:")) ;
  }
  if (entry.getMessage().contains("Executed:")) {
      message = message + entry.getMessage().substring(entry.getMessage().indexOf("Executed:")) ;
  }
   message = message + "</td><td>" + entry.getLevel() + "</td></tr>\n";

  return message;
}
项目:gatf    文件:SerializableLogEntries.java   
public SerializableLogEntries(List<LogEntry> entries) {
    List<SerializableLogEntry> mutableEntries = new ArrayList<SerializableLogEntry>();
    for (LogEntry e : entries) {
        mutableEntries.add(new SerializableLogEntry(e.getLevel(), e.getTimestamp(), e.getMessage()));
    }
    this.entries = Collections.unmodifiableList(mutableEntries);
}
项目:gatf    文件:SeleniumTest.java   
public SeleniumTestResult(SeleniumTest test, Throwable cause) {
    this.status = false;
    this.internalTestRes = test.internalTestRs;
    List<LogEntry> entries = new ArrayList<LogEntry>();
    entries.add(new LogEntry(Level.ALL, new Date().getTime(), cause.getMessage()));
    entries.add(new LogEntry(Level.ALL, new Date().getTime(), ExceptionUtils.getStackTrace(cause)));
    this.logs.put("gatf", new SerializableLogEntries(entries));
}
项目:gatf    文件:SeleniumException.java   
public SeleniumException(WebDriver d, Throwable cause, SeleniumTest test) {
    super(cause);
    Map<String, SerializableLogEntries> lg = new HashMap<String, SerializableLogEntries>();
       Logs logs = d.manage().logs();
       for (String s : d.manage().logs().getAvailableLogTypes()) {
           LogEntries logEntries = logs.get(s);
           if(!logEntries.getAll().isEmpty()) {
               lg.put(s, new SerializableLogEntries(logEntries.getAll())); 
           }
       }
       List<LogEntry> entries = new ArrayList<LogEntry>();
       entries.add(new LogEntry(Level.ALL, new Date().getTime(), cause.getMessage()));
       entries.add(new LogEntry(Level.ALL, new Date().getTime(), ExceptionUtils.getStackTrace(cause)));
       lg.put("gatf", new SerializableLogEntries(entries));
}
项目:testng_samples    文件:MyTest.java   
@AfterMethod
public void tearDown(Method m) throws IOException {
  LogEntries logEntries = driver.manage().logs().get("browser");
  File driverLog = new File(m.getName() + ".log");
  FileWriter out = new FileWriter(driverLog);
  for (LogEntry logEntry : logEntries.getAll()) {
    out.write(logEntry.toString() + "\n");
  }
  out.close();
}
项目:seleniumcapsules    文件:LogsTest.java   
@Test
public void getAvailableLogTypes() {
    WebDriver driver = new ChromeDriver();
    driver.get("http://ticketfly.com");

    Options manage = driver.manage();
    Logs logs = manage.logs();
    Set<String> availableLogTypes = logs.getAvailableLogTypes();
    System.out.println(availableLogTypes);
    availableLogTypes.stream().forEach(logType -> {
        System.out.println("logType=" + logType);
        LogEntries logEntries = logs.get(logType);
        List<LogEntry> all = logEntries.getAll();
        all.forEach(entry -> {
            System.out.println(entry.getLevel());
            System.out.println(entry.getMessage());
            System.out.println(entry.getTimestamp());
            System.out.println(entry.toMap());
            System.out.println(entry);
        });

        List<LogEntry> filter = logEntries.filter(Level.SEVERE);
        System.out.println("After filtering");
        filter.forEach(System.out::println);
        System.out.println("Done");
    });

}
项目:dropwizard-experiment    文件:ReportingWebDriverEventListener.java   
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);
    }
}
项目:selendroid    文件:GetLogs.java   
@Override
public Response handleRequest(HttpRequest request, JSONObject payload) throws JSONException {
  ActiveSession session = getActiveSession(request);
  JSONArray logs = new JSONArray();
  for (LogEntry l : session.getDevice().getLogs()) {
    logs.put(l.toString());
  }
  return new SelendroidResponse(getSessionId(request), logs);
}
项目:cerberus-source    文件:WebDriverService.java   
@Override
public List<String> getSeleniumLog(Session session) {
    List<String> result = new ArrayList();
    Logs logs = session.getDriver().manage().logs();

    for (String logType : logs.getAvailableLogTypes()) {
        LogEntries logEntries = logs.get(logType);
        result.add("********************" + logType + "********************\n");
        for (LogEntry logEntry : logEntries) {
            result.add(new Date(logEntry.getTimestamp()) + " : " + logEntry.getLevel() + " : " + logEntry.getMessage() + "\n");
        }
    }

    return result;
}
项目:devtools-driver    文件:WebDriverLog.java   
@Override
public void addEntryTimestamped(long timestamp, Level level, String message) {
  if (level.intValue() >= minLogLevel.intValue()) {
    logEntries.add(new LogEntry(level, timestamp, message));
  }
}
项目:devtools-driver    文件:WebDriverLog.java   
public List<LogEntry> getAndClearEntries() {
  List<LogEntry> ret = new ArrayList<LogEntry>(logEntries);
  logEntries.clear();
  return ret;
}
项目:devtools-driver    文件:IOSLogManager.java   
public List<LogEntry> getLog(String type) {
  WebDriverLog log = (WebDriverLog) logs.get(type);
  return (log == null ? (Collections.<LogEntry>emptyList()) : log.getAndClearEntries());
}
项目:spa-perf    文件:TimelineMetrics.java   
public void getResult(SPAPerfChromeDriver driver) {
    List entries = getPerfLogFromDriver(driver);

    performanceResult = new HashMap<String, double[]>();
    HashMap<String, Double> startTime = new HashMap<>();
    for (int i = 0; i < selectedPerformanceCounters.length; i++) {
        performanceResult.put(selectedPerformanceCounters[i], new double[]{0.0, 0.0, 0.0});
        startTime.put(selectedPerformanceCounters[i], 0.0);
    }

    for (Object entryObj : entries) {
        LogEntry entry = (LogEntry) entryObj;
        try {
            JsonObject message = JsonObject.readFrom(entry.getMessage()).get("message").asObject();
            if (message.get("method").asString().equals("Tracing.dataCollected")) {
                //System.out.println(entry.getLevel() + " " + entry.getMessage());
                JsonObject event = message.get("params").asObject();
                String name = event.get("name").asString();
                if (performanceResult.containsKey(name)) {
                    String eventStatus = event.get("ph").asString();
                    double[] currentValue = performanceResult.get(name);
                    Double dur = 0.0;
                    switch (eventStatus) {
                        case "X":
                            dur = event.get("dur").asDouble() / 1000.0;
                            break;
                        case "B":  //add start time for this event
                            startTime.put(name, event.get("ts").asDouble());
                            continue;
                        case "E":
                            if (startTime.get(name) < 0.001)  // this means no beginning time for this event
                                //throw new Exception();
                                continue;
                            else {
                                dur = (event.get("ts").asDouble() - startTime.get(name)) / 1000.0;
                                startTime.put(name, 0.0);  //reset the startTime
                            }
                            break;
                        default:
                            break;
                    }
                    currentValue[0] = currentValue[0] + dur;
                    currentValue[1] = currentValue[1] > dur ? currentValue[1] : dur;
                    currentValue[2]++;
                    performanceResult.put(name, currentValue); //calculate event duration
                }
            }
        } catch (Exception ex) {
            continue;
        }
    }
}
项目:spa-perf    文件:SPAPerfChromeDriver.java   
public List<LogEntry> getPerformanceLog ()
{
    return this.manage().logs().get(LogType.PERFORMANCE).getAll();
}
项目:grid-refactor-remote-server    文件:NoOpSessionLogHandler.java   
@Override
public LogEntries getSessionLog(SessionId sessionId) {
  return new LogEntries(ImmutableList.<LogEntry>of());
}
项目:selendroid    文件:DeviceForTest.java   
@Override
public List<LogEntry> getLogs() {
  return null;
}
项目:liveoak    文件:AbstractLiveOakTest.java   
/**
 * Output the content within the logType. Use {@link org.openqa.selenium.logging.LogType} to specify
 * which logType to output.
 *
 * @param logType
 */
protected void outputLog(String logType) {
    for (LogEntry o : browser.manage().logs().get(logType).getAll()) {
        System.out.println(logType + " Log: " + o.getMessage());
    }
}
项目:selendroid    文件:AndroidDevice.java   
public List<LogEntry> getLogs();