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; }
@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; } }
@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)); }
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); }
@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); } } } }
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"); }
@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); } } }
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); } }
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)); }
@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()); } }
@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; }
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 = ")); }
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()); }
/** * 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; }
@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); }
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()); } }
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()); } }
/** * 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); }
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; }
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); }
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)); }
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)); }
@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(); }
@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"); }); }
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); } }
@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); }
@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; }
@Override public void addEntryTimestamped(long timestamp, Level level, String message) { if (level.intValue() >= minLogLevel.intValue()) { logEntries.add(new LogEntry(level, timestamp, message)); } }
public List<LogEntry> getAndClearEntries() { List<LogEntry> ret = new ArrayList<LogEntry>(logEntries); logEntries.clear(); return ret; }
public List<LogEntry> getLog(String type) { WebDriverLog log = (WebDriverLog) logs.get(type); return (log == null ? (Collections.<LogEntry>emptyList()) : log.getAndClearEntries()); }
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; } } }
public List<LogEntry> getPerformanceLog () { return this.manage().logs().get(LogType.PERFORMANCE).getAll(); }
@Override public LogEntries getSessionLog(SessionId sessionId) { return new LogEntries(ImmutableList.<LogEntry>of()); }
@Override public List<LogEntry> getLogs() { return null; }
/** * 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()); } }
public List<LogEntry> getLogs();