Im trying to set up selenium tests using zap, the webdriver should be firefox and the port 8080. But when it opens up the port is always a different number.
This is the test below, I dont know how o open the browser under the port 8080 anfd firefox browser, the browser does actually open but nothing appears.
public class Sport {
WebDriver driver;
final static String BASE_URL = "https://web-test.com/";
final static String USERNAME = "test#hotmail.com";
final static String PASSWORD = "tables";
public Sport(WebDriver driver) {
this.driver = driver;
this.driver.manage().timeouts().pageLoadTimeout(5, TimeUnit.SECONDS);
this.driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
}
public void login()throws Exception {
driver.get(BASE_URL);
Header header = new Header();
header.guest_select_login();
Pages.Login login = new Pages.Login();
login.login_with_empty_fields();
login.login_with_invalid_email();
login.email_or_password_incorrect();
login.login_open_and_close();
}
The Client zap api is working and starting it seems but the browser doesnt seem to open correctly to port 8080
public class ZapScanTest {
static Logger log = Logger.getLogger(ZapScanTest.class.getName());
private final static String ZAP_PROXYHOST = "127.0.0.1";
private final static int ZAP_PROXYPORT = 8080;
private final static String ZAP_APIKEY = null;
// Change this to the appropriate driver for the OS, alternatives in the
drivers directory
private final static String FIREFOX_DRIVER_PATH = "drivers/geckodriver.exe";
private final static String MEDIUM = "MEDIUM";
private final static String HIGH = "HIGH";
private ScanningProxy zapScanner;
private Spider zapSpider;
private WebDriver driver;
private Sportdec myApp;
private final static String[] policyNames = {"directory-browsing","cross-
site-scripting","sql-injection","path-traversal","remote-file-
inclusion","server-side-include",
"script-active-scan-rules","server-side-code-injection","external-
redirect","crlf-injection"};
int currentScanID;
#Before
public void setup() {
zapScanner = new ZAProxyScanner(ZAP_PROXYHOST,ZAP_PROXYPORT,ZAP_APIKEY);
zapScanner.clear(); //Start a new session
zapSpider = (Spider)zapScanner;
log.info("Created client to ZAP API");
driver = DriverFactory.createProxyDriver ("firefox",createZapProxyConfigurationForWebDriver(), FIREFOX_DRIVER_PATH);
myApp = new Sportdec(driver);
//myApp.registerUser();
}
#After
public void after() {
driver.quit();
}
#Test
public void testSecurityVulnerabilitiesBeforeLogin()throws Exception {
myApp.login();
log.info("Spidering...");
spiderWithZap();
log.info("Spider done.");
setAlertAndAttackStrength();
zapScanner.setEnablePassiveScan(true);
scanWithZap();
List<Alert> alerts = filterAlerts(zapScanner.getAlerts());
logAlerts(alerts);
assertThat(alerts.size(), equalTo(0));
}
Related
I have 3 test classes consisting of multiple test methods that I want to run in parallel. I'm using ThreadLocal for isolating webdriver instances per thread. When I run the tests in sequential manner everything looks fine but problem arises when I run them in parallel. Below is my suite file
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="platform" parallel="classes" thread-count="5">
<test name="platform">
<classes>
<class name="com.sat.platform.mobile.PlatformMobileIdCaptureMonitoringWf11"></class>
<class name="com.sat.platform.mobile.PlatformMobileIdVerificationMonitoringWf2"></class>
<class name="com.sat.platform.mobile.PlatformMobileIdandIVMonitoringWf3"></class>
<class name="com.sat.platform.mobile.PlatformMobileLivenessMonitoringWf6"></class>
<class name="com.sat.platform.mixed.PlatformMixedIdSimilarityMonitoringWf2and5"></class>
</classes>
</test>
</suite>
I'm initializing Webdriver in #BeforeClass in BrowserClient.java as below.
protected WebDriver driver;
private static int implicitWaitTime;
private static int explicitWaitTime;
private static int fluentWaitTime;
private static int pollingTime;
protected static WebDriverWait explicitWait;
protected static Wait<WebDriver> fluentWait;
private static String browser;
protected static Browsers browsers;
static {
Properties prop = new Properties();
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream stream = loader.getResourceAsStream("browser.properties");
try {
prop.load(stream);
} catch (IOException e) {
}
implicitWaitTime = Integer.parseInt(prop.getProperty("browser.implicit.wait.timeout"));
explicitWaitTime = Integer.parseInt(prop.getProperty("browser.explicit.wait.timeout"));
fluentWaitTime = Integer.parseInt(prop.getProperty("browser.fluent.wait.timeout"));
pollingTime = Integer.parseInt(prop.getProperty("browser.wait.polling.time"));
browser = System.getProperty("browser");
}
#BeforeClass
public void initializeEnv() throws MalformedURLException {
driver = BrowserFactory.createInstance(browser, implicitWaitTime);
DriverFactory.getInstance().setDriver(driver);
driver = DriverFactory.getInstance().getDriver();
explicitWait = new WebDriverWait(driver, explicitWaitTime);
fluentWait = new FluentWait(driver).withTimeout(Duration.of(fluentWaitTime, SECONDS))
.pollingEvery(Duration.of(pollingTime, SECONDS))
.ignoring(NoSuchElementException.class);
}
the used class here i.e BrowserFactory.java
public static WebDriver createInstance(String browser, int implicitWaitTime) throws MalformedURLException {
WebDriver driver = null;
Browsers browserEnum = Browsers.valueOf(browser);
String testVideo = ImageProcessingUtils.getAbsolutePath("digital_copy.mjpeg", false);
switch (browserEnum) {
case chrome:
ChromeOptions options = new ChromeOptions();
options.addArguments("--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream",
"--use-file-for-fake-video-capture=" + testVideo, "--start-maximized");
driver = new ChromeDriver(options);
break;
case firefox:
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("media.navigator.permission.disabled", true);
firefoxProfile.setPreference("media.navigator.streams.fake", true);
firefoxProfile .setPreference("browser.private.browsing.autostart", false);
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setProfile(firefoxProfile);
driver = new FirefoxDriver(firefoxOptions);
break;
}
}
DriverFactory.java
public class DriverFactory {
private static DriverFactory instance = new DriverFactory();
private static ThreadLocal<WebDriver> driver = new ThreadLocal<>();
private static List<WebDriver> driversList = new ArrayList();
private DriverFactory(){
}
public static DriverFactory getInstance() {
return instance;
}
public WebDriver getDriver(){
WebDriver localDriver = driver.get();
driversList.add(localDriver);
return localDriver;
}
public void setDriver(WebDriver driver){
this.driver.set(driver);
}
public static void removeDriver(){
for(WebDriver driver : driversList) {
driver.quit();
}
}
}
And my test classes extends BrowserClient.java where i can use the driver directly. One of the common method in all 3 test classes is merchant_gets_oauth_token() as shown below. The problem is when test suite is run, 3 firefox browsers are open in parallel and all of them navigates to the login page but only 1 and sometimes 2 of the tests passes while the 3rd one fails (unable to login).
#Test
public void merchant_gets_oauth_token() {
OAuth2Client client = new OAuth2Client();
String loginUrl = DslConfigFactory.getEnvConfig("portal.customer.url");
driver.get(loginUrl);
CustomerPortalLoginPage loginPage = new CustomerPortalLoginPage(driver);
log.info("----------merchant logging to customer portal to get oauth token----------");
loginPage.login(merchantUser.getEmail(), merchantUser.getPassword());
CustomerPortalHomePage homePage = new CustomerPortalHomePage(driver);
homePage.clickOnSettings();
CustomerPortalSettingsPage settingsPage = new CustomerPortalSettingsPage(driver);
settingsPage.clickOnApiCredentials();
CustomerPortalApiCredentialsPage apiCredentialsPage = new CustomerPortalApiCredentialsPage(driver);
clientCredentials = apiCredentialsPage.getOauth2ClientCredentials();
oauthToken = client.getOauthToken(clientCredentials.get("token"), clientCredentials.get("secret"));
}
I have been struggling with this problem for a while and had looked up lot of online resources without help. Maybe somebody here is able to do the RCA. Thanks in Advance!!
public static void removeDriver(){
for(WebDriver driver : driversList) {
driver.quit();
}
}
Here, replace driver.quit() with driver.close().
driver.close() method it will close only current driver. driver.close() closes all drivers.
When first instance executes removeDriver(), it will closes all windows/drivers. Then next instance try to execute removeDriver(),there driver is not available because it is already closed by previous instance of driver.so you get error.
Im trying to open a page using java and selenium on port 8080. Ive tried using the page and :8080 but the page continually keeps opening on a different port. Im basically trying to use zap and it configured to use firefox on port 8080. ANy help appreciated. Ive added my test and my class thats added to the test below, i think somewhere int he driver part it must call a different port but i cant see how this is happening
Test:
public class ZapScanTest {
static Logger log = Logger.getLogger(ZapScanTest.class.getName());
private final static String ZAP_PROXYHOST = "127.0.0.1";
private final static int ZAP_PROXYPORT = 8080;
private final static String ZAP_APIKEY = null;
// Change this to the appropriate driver for the OS, alternatives in the
drivers directory
private final static String FIREFOX_DRIVER_PATH =
"drivers/geckodriver.exe";
private final static String MEDIUM = "MEDIUM";
private final static String HIGH = "HIGH";
private ScanningProxy zapScanner;
private Spider zapSpider;
private WebDriver driver;
private Dec myApp;
private final static String[] policyNames = {"directory-browsing","cross-
site-scripting","sql-injection","path-traversal","remote-file-
inclusion","server-side-include",
"script-active-scan-rules","server-side-code-injection","external-
redirect","crlf-injection"};
int currentScanID;
#Before
public void setup() {
zapScanner = new
ZAProxyScanner(ZAP_PROXYHOST,ZAP_PROXYPORT,ZAP_APIKEY);
zapScanner.clear(); //Start a new session
zapSpider = (Spider)zapScanner;
log.info("Created client to ZAP API");
driver = DriverFactory. createProxyDriver("firefox",createZapProxyConfigurationForWebDriver(), FIREFOX_DRIVER_PATH);
myApp = new Dec(driver);
//myApp.registerUser(); //Doesn't matter if user already exists, bodgeit just throws an error
}
#After
public void after() {
driver.quit();
}
#Test
public void testSecurityVulnerabilitiesBeforeLogin()throws Exception {
myApp.login();
log.info("Spidering...");
spiderWithZap();
log.info("Spider done.");
setAlertAndAttackStrength();
zapScanner.setEnablePassiveScan(true);
scanWithZap();
List<Alert> alerts = filterAlerts(zapScanner.getAlerts());
logAlerts(alerts);
assertThat(alerts.size(), equalTo(0));
}
Dec class:
public class Sportdec {
WebDriver driver;
final static String BASE_URL = "https://web-game-stage.dec.com/games:8080";
final static String USERNAME = "dec2009#hotmail.com";
final static String PASSWORD = "tables";
public Dec(WebDriver driver) {
this.driver = driver;
this.driver.manage().timeouts().pageLoadTimeout(5, TimeUnit.SECONDS);
this.driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
}
public void login()throws Exception {
driver.get(BASE_URL);
Header header = new Header();
header.guest_select_login();
Pages.Login login = new Pages.Login();
login.login_with_empty_fields();
login.login_with_invalid_email();
login.email_or_password_incorrect();
login.login_open_and_close();
}
By any chance have you tried using this
final static String BASE_URL = "https://web-game-stage.dec.com:8080/games";
instead of this
final static String BASE_URL = "https://web-game-stage.dec.com/games:8080";
You are adding port number to the games directory instead of the host
I need some help to figure out the problem while cross-browser selenium java test execution through the Saucelabs. I'm running one test over 2 browsers selected from the Jenkins job.
While the execution one test is passed another one (the similar) is getting failure with the error: 504 Gateway Time-out. The server didn't respond in time.
So it's unable to move into the next step.
It seems like one test interrupts another. Both tests are running under their own tunnel and thread.
Aug 30, 2018 7:17:44 AM org.openqa.selenium.remote.ProtocolHandshake
createSession
INFO: Detected dialect: OSS
30-08-2018 07:17:49.235 [TestNG-PoolService-0] INFO
[com.***.tests.TestBase_Local:96] - Open a site URLDriver: RemoteWebDriver:
chrome on XP (4f5a5d685f4c44c9a5864e91cb8f11e9)
Driver: RemoteWebDriver: chrome on XP (4f5a5d685f4c44c9a5864e91cb8f11e9)
thread id:14 Timestamp :2018-08-30T07:17:49.370
30-08-2018 07:17:51.912 [TestNG-PoolService-0] INFO
[com.**.tests.TestBase_Local:35] - Select 'No thanks' on the popup
Aug 30, 2018 7:17:53 AM org.openqa.selenium.remote.ProtocolHandshake
createSession
INFO: Detected dialect: OSS
30-08-2018 07:17:58.886 [TestNG-PoolService-1] INFO
[com.**.tests.TestBase_Local:96] - Open a site URLDriver:
RemoteWebDriver: MicrosoftEdge on ANY (c6978c03531d408485588ba501ff0589)
Driver: RemoteWebDriver: MicrosoftEdge on ANY
(c6978c03531d408485588ba501ff0589)
thread id:15 Timestamp :2018-08-30T07:17:58.887
30-08-2018 07:18:03.406 [TestNG-PoolService-1] INFO
[com.**.tests.TestBase_Local:35] - Select 'No thanks' on the popup
30-08-2018 07:18:05.337 [TestNG-PoolService-1] INFO
[com.**.tests.TestBase_Local:38] - Search by input
Sharing the code:
public class Search extends RemoteTestBase {
#Test(dataProvider = "browsers")
public void SolrSearchTest(String browser, String version, String os, Method method) throws Exception {
this.createRemoteDriver(browser, version, os, method.getName());
System.out.println("Driver: " + driver.toString());
Application app = new Application(driver);
ConfigFileReader configRead = new ConfigFileReader();
WebDriverWait wait = new WebDriverWait(driver,100);
app.homePage().SelectNoThanks();
Log.info("Select 'No thanks' on the popup");
app.searchField().SearchBy(configRead.SearchInput());
Log.info("Search by input");
}
}
The extended RemoteTestBase class:
public class RemoteTestBase {
public WebDriver driver;
private static String baseUrl;
RandomDataSelect randomuser;
private PropertyLoader propertyRead;
public Logger Log = Logger.getLogger(TestBase_Local.class.getName());
private static final String SAUCE_ACCESS_KEY = System.getenv("SAUCE_ACCESS_KEY");
private static final String SAUCE_USERNAME = System.getenv("SAUCE_USERNAME");
#BeforeMethod
#DataProvider(name = "browsers", parallel = true)
public static Object[][] sauceBrowserDataProvider(Method testMethod) throws JSONException {
String browsersJSONArrayString = System.getenv("SAUCE_ONDEMAND_BROWSERS");
System.out.println(browsersJSONArrayString);
JSONArray browsersJSONArrayObj = new JSONArray(browsersJSONArrayString);
Object[][] browserObjArray = new Object[browsersJSONArrayObj.length()][3];
for (int i=0; i < browsersJSONArrayObj.length(); i++) {
JSONObject browserObj = (JSONObject)browsersJSONArrayObj.getJSONObject(i);
browserObjArray[i] = new Object[]{ browserObj.getString("browser"), browserObj.getString("browser-version"), browserObj.getString("os")};
}
return browserObjArray;
}
void createRemoteDriver(String browser, String version, String os, String methodName) throws Exception {
DesiredCapabilities capabilities = new DesiredCapabilities();
Class<? extends RemoteTestBase> SLclass = this.getClass();
capabilities.setCapability("browserName", browser);
if (version != null) {
capabilities.setCapability("browser-version", version);
}
capabilities.setCapability("platform", os);
capabilities.setCapability("name", SLclass.getSimpleName());
capabilities.setCapability("tunnelIdentifier", "***");
driver = (new RemoteWebDriver(new URL("http://" + SAUCE_USERNAME + ":" + SAUCE_ACCESS_KEY + "#ondemand.saucelabs.com:80/wd/hub"), capabilities));
randomuser = new RandomDataSelect();
propertyRead = new PropertyLoader();
baseUrl = propertyRead.getProperty("site.url");
getURL();
}
private void getURL () {
driver.get(baseUrl);
driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
this.annotate("Visiting HDSupply page..." + driver.toString());
Log.info("Open a site URL" + "Driver: " + driver.toString());
}
private void printSessionId() {
String message = String.format("SauceOnDemandSessionID=%1$s job-name=%2$s",(((RemoteWebDriver) driver).getSessionId()).toString(), "some job name");
System.out.println(message);
}
#AfterMethod(description = "Throw the test execution results into saucelabs")
public void tearDown(ITestResult result) throws Exception {
((JavascriptExecutor) driver).executeScript("sauce:job-result=" + (result.isSuccess() ? "passed" : "failed"));
printSessionId();
driver.quit();
}
void annotate(String text) {
((JavascriptExecutor) driver).executeScript("sauce:context=" + text);
}
}
The suite.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Tests Suite" verbose="4" parallel="tests" data-provider-thread-count="2">
<test name="AllTests" parallel="methods">
<classes>
<class name="com.***.tests.Search"/>
</classes>
</test>
</suite>
Project info: java, selenium, testng, maven, saucelabs, jenkins
The problem lies in your test code. Its definitely related to race condition between your #Test methods [ you have your parallel="true" in your #DataProvider annotation and parallel="methods" ]
You need to refactor your code such that your driver object is thread safe.
Some of the ways in which you can do it is using :
ThreadLocal variants of WebDriver.
Create your webdriver instance and inject that as an attribute into the ITestResult object.
The below sample shows how to use a ThreadLocal variant to make your code thread-safe
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
public class RemoteTestBase {
public static final ThreadLocal<RemoteWebDriver> driver = new ThreadLocal<>();
private static String baseUrl;
private static final String SAUCE_ACCESS_KEY = System.getenv("SAUCE_ACCESS_KEY");
private static final String SAUCE_USERNAME = System.getenv("SAUCE_USERNAME");
void createRemoteDriver(String browser, String version, String os, String methodName)
throws Exception {
DesiredCapabilities capabilities = new DesiredCapabilities();
Class<? extends RemoteTestBase> SLclass = this.getClass();
capabilities.setCapability("browserName", browser);
if (version != null) {
capabilities.setCapability("browser-version", version);
}
capabilities.setCapability("platform", os);
capabilities.setCapability("name", SLclass.getSimpleName());
capabilities.setCapability("tunnelIdentifier", "***");
URL url = new URL(
"http://" +
SAUCE_USERNAME + ":" +
SAUCE_ACCESS_KEY + "#ondemand.saucelabs.com:80/wd/hub");
RemoteWebDriver rwd = new RemoteWebDriver(url, capabilities);
driver.set(rwd);
getURL();
}
protected static RemoteWebDriver getDriver() {
return driver.get();
}
private void getURL() {
getDriver().get(baseUrl);
getDriver().manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
this.annotate("Visiting HDSupply page..." + driver.toString());
}
private void printSessionId() {
String message = String.format("SauceOnDemandSessionID=%1$s job-name=%2$s",
getDriver().getSessionId(), "some job name");
System.out.println(message);
}
#AfterMethod(description = "Throw the test execution results into saucelabs")
public void tearDown(ITestResult result) {
String txt = "sauce:job-result=" + (result.isSuccess() ? "passed" : "failed");
getDriver().executeScript(txt);
printSessionId();
getDriver().quit();
}
void annotate(String text) {
getDriver().executeScript("sauce:context=" + text);
}
}
All your sub-classes would try to access the RemoteWebDriver object via getDriver() method.
The caveat is that your #BeforeMethod needs to call createRemoteDriver() so that the RemoteWebDriver object gets instantiated and pushed into the ThreadLocal context which will be valid and be accessible within a #Test method.
The rule is always #BeforeMethod (driver instantiation happens) > #Test (driver gets consumed > #AfterMethod (driver cleanup should happen). This is the only combo wherein a RemoteWebDriver object is valid within a ThreadLocal context.
I have written some code to automate a certain task I want to perform and it works fine on my computer. Since this task has to be executed every hour, I am running it on my VPS (Amazon).
But running the code on my VPS gives me most of the times errors that I can't reproduce on my own computer. On my own computer I can run it as many time as I want and every time it works correctly.
Can anyone think of a possible reason why this is happening?
My code is:
public final class Test {
// XPath elements
private static final String USERNAME_FIELD = "//*[#id=\"username\"]";
private static final String PASSWORD_FIELD = "//*[#id=\"password\"]";
private static final String SIGN_IN_BUTTON = "//*[#id=\"loginForm\"]/fieldset[2]/button";
private static final String RUN_TEST_BUTTON = "/html/body/div[1]/div/header/div/div/button/span";
// User credentials
private static final String USERNAME = "my-username";
private static final String PASSWORD = "my-password";
// TestObject URL's
private static final String LOGIN_URL = "url";
private static final String RUN_TEST_URL = "my-test-url;
private static final int TIME_OUT = 10000;
public static void main(String[] args) throws IOException {
java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);
System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog");
try (final WebClient client = new WebClient(BrowserVersion.CHROME)) {
client.setAjaxController(new NicelyResynchronizingAjaxController());
client.setCssErrorHandler(new SilentCssErrorHandler());
client.getOptions().setCssEnabled(true);
client.getOptions().setRedirectEnabled(true);
client.getOptions().setAppletEnabled(false);
client.getOptions().setJavaScriptEnabled(true);
client.getOptions().setPopupBlockerEnabled(true);
client.getOptions().setTimeout(TIME_OUT);
client.getOptions().setThrowExceptionOnFailingStatusCode(false);
client.getOptions().setThrowExceptionOnScriptError(false);
client.getOptions().setPrintContentOnFailingStatusCode(true);
//client.setHTMLParserListener(HTMLParserListener.LOG_REPORTER);
client.waitForBackgroundJavaScript(TIME_OUT/2);
HtmlPage page = client.getPage(LOGIN_URL);
HtmlTextInput user = (HtmlTextInput) page.getByXPath(USERNAME_FIELD).get(0);
HtmlPasswordInput pass = (HtmlPasswordInput) page.getByXPath(PASSWORD_FIELD).get(0);
HtmlButton login = (HtmlButton) page.getByXPath(SIGN_IN_BUTTON).get(0);
user.setValueAttribute(USERNAME);
pass.setValueAttribute(PASSWORD);
page = login.click();
page = client.getPage(RUN_TEST_URL);
HtmlSpan runTest = (HtmlSpan) page.getByXPath(RUN_TEST_BUTTON).get(0); // this is the place where it gives an "out-of-bound exception"
page = runTest.click();
client.close();
}
}
}
Error:
net.sourceforge.htmlunit.corejs.javascript.Undefined#2c543bc5
Exception in thread "main"
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at eu.theappfactory.testobject.driver.TestObjectDriver.main(TestObjectDriver.java:71)
I'm trying to get an item from local storage using Selenium Webdriver.
I followed this site but when I run my code I get NullPointerException.
When I debug the code I see the function: getItemFromLocalStorage returns NULL for some reason.
Here is my code:
public class storage
{
public static WebDriver driver;
public static JavascriptExecutor js;
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver", "D://chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://html5demos.com/storage");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.id("local")).sendKeys("myLocal");
driver.findElement(By.id("session")).sendKeys("mySession");
driver.findElement(By.tagName("code")).click(); // just to escape textbox
String sItem = getItemFromLocalStorage("value");
System.out.println(sItem);
}
public static String getItemFromLocalStorage(String key)
{
return (String) js.executeScript(String.format(
"return window.localStorage.getItem('%s');", key));
}
}
That is because you forgot to instantiate js object correctly. Add below line after driver = new ChromeDriver();.
js = ((JavascriptExecutor)driver);
It will work.
I assume you have NPE on your driver instance.
You can setup driver location property while driver instance creating:
final ChromeDriverService chromeDriverService = new ChromeDriverService.Builder()
.usingDriverExecutable(new File("D://chromedriver.exe")).build();
driver = new ChromeDriver(chromeDriverService);
BTW, I used selenium 2.44.0
Use this Code
WebStorage webStorage = (WebStorage) new Augmenter().augment(driver);
LocalStorage localStorage = webStorage.getLocalStorage();
String user_data_remember = localStorage.getItem("user_data_remember");
String emailAfterLogout;
String passwordAfterLogout;
if (!user_data_remember.equals("")) {
JSONObject jsonObject = new JSONObject(user_data_remember);
Boolean remember = jsonObject.getBoolean("remember");
if (remember) {
emailAfterLogout = jsonObject.getString("email");
passwordAfterLogout = jsonObject.getString("password");
if (emailAfterLogout.equals(email) && passwordAfterLogout.equals(password)) {
System.out.println("Remember me is working properly.");
} else {
System.out.println("Remember me is not working.");
}
}
} else {
System.out.println("Remember me checkbox is not clicked.");
}