Setting downloads directory for chrome driver suddenly stopped working after upgrade - selenium-webdriver

After I've upgraded my project to use latest java selenium webdriver 3.7.1 and latest chrome driver 2.33 I noticed that my tests dealing with Excel export started to fail.
After debugging I see that for some reasons downloads directory is not being set to custom location and instead the default one is used. Nothing shows up in logs or whatsoever.
Any help appreciated.
Setting downloads directory is like usual:
val prefs = Map(
"profile.default_content_settings.popups" -> Integer.valueOf(0),
"download.default_directory" -> downloadsDir,
"credentials_enable_service" -> false,
"profile.password_manager_enabled" -> false
)
val chromeOptions:ChromeOptions = new ChromeOptions()
chromeOptions.setExperimentalOption("prefs", prefs)
val d = new ChromeDriver(chromeOptions)

I use WebDriver 3.7.1 and Chromedriver 2.33 and of course Chrome v.62 (try check Your Version of Chrome), and I can download files.
I'm using folder
public static String javaIoTmpDir = System.getProperty("java.io.tmpdir")+"/autotest/";
and I create/clean it with script in TestNG annotation: #BeforeSuite
File theDir = new File(javaIoTmpDir);
// if the directory does not exist, create it
if (!theDir.exists()) {
System.out.println("creating directory: " + theDir.getName());
boolean result = false;
try{
theDir.mkdir();
result = true;
}
catch(SecurityException se){
se.printStackTrace();
}
if(result) {
System.out.println(javaIoTmpDir+" created");
}
}
FileUtils.cleanDirectory(new File(javaIoTmpDir));
}

Related

In Selenium webdriver, for remote Firefox how to use OSS bridge instead of w3c bridge for handshaking

I am using selenoid for remote browser testing in ruby.
In that I am using 'selenium-webdriver', 'capybara', 'rspec' for automation. And I am using attach_file method for uploading file to browser
I want to upload file on Firefox and Chrome browser but it raises error on both;
In chrome
Selenium::WebDriver::Error::UnknownCommandError: unknown command: unknown command: session/***8d32e045e3***/se/file
In firefox
unexpected token at 'HTTP method not allowed'
So After searching I found the solution for chrome which is to set w3c option false in caps['goog:chromeOptions'] > caps['goog:chromeOptions'] = {w3c: false}
So now chrome is using OSS bridge for handshaking but I don't know how to do it in Firefox. Similar solution is not available for Firefox.
My browser capabilities are following:
if ENV['BROWSER'] == 'firefox'
caps = Selenium::WebDriver::Remote::Capabilities.new
caps['browserName'] = 'firefox'
# caps['moz:firefoxOptions'] = {w3c: false} ## It is not working
else
caps = Selenium::WebDriver::Remote::Capabilities.new
caps["browserName"] = "chrome"
caps["version"] = "81.0"
caps['goog:chromeOptions'] = {w3c: false}
end
caps["enableVNC"] = true
caps["screenResolution"] = "1280x800"
caps['sessionTimeout'] = '15m'
Capybara.register_driver :selenium do |app|
Capybara::Selenium::Driver.new(app, browser: :remote,
:desired_capabilities => caps,
:url => ENV["REMOTE_URL"] || "http://*.*.*.*:4444/wd/hub"
)
end
Capybara.configure do |config|
config.default_driver = :selenium
end
I have found the problem. There is bug in selenium server which run on java so I have to change my selenium-webdriver gem version 3.142.7 and monkey-patch.
You can find more information here about the bug and resolution.
For now I have to change my gem and monkey patch the selenium-webdriver-3.142.7\lib\selenium\webdriver\remote\w3c\commands.rb file. check for below line which is on line no 150.
upload_file: [:post, 'session/:session_id/se/file']
and update it to
upload_file: [:post, 'session/:session_id/file']
i had a similar issue with rails 7. the issue is connected with the w3c standard. the core problem is that the webdriver for chrome uses a non-w3c standard url for handling file uploads. when uploading a file, the webdriver uses the /se/file url path to upload. this path is only supported by the selenium server. subsequently, the docker image provided by selenium works fine. yet, if we use chromedriver, the upload fails. more info.
we can solve this, by forcing the webdriver to use the standard-compliant url by overriding the :upload_file key in Selenium::WebDriver::Remote::Bridge::COMMANDS. since, the initialization of this the COMMANDS constant does not happen when the module is loaded, we can override the attach_file method to make sure the constant is set correctly. here the hacky code:
module Capybara::Node::Actions
alias_method :original_attach_file, :attach_file
def attach_file(*args, **kwargs)
implement_hacky_fix_for_file_uploads_with_chromedriver
original_attach_file(*args, **kwargs)
end
def implement_hacky_fix_for_file_uploads_with_chromedriver
return if #hacky_fix_implemented
original_verbose, $VERBOSE = $VERBOSE, nil # ignore warnings
cmds = Selenium::WebDriver::Remote::Bridge::COMMANDS.dup
cmds[:upload_file] = [:post, "session/:session_id/file"]
Selenium::WebDriver::Remote::Bridge.const_set(:COMMANDS, cmds)
$VERBOSE = original_verbose
#hacky_fix_implemented = true
end
end
In Firefox images we support /session/<id>/file API by adding Selenoid binary which emulates this API instead of Geckodriver (which does not implement it).

selenium c# edge browser : 'Unexpected error. Unknown error'

OS Build Number:- 18363.900
Edge Version: 83.0.478.54
MicrosoftWebDriver Version: 83.0.478.54
Here is the code:
System.Environment.SetEnvironmentVariable("webdriver.edge.driver", "E:\\edgedriver_win64\\msedgedriver.exe");
IWebDriver driver = new EdgeDriver();
I am getting error as: OpenQA.Selenium.WebDriverException: 'Unexpected error. Unknown error'
Which version of Selenium WebDriver are you using? I suggest you to use the latest version 4.0.0-alpha05 and use the code below:
EdgeOptions edgeOptions = new EdgeOptions();
edgeOptions.UseChromium = true;
edgeOptions.BinaryLocation = #"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe";
var msedgedriverDir = #"D:\webdriver83.0.478.54";
var driver = new EdgeDriver(msedgedriverDir, edgeOptions);
driver.Navigate().GoToUrl("https://bing.com");
Thread.Sleep(3000);
driver.Close();
Note: Change the paths in the code to your owns.
Result:

ASP.Net Core React spa integration test

Asp.Net Core integration testing seems pretty simple but for the life of me I can't test the starter app with my react dev server. It runs fine from a browser so I assume node, npm and react are set up correctly but not under xUnit. It fails with the following exception:
System.AggregateException: One or more errors occurred. ---> System.AggregateException: One or more errors occurred. ---> System.InvalidOperationException: Failed to start 'npm'. To resolve this:.
[1] Ensure that 'npm' is installed and can be found in one of the PATH directories.
Current PATH enviroment variable is: {PATH}
Make sure the executable is in one of those directories, or update your PATH.
[2] See the InnerException for further details of the cause. ---> System.ComponentModel.Win32Exception: The directory name is invalid
...
I assume this is because it can't find the content root of my spa so I have tried adding to my web host builder with no luck:
.UseSolutionRelativeContentRoot( "Solution Relative Path to My App" ) );
This is my test class:
public class SampleDataControllerTest
{
private readonly TestServer server;
private readonly HttpClient client;
public SampleDataControllerTest()
{
server = new TestServer( WebHost.CreateDefaultBuilder()
.UseStartup<Startup>()
.UseSolutionRelativeContentRoot( "Solution Relative Path to My App" ) );
.UseEnvironment( "Development" );
client = server.CreateClient();
}
[Fact]
public async Task RootTest()
{
HttpResponseMessage page = await client.GetAsync( "/" );
Assert.NotNull( page );
Assert.Equal( HttpStatusCode.OK, page.StatusCode );
}
What am I missing?
The trick for me was setting the development environment variable to point to the directory where the packages.json file resides.
Below is an excerpt of the constructor of my xUnit integration test class.
Note that it first determines the solution directory (using GetExecutingAssembly().Location), and then points to the web source project folder. (In our environment, Client.React is a directory under the solution directory that contains the packages.json file).
Then, the directory is set using Directory.SetCurrentDirectory, followed by the test server being set up wit hthe UseWebRoot, again pointing to the directory where the packages.json file resides.
Startup is the ASP.NET web startup class.
/// <summary>
/// Constructor
/// </summary>
public IntegrationTest() : base()
{
var testAssemblyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
// Remove the "\\bin\\Debug\\netcoreapp2.1"
var solutionPath = Directory.GetParent(testAssemblyPath.Substring(0, testAssemblyPath.LastIndexOf(#"\bin\", StringComparison.Ordinal))).FullName;
var clientReactPath = Path.Join(solutionPath, "Client.React");
// Important to ensure that npm loads and is pointing to correct directory
Directory.SetCurrentDirectory(clientReactPath);
var server = new TestServer(new WebHostBuilder()
.UseEnvironment("Development")
.UseWebRoot(clientReactPath)
.UseStartup<Startup>());
_client = server.CreateClient();
}

How to get adf-richclient-automation-11.jar compatible with the latest selenium-java 3.x

I'm develping Selenium tests for Oracle ADF application.
I'm using for that:
JDeveloper fmw_12.2.1.3.0_bpmqs installation
Very usefull library SelniumTools
And I faced with problem:
The SelniumTools based on adf-richclient-automation-11.jar which is distributed with JDeveloper (use can find it in *Oracle_Home\oracle_common\modules\oracle.adf.view* folder) and described in docs as Oracle Customized Selenium.
And everything works fine with selenium-java library up to 2.53.1 version.
But when I upgrade selenium-java library to 3.3.1 version my test project fall with exception:
org.openqa.selenium.WebDriverException: java.lang.NoSuchMethodError: org.openqa.selenium.support.ui.**WebDriverWait.until(Lcom/google/common/base/Function;)Ljava/lang/Object;** Build info: version: 'unknown', revision: '5234b32', time: '2017-03-10 09:00:17 -0800' System info: host: 'EE-LATITUDE-749', ip: '10.10.207.64', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_172' Driver info: driver.version: unknown
com.redheap.selenium.junit.PageProvider.createPage(PageProvider.java:49)
com.redheap.selenium.junit.PageProvider.goHome(PageProvider.java:36)
ru.russvet.selenium.tests.P6_ProcessPageTest.(P6_ProcessPageTest.java:38)
java.lang.reflect.Constructor.newInstance(Constructor.java:423)
Caused by: java.lang.NoSuchMethodError: org.openqa.selenium.support.ui.WebDriverWait.until(Lcom/google/common/base/Function;)Ljava/lang/Object;
oracle.adf.view.rich.automation.selenium.RichWebDrivers.waitForServer(RichWebDrivers.java:112)
oracle.adf.view.rich.automation.selenium.RichWebDrivers.waitForRichPageToLoad(RichWebDrivers.java:175)
oracle.adf.view.rich.automation.selenium.RichWebDrivers.waitForRichPageToLoad(RichWebDrivers.java:158)
com.redheap.selenium.page.Page.(Page.java:53)
com.redheap.selenium.page.Page.(Page.java:45)
ru.russvet.selenium.pages.BPMWorkspaceLoginPage.(BPMWorkspaceLoginPage.java:19)
com.redheap.selenium.junit.PageProvider.createPage(PageProvider.java:47)
Investigations follow to the reason:
1) in selenium-java library starting from 3.3.1 interface for until function has been changed and accept Function, Predicate или Supplier classes from Java 8 library instead of Guava library https://github.com/SeleniumHQ/selenium/commit/b2aa9fd534f7afbcba319231bb4bce85f825ef09 :
-import com.google.common.base.Function;
-import com.google.common.base.Predicate;
-import com.google.common.base.Supplier;
+import java.util.function.Function;
+import java.util.function.Predicate;
+import java.util.function.Supplier;
2) what could be probably worked around with recent guava release (21+ version), where the Google versions of both Function and Predicate extend the Java 8 equivalents
So, it is look like that adf-richclient-automation-11.jar is built with selenium-java library 2.x, and that causes the exception during running the tests.
We raised it via Oracle support, but there is no information from them about new version for this library yet.
So, my questions are:
1) what is possible way to rebuild the adf-richclient-automation-11.jar to make it compatible with the latest version of selenium-java as 3.x?
2) Has anybody found newer version of adf-richclient-automation-11.jar in maybe some specific distribution of JDeveloper?
I was once upon a time part of the small team within Oracle that built the automation library you are referring to.
The issue here is API compatibility and unless the ADF automation library is repackaged against WebDriver 3.x and redistributed by Oracle OTN, you have no options but to stick to using Selenium 2.x libraries. WebDriver 3.x is meant for Java 8, which would be one more reason Oracle would want to soon upgrade to 3.x. Have you raised your concerns via OTN forums or Oracle support?
Well, answer myself. The only way for now to make this works were decompiling adf-richclient-automation-11.jar, clean and repackage it against WebDriver 3.x.
The corresponding Eclipse project is here https://github.com/EgorBEremeev/adf-richclient-automation-selenium-3-rebuild
This project does not contains test classes as original lib. I didn't run any tests from the original lib because I have no idea of required test environment for that.
So, I tested the repackaged library directly in my main project.
How ever the complete steps to get sources, clean it, fix errors and repackage library you can find in readme.md in the git repository and as well below:
Full Steps to manualy rebuilt adf-richclient-automation-11.jar:
Environment
Install Eclipse
Install Decompiler pluging
Help -> Marketplace -> Enhanced Class Decompiler
Windows -> Preferences -> Java -> Decompiler -> Default Class Decompiler: CFR -> Applay and Close
Set User Libraries
Windows -> Preferences -> Java -> Build Path -> User Libraries
New->
Name -> selenium-java-3.3.1
Add External JARs... ->
path\to\selenium-java-3.3.1\
client-combined-3.3.1-nodeps.jar
lib\*.jar
->Finish
New->
Name -> adf-richclient-automation-11.jar
Add External JARs... ->
path\to\Oracle_Home\oracle_common\modules\oracle.adf.view\
adf-richclient-automation-11.jar
->Finish
-> Applay and Close
Steps
Create Java Project
Eclipse -> New -> Java Project
Name -> project_name
JDK -> 1.8
Build Path -> Libraries -> Add Library -> User Library -> Next
User Libraries ...
selenium-java-3.3.1
adf-richclient-automation-11.jar
Decompile adf-richclient-automation-11.jar
Project Explorer -> adf-richclient-automation-11.jar -> Context Menu -> Export Sources
path\to\project_name\src\
adf-richclient-automation-11-src.zip
Project Explorer -> Refresh
src -> adf-richclient-automation-11-src.zip
Extract decompiled sources into path\to\project_name\src\
Check the src
Project Explorer -> Refresh
src -> adf-richclient-automation-11-src.zip
* oracle.adf.view.rich.automation.selenium
* oracle.adf.view.rich.automation.test
oracle.adf.view.rich.automation.test.browserfactory
* oracle.adf.view.rich.automation.test.component
* oracle.adf.view.rich.automation.test.selenium
org.openqa.selenium
org.openqa.selenium.firefox
5.1 Delete classes used for and with Selenium RC:
path/to/project_name/src/
oracle/adf/view/rich/automation/selenium/RichSelenium.java -> Delete
5.2 Delete packages oracle.adf.view.rich.automation.test.* -> Delete
oracle.adf.view.rich.automation.test
oracle.adf.view.rich.automation.test.browserfactory
oracle.adf.view.rich.automation.test.component
oracle.adf.view.rich.automation.test.selenium
Fix errors:
path/to/project_name/src/oracle/adf/view/rich/automation/selenium/RichWebDrivers.java
[] 241 Type mismatch: cannot convert from element type Object to String ->
fix 239 -> List<String> logs = (List) jsExecutor.executeScript(_GET_AND_CLEAR_LOG_MESSAGES_JS,
=
List<String> logs = (List) jsExecutor.executeScript(_GET_AND_CLEAR_LOG_MESSAGES_JS,
new Object[]{logLevel.toString().toUpperCase()});
for (String s : logs) {
sbf.append(s).append(_NEW_LINE);
}
[] 321 Type mismatch: cannot convert from element type Object to String ->
fix 320 -> Set<String> handles = webDriver.getWindowHandles();
=
public String apply(WebDriver webDriver) {
Set<String> handles = webDriver.getWindowHandles();
for (String handle : handles) {
if (openWindowHandles.contains(handle))
continue;
return handle;
}
return null;
}
Build and Export into jar
remove -> path\to\project_name\src\adf-richclient-automation-11-src.zip
Project Explorer -> Export -> Java -> JAR file -> Next
select src folder only
check Export generated classes and resources
uncheck .classpath, .project
-> Finish -> Ok in warning dialog
Optional fix error in classes from oracle.adf.view.rich.automation.test.* packages.
path/to/project_name/src/oracle/adf/view/rich/automation/test/selenium/WebDriverManager.java
[] 87 Type mismatch: cannot convert from element type Object to String ->
fix 85 Set<String> windowHandles = webDriver.getWindowHandles();
=
try {
Set<String> windowHandles = webDriver.getWindowHandles();
_LOG.fine("try to close all windows... ");
for (String handle : windowHandles) {
path/to/project_name/src/oracle/adf/view/rich/automation/test/selenium/RichWebDriverTest.java
[] 953 Syntax error on token "finally", delete this token ->
fix -> delete 956,952,949, 941
=
protected void refresh() {
_LOG.fine("Executing refresh()");
this.getWebDriver().navigate().refresh();
try {
Alert alert = this.getWebDriver().switchTo().alert();
if (alert != null) {
alert.accept();
};
}
catch (WebDriverException alert) {}
finally {
this.waitForPage();
}
}
[] 1026 Unreachable catch block for Exception. It is already handled by the catch block for Throwable ->
fix -> replace whole method by variant of Jad Decompiler->
-> Windows -> Preferences -> Java -> Decompiler -> Default Class Decompiler: Jad -> Applay and Close
-> fix 1020, 1028 Duplicate local variable cachingEnabled ->
fix-> delete
-> 1019 String msg;
-> 1018 boolean cachingEnabled;
=
protected void onShutdownBrowser() {
_LOG.finest("Shutting down browser");
try {
_logSeleniumBrowserLogAndResetLoggerLevel();
} catch (Exception e) {
boolean cachingEnabled;
String msg;
_LOG.warning("The page did not generate any logs.");
} finally {
boolean cachingEnabled = isBrowserCachingEnabled();
try {
if (cachingEnabled) {
getWebDriverManager().releaseInstance();
} else {
getWebDriverManager().destroyInstance();
}
} catch (Throwable t) {
String msg = cachingEnabled
? "Failed to release the browser. Error message: %s"
: "Failed to shutdown the browser. Error message: %s";
_LOG.severe(String.format(msg, new Object[]{t.getMessage()}));
}
}
}
[] 1047 Type mismatch: cannot convert from element type Object to WebElement ->
fix 1046 List<WebElement> allOptions = element.findElements(By.xpath((String) builder.toString()));
=
List<WebElement> allOptions = element.findElements(By.xpath((String) builder.toString()));
for (WebElement option : allOptions) {
path/to/project_name/src/oracle/adf/view/rich/automation/test/UrlFactories.java
[] 34 Type mismatch: cannot convert from UrlFactory to UrlFactories.UrlFactoryImpl ->
fix Add cast to 'UrlFactoryImpl'
=
factory = (UrlFactoryImpl) urlFactoryIterator.next();
[] 52 Type mismatch: cannot convert from UrlFactory to UrlFactories.UrlFactoryImpl
fix Add cast to 'UrlFactoryImpl'
=
UrlFactoryImpl urlFactoryImpl = (UrlFactoryImpl) (_INSTANCE = factory != null ? factory : new UrlFactoryImpl());

Whether selenium Standalone server 2.53 support fire fox browser 49.0 version? If not means what is the solutions

Whether selenium Standalone server 2.53 support fire fox browser 49.0 version? If not means what is the solutions
Yes, 2.53.0 supports FF 49.0.
You can download geckodriver from the link
https://github.com/mozilla/geckodriver/releases
Then save the file in your local system. unzip the file and change the application name as "wires.exe".
Then specify the path upto wires.exe in the code.
add selenium-2.53.0 jar files.
Try below code to start working on FF 47.0 or above.
package com.marionette.programs;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.MarionetteDriver;
public class HandleLatestFirefox {
public static void main(String[] args) {
String currentDir = System.getProperty("user.dir");
System.out.println(currentDir);
//String marionetteDriverLocation = currentDir + "G:\\ravik\\Ravi-Training\\Selenium\\Marionette for firefox\\wires.exe";
System.setProperty("webdriver.gecko.driver", "G:\\ravik\\Ravi-Training\\Selenium\\Marionette for firefox\\wires.exe");
WebDriver driver = new MarionetteDriver();
driver.get("https://www.google.co.in/webhp?hl=en&sa=X&ved=0ahUKEwjdgc21jJHOAhVCvY8KHZ4aCdcQPAgD");
System.out.println("marionette working fine....");
}
}
I referred to this example. This may help you.
http://howtoselenium.blogspot.ca/2016/08/this-is-how-to-use-selenium-geckodriver.html

Resources