AppiumServerHasNotBeenStartedLocallyException: The local appium server has not been started - java

Im trying to start Appium server programmatically from Java
(OS: Windows7 x64)
using first method from source: http://www.automationtestinghub.com/3-ways-to-start-appium-server-from-java/
The code that I use for starting Appium sever is:
public void startServer() {
//Set Capabilities
cap = new DesiredCapabilities();
cap.setCapability("noReset", "false");
//Build the Appium service
builder = new AppiumServiceBuilder();
builder.withIPAddress("127.0.0.1");
builder.usingPort(4723);
builder.withCapabilities(cap);
builder.withArgument(GeneralServerFlag.SESSION_OVERRIDE);
builder.withArgument(GeneralServerFlag.LOG_LEVEL, "error");
//added by myself:
builder.usingDriverExecutable(new File("C:/node/node.exe"));
builder.withAppiumJS(new File("C:/Users/[user]/AppData/Roaming/npm/node_modules/appium/lib/appium.js"));
//Start the server with the builder
service = AppiumDriverLocalService.buildService(builder);
service.start();
}
I'm getting an exception:
Exception in thread "main" io.appium.java_client.service.local.AppiumServerHasNotBeenStartedLocallyException: The local appium server has not been started. The given Node.js executable: C:\node\node.exe Arguments: [C:\Users\Dima\AppData\Roaming\npm\node_modules\appium\lib\appium.js, --port, 4723, --address, 127.0.0.1, --log-level, error, --session-override, --default-capabilities, {\"noReset\": \"false\"}]
Process output: C:\Users[user]\AppData\Roaming\npm\node_modules\appium\lib\appium.js:1
(function (exports, require, module, __filename, __dirname) { import _ from 'lodash'; ^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:616:28)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
I tried every way to start Appium server from the source, but second one causes to the same, but third causes to error
Any ideas? Thanks to all in advance!

Take a look at official documentation:
https://github.com/appium/java-client/blob/master/docs/The-starting-of-an-app-using-Appium-node-server-started-programmatically.md
Make sure your env setup for Appium is correct and that appium service/client versions are compatible.

It did mistake in code. Fixed method is:
public static String runAppiumService(int appiumPort) {
//Build parameters for appium server:
AppiumServiceBuilder appiumServiceBuilder = new AppiumServiceBuilder();
appiumServiceBuilder.usingPort(appiumPort)
.withIPAddress(APPIUM_IP)
.withAppiumJS(new File(getAppiumJsPath()))
.withArgument(GeneralServerFlag.SESSION_OVERRIDE)
.withLogFile(new File(System.getProperty("user.dir") + "/target/resources/appium_server_logs" + Thread.currentThread().getId()));
AppiumDriverLocalService service = AppiumDriverLocalService.buildService(appiumServiceBuilder);
service.start();
}

public class ServerManager {
AppiumDriverLocalService service;
public static void main(String args[]) {
ServerManager sm = new ServerManager();
sm.startServer();
}
public void startServer() {
final DesiredCapabilities cap = new DesiredCapabilities();
//Set Capabilities
cap.setCapability("noReset", "false");
//Build the Appium service
AppiumServiceBuilder builder = new AppiumServiceBuilder();
builder = new AppiumServiceBuilder();
builder.withIPAddress("127.0.0.1");
builder.usingPort(4723);
builder.withCapabilities(cap);
builder.withArgument(GeneralServerFlag.SESSION_OVERRIDE);
builder.withArgument(GeneralServerFlag.LOG_LEVEL,"error");
//Start the server with the builder
service = AppiumDriverLocalService.buildService(builder);
service = AppiumDriverLocalService.buildService(builder);
service.start();
}
public void stopServer() {
service.stop();
}
}

Related

Getting Webdriver exception while using #android find by in appium

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);
}

Run the appium server programmatically

I am trying to run the Appium server programmatically. I tried all the possible options that Appium is providing, but not getting any result
From the command line, if I am trying C:\Users\User>appium it's starting the server. How to do the same by using java code?
Note: the version of Appium is 1.6.5
AppiumDriverLocalService service=AppiumDriverLocalService.buildDefaultService();
service.start();
This the code what i am using to run the appium server programmatically .
The error i am getting is
java.lang.NoClassDefFoundError: org/apache/commons/validator/routines/InetAddressValidator
Did you tried this,
import java.io.*;
public class CmdTest {
public static void main(String[] args) throws Exception {
Process p = Runtime.getRuntime().exec("appium");
}
}
I know you are asking for Java, but I do this programmatically with C#. So I paste my solution in case it can help to get an idea:
C# Code:
public void startAppiumServerLocally()
{
try
{
string nodejs = "\"" + Environment.GetEnvironmentVariable("nodejs") + "\""; // Environment path for node.exe
string appium = "\"" + Environment.GetEnvironmentVariable("appium") + "\""; // Environment path for main.js or appium.js
ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(nodejs);
myProcessStartInfo.UseShellExecute = false;
myProcessStartInfo.RedirectStandardOutput = true;
myProcessStartInfo.RedirectStandardError = true;
myProcessStartInfo.CreateNoWindow = true;
// getOverride() method returns '--session-override'
// getDesiredCapabilitiesJson() returns a JSON with some capabilities '--default-capabilities {"udid":identifier..., deviceName: "Samsung S7"....}'
// getDriverPort() returns --port X just in case I need to start in a different and unused port.
string args = appium + getOverride() + getDesiredCapabilitiesJson() + getDriverPort();
myProcessStartInfo.Arguments = args;
nodeProcess = new Process();
nodeProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
nodeProcess.StartInfo = myProcessStartInfo;
nodeProcess.Start();
nodeProcess.BeginErrorReadLine();
StreamReader myStreamReader = nodeProcess.StandardOutput;
while (_bAppiumForceEnd == false)
{
if (_bAppiumInit == false)
{
string line = myStreamReader.ReadLine();
if (line.Contains("listener started"))
{
// _bAppiumInit is a flag to start my tests once the server started
_bAppiumInit = true;
}
}
else
{
myStreamReader.ReadLine();
}
}
myStreamReader.Close();
}
catch (Exception e)
{
//Log(e.Message);
}
}
I know that creating a while loop is not the best solution, but sometimes my nodeProcess was not stoping... So I changed it to this way, and it works perfectly.
Make sure you installed Appium globally...
npm install -g appium
Here is how you start and stop appium server programmatically using Java code
import java.nio.file.Paths;
public class AppiumSetupAndTearDown {
public static void startAppiumServer() throws IOException, InterruptedException {
String logDir = <the path where you want to create the appium output file>;
File appiumOutput = new File(logDir);
if (!appiumOutput.exists()) {
boolean status = appiumOutput.createNewFile();
if (!status) {
throw new IOException("Failed to create Appium output file!");
}
}
String cmd[] = {"/bin/bash", Paths.get(System.getProperty("user.dir")).getParent().getParent().toString() + "/Modules/Shared/startAppium.sh"};
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.redirectError(new File(logDir));
pb.redirectInput(new File(logDir));
pb.redirectOutput(new File(logDir));
pb.start();
System.out.println("Appium server started!");
}
public static void stopAppiumServer() throws IOException, InterruptedException {
String cmd[] = {"/bin/bash", Paths.get(System.getProperty("user.dir")).getParent().getParent().toString() + "/Modules/Shared/stopAppium.sh"};
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.start();
System.out.println("Appium server stopped!");
}
}
You can also add Thread.sleep(5000) after starting and stopping the appium server in case you run into timing issues.
Try to addthe commons validator lib to your classpath/pom.xml (commons-validator-1.4.0.jar)

org.openqa.selenium.SessionNotCreatedException: desired capabilities error

After the attempt to run my tests I always get:
org.openqa.selenium.SessionNotCreatedException: Unable to create new remote session. desired capabilities = Capabilities [{platformVersion=6.0, platformName=Android, deviceName=Xiomi}], required capabilities = Capabilities [{}]
java-client 5.0.0 beta 9
Appium 1.6.5
selenium standalone 3.4.0
Using Android Studio
public class MyTest1 {
AppiumDriver driver;
#Before
public void setUp() throws Exception {
DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
desiredCapabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
desiredCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Xiomi");
desiredCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "6.0");
URL url = new URL("http://127.0.0.1:4723/wd/hub");
driver = new AppiumDriver(url, desiredCapabilities);
}
#After
public void tearDown() throws Exception {
driver.quit();
}
#Test
public void Test(){
}
}
Please help! I can't understand what am I doing wrong
I've added next desired capabilities and exception stopped occurring:
desiredCapabilities.setCapability("appPackage", "com.package.app");
desiredCapabilities.setCapability("appActivity", ".activities.App");
// Add real app package and activity instead of mine.

How to set Proxy Authentication in seleniumWebdriver for Chrome Browser

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.

Appium and Eclipse

I am new to Appium and I have installed Appium on ubuntu and make my first test using java command in an Eclipse while running my test I get an error: A new session could not be created.permission to start activity denied.
please Advice.
Here is my code:
public class BoxerTest {
AndroidDriver dr;
#Test
public void setUp() throws MalformedURLException{
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability("deviceName","TA09402ERN");
cap.setCapability("platformVersion","5.0.2");
cap.setCapability("platformAndroid","Android");
cap.setCapability("appPackage","com.boxer.browser");
cap.setCapability("appActivity","com.boxer.browser.MainActivity");
dr = new AndroidDriver(new URL ("http://0.0.0.0:4723/wd/hub"), cap);
}
#After
public void End(){
dr.quit();
}
}
Launchable app activity might be wrong. To get the launchable activity, take the APK and run the command aapt dump badging <boxer.apk>

Categories

Resources