Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set environment variables for Selenium Java FirefoxDriver?

From within Java unit tests, I want to use Selenium to test my web page with Firefox. My tests require that I set an environment variable for Firefox. (Specifically, I want to set the DISPLAY variable.)

The FirefoxBinary class has a method setEnvironmentProperty, which sounds like it should set environment variables for the environment the Firefox process runs in, but in practice it does not have that effect. (I have confirmed that with cat /proc/<firefox_pid>/environ.)

Back with selenium-java 3.0.1, I could build a GeckoDriverService with custom environment variables, and the FirefoxDriver constructor accepted the driver service as an argument, like so:

Map<String, String> customEnvironmentMap = new HashMap<>();
customEnvironmentMap.put("DISPLAY", ":1");
GeckoDriverService driverService = new GeckoDriverService.Builder(binary)
        .withEnvironment(customEnvironmentMap)
        .usingPort(0)
        .build()
FirefoxDriver driver = new FirefoxDriver(driverService, capabilities, null);

The custom variables would be present in the environment of the geckodriver process and the environment of the Firefox process.

That constructor is not present in version 3.4.0, and FirefoxDriver uses a private method to create the driver service, so I can't customize it. So, how do I configure the environment of the Firefox process that Selenium launches?

My current workaround is to substitute a script like this one for the geckodriver executable path:

#!/bin/bash
exec /usr/bin/env DISPLAY=:1 /path/to/geckodriver $@

I don't really like this technique, for various reasons (it's hacky, I have to create a temp file for the script in the filesystem, etc.).

like image 636
user4851 Avatar asked Oct 17 '25 16:10

user4851


1 Answers

As of Selenium 3.7.1, the constructor that takes a GeckoDriverService has returned, so you can once again do the following:

Map<String, String> environment = new HashMap<>();
environment.put("DISPLAY", ":1");
GeckoDriverService service = new GeckoDriverService.Builder()
        .usingAnyFreePort()
        .withEnvironment(environment)
        .build();
FirefoxDriver driver = new FirefoxDriver(service);
like image 114
user4851 Avatar answered Oct 19 '25 06:10

user4851



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!