How to start the Appium server from command prompt in MAC machine? - ios

I am automating ios native mobile application using appium. Until now I was launching the server from the Appium GUI by clicking on the Launch button. Now I want to start the server from a command prompt.
I was able to do the same in Windows machine by following the below steps:
Launch Node.js command prompt
Navigate till the Appium bin folder
Use the command node appium
I got blocked on how to start the Node.js command prompt on a Mac. Can you pleases tell me how I can start the Appium server from a command prompt on a Mac.

if you used npm install -g appium then you should be able to directly open one with the command
appium //plus any server args you want ex: appium -p 4474
Or you can still navigate to the folder of your node_modules and into appium and go with
node . //plus any server args you want
if you want to have additional server flags, all are available at their site with documentations.

Open the terminal and type in the following command
appium --address 127.0.0.1 --port 4723
Press enter then it will register itself to 127.0.0.1 and will listen 4723 port. You can extend this command by adding app type etc.
Hope this will help you
cheers

/Applications/Appium.app/Contents/Resources/node/bin/node /Applications/Appium.app/Contents/Resources/node_modules/appium/bin/appium.js --address 127.0.0.1 --chromedriver-port 9516 --bootstrap-port 4725 --no-reset --local-timezone --command-timeout 7200 --session-override --debug-log-spacing --platform-version 9.0 --platform-name iOS --app /Users/chennareddy/u/apps/TestApp/build/release-iphonesimulator/Handstand/Handstand.app --show-ios-log --device-name iPhone-6s --native-instruments-lib --orientation Portrait

To start appium in MAC, all you need to do is to type => appium & in the terminal application. In order for the above command to work, you have to install appium in terminal mode. However there are 2 ways of doing it, one is with HomeBrew and the other directly with Node.js . You can find the tutorial of installing HomeBrew online. Follow the steps below to install it directly with node.js -
Go to https://nodejs.org/
Download and install the latest stable version of node.js package in your mac
Now open the terminal application
Run the following command => npm install -g appium
This should install Appium in your system with global privileges. After installation of appium, you can run the command => appium-doctor in the same terminal window to verify if everything is installed properly.
If everything is in green ticks, run => appium & to start the appium server
Hope this helped.

As other answers points out, if you have installed Appium thru terminal then simply type appium & on a terminal window to start appium server. Here all you need to know, how to install appium thru terminal.
1. Install Homebrew.
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
2. Give Following commands one by one to install appium
brew install node # get node.js
npm install -g appium # get appium
npm install wd # get appium client
appium & # start appium
You can find refer to step by guide for appium download osx here.

String tellCommand = "tell application \"Terminal\" to do script \"/usr/bin/node_modules/appium/bin/appium.js";
String parameters = " -p "+port;
parameters += " "+ (fullReset ? "--full-reset" : "--no-reset")+"\"";
tellCommand += parameters;
String[] command = { "osascript", "-e",
tellCommand };
ProcessBuilder pBuilder = new ProcessBuilder(command);
pBuilder.start();

Try this to launch your appium server programmatically for mac os, it includes automating the webkit debug proxy as well which is needed for debugging.
//customize the below in start server method
//Webkit Proxy command
CommandLine iOSProxyCommand = new CommandLine("ios_webkit_debug_proxy");
iOSProxyCommand.addArgument("-c");
iOSProxyCommand.addArgument(udid+":27753");//provide your udid of the device
iOSProxyCommand.addArgument("-F");//to disable console output in eclipse
DefaultExecuteResultHandler iOSProxyresultHandler = new DefaultExecuteResultHandler();
DefaultExecutor iOSProxyexecutor = new DefaultExecutor();
iOSProxyexecutor.setExitValue(1);
try {
iOSProxyexecutor.execute(iOSProxyCommand, iOSProxyresultHandler);
iOSProxyCommand.toString()));
Thread.sleep(5000);
System.out.println("iOS Proxy started.");
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
CommandLine command = new CommandLine(
"/Applications/Appium.app/Contents/Resources/node/bin/node");
command.addArgument( "/Applications/Appium.app/Contents/Resources/node_modules/appium/bin/appium.js",
false);
command.addArgument("--address", false);
command.addArgument("127.0.0.1");
command.addArgument("--port", false);
command.addArgument("4723");
command.addArgument("--full-reset", false);
command.addArgument("--log-level", false);//to disable console output in eclipse
command.addArgument("error");
command.addArgument("--log", false);
Timestamp currentTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime());
command.addArgument("/Users/sethupandi/appium"+currentTimestamp+".log");
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
DefaultExecutor executor = new DefaultExecutor();
executor.setExitValue(1);
try {
executor.execute(command, resultHandler);
Thread.sleep(5000);
System.out.println("Appium server started.");
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//customize the below in stop appium server-
//kill appium node after end of your execution
String[] command = { "/usr/bin/killall", "-9", "node" };
try {
Runtime.getRuntime().exec(command);
System.out.println("Appium server stopped.");
} catch (IOException e) {
e.printStackTrace();
}
//Kill webkit proxy for iOS
String[] commandProxy = { "/usr/bin/killall", "-9", "ios_webkit_debug_proxy" };
try {
Runtime.getRuntime().exec(commandProxy);
System.out.println("iOS Webkit proxy stopped");
} catch (IOException e) {
e.printStackTrace();
}

For anybody reading this who happens to be using npm (node/js/typescript), I've created a module called appium-controller that starts and stops appium in the background programmatically (mac or windows). It has an option to pass in a specific port either through a node call to the method or through cli.

Related

Starting Appium programatically using javascript

I am using Javascript with Node.JS and WDIO and trying to start appium programatically in beforeTest hook and stop it in afterTest hook.
I've tried doing so with child_process or some appium-service builder but without any success.
Is there a possibility to start/stop appium server programatically using certain portion of code?
Thanks
You can install appium in your project directory. Import appium and call appium.main(). This will start appium in the default port.
Start appium :
const appium = require('appium');
await appium.main({port : 4723, address : "127.0.0.1"})
Stop appium :
To stop appium programatically, you can kill the process. I used this package - https://www.npmjs.com/package/find-process to find the pid and kill process.
const findProcess = require('find-process')
let processList = await findProcess('port', 4723)
if(processList.length > 0) {
processList.forEach(proc => {
process.kill(proc.pid)
})
}

intermittently occuring appium unknown server-side error

I seem to get this issue intermittently. no error if i were to un plug and replug the devices and re-excuite the test, however this is only temperory fix till the time it shows up again.
i have 2 instances of appium server for 2 devices-
server1
Host-0.0.0.0
server port-5050
Bootstrap port- 4734
allow session overrides- ticked
server2
Host-0.0.0.0
server port-4723
Bootstrap port- 4724
allow session overrides- ticked
appium version- 1.15.1
List of devices attached-
52002dd24392b5a1 device
5200472dec01a4a9 device
error on appium server console-
W3C] Encountered internal error running command: Error: Cannot start the 'com.XYZ.XYZ' application. Visit https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/android/activity-startup.md for troubleshooting. Original error: Error executing adbExec. Original error: 'Command ''C:\\Users\\XYZ\\AppData\\Local\\Android\\Sdk\\platform-tools\\adb.exe' -P 5037 -s 5200472dec01a4a9 shell am start -W -n com.XYZ.XYZ/host.exp.exponent.LauncherActivity -S' timed out after 120000ms'. Try to increase the 120000ms adb execution timeout represented by 'adbExecTimeout' capability
[W3C] at ADB.startApp (C:\Program Files\Appium\resources\app\node_modules\appium\node_modules\appium-adb\lib\tools\apk-utils.js:153:11)
[HTTP] <-- POST /wd/hub/session 500 132866 ms - 1782
[HTTP]
[Instrumentation] .
[Instrumentation] Time: 123.085
[Instrumentation]
[Instrumentation] OK (1 test)
[Instrumentation] The process has exited with code 0
error on IDE-
org.openqa.selenium.SessionNotCreatedException: Unable to create a new remote session. Please check the server log for more details. Original error: An unknown server-side error occurred while processing the command. Original error: Cannot start the 'com.XYZ.XYZ' application. Visit https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/android/activity-startup.md for troubleshooting. Original error: Error executing adbExec. Original error: 'Command ''C:\\Users\\XYZ\\AppData\\Local\\Android\\Sdk\\platform-tools\\adb.exe' -P 5037 -s 5200472dec01a4a9 shell am start -W -n com.XYZ.XYZ/host.exp.exponent.LauncherActivity -S' timed out after 120000ms'. Try to increase the 120000ms adb execution timeout represented by 'adbExecTimeout' capability
Driver info: driver.version: AndroidDriver
remote stacktrace: UnknownError: An unknown server-side error occurred while processing the command. Original error: Cannot start the 'com.XYZ.XYZ' application. Visit https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/android/activity-startup.md for troubleshooting. Original error: Error executing adbExec. Original error: 'Command ''C:\\Users\\XYZ\\AppData\\Local\\Android\\Sdk\\platform-tools\\adb.exe' -P 5037 -s 5200472dec01a4a9 shell am start -W -n com.XYZ.XYZ/host.exp.exponent.LauncherActivity -S' timed out after 120000ms'. Try to increase the 120000ms adb execution timeout represented by 'adbExecTimeout' capability
desired capabilities for device1-
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("deviceName", "Tab");
capabilities.setCapability("platformVersion", "8.0.0");
capabilities.setCapability("platformName", "ANDROID");
capabilities.setCapability("udid", "5200472dec01a4a9");
capabilities.setCapability("noReset", "true");
capabilities.setCapability("appPackage", "com.xyz.xyz");
capabilities.setCapability("appActivity", "host.exp.exponent.LauncherActivity");
capabilities.setCapability("adbExecTimeout", 120000);
capabilities.setCapability("newCommandTimeout", 3000);
capabilities.setCapability("noSign", "true");
URL mobileURL = new URL("http://0.0.0.0:5050/wd/hub");
mobileParent = new AndroidDriver(mobileURL, capabilities);
mobile capabilities for device2-
capabilities.setCapability("deviceName", "Tab");
capabilities.setCapability("platformVersion", "8.0.0");
capabilities.setCapability("platformName", "ANDROID");
capabilities.setCapability("udid", "52002dd24392b5a1");
capabilities.setCapability("noReset", "true");
capabilities.setCapability("appPackage", "com.coachhire.kura");
capabilities.setCapability("appActivity", "host.exp.exponent.LauncherActivity");
capabilities.setCapability(AndroidMobileCapabilityType.AUTO_GRANT_PERMISSIONS, true);
capabilities.setCapability("adbExecTimeout", 120000);
capabilities.setCapability("newCommandTimeout", 3000);
capabilities.setCapability("noSign", "true");
URL mobileURL = new URL("http://0.0.0.0:4723/wd/hub");
mobileDriver = new AndroidDriver(mobileURL, capabilities);
any help greatly appretiated!
Looking at the details you have provided, there should not be any errors. It should work fine.
Unknown error usually accrues when Appium not able to figure out the list of capabilities provided for the run. I would suggest double check appPackage and appActivity details are right.
Also, try to run tests on one devices and see any errors. see the consistency of test run. if not errors than you can add one more device and see how it goes.
Add below in the capabilities,
"automationName": "UiAutomator2"
If you are running test on local machine use http://127.0.0.1:<Port>/wd/hubinstead 0.0.0.0
If you are running tests remotely make sure in above, local IP 127.0.0.0 replaced with the machine IP where Appium server is running.
As you are running Android devices only, I hope prerequisites softwares are installed as per Android test setup.
For mac device setup, follow steps here - https://www.swtestacademy.com/how-to-install-appium-on-mac/
Try below steps,
Check you can install the app manually by running below command.
adb -P <port> -s <device id > shell pm install -t -g <apk path>
If this could work, it indicates that there are no issues with the device. Else, you should reset the device and re test it.
Check Appium server is running with no issues. and access this link and see you get 200 response on appium server console.
http://<appium server ip>:4723/wd/hub/sessions
If you see an error there, it indicates that there is an issue with Appium. Un-install and install stable version of Appium and re test.
You should know that sometimes Node.js could not talk to 127.0.0.1:4723, So use 0.0.0.0:4723 instead and visa versa. Remember to change this in both code (DesiredCapabilities) and appium setting.
Try "udid" parametre is required for desired capabilities -
Example, caps.setCapability("udid", "ce0217124184c72505"); //DeviceId from "adb devices" command

error on paypal\rest-api-sdk-php\lib\PayPal\Transport\PayPalRestCall.php

this is the code where i have problem
i had the api paypal downloasded whi composer.json
i get the error
"Notice: Use of undefined constant CURLOPT_SSLVERSION - assumed 'CURLOPT_SSLVERSION' in C:\wamp\www\Nouveau dossier\vendor\paypal\rest-api-sdk-php\lib\PayPal\Transport\PayPalRestCall.php on line 57"
<?php
use PayPal\Api\Payer;
use PayPal\Api\Details;
use PayPal\Api\Amount;
use PayPal\Api\Transaction;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
require '../src/start.php';
$payer = new Payer();
$details = new Details();
$amount= new Amount();
$transaction = new Transaction();
$payment = new Payment();
$redirectUrls = new RedirectUrls();
$payer->setPaymentMethod("paypal");
//detail
$details->setShipping('2.00')
->setTax('0.00')
->setSubtotal('20.00');
// amount
$amount->setCurrency('GBP')
->setTotal('22.00')
->setDetails($details);
// transaction
$transaction->setAmount($amount)
->setDescription('membership');
// payment
$payment->setIntent('sale')
->setPayer($payer)
->setTransactions([$transaction]);
//redirectUrls
$redirectUrls->setReturnUrl('http://localhost/Nouveau%20dossier/paypal/pay.php?approved=true')
->setCancelUrl('http://localhost/Nouveau%20dossier/paypal/pay.php?approved=false');
$payment->setRedirectUrls($redirectUrls);
try{
$payment->create($api);
}
catch (PayPal\Exception\PPConnectionException $ex) {
echo "Exception: " . $ex->getMessage() . PHP_EOL;
echo "<pre>";
var_dump($ex->getData());
exit(1);
//catch(PPConnectionException $e){
//header('Location: ../paypal/error.php');
}
//foreach($payment->getLinks() as $link){
//if($link->getRek() == 'approval_url'){
//$redirectUrl = $link->getHref();
//}
//}
//var_dump($redirectUrl);
$approvalUrl = $payment->getApprovalLink();
?>
If you are using PHP 5.1+, this error means that you do not have PHP cUrl installed (or, your php.ini is not configured to use cUrl). I was facing the same problem on my Ubuntu host and after installing cUrl and restarting the server, problem got solved. To install cUrl, type the following in your SSH console:
sudo apt-get install php5-curl
Then restart your apache server:
sudo service apache2 restart
Of course, commands will be different for different type of servers.
I had the same issue on DigitalOcean.com hosting. I just restarted the droplet and the problem went away.

Appium Server not connected and throwing org.openqa.selenium.remote.UnreachableBrowserException

I have recently started mobile devices automation on appium with the java language.
I am trying to run the initial setup code through program it is returning this failure message.
Caused by: org.apache.http.conn.HttpHostConnectException: Connect to 127.0.0.1:4723 [/127.0.0.1] failed: Connection refused: connect
When Manual run Appium server it doesn't have any errors and server started; the android apk file is installed.
Below is my code; Eclipse doesn't show any errors. I use Android Emulator for this Initial test. Appium and Java Project code in same host machine.
public void setup() throws MalformedURLException {
WebDriver AppWebDriver = null;
AppiumDriver ApUMDriver = null;
AndroidDriver AppiumURLDriver;
URL Serverurl;
// TODO Auto-generated method stub
DesiredCapabilities Appiumcapabiliy = new DesiredCapabilities();
File appDir = new File("c:\ApkbuildsDir");
File app = new File(appDir, "xxx.apk");
Appiumcapabiliy.setCapability("devicename","Device11");
Appiumcapabiliy.setCapability("platformname","Android");
Appiumcapabiliy.setCapability("platformVersion","4.2.2");
Appiumcapabiliy.setCapability("app-package","packagename");
Appiumcapabiliy.setCapability("app-activity","activityscreen");
Appiumcapabiliy.setCapability("app", app.getAbsolutePath());
Serverurl = new URL("http://127.0.0.1:4723/wd/hub");
AppWebDriver = new AndroidDriver(Serverurl,Appiumcapabiliy);
AppWebDriver.manage().timeouts().implicitlyWait(80, TimeUnit.SECONDS);
ApUMDriver.findElement(By.name("My Card"));
}
Could you please guide me how to eliminate this server connect error through program.
Regards, Kiran
Looks like "Appium server" instance is NOT running in your machine. That is, http://127.0.0.1:4723/wd/hub
Please start the Appium server on 4723 port and try execute your code.

Debugging Jest test cases using node-inspector

Is there a way to use node-inspector to debug unit tests with Jest? It would be nice to step through sometimes to see why tests are failing
I have tried a few ways
node-debug jest --runInBand
from the as well as starting up the inspector first eg
$ node-inspector
$ node --debug-brk .\node_modules\jest-cli --runInBand
and then navigate to http://127.0.0.1:8080/debug?port=5858
I have found that occasionally (1 in 10 or so times), the debugger opens the jest src files and its possible to debug them. Generally though, the scripts in the debugger only contain a 'no domain' folder and another irrelevant folder.
Also the test scripts themselves are never loaded in the debugger.
Has anyone tried this before?
Looks like the issue is that jest is using harmonize, which spawns a child process to ensure that the --harmony option is used.
harmonize/harmonize.js, lines 30-35
var node = child_process.spawn(process.argv[0], ['--harmony'].concat(process.argv.slice(1)), {});
node.stdout.pipe(process.stdout);
node.stderr.pipe(process.stderr);
node.on("close", function(code) {
process.exit(code);
});
I was able to successfully debug jest tests (although tests that use JSX transforms are incredibly slow) by commenting out the code that jest is using to spawn the harmonized process.
node_modules/jest-cli/bin/jest.js, last lines of the file:
if (require.main === module) {
//harmonize(); <--- comment out
_main(function (success) {
process.exit(success ? 0 : 1);
});
}
Then you can run:
$ node-debug --nodejs --harmony ./node_modules/jest-cli/bin/jest.js --runInBand
Jest relies on the --harmony flag being there, so that's why we need to add it back with --nodejs --harmony. We also add --runInBand so that the tests run in sequence, not in parallel.
This opens up the web debugger, and you can debug the tests, although it can be pretty slow to get to the test you want. Please comment if anyone knows a way to make this faster, and I'll update my answer.
You can add this to your package.json to make it easier to kick off:
...
scripts: {
"test": "jest",
"test-debug": "node-debug --nodejs --harmony ./node_modules/jest-cli/bin/jest.js --runInBand"
}
...
Of course, main concern with this solution is the editing of the jest source code. Will think about how to make a pull request to make this stick.
Created Github Issue Here: https://github.com/facebook/jest/issues/152
This is now officially supported with Node >= 6.3.
Quoting Jest documentation:
Place a debugger; statement in any of your tests, and then, in your project's directory, run:
node --debug-brk --inspect ./node_modules/.bin/jest -i [any other arguments here]
This will output a link that you can open in Chrome. After opening that link, the Chrome Developer Tools will be displayed, and a breakpoint will be set at the first line of the Jest CLI script (this is done simply to give you time to open the developer tools and to prevent Jest from executing before you have time to do so). Click the button that looks like a "play" button in the upper right hand side of the screen to continue execution. When Jest executes the test that contains the debugger statement, execution will pause and you can examine the current scope and call stack.
Note: the -i cli option makes sure Jest runs test in the same process rather than spawning processes for individual tests. Normally Jest parallelizes test runs across processes but it is hard to debug many processes at the same time.
More information on the V8 inspector can be found here: https://nodejs.org/api/debugger.html#debugger_v8_inspector_integration_for_node_js
Using Node 7.4.0, Jest 18.x, and the jest-environment-node-debug package (from this comment), it's now possible to use the chrome devtools to debug Jest tests:
$ npm install -D jest-environment-node-debug
$ node --inspect-brk ./node_modules/.bin/jest -i --env jest-environment-node-debug
Here's a Gruntfile.js config to automate #Sean's answer with Grunt.
grunt testd
OR
grunt testd --tests=MyTestName
OR
grunt testd --tests=MyTestName,AnotherTestName
Requires "node-inspector" (must be installed globally to get the node-debug bin in your path), "lodash", "jest-cli" and "grunt-shell" node modules.
var _ = require('lodash');
var commaSplitToRegex = function(input) {
return _.map(input.split(','), function(part) {
return '(' + part + ')';
}).join('|');
};
var getTestRegex = function(tests) {
if (tests) {
return '.*' + commaSplitToRegex(tests) + '.*';
}
return '.*';
}
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-shell');
grunt.initConfig({
shell: {
jestd: {
command: function() {
var testsRegex = getTestRegex(grunt.option('tests'));
var cmd = 'node-debug --nodejs --harmony ./node_modules/jest-cli/bin/jest.js --runInBand --config="test_utils/jest.json"';
if (testsRegex) {
cmd += ' "' + testsRegex + '"';
}
return cmd;
}
},
monkeypatchjest: {
command: 'sed -i.bak s\\/harmonize\\(\\)\\;\\/\\\\/\\\\/wtf\\/g ./node_modules/jest-cli/bin/jest.js'
},
unmonkeypatchjest: {
command: 'sed -i.bak s\\/\\\\/\\\\/wtf\\/harmonize\\(\\)\\;\\/g ./node_modules/jest-cli/bin/jest.js'
}
}
});
grunt.registerTask('testd', 'Run tests with debugger.', ['shell:monkeypatchjest', 'shell:jestd']);
};

Resources