下面列出了怎么用org.openqa.selenium.logging.LogType的API类实例代码及写法,或者点击链接到github查看源代码。
@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))));
}
private void setChromeDriver() {
ChromeOptions options = new ChromeOptions();
List<String> chromeOptions = new ArrayList<>();
LoggingPreferences logPrefs = new LoggingPreferences();
chromeOptions.add(String.format("--proxy-server=%s", proxies.getCurrentProxyModel().getIp()));
chromeOptions.add(String.format("--user-agent=%s", userAgent.randomUA()));
chromeOptions.add("--mute-audio");
logPrefs.enable(LogType.BROWSER, Level.ALL);
logPrefs.enable(LogType.PERFORMANCE, Level.INFO);
options.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
options.addArguments(chromeOptions);
options.setBinary(this.driverLocation);
options.setHeadless(true);
// options.setProxy(this.proxies.getCurrentProxy());
options.setCapability("proxy", this.proxies.getCurrentProxy());
this.webDriver = new ChromeDriver(options);
Log.WINFO(this.workerName, this.workerColor, "Chrome Driver Set.");
}
@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);
}
/**
* @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"));
}
/**
* @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"));
}
/**
* @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\"})"));
}
/**
* @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\"})"));
}
/**
* @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"));
}
/**
* 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);
}
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"));
}
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"));
}
@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;
}
}
@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;
}
}
@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;
}
}
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);
}
}
@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);
}
@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");
}
@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");
}
@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");
}
@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);
}
@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;
}
private static Optional<LogEntries> getLog(WebDriver driver, boolean ignoreUnsupportedDrivers)
{
// The Selenium log API isn't supported: https://github.com/w3c/webdriver/issues/406
if (WebDriverManager.isTypeAnyOf(driver, WebDriverType.FIREFOX, WebDriverType.IEXPLORE))
{
if (ignoreUnsupportedDrivers)
{
return Optional.empty();
}
throw new IllegalStateException("Firefox does not support retrieval of browser logs");
}
return Optional.of(driver.manage().logs().get(LogType.BROWSER));
}
private static LogEntries mockLogRetrieval(WebDriver webDriver)
{
Options options = mock(Options.class);
when(webDriver.manage()).thenReturn(options);
Logs logs = mock(Logs.class);
when(options.logs()).thenReturn(logs);
when(options.logs()).thenReturn(logs);
LogEntry severeEntry = new LogEntry(Level.SEVERE, 1L, ERROR_MESSAGE);
LogEntry infoEntry = new LogEntry(Level.INFO, 1L, ERROR_MESSAGE);
LogEntries logEntries = new LogEntries(Arrays.asList(severeEntry, infoEntry));
when(logs.get(LogType.BROWSER)).thenReturn(logEntries);
return logEntries;
}
private LogEntry mockGetLogEntry(String logErrorMessage)
{
WebDriver webDriver = mock(WebDriver.class, withSettings().extraInterfaces(HasCapabilities.class));
when(webDriverProvider.get()).thenReturn(webDriver);
when(webDriver.getCurrentUrl()).thenReturn(URL);
Options options = mock(Options.class);
when(webDriver.manage()).thenReturn(options);
Logs logs = mock(Logs.class);
when(options.logs()).thenReturn(logs);
LogEntry severeEntry = new LogEntry(Level.SEVERE, 1L, logErrorMessage);
LogEntry infoEntry = new LogEntry(Level.INFO, 1L, logErrorMessage);
LogEntries logEntries = new LogEntries(Arrays.asList(severeEntry, infoEntry));
when(logs.get(LogType.BROWSER)).thenReturn(logEntries);
return severeEntry;
}
/**
* Sets the webdriver to FireFox. We set our optimal parameters here
* to ensure our proxy is set correctly.
*/
private void setFirefoxDriver() {
FirefoxOptions options = new FirefoxOptions();
FirefoxProfile profile = new FirefoxProfile();
FirefoxBinary binary = new FirefoxBinary(this.driverLocation);
LoggingPreferences logPrefs = new LoggingPreferences();
System.setProperty(FirefoxDriver.SystemProperty.DRIVER_USE_MARIONETTE,"true");
// hide firefox logs from console
System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE,"/tmp/rust_");
profile.setPreference("media.volume_scale", "0.0");
profile.setPreference("general.useragent.override", userAgent.randomUA());
profile.setPreference("network.proxy.type", 1);
profile.setPreference("network.proxy.http", this.proxies.getCurrentProxyModel().getIp());
profile.setPreference("network.proxy.http_port", this.proxies.getCurrentProxyModel().getPort());
profile.setPreference("network.proxy.ssl", this.proxies.getCurrentProxyModel().getIp());
profile.setPreference("network.proxy.ssl_port", this.proxies.getCurrentProxyModel().getPort());
logPrefs.enable(LogType.BROWSER, Level.ALL);
logPrefs.enable(LogType.PERFORMANCE, Level.INFO);
options.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
options.setProfile(profile);
options.setHeadless(true);
options.setBinary(binary);
// options.setProxy(this.proxies.getCurrentProxy());
options.setCapability("proxy", this.proxies.getCurrentProxy());
this.webDriver = new FirefoxDriver(options);
Log.WINFO(this.workerName, this.workerColor, "Firefox Driver Set");
}
@Test
public void testLogging_Chrome() throws MalformedURLException {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("automationName", "UiAutomator2");
capabilities.setCapability("deviceName", "Android Emulator");
capabilities.setCapability("browserName", "Chrome");
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);
loggingRoutine(driver);
}
/**
* @throws Exception if the test fails
*/
@Test
@BuggyWebDriver
public void simpleString() throws Exception {
final String html
= "<html>\n"
+ "<body>\n"
+ "<script>\n"
+ " for (i = 0; i < 4; i++) {\n"
+ " console.log('test log ' + i);\n"
+ " }\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();
final int count = logEntryList.size();
assertTrue(count > 0);
long timestamp = 0;
for (int i = 0; i < 4; i++) {
final LogEntry logEntry = logEntryList.get(i);
assertTrue(logEntry.getMessage(), logEntry.getMessage().contains("test log " + i));
assertTrue(logEntry.getTimestamp() >= timestamp);
timestamp = logEntry.getTimestamp();
}
}
Capabilities createCapabilities() {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, createProxy());
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.BROWSER, Level.ALL);
capabilities.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
if(isAndroidEnabled() || isHeadlessEnabled() || isIncognitoEnabled()) {
//Map<String, String> chromeOptions = new HashMap<String, String>();
//chromeOptions.put("androidPackage", "com.android.chrome");
ChromeOptions chromeOptions = new ChromeOptions();
if (isAndroidEnabled()) {
chromeOptions.setExperimentalOption("androidPackage", "com.android.chrome");
}
if (isHeadlessEnabled()) {
chromeOptions.addArguments("--headless");
}
if (isIncognitoEnabled()) {
chromeOptions.addArguments("--incognito");
}
capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
}
if(isInsecureCertsEnabled()) {
capabilities.setCapability("acceptInsecureCerts", true);
}
return capabilities;
}
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.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());
}