I'm testing a Windows hybrid application, I'm using the codes below to get contexts but I got an UnsupportedCommandException when I launch it.
Here's my code :
public void initialize() throws MalformedURLException {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Windows");
capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "10");
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Max");
capabilities.setCapability("app", "D:\\Users\\Max\\Desktop\\TI\\ti.exe");
driver = new AppiumDriver<>(new URL("http://localhost:4723/wd/hub"), capabilities);
Set<String> contextNames = driver.getContextHandles();
for (String contextName : contextNames) {
System.out.println(contextName);
}
driver.context((String) contextNames.toArray()[1]);
}
Here's the output on the Appium Server:
Appium server screen
It says that the command contexts is not recognized.
I'm using :
Appium Desktop v1.20.2
Appium Java client v7.5.1
WinAppDriver v1.2.1
The first of all, you need to get all contexts. More info in official docs
Here how I implemented it in tests.
In some Page Object files I keep Android contexts.
ANDROID_CONTEXTS = {
'webview': 'WEBVIEW_ru.myapp',
'native': 'NATIVE_APP'
}
In some tests I switch context from Native to Webview.
#allure.link(url='https://jira.project.tech/browse/TEST-1', name='TEST-1 - Fill payment form')
#allure.title('Fill payment form')
def test_card_standard_1_month(appdriver):
Paywall(appdriver).press_one_month_button()
PaymentsPage(appdriver).select_card_payment()
PaymentsPage(appdriver).press_payment_button()
appdriver.switch_to.context(ANDROID_CONTEXTS['webview'])
Payform(appdriver).fill_and_submit_payform()
appdriver.switch_to.context(ANDROID_CONTEXTS['native'])
assert SuccessPayment(appdriver).get_successful_payment_title_text() == 'Your subscription is successful!'
You can check all available contexts in your app. More info here -> http://appium.io/docs/en/commands/context/set-context/
Related
I am attempting to setup some tests using BrowserStack Automate + TestNG. I have followed the documentation here. I used the SDK and thus am using browserstack.yml for config; i.e.
buildName: xxx
projectName: xxx
framework: testng
platforms:
- deviceName: iPhone 14
osVersion: 16
browserName: ios
- os: Windows
osVersion: 11
browserName: Chrome
browserVersion: 103.0
- os: Windows
osVersion: 10
browserName: Firefox
browserVersion: 102.0
parallelsPerPlatform: 1
debug: true
networkLogs: false
consoleLogs: warnings
This works fine for simple tests. However, I am needing to set some browser specific capabilities, specifically to disable Geolocation pop-ups. I saw Browserstack provided some documentation on the topic here; however, this does not show how to use it with the SDK/.yml config file.
I attempted to merge the capabilities as follows, but not luck:
/*
* This Java source file was generated by the Gradle 'init' task.
*/
public class BaseTest {
public WebDriver driver;
#BeforeMethod(alwaysRun = true)
#SuppressWarnings("unchecked")
public void setUp() throws Exception {
driver = new RemoteWebDriver(new URL("https://hub.browserstack.com/wd/hub"), new MutableCapabilities());
ChromeOptions options = new ChromeOptions();
Map<String, Object> prefs = new HashMap<String, Object>();
Map<String, Object> profile = new HashMap<String, Object>();
Map<String, Object> contentSettings = new HashMap<String, Object>();
contentSettings.put("geolocation", 2);
profile.put("managed_default_content_settings", contentSettings);
prefs.put("profile", profile);
options.setExperimentalOption("prefs", prefs);
var caps = new MutableCapabilities();
caps.setCapability(ChromeOptions.CAPABILITY, options);
((RemoteWebDriver) driver).getCapabilities().merge(caps);
}
#AfterMethod(alwaysRun = true)
public void tearDown() throws Exception {
driver.quit();
}
}
The geolocation prompt still appears and there is no indication that the Chrome capability has been set when reviewing the build in Browserstack.
I am getting this exception
org.openqa.selenium.WebDriverException: org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. Original error: 'POST /element' cannot be proxied to UiAutomator2 server because the instrumentation process is not running (probably crashed)
while launching another app after working on an app. The first app, which was launched is working fine with #Android Find by(Xpath ="").but when the second app is launched, it is not clicking the element given in #android find by mobile element format, but working in driver.findElement by format.
How to resolve this?
The method used for launching the second app.
public void supplier() throws Exception { PageFactory.initElements(new AppiumFieldDecorator(driver), this);
props = new Properties();
String propFileName = "config.properties";
String xmlfileName = "strings/strings.xml";
inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
props.load(inputStream);
stringis = getClass().getClassLoader().getResourceAsStream(xmlfileName);
utils = new TestUtils();
strings = utils.parseStringXML(stringis);
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("platformName","Android");
URL url = new URL(props.getProperty("appiumURL"));
caps.setCapability("deviceName","0dac3ec7");
caps.setCapability("appPackage", "appPackage");
caps.setCapability("appActivity",props.getProperty("appActivity"));
driver = new AndroidDriver<MobileElement>(url, caps);
}
I'm trying to Automate a web application selenium 2.0 [webdriver+java].The web application is currently deployed in our UAT servers on our local network.My test cases are executing, but I have to manually enter the Proxy Authentication details for my Chrome instance at the start of the test execution. I have tried all the solutions provided on stack overflow but still, the authentication message pops out.
This is the code I'm using in my driver initializing process
package com.misyn.ess.ui;
import java.util.Arrays;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
/**
*
* #author User
*/
public class DriverClass {
private String baseUrl;
private String driverPath;
private String driverName;
private static WebDriver driver;
private static DriverClass driverClass;
private DriverClass() {
try {
baseUrl = "http://192.168.0.10:8282/ess";
driverPath = "E:\\Work_Folder\\SelTools\\chromedriver.exe";
driverName = "webdriver.chrome.driver";
//Set the location of the ChromeDriver
System.setProperty(driverName, driverPath);
//Create a new desired capability
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
// Create a new proxy object and set the proxy
Proxy proxy = new Proxy();
proxy.setHttpProxy("192.168.0.200:3128");
proxy.setSocksUsername("avishka");
proxy.setSocksPassword("12345678");
//Add the proxy to our capabilities
capabilities.setCapability("proxy", proxy);
//Start a new ChromeDriver using the capabilities object we created and added the proxy to
driver = new ChromeDriver(capabilities);
//Navigation to a url and a look at the traffic logged in fiddler
driver.navigate().to(baseUrl);
// System.setProperty(driverName, driverPath);
// driver = new ChromeDriver();
// driver.get(baseUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Can anyone give me a solution how to give this proxy username and password thing from the application itself than manually entering details on the pop-up(Authentication), any help would be much appreciated.Thanks
the currently answered one is only for
As of Selenium 3.4 it is still in beta
Right now implementation is only done for InternetExplorerDriver
Where I'm using selenium 3.0 and Google Chrome as my web browser.
You can do via MultiPass for HTTP basic authentication
Download the extension from
https://chrome.google.com/webstore/detail/multipass-for-http-basic/enhldmjbphoeibbpdhmjkchohnidgnah
Download the extension as crx. You can get it as crx from chrome-extension-downloader
After that the config is simple.
import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
/**
*
* #author Phystem
*/
public class ChromeAuthTest {
WebDriver driver;
public ChromeAuthTest() {
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
}
private void initDriver() {
ChromeOptions cOptions = new ChromeOptions();
cOptions.addExtensions(new File("MultiPass-for-HTTP-basic-authentication_v.crx"));
driver = new ChromeDriver(cOptions);
configureAuth(
"https://the-internet.herokuapp.com/basic_auth",
"admin",
"admin");
}
private void configureAuth(String url, String username, String password) {
driver.get("chrome-extension://enhldmjbphoeibbpdhmjkchohnidgnah/options.html");
driver.findElement(By.id("url")).sendKeys(url);
driver.findElement(By.id("username")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
driver.findElement(By.className("credential-form-submit")).click();
}
public void doTest() {
initDriver();
driver.get("https://the-internet.herokuapp.com/basic_auth");
System.out.println(driver.getTitle());
driver.quit();
}
public static void main(String[] args) {
new ChromeAuthTest().doTest();
}
}
I have used a sample site for testing.
Provide your url,username and password in the configure Auth function and try
public class DriverClass {
private String baseUrl;
private String driverPath;
private String driverName;
private static WebDriver driver;
private static DriverClass driverClass;
public DriverClass() {
try {
baseUrl = "http://192.168.0.10:8282/ess";
driverPath = "E:\\Work_Folder\\SelTools\\chromedriver.exe";
driverName = "webdriver.chrome.driver";
System.setProperty(driverName, driverPath);
Proxy proxy = new org.openqa.selenium.Proxy();
proxy.setSslProxy("192.168.0.200" + ":" + 3128);
proxy.setFtpProxy("192.168.0.200" + ":" + 3128);
proxy.setSocksUsername("avishka");
proxy.setSocksPassword("12345678");
DesiredCapabilities desiredCapabilities = DesiredCapabilities.chrome();
desiredCapabilities.setCapability(CapabilityType.PROXY, proxy);
driver = new ChromeDriver(desiredCapabilities);
driver.get(baseUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The proxy setting has been added with desired capabilities to pass values to proxy authentication,worked finally
This code (from Avishka Perera's answer) does not work for me:
proxy.setSocksUsername("avishka");
proxy.setSocksPassword("12345678");
The username and password set in this way do not take effect for the http/https proxy - the Proxy Authentication box still popped up.
I'm using Selenium java 3.141.0, ChromeDriver 2.33 and chrome 70. What works for me is to follow Mike's answer here Selenium using Python: enter/provide http proxy password for firefox .
Create the zip file, then add the extension like this:
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addExtensions(new File("src/test/resources/proxy.zip"));
WebDriver driver = new ChromeDriver(chromeOptions);
One catch is that the above code will run into error if you set "--headless" argument because chrome in headless mode cannot have extension (Is it possible to run Google Chrome in headless mode with extensions?). If your Chrome runs in Docker container and cannot show the UI, then to get this solution work, you'll need to run with Xvfb instead of in headless mode.
Simple method to add authenticated proxy using selenium wire in Both firefox and chrome
In python
Step:1
pip3 install selenium-wire
Step:2
from seleniumwire import webdriver
from selenium import webdriver
step:3
Add proxy in below-mensioned format
proxy= "username:password#ip:port"
options = {'proxy': {'http': proxy, 'https': proxy, 'no_proxy': 'localhost,127.0.0.1,dev_server:8080'}}
step:4
pass proxy as an argument
CHROME
driver = webdriver.Chrome(options=chrome_options, executable_path="path of chrome driver", seleniumwire_options=options)
Firefox
driver = webdriver.Firefox(seleniumwire_options=options, executable_path="path of firefox driver", options=firefox_options)
step:5
Verify proxy applied by requesting the url https://whatismyipaddress.com/
time.sleep(20)
driver.get("https://whatismyipaddress.com/")
Note:
But selenium log shows it runs in without proxy because we are using an external package to apply proxy.
I know this is an old thread, still leaving a solution which worked for me using browsermob proxy, for someone who still needs an option.
Maven dependency:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>net.lightbody.bmp</groupId>
<artifactId>browsermob-core</artifactId>
<version>2.1.5</version>
</dependency>
Java Code:
// I am using firefox
System.setProperty("webdriver.gecko.driver", "C:\\Selenium\\geckodriver.exe");
BrowserMobProxy browsermobProxy = new BrowserMobProxyServer();
browsermobProxy.setChainedProxy(new InetSocketAddress(PROXY_HOSTNAME, PROXY_PORT));
browsermobProxy.chainedProxyAuthorization(PROXY_USERNAME, PROXY_PASSWORD, AuthType.BASIC);
browsermobProxy.start(0);
FirefoxBinary firefoxBinary = new FirefoxBinary();
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setBinary(firefoxBinary );
firefoxOptions.setProfile(firefoxProfile);
firefoxOptions.setProxy(ClientUtil.createSeleniumProxy(browsermobProxy));
WebDriver webDriverWithProxy = new FirefoxDriver(firefoxOptionsWithProxy);
webDriverWithProxy.get("https://stackoverflow.com/");
The approach that worked perfectly fine for me is by using AutoIT.
Install autoIT and prepare a simple script as shown in the picture attached and execute the script file from your testscript using Runtime.getRuntime().exec("\YOUR_SCRIPT.exe") before navigating to the baseURL.
Every time I launch a script, instead of automating the login page, driver takes session from previous script. I am running the script on iPhone simulator. I am also resetting the device. Please refer the above code for more info,
ServerArguments serverArguments = new ServerArguments();
serverArguments.setArgument("--address", "127.0.0.1");
serverArguments.setArgument("--no-reset", false);
serverArguments.setArgument("--command-timeout", 2400);
serverArguments.setArgument("--local-timezone", true);
serverArguments.setArgument("--full-reset", true);
this.appiumServer = new AppiumServer(new File("/usr/local/bin/node"), new File("/usr/local/lib/node_modules/appium/build/lib/main.js"),serverArguments);
this.appiumServer.startServer();
I am using Genium framework for starting/stopping appium server.
I am setting the above capabilities in DesiredCapabilities class,
capabilities.setCapability("platformName", "iOS");
capabilities.setCapability("udid", udid);
capabilities.setCapability("browserName", "Safari");
if (!platformVersion.equals("")) {
capabilities.setCapability("platformVersion", platformVersion);
}
capabilities.setCapability("deviceName", deviceName);
capabilities.setCapability("autoWebview", true);
capabilities.setCapability("newCommandTimeout", 120);
I want to run my selenium tests on different browsers based on the browser name set in the Properties file.
I have a method named as initiateDriver() in which I get the browser name as set in the Properties file(valid values being ff, chrome or ie) and do the necessary settings for each of the web driver type. This method will return a WebDriver object to my methods.
public WebDriver initiateDriver()
{
// Created webdriver instance
WebDriver _drv = null;
String IEDriverPath, ChromeDriverPath;
try
{
//Get the Browser Name set in the properties file
String browserType = loadPropertiesFile("BrowserName");
Log4j.logger.warn("Browser name-----------"+browserType);
//Test if the browser is IE
if (browserType.equalsIgnoreCase("ie"))
{
//Currently, IEDriverServer.exe is copied on to Drivers folder of framework
IEDriverPath= "\\Drivers\\IEDriverServer.exe";
//Set the required properties to instantiate IE driver. Place any latest IEDriverServer.exe files under Drivers folder
System.setProperty("webdriver.ie.driver", IEDriverPath);
DesiredCapabilities cap= new DesiredCapabilities();
cap.setCapability("ignoreProtectedModeSettings", true);
_drv = new InternetExplorerDriver(cap);
}
//Check if BrowserType is set to Firefox
else if (browserType.equalsIgnoreCase("ff") || browserType.equalsIgnoreCase("firefox"))
{
//Getting the default Firefox with some settings
FirefoxProfile fp = new FirefoxProfile();
fp.setAcceptUntrustedCertificates(false);
//setting the Firefox preference "auto upgrade browser" to false and to prevent compatibility issues
fp.setPreference("app.update.enabled", false);
_drv = new FirefoxDriver();
}
//Check if BrowserType is set to Chrome
else if (browserType.equalsIgnoreCase("chrome"))
{
//Currently, chromedriver.exe is copied on to Drivers folder of framework
ChromeDriverPath= "\\Drivers\\chromedriver.exe";
//Set the required properties to instantiate Chrome driver. Place any latest Chromedriver.exe files under Drivers folder
System.setProperty("webdriver.chrome.driver", ChromeDriverPath);
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
_drv= new ChromeDriver(options);
}
else
{
Reporter.log("Invalid browser name. Please check the Resources/PropertiesLocation.properties file.");
System.out.println("Invalid browser name. Please check the Resources/PropertiesLocation.properties file.");
System.exit(0);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
Reporter.log("Enter valid browser name---");
System.exit(0);
}
return _drv;
}`
I am calling this method in the following class.
public class SmokeTest1
{
WebDriver d;
#BeforeClass
public void setUp() throws Exception
{
d = gm.initiateDriver();
d.manage().window().maximize();
d.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void firstSmokeTest() throws Exception
{
loginTest(d);
}
}
I am running my tests via ant build.xml file. However I am getting error as -
Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure."
Can somebody suggest what is going wrong or am I missing anything?