I'm encountering the below error while trying to set Request headers using browsermobproxy for selenium tests.
Exception in thread "main" org.openqa.selenium.WebDriverException: : Failed to read the 'localStorage' property from 'Window': Access is denied for this document.
Build info: version: '3.13.0', revision: '2f0d292', time: '2018-06-25T15:24:21.231Z'
System info: host: 'G9HQBVT2E', ip: '10.62.6.122', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_271'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 87.0.4280.141, chrome: {chromedriverVersion: 87.0.4280.20 (c99e81631faa0..., userDataDir: C:\Users\abc\AppData\...}, goog:chromeOptions: {debuggerAddress: localhost:64062}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(manual, http=G9HQBVT2..., setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:virtualAuthenticators: true}
Session ID: 73d6ecf19b420b0bc368f2bc3d5f78b1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:548)
at org.openqa.selenium.remote.RemoteWebDriver.executeScript(RemoteWebDriver.java:485)
at com.sample.test.DataReader.main(DataReader.java:79)
Driver program
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "C:\\Try\\drivers\\chromedriver.exe"); //PropertyReader.getProperty("chromedriverpath")
// start the proxy
BrowserMobProxy proxy = new BrowserMobProxyServer();
proxy.setTrustAllServers(true);
proxy.start(0);
// get the Selenium proxy object
Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
String chromeProfilePath = "C:\\Users\\AppData\\Local\\Google\\Chrome\\User Data\\Default";
//capabilities
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-web-security");
options.addArguments("--ignore-certificate-errors");
options.addArguments("--user-data-dir="+chromeProfilePath);
// configure it as a desired capability
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
//capabilities.setCapability("disable-web-security", true);
// start the browser up
WebDriver driver = new ChromeDriver(capabilities);
// enable more detailed HAR capture, if desired (see CaptureType for the complete list)
proxy.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT);
//
driver.get("chrome-extension://idgpnmonknjnojddfkpgkljpfnnfcklj/_generated_background_page.html");
String jsScript = "localStorage.setItem('profiles', JSON.stringify([{ title: 'Selenium', hideComment: true, appendMode: '', \n" +
" headers: [ \n" +
" {enabled: true, name: 'token-1', value: '{\"abc\": 1234, \"type\": \"def\"}', comment: ''}\n" +
" ], \n" +
" respHeaders: [],\n" +
" filters: []\n" +
" }]));";
((JavascriptExecutor)driver).executeScript(jsScript);
// create a new HAR with the label "yahoo.com"
proxy.newHar("localhost:4200");
// open app
driver.get("http://localhost:4200/app/");
It would be great if anyone can help me on this. Thank you.
This is because your browser privacy settings disallow javascript on the page to set up cookies (third-party cookies). You need to change them using properties.
The list of relevant properties you can find here: https://stackoverflow.com/a/48670137/8343843
How to set the property with web driver you can find here: https://stackoverflow.com/a/25090103/8343843
Related
I'm writing mobile test using Appium+UIAutomator2+Java+JUnit5.
The point is when I'm calling the code from the test everything works fine and all elements can be located. When I'm using the same code in a PO model function, one element cannot be located and the test fails. I have no idea why.
Working solution:
#Test
public void loginTest () throws InterruptedException {
WelcomeScreen welcomeScreen = new WelcomeScreen(driver);
welcomeScreen.clickLoginButton();
LoginScreen loginScreen = new LoginScreen(driver);
loginScreen.typeEmail("email#test.com");
loginScreen.clickNextButton();
PasswordScreen passwordScreen = new PasswordScreen(driver);
passwordScreen.typePassword("Password12345");
passwordScreen.clickLoginButton();
}
Failing solution (upd below, works with one condition):
#Test
public void loginTest () throws InterruptedException {
PasswordScreen passwordScreen = new PasswordScreen(driver);
passwordScreen.login("email#test.com", "Password12345");
}
UPD (Aug 20, 2022):
The order of the code execution is first to find all the declared elements, only then the tests can be executed and class objects are created.
Originally I have helper wrapper function to allocate elements, that can process exceptions (I haven't paste it here to save some space in the beginning, will add it now below).
Using this function it becomes more interesting:
Running the test it still not able to find passwordInput element, but not fail the test, since the exception is processed.
This allows to start the test. The fun part is that when the class object PasswordScreen passwordScreen is created, no problem now happen and the test can be passed.
Helper function:
public static Boolean xpathElementIsPresent(String text) {
Logger logger = Logger.getLogger("LOG:");
WebDriverWait wait = new WebDriverWait (driver, Duration.ofSeconds(5));
try {
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#text='%s']".formatted(text))));
return true;
} catch (Exception e) {
logger.log(Level.WARNING,"No element found by xpath: %s".formatted(text));
return false;
}
public static WebElement findByXpath(String text) {
WebElement element;
if (xpathElementIsPresent(text)){
element = driver.findElement(By.xpath("//*[#text='%s']".formatted(text)));
return element;
}
return null;
}
PasswordScreen class:
public class PasswordScreen extends BaseDriver {
public PasswordScreen (AndroidDriver driver) {
this.driver = driver;
}
/* private WebElement passwordInput = driver.findElement(By.xpath("//*[#text='%s']".formatted("Password")));
Using this code the original problem appears with the logs and exception provided below.
The WebElement can't be located in case of calling from passwordScreen.login(),
But works calling it from the test. login() function call from the class with tests also works */
private WebElement passwordInput = findByXpath("Password");
/* Finding element like this processes the NoSuchElementError and the test can be executed after that.
The main question now is why? */
private WebElement loginButton = findByAccessibilityId("Log in");
#Step
public void typePassword(String password) {
WebElement passwordInput = this.passwordInput;
typeText(passwordInput, password);
}
#Step
public void clickLoginButton() {
WebElement loginButton = this.loginButton;
loginButton.click();
}
#Step
public void login(String email, String password) {
WelcomeScreen welcomeScreen = new WelcomeScreen(driver);
welcomeScreen.clickLoginButton();
LoginScreen loginScreen = new LoginScreen(driver);
loginScreen.typeEmail(email);
loginScreen.clickNextButton();
PasswordScreen passwordScreen = new PasswordScreen(driver);
passwordScreen.typePassword(password);
passwordScreen.clickLoginButton();
} // ^^^ Exact the same code that was used in working solution
}
The point is that LoginScreen class has absolutely the same logic and structure and WebElement emailInput there has no errors using the same finder.
Logs:
[HTTP] {"using":"xpath","value":"//*[#text='Password']"}
[debug] [AndroidUiautomator2Driver#bda7 (7345ce7a)] Calling AppiumDriver.findElement() with args: ["xpath","//*[#text='Password']","7345ce7a-7b53-4fe3-a3f2-79ca9f4f3073"]
[debug] [AndroidUiautomator2Driver#bda7 (7345ce7a)] Valid locator strategies for this request: xpath, id, class name, accessibility id, css selector, -android uiautomator
[debug] [AndroidUiautomator2Driver#bda7 (7345ce7a)] Waiting up to 10000 ms for condition
[debug] [AndroidUiautomator2Driver#bda7 (7345ce7a)] Matched '/element' to command name 'findElement'
[debug] [AndroidUiautomator2Driver#bda7 (7345ce7a)] Proxying [POST /element] to [POST http://127.0.0.1:8200/session/c63da5b5-f741-4b68-87ca-2bd161e3b3af/element] with body: {"strategy":"xpath","selector":"//*[#text='Password']","context":"","multiple":false}
[AndroidUiautomator2Driver#bda7 (7345ce7a)] Got response with status 404: {"sessionId":"c63da5b5-f741-4b68-87ca-2bd161e3b3af","value":{"error":"no such element","message":"An element could not be located on the page using the given search parameters","stacktrace":"io.appium.uiautomator2.common.exceptions.ElementNotFoundException: An element could not be located on the page using the given search parameters\n\tat io.appium.uiautomator2.handler.FindElement.findElement(FindElement.java:90)\n\tat io.appium.uiautomator2.handler.FindElement.safeHandle(FindElement.java:67)\n\tat io.appium.uiautomator2.handler.request.SafeRequestHandler.handle(SafeRequestHandler.java:59)\n\tat io.appium.uiautomator2.server.AppiumServlet.handleRequest(AppiumServlet.java:267)\n\tat io.appium.uiautomator2.server.AppiumServlet.handleHttpRequest(AppiumServlet.java:261)\n\tat io.appium.uiautomator2.http.ServerHandler.channelRead(ServerHandler.java:68)\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:366)\n\tat io.netty.channel.AbstractChannelHandlerCont...
[debug] [W3C] Matched W3C error code 'no such element' to NoSuchElementError
Exception:
An element could not be located on the page using the given search parameters.
For documentation on this error, please visit: https://selenium.dev/exceptions/#no_such_element
Build info: version: '4.4.0', revision: 'e5c75ed026a'
System info: host: 'ip-192-168-0-13.eu-west-1.compute.internal', ip: '192.168.0.13', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '12.5', java.version: '17.0.4.1'
Driver info: io.appium.java_client.android.AndroidDriver
Command: [7345ce7a-7b53-4fe3-a3f2-79ca9f4f3073, findElement {using=xpath, value=//*[#text='Password']}]
Capabilities {appium:app: /Users/.../IdeaPro..., appium:appPackage: com.org.wallet.cordova, appium:automationName: UiAutomator2, appium:databaseEnabled: false, appium:desired: {app: /Users/.../IdeaPro..., automationName: UiAutomator2, deviceName: emulator-5554, noReset: false, platformName: android}, appium:deviceApiLevel: 30, appium:deviceManufacturer: Google, appium:deviceModel: sdk_gphone_x86, appium:deviceName: emulator-5554, appium:deviceScreenDensity: 440, appium:deviceScreenSize: 1080x2160, appium:deviceUDID: emulator-5554, appium:javascriptEnabled: true, appium:locationContextEnabled: false, appium:networkConnectionEnabled: true, appium:noReset: false, appium:pixelRatio: 2.75, appium:platformVersion: 11, appium:statBarHeight: 66, appium:takesScreenshot: true, appium:viewportRect: {height: 1962, left: 0, top: 66, width: 1080}, appium:warnings: {}, appium:webStorageEnabled: false, platformName: ANDROID}
Session ID: 7345ce7a-7b53-4fe3-a3f2-79ca9f4f3073
org.openqa.selenium.NoSuchElementException: An element could not be located on the page using the given search parameters.
For documentation on this error, please visit: https://selenium.dev/exceptions/#no_such_element
Build info: version: '4.4.0', revision: 'e5c75ed026a'
System info: host: 'ip-192-168-0-13.eu-west-1.compute.internal', ip: '192.168.0.13', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '12.5', java.version: '17.0.4.1'
Driver info: io.appium.java_client.android.AndroidDriver
Command: [7345ce7a-7b53-4fe3-a3f2-79ca9f4f3073, findElement {using=xpath, value=//*[#text='Password']}]
Capabilities {appium:app: /Users/.../IdeaPro..., appium:appPackage: com.org.wallet.cordova, appium:automationName: UiAutomator2, appium:databaseEnabled: false, appium:desired: {app: /Users/.../IdeaPro..., automationName: UiAutomator2, deviceName: emulator-5554, noReset: false, platformName: android}, appium:deviceApiLevel: 30, appium:deviceManufacturer: Google, appium:deviceModel: sdk_gphone_x86, appium:deviceName: emulator-5554, appium:deviceScreenDensity: 440, appium:deviceScreenSize: 1080x2160, appium:deviceUDID: emulator-5554, appium:javascriptEnabled: true, appium:locationContextEnabled: false, appium:networkConnectionEnabled: true, appium:noReset: false, appium:pixelRatio: 2.75, appium:platformVersion: 11, appium:statBarHeight: 66, appium:takesScreenshot: true, appium:viewportRect: {height: 1962, left: 0, top: 66, width: 1080}, appium:warnings: {}, appium:webStorageEnabled: false, platformName: ANDROID}
Session ID: 7345ce7a-7b53-4fe3-a3f2-79ca9f4f3073
at java.base#17.0.4.1/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base#17.0.4.1/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
at java.base#17.0.4.1/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base#17.0.4.1/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at java.base#17.0.4.1/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
at app//org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:200)
at app//org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:133)
at app//org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:53)
at app//org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:184)
at app//io.appium.java_client.remote.AppiumCommandExecutor.execute(AppiumCommandExecutor.java:180)
at app//org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:547)
at app//org.openqa.selenium.remote.ElementLocation$ElementFinder$2.findElement(ElementLocation.java:162)
at app//org.openqa.selenium.remote.ElementLocation.findElement(ElementLocation.java:60)
at app//org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:365)
at app//org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:357)
at app//org.example.po.PasswordScreen.<init>(PasswordScreen.java:18)
at app//org.example.HealthCheckTest.basicTest(HealthCheckTest.java:31)
at java.base#17.0.4.1/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base#17.0.4.1/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base#17.0.4.1/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base#17.0.4.1/java.lang.reflect.Method.invoke(Method.java:568)
at app//org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
at app//org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at app//org.junit.jupiter.api.extension.InvocationInterceptor.interceptTestMethod(InvocationInterceptor.java:118)
at app//org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at app//org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at app//org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at app//org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
at app//org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
at app//org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at app//org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at app//org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at app//org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214)
at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at app//org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base#17.0.4.1/java.util.ArrayList.forEach(ArrayList.java:1511)
at app//org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at app//org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base#17.0.4.1/java.util.ArrayList.forEach(ArrayList.java:1511)
at app//org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at app//org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at app//org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at app//org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at app//org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
at app//org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
at app//org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
at app//org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
at app//org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
at app//org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
at app//org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
at app//org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
at app//org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
at app//org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)
at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
at java.base#17.0.4.1/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base#17.0.4.1/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base#17.0.4.1/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base#17.0.4.1/java.lang.reflect.Method.invoke(Method.java:568)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
at jdk.proxy1/jdk.proxy1.$Proxy2.stop(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker$3.run(TestWorker.java:193)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.executeAndMaintainThreadName(TestWorker.java:129)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:100)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:60)
at org.gradle.process.internal.worker.child.ActionExecutionWorker.execute(ActionExecutionWorker.java:56)
at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:133)
at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:71)
at app//worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69)
at app//worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74)
This may work. You are trying to pass driver which is not accessible to your functions apart from the constructor. Then you are trying to create an object of the class in its definition itself.
#Step
public void login(String email, String password) {
WelcomeScreen welcomeScreen = new WelcomeScreen(this.driver);
welcomeScreen.clickLoginButton();
LoginScreen loginScreen = new LoginScreen(this.driver);
loginScreen.typeEmail(email);
loginScreen.clickNextButton();
this.typePassword(password);
this.clickLoginButton();
}
So all my problems are caused because I'm calling the login() function from the PasswordScreen class. At that moment all the variables seems cannot be yet declared, because the screen is not open in the app.
The easiest solution was to move login() function to separate class and to call it from there. This solution allows to declare the variables in the right order while appropriate screen is open
I'm starting to automate a test for an Android mobile app with Appium which is a calculator application on my mobile.
To start, I want to test a simple additive "2 + 3 = 5" equation, I use Eclipse and Appium inspector to get the element Id.
This is my code :
public class CalculatorTest {
static AndroidDriver<AndroidElement> driver;
public static void main(String[] args)
{
try {
openCalculator();
} catch (Exception e) {
System.out.println(e.getCause());
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public static void openCalculator() throws MalformedURLException, InterruptedException {
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability("deviceName", "OPPO A73");
cap.setCapability("udid", "9b487dea");
cap.setCapability("platformName", "Android");
cap.setCapability("platformVersion", "11");
cap.setCapability("appPackage", "com.coloros.calculator");
cap.setCapability("appActivity", "com.android.calculator2.Calculator");
URL url = new URL("http://127.0.0.1:4723/wd/hub");
driver = new AndroidDriver<AndroidElement>(url, cap);
System.out.println("Application started ..... ");
MobileElement agree= driver.findElement(By.id("com.coloros.calculator:id/btn_confirm"));
agree.click();
System.out.println("Application started ..... ");
driver.manage().timeouts().implicitlyWait(25,TimeUnit.SECONDS);
MobileElement one= driver.findElement(By.id("com.coloros.calculator:id/digit_2"));
MobileElement add= driver.findElement(By.id("com.coloros.calculator:id/op_add"));
MobileElement two= driver.findElement(By.id("com.coloros.calculator:id/digit_3"));
MobileElement equal= driver.findElement(By.id("com.coloros.calculator:id/eq"));
one.click();
add.click();
two.click();
equal.click();
}
}
The calculator app start with , If I click on agree I go to the .
In my code, I just click on agree button And then I want to click on 2 plus 1 and equal, But I got this an error as follows :
org.openqa.selenium.NoSuchElementException: An element could not be located on the page using the given search parameters.
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'DESKTOP-IJHSE2I', ip: '192.168.1.146', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '16.0.2'
Driver info: io.appium.java_client.android.AndroidDriver
Capabilities {appActivity: com.android.calculator2.Cal..., appPackage: com.coloros.calculator, databaseEnabled: false, desired: {appActivity: com.android.calculator2.Cal..., appPackage: com.coloros.calculator, deviceName: OPPO A73, platformName: android, platformVersion: 11, udid: 9b487dea}, deviceApiLevel: 30, deviceManufacturer: OPPO, deviceModel: CPH2095, deviceName: 9b487dea, deviceScreenDensity: 480, deviceScreenSize: 1080x2400, deviceUDID: 9b487dea, javascriptEnabled: true, locationContextEnabled: false, networkConnectionEnabled: true, pixelRatio: 3, platform: LINUX, platformName: Android, platformVersion: 11, statBarHeight: 96, takesScreenshot: true, udid: 9b487dea, viewportRect: {height: 2076, left: 0, top: 96, width: 1080}, warnings: {}, webStorageEnabled: false}
Session ID: 3a2d4b25-9e4a-4aa8-a9cf-6b0faa812c6a
*** Element info: {Using=id, value=com.coloros.calculator:id/digit_2}
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:78)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
at io.appium.java_client.remote.AppiumCommandExecutor.execute(AppiumCommandExecutor.java:239)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
at io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:42)
at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:1)
at io.appium.java_client.android.AndroidDriver.execute(AndroidDriver.java:1)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:323)
at io.appium.java_client.DefaultGenericMobileDriver.findElement(DefaultGenericMobileDriver.java:62)
at io.appium.java_client.AppiumDriver.findElement(AppiumDriver.java:1)
at io.appium.java_client.android.AndroidDriver.findElement(AndroidDriver.java:1)
at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:372)
at io.appium.java_client.DefaultGenericMobileDriver.findElementById(DefaultGenericMobileDriver.java:70)
at io.appium.java_client.AppiumDriver.findElementById(AppiumDriver.java:1)
at io.appium.java_client.android.AndroidDriver.findElementById(AndroidDriver.java:1)
at org.openqa.selenium.By$ById.findElement(By.java:188)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:315)
at io.appium.java_client.DefaultGenericMobileDriver.findElement(DefaultGenericMobileDriver.java:58)
at io.appium.java_client.AppiumDriver.findElement(AppiumDriver.java:1)
at io.appium.java_client.android.AndroidDriver.findElement(AndroidDriver.java:1)
at appiumtests.CalculatorTest.openCalculator(CalculatorTest.java:52)
at appiumtests.CalculatorTest.main(CalculatorTest.java:25)
I found a solution in the following link
solution but I want to do it automatically with Java in my code.
How to locate an element in android app in new screen with Appium
I have a few selenium tests on a react application. All tests are passing for chrome and firefox without any error. However, in IE (internet explorer v11) - all tests pass, but fails at the tearDown method: -
teardown method: -
#AfterClass
public void tearDown(){
driver.close();
//driver.quit();
}
screenshot of TestNG error log: -
Browser Base Class: -
public class TestBase {
public static WebDriver driver;
public static Properties prop;
public static EventFiringWebDriver e_driver;
public static WebEventListener eventlistener;
public static ChromeDriver chrome;
public static WebDriver driverName;
public TestBase(){
try {
prop = new Properties();
FileInputStream ip = new FileInputStream("src/main/java/config/config.properties");
prop.load(ip);
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e ){
e.printStackTrace();
}
}
public static void initialization(String browser){
try {
if(browser.equals("chrome")){
System.setProperty("webdriver.chrome.driver", "C:\\Browser\\chromedriver.exe");
driver = new ChromeDriver();
}else if (browser.equals("firefox")){
System.setProperty("webdriver.gecko.driver", "C:\\Browser\\geckodriver.exe");
driver = new FirefoxDriver();
}else if(browser.equals("ie")){
System.setProperty("webdriver.ie.driver", "C:\\Browser\\IEDriverServer.exe");
DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
ieCapabilities.setCapability("nativeEvents", false);
ieCapabilities.setCapability("unexpectedAlertBehaviour", "accept");
ieCapabilities.setCapability("ignoreProtectedModeSettings", true);
ieCapabilities.setCapability("disable-popup-blocking", true);
ieCapabilities.setCapability("enablePersistentHover", true);
ieCapabilities.setCapability("ignoreZoomSetting", true);
driver = new InternetExplorerDriver(ieCapabilities);
}else if(browser.equals("edge")){
System.setProperty("webdriver.edge.driver", "C:\\Browser\\MicrosoftWebDriver.exe");
EdgeOptions options = new EdgeOptions();
options.setCapability("unexpectedAlertBehaviour", "accept");
driver = new EdgeDriver(options);
e_driver = new EventFiringWebDriver(driver);
//now create object of event listner handler to register it with eventfiring web driver
eventlistener = new WebEventListener();
e_driver.register(eventlistener);
driverName = driver;
driver = e_driver;
}
if(!browser.contains("edge")){
e_driver = new EventFiringWebDriver(driver);
//now create object of event listner handler to register it with eventfiring web driver
eventlistener = new WebEventListener();
e_driver.register(eventlistener);
driverName = driver;
driver = e_driver;
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(TestUtil.PAGE_LOAD_TIMEOUT, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(TestUtil.IMPLICIT_WAIT, TimeUnit.SECONDS);
}
driver.get(prop.getProperty("url"));
} catch (TimeoutException e){
if (driver != null)
driver.close();
//driver.quit();
e.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
}
console error log
Starting MSEdgeDriver ... (...) on port 2440
Only local connections are allowed.
Please protect ports used by MSEdgeDriver and related test frameworks to prevent access by malicious code.
org.openqa.selenium.WebDriverException: unknown error: cannot find MSEdge binary
Build info: version: '3.12.0', revision: '7c6e0b3', time: '2018-05-08T14:04:26.12Z'
System info: host: '<host>', ip: '<ip>', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_221'
Driver info: driver.version: EdgeDriver
remote stacktrace: Backtrace:
Ordinal0 [0x00007FF605E27542+1930562]
Ordinal0 [0x00007FF605D8BCC2+1293506]
Ordinal0 [0x00007FF605CF0801+657409]
Ordinal0 [0x00007FF605C60F1F+69407]
Ordinal0 [0x00007FF605C5EF02+61186]
Ordinal0 [0x00007FF605C87C9D+228509]
Ordinal0 [0x00007FF605C850EF+217327]
Ordinal0 [0x00007FF605C6702F+94255]
Ordinal0 [0x00007FF605C681EE+98798]
Ordinal0 [0x00007FF605DAA6A1+1418913]
GetHandleVerifier [0x00007FF605EE8AF9+656601]
GetHandleVerifier [0x00007FF605EE8891+655985]
GetHandleVerifier [0x00007FF605EF095C+688956]
GetHandleVerifier [0x00007FF605EE92D3+658611]
Ordinal0 [0x00007FF605DA069E+1377950]
Ordinal0 [0x00007FF605DACB46+1428294]
Ordinal0 [0x00007FF605DAB9BD+1423805]
BaseThreadInitThunk [0x00007FFF02907974+20]
RtlUserThreadStart [0x00007FFF0402A271+33]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$new$0(W3CHandshakeResponse.java:57)
at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$getResponseFunction$2(W3CHandshakeResponse.java:104)
at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$0(ProtocolHandshake.java:123)
at java.util.stream.ReferencePipeline$3$1.accept(Unknown Source)
at java.util.Spliterators$ArraySpliterator.tryAdvance(Unknown Source)
at java.util.stream.ReferencePipeline.forEachWithCancel(Unknown Source)
at java.util.stream.AbstractPipeline.copyIntoWithCancel(Unknown Source)
at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
at java.util.stream.FindOps$FindOp.evaluateSequential(Unknown Source)
at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
at java.util.stream.ReferencePipeline.findFirst(Unknown Source)
at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:126)
at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:73)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:136)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:543)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:207)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:130)
at org.openqa.selenium.edge.EdgeDriver.<init>(EdgeDriver.java:141)
at org.openqa.selenium.edge.EdgeDriver.<init>(EdgeDriver.java:130)
at com.testapp.base.TestBase.initialization(TestBase.java:73)
at com.testingapp.testcases.BusyIndicatorTest.setUp(BusyIndicatorTest.java:48)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:108)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:523)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:224)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:146)
at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:166)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:105)
at org.testng.TestRunner.privateRun(TestRunner.java:744)
at org.testng.TestRunner.run(TestRunner.java:602)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:380)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:375)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
at org.testng.SuiteRunner.run(SuiteRunner.java:289)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1301)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1226)
at org.testng.TestNG.runSuites(TestNG.java:1144)
at org.testng.TestNG.run(TestNG.java:1115)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
driver : InternetExplorerDriver: internet explorer on WINDOWS (d8509abb-d16b-4872-bdc2-010789af308c)
Trying to find Element By : By.xpath: //div[#id='hamburger_menu']
Exception occured: org.openqa.selenium.NoSuchSessionException: session d8509abb-d16b-4872-bdc2-010789af308c does not exist
Build info: version: '3.12.0', revision: '7c6e0b3', time: '2018-05-08T14:04:26.12Z'
System info: host: '<host>', ip: '<ip>', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_221'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities {acceptInsecureCerts: false, browserName: internet explorer, browserVersion: 11, javascriptEnabled: true, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(), se:ieOptions: {browserAttachTimeout: 0, elementScrollBehavior: 0, enablePersistentHover: true, ie.browserCommandLineSwitches: , ie.ensureCleanSession: false, ie.fileUploadDialogTimeout: 3000, ie.forceCreateProcessApi: false, ignoreProtectedModeSettings: true, ignoreZoomSetting: true, initialBrowserUrl: http://localhost:7136/, nativeEvents: true, requireWindowFocus: false}, setWindowRect: true, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: accept}
Session ID: <id>
What I've tried: -
initializing WebDriver driver = null in browser case class
Control Panel -> Internet Options -> Security -> Disabled "protected zone" for all four zones
ieCapabilities.setCapability("ignoreProtectedModeSettings", true); this is an alias for INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS
if(driver != null) {
driver.close();
}
I've tried all these which were mentioned in other stack overflow questions, however, I end up with the same error.
Do let me know if any more info. regarding the code is required.
EDIT:
I've noticed that my instance to the new InternetExplorerDriver has been striked through
driver = new InternetExplorerDriver (ieCapabilities);
This was striked, as DesiredCapabilities have been deprecated.
Before: -
DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
ieCapabilities.setCapability("ignoreProtectedModeSettings", true);
driver = new InternetExplorerDriver(ieCapabilities);
Now: -
InternetExplorerOptions IEoptions = new InternetExplorerOptions();
IEoptions.setCapability("ignoreProtectedModeSettings", true);
driver = new InternetExplorerDriver(IEoptions);
This fixed the striked-through.
When I run the IE set of tests individually i.e. without chrome, firefox & edge tests. I can see all the tests passing & no error at teardown method. I am Unable to figure out the reason!
After switching to native popup Allow is clicked then it will not switch to webview and control doesn't go to next tab. I am getting Native, Webview_4,Webview_5 like wise.
Error stack trace:
May 28, 2019 9:36:30 AM org.openqa.selenium.support.ui.ExpectedConditions findElement WARNING: WebDriverException thrown by findElement(By.xpath: //button[#class='little130 blue']) org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. Original error: Did not get any response after 20s Build info: version: '3.13.0', revision: '2f0d292', time: '2018-06-25T15:32:19.891Z' System info: host: 'local', ip: 'fe80:0:0:0:c1a:bce1:50e1:ac1d%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.14.4', java.version: '12' Driver info: io.appium.java_client.ios.IOSDriver Capabilities {appiumVersion:
1.9.1, autoAcceptAlerts: true, autoDismissAlerts: true, autoGrantPermissions: true, automationName: XCUITest, browserName: Safari, databaseEnabled: false, deviceName:TS, javascriptEnabled: true, locationContextEnabled: falsenetworkConnectionEnabled: false, newCommandTimeout: 2000,platform: MAC, platformName: iOS, platformVersion: 12.2, safariAllowPopups: false, startIWDP: true, takesScreenshot: true, udid: ****..., unexpectedAlertBehaviour: true, unhandledPromptBehavior: true, webStorageEnabled: false, webkitResponseTimeout: 20000, xcodeOrgId: BYKRN84M2R, xcodeSigningId: iPhone Developer} Session ID: fc7d6ca1-3901-4fb0-a001-69ff9a499308
*** Element info: {Using=xpath, value=//button[#class='little']} at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) atjava.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)atjava.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500) at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481) at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187) at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122) at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49) at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158) at io.appium.java_client.remote.AppiumCommandExecutor.execute(AppiumCommandExecutor.java:231) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:548) at io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:42) at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:1)
the used following code but it doesn't work
Set<String> strcont=null; strcont=driver.getcontextHandles();
For(String s: strcont) {
if(s.contains(WEBVIEW)) {
driver.context(s);
}
} catch (Exception e) {
e.printStackTrace();
}
After clicking the "popup" button again switch to webview,give break inside the condition find the below code
Set<String> strcont=null; strcont=driver.getcontextHandles();
For(String s: strcont) {
if(s.contains(WEBVIEW)) {
driver.context(s);
break;
}
} catch (Exception e) {
e.printStackTrace();
}
I am new to selenium web-driver. I am facing a issue 'handling a javascript popup' I click on a button and after clicking that button a popup comes it has a ok button.when I recorded in selenium ide, it shows a (COMMAND) assertAlert and (TARGET) *A copy of your e-Quote #514106617764 has been generated successfully and sent to your e-mail id.\nPlease continue with your online purchase process. in table(recorded script).so i wrritten following code to handle this popup. i am trying on getQoute page of igaruntee of https://buyonline.aegonreligare.com/cordys/buyonlineesales/startiGuarantee.htm?key=websitedirect#
try{
Actions aa=new Actions(dd);
aa.sendKeys("ENTER");
}
catch(Exception e)
{System.out.println(e)}
try
{
dd.manage().timeouts().pageLoadTimeout(120, TimeUnit.SECONDS);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("check1")));
WebElement a=dd.findElement(By.id("check1"));
if(a != null)
{
status = 1;
System.out.println("iGurantee_Premium Qoute Page " + status);
}
else
{
status = 0;
System.out.println("iGurantee_Premium Qoute Page " + status);
}
Monitoring_FrameWork.SaveResult(tstartTime,"iGurantee_Premium QoutePage ", status,120);
}
catch(Exception e)
{
status = 0;
System.out.println(e);
System.out.println("iGurantee_Premium Qoute Page " + status);
}
but I am getting an exception as:
org.openqa.selenium.UnhandledAlertException: Modal dialog present
Build info: version: '2.28.0', revision: '18309', time: '2012-12-11 20:21:45'
System info: os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_67'
Session ID: db7cdba6-b905-49e0-9947-947d18761929
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{platform=XP, databaseEnabled=true, cssSelectorsEnabled=true, javascriptEnabled=true, acceptSslCerts=true, handlesAlerts=true, browserName=firefox, browserConnectionEnabled=true, nativeEvents=true, webStorageEnabled=true, rotatable=false, locationContextEnabled=true, applicationCacheEnabled=true, takesScreenshot=true, version=18.0}]
iGurantee_Premium Qoute Page 0
Oct 29, 2014 3:46:38 AM org.openqa.selenium.support.ui.ExpectedConditions findElement
WARNING: WebDriverException thrown by findElement(By.id: check1)
org.openqa.selenium.UnhandledAlertException: Modal dialog present
Build info: version: '2.28.0', revision: '18309', time: '2012-12-11 20:21:45'
System info: os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_67'
Session ID: db7cdba6-b905-49e0-9947-947d18761929
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{platform=XP, databaseEnabled=true, cssSelectorsEnabled=true, javascriptEnabled=true, acceptSslCerts=true, handlesAlerts=true, browserName=firefox, browserConnectionEnabled=true, nativeEvents=true, webStorageEnabled=true, rotatable=false, locationContextEnabled=true, applicationCacheEnabled=true, takesScreenshot=true, version=18.0}]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:187)
at org.openqa.selenium.remote.ErrorHandler.createUnhandledAlertException(ErrorHandler.java:168)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:141)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:533)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:302)
at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:331)
at org.openqa.selenium.By$ById.findElement(By.java:216)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:294)
at org.openqa.selenium.support.ui.ExpectedConditions.findElement(ExpectedConditions.java:523)
at org.openqa.selenium.support.ui.ExpectedConditions.access$0(ExpectedConditions.java:521)
at org.openqa.selenium.support.ui.ExpectedConditions$4.apply(ExpectedConditions.java:130)
at org.openqa.selenium.support.ui.ExpectedConditions$4.apply(ExpectedConditions.java:1)
at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:204)
at aegonreligare.test.main(test.java:224)
Please tell me how to sovle this.
I even tried using
Alert a=driver.switchTo.alert;
a.accept(); or a.getText();
but it throws a exception :There is no alert...
You need to switch your window, set focus on the pop up and accept or deny.
var alert = Driver.SwitchTo().Alert();
alert.Accept();
written in c#