How to setup Selenium grid remotely in protractor - selenium

I have my conf.js file which runs fine locally. But now as per my requirement I need to run it in a bamboo task. Since my code is going to run on server there is a remote selenium webdriver that i need to add to the conf.js.
Can you please help me out how it is done? My conf.js looks like this :
exports.config = {
params: {
url: "URL",
testroadname:"Testing123",
sleeptime:1000
},
directConnect: true,
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'chrome'
},
// Framework to use. Jasmine is recommended.
framework: 'jasmine',
// Spec patterns are relative to the current working directly when
// protractor is called.
specs: ['mapfeedback.js'],
// Options to be passed to Jasmine.
jasmineNodeOpts: {
defaultTimeoutInterval: 30000
}

You have to remove directConnect = true and just give the seleniumAddress in your config or setup an environment.js file- you can simply add your remote selenium's address and fire up your protractor tests, following will be your environment.js-
// Common configuration files with defaults plus overrides from environment vars
var webServerDefaultPort = 8081;
module.exports = {
// The address of a running selenium server.You can add your remote address here
seleniumAddress:
(process.env.SELENIUM_URL || 'http://localhost:4444/wd/hub'),
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName':
(process.env.TEST_BROWSER_NAME || 'chrome'),
'version':
(process.env.TEST_BROWSER_VERSION || 'ANY')
},
// Default http port to host the web server
webServerDefaultPort: webServerDefaultPort,
// Protractor interactive tests
interactiveTestPort: 6969,
// A base URL for your application under test.
baseUrl:
'http://' + (process.env.HTTP_HOST || 'localhost') +
':' + (process.env.HTTP_PORT || webServerDefaultPort)
};
your config file will look like -
var env = require('./environment.js');
exports.config = {
params: {
url: "URL",
testroadname:"Testing123",
sleeptime:1000
},
seleniumAddress: env.seleniumAddress,
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'chrome'
},
// Framework to use. Jasmine is recommended.
framework: 'jasmine',
// Spec patterns are relative to the current working directly when
// protractor is called.
specs: ['mapfeedback.js'],
// Options to be passed to Jasmine.
jasmineNodeOpts: {
defaultTimeoutInterval: 30000
}

To setup selenium-grid remotely for Protractor :-
start hub with command :-
java -jar selenium-server-standalone-3.3.1.jar -role hub -port 4444
Now start your remote node with command where you want execute remote test cases :-
java -jar selenium-server-standalone-3.3.1.jar -role webdriver -hub http://HubDomain-IP:4444/grid/register -port 5556 -browser browserName=internet explorer,maxInstances=1,platform=WINDOWS,applicationName=remoteNode -Dwebdriver.ie.driver=path to IEDriverServer.exe
Once your selenium-grid setup is done and node get connected with Hub, then take config file with configuratiion set as this conf.js file:-
exports.config = {
//The address of your running selenium Hub server.
seleniumAddress: 'http://HubDomain-IP:4444/wd/hub',
//Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'internet explorer',
// add node-name as applicationName where you have started node and wanted to remotely execute test cases
'applicationName': 'remoteNode'
},
//Specify the name of the specs files.
specs: ['grid_spec.js'],
//Options to be passed to Jasmine-node.
jasmineNodeOpts: {
onComplete: null,
isVerbose: false,
showColors: true,
includeStackTrace: true
}
};
With above mentioned configuration and setup commands you could run selenium-grid setup for Protractor.Thanks !

Related

Bypass docker to run selenium scripts locally

I have selenium scripts to run on docker container selenium grid that were written before I join this project. due to the docker I don't have access to view the browser while running the scripts. And when scripts fail its very hard to debug. Can someone help me how to modify the below conf.js file to run my scripts locally for debugging.
Conf.js
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0;
const log = require('loglevel');
const util = require('#raven/common-protractor-test-utils');
const { ExpectedConditions } = require('protractor');
require('dotenv').config({ path: '.local.env' })
var testOutputDir = './test_output/';
let peregrineUrl = util.functionalTestBaseUrl(
'https://ea-webapp-int-raven.ocp-nonprod/'
);
let domainName = util.domainName;
exports.config = {
directConnect: true, // Set to true for local testing, or provide a link to a running selenium grid.
specs: ['e2e/**/mailbox-test.js', 'e2e/**/email-dumps-test.js'],
capabilities: {
browserName: 'chrome',
acceptInsecureCerts: true,
'goog:chromeOptions': {
w3c: false,
args: [
'--no-sandbox',
// '--headless',
'--disable-gpu',
'--window-size=1200,1200',
'--allow-insecure-localhost',
'--allow-running-insecure-content',
'--ignore_ssl',
'--user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',
],
},
},
allScriptsTimeout: 600000,
baseUrl: peregrineUrl,
framework: 'jasmine',
jasmineNodeOpts: {
isVerbose: true,
showColors: true,
includeStackTrace: true,
defaultTimeoutInterval: 600000,
stackTrace: true
},
onPrepare: async () => {
/* Set Log Level */
log.setLevel('INFO');
log.info('Base URL: ' + peregrineUrl);
log.info('Domain Name: ' + domainName);
browser.ignoreSynchronization = true;
const ec = protractor.ExpectedConditions;
/* Set up the test directory. */
util.mkdirs(testOutputDir);
console.time('Peregrine Load Time');
await browser.get(peregrineUrl);
browser.driver.sleep(3000);
await username_area.sendKeys('rv-peregrine-test-user');
await password_area.sendKeys(process.env.SELENIUM_SERVICE_PASSWORD);
await agree_button.click();
await login_button.click();
},
};
When I try to change directConnect: ture and disable --headless to run locally I am able to see the chrome browser launched but the application opened. This is the trace from my console
[21:28:19] I/launcher - Running 1 instances of WebDriver
[21:28:19] I/direct - Using ChromeDriver directly...
DevTools listening on ws://127.0.0.1:51650/devtools/browser/bf44c6c7-72a6-49e5-ab80-b13139ce9005
[15808:15796:0115/212822.298:ERROR:url_util.cc(414)] Invalid pattern javascript://
[15808:4128:0115/212826.609:ERROR:chrome_browser_main_extra_parts_metrics.cc(227)] START: ReportBluetoothAvailability(). If you don't see the END: message, this is crbug.com/1216328.
[15808:4128:0115/212826.610:ERROR:chrome_browser_main_extra_parts_metrics.cc(230)] END: ReportBluetoothAvailability()
[15808:4128:0115/212826.611:ERROR:chrome_browser_main_extra_parts_metrics.cc(235)] START: GetDefaultBrowser(). If you don't see the END: message, this is crbug.com/1216328.
[15808:15796:0115/212826.611:ERROR:device_event_log_impl.cc(214)] [21:28:26.611] USB: usb_device_handle_win.cc:1050 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)
[15808:15796:0115/212826.613:ERROR:device_event_log_impl.cc(214)] [21:28:26.613] USB: usb_device_handle_win.cc:1050 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)
[15808:4128:0115/212826.672:ERROR:chrome_browser_main_extra_parts_metrics.cc(239)] END: GetDefaultBrowser()
[15808:15796:0115/212826.687:ERROR:device_event_log_impl.cc(214)] [21:28:26.688] Bluetooth: bluetooth_adapter_winrt.cc:1206 Getting Radio failed. Chrome will be unable to change the power state by itself.
[15808:15796:0115/212826.730:ERROR:device_event_log_impl.cc(214)] [21:28:26.730] Bluetooth: bluetooth_adapter_winrt.cc:1284 OnPoweredRadioAdded(), Number of Powered Radios: 1
[15808:15796:0115/212826.732:ERROR:device_event_log_impl.cc(214)] [21:28:26.732] Bluetooth: bluetooth_adapter_winrt.cc:1299 OnPoweredRadiosEnumerated(), Number of Powered Radios: 1
Thanks in advance

Custom args for each instance of Chrome when running parallel tests with Protractor

Is it possible to pass custom args for each instance of Chrome when running parallel tests in Protractor? I need to know the Remote debugging port for each instance so I can connect with the Dev Tools protocol.
As I see it there's two options. Set the port to a specific unique value for each instance, or let it be set automatically and fetch it somehow when preparing the tests. Would it be possible with any of these options?
exports.config = {
framework: 'jasmine',
chromeDriver: chromeDriverPath,
multiCapabilities: [{
browserName: 'chrome',
chromeOptions: {
args: process.env.HEADLESS && puppeteer ? ['--headless', `--remote-debugging-port=${DEV_TOOLS_PORT}`] : [`--remote-debugging-port=${DEV_TOOLS_PORT}`],
binary: puppeteer.executablePath()
},
shardTestFiles: true,
maxInstances: 1
}]
}
If I got the problem right, what you could do is to pass parameters as env variables to protractor on start. So your config would look like this:
exports.config = {
framework: 'jasmine',
chromeDriver: chromeDriverPath,
multiCapabilities: [{
'browserName': 'chrome',
'chromeOptions': {
args: [`--remote-debugging-port=${process.env.PORT_ONE}`]
}
}, {
'browserName': 'chrome',
'chromeOptions': {
args: [`--remote-debugging-port=${process.env.PORT_TWO}`]
}
}]
}
And then start your protractor process with env variables like so:
PORT_ONE=90 PORT_TWO=80 protractor protractor.conf.js
One of the two options are solved. But I would still like to know if there's a possibility to use custom args for each instance.
// Get Remote debugging port for chrome
let chromeRemoteDebuggingPort;
browser.getCapabilities().then((capabilities) => {
const chromeOptions = capabilities.get('goog:chromeOptions');
if( chromeOptions && chromeOptions.debuggerAddress) {
chromeRemoteDebuggingPort = chromeOptions.debuggerAddress.split(':')[1];
}
});

How to skip protractor+jasmine tests specific to browsers

Assume that I've automated 25 tests and executing in multiple browsers like chrome, firefox, IE, Edge & Safari. All tests (25) are executing well on Chrome. In Firefox, Only 20 tests are running fine due to few protractor APIs are not supported. Similarly IE can execute only 23 tests.
I would like to skip the test only for browsers, which are not supported for particular test? Is there any way available?
You can create protracotr.conf file for each browser with specific suites where will be specified what tests should run. And execute in one time all protractor.conf files.
//protractor.chrome.conf
export let config: Config = {
...
capabilities: {
browserName: 'chrome',
shardTestFiles: true,
maxInstances: 1
},
SELENIUM_PROMISE_MANAGER: false,
specs: [
'../test/chrome/**/*.js'
]
};
and
//protractor.ie.conf
export let config: Config = {
...
capabilities: {
browserName: 'internet explorer',
shardTestFiles: true,
maxInstances: 1
},
SELENIUM_PROMISE_MANAGER: false,
specs: [
'../test/ie/**/*.js'
]
};
in your package.json:
{
...
"scripts": {
"test:all": "npm run test:chrome && test:ie",
"test:chrome": "protractor ./config/protractor.chrome.conf.js",
"test:ie": "protractor ./config/protractor.ie.conf.js",
...
},
...
}
With jasmine2 you can filter tests using a regular expression. Maybe you can add something like #chrome, #ie to your tests and then only run those ones by passing the grep flag:
it('should do stuff #ie #chrome', function() {
...
});
Then run protractor passing the grep flag:
protractor conf.js --grep='#ie'

Protractor fails to find web-manager

I have protractor installed in project folder + web-manager (installed the same way).
The web-manager is started:
$npm-run webdriver-manager status
webdriver-manager: using global installed version 12.0.6
- selenium standalone version available: 3.8.1 [last]
- chromedriver version available: 2.35 [last]
- geckodriver version available: v0.19.1 [last]
- IEDriverServer is not present
However, when I run protractor
$ npm-run protractor conf.js
[15:22:12] I/launcher - Running 1 instances of WebDriver
[15:22:12] E/local - Error code: 135
[15:22:12] E/local - Error message: No update-config.json found. Run 'webdriver-manager update' to download binaries.
[15:22:12] E/local - Error: No update-config.json found. Run 'webdriver-manager update' to download binaries.
Here is my conf.js for protractor
exports.config = {
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'chrome',
},
// Spec patterns are relative to the current working directly when
// protractor is called.
specs: ['tests/common/*.js'],
};
How do I fix the config/run protrator?
you need to run npm-run webdriver-manager update to install webdriver binary and selenium-standalon-server.jar if you never execute it, otherwise the command will update existed stuff.
After that, find update-config.json in node_modules\protractor\node_modules\webdriver-manager\selenium.
Its content should be like this:
{
"chrome": {
"last": "xxx\\node_modules\\protractor\\node_modules\\webdriver-manager\\selenium\\chromedriver_2.35.exe",
"all": ["xxx\\node_modules\\protractor\\node_modules\\webdriver-manager\\selenium\\chromedriver_2.35.exe"]
},
"standalone": {
"last": "xxx\\node_modules\\protractor\\node_modules\\webdriver-manager\\selenium\\selenium-server-standalone-3.9.0.jar",
"all": ["xxx\\node_modules\\protractor\\node_modules\\webdriver-manager\\selenium\\selenium-server-standalone-3.9.0.jar"]
},
"gecko": {
"last": "xxx\\node_modules\\protractor\\node_modules\\webdriver-manager\\selenium\\geckodriver-v0.19.1.exe",
"all": ["xxx\\node_modules\\protractor\\node_modules\\webdriver-manager\\selenium\\geckodriver-v0.19.1.exe"]
}
}
Then execute node_modules\.bin\webdriver-manager start to see will success or fail.
FYI, you need JDK 8 installed to start webdriver-manager.
Finally, found a solution using gulp.
The config below allows to run webmanager-update, webmanager-start and proptractor on by one.
gulp.js
var gulp = require('gulp'),
shell = require('gulp-shell'),
connect = require('gulp-connect'); // Webserver
protractor = require('gulp-protractor').protractor,
webdriver_standalone = require('gulp-protractor').webdriver_standalone,
webdriver_update = require('gulp-protractor').webdriver_update;
gulp.task('webdriver_update', webdriver_update);
gulp.task('webdriver_standalone', webdriver_standalone);
gulp.task('e2e', ['webdriver_update'], function() {
gulp.src(["tests/protractor/*.js"])
.pipe(protractor({
configFile: "protractor.conf.js",
args: [
//'--baseUrl', 'http://127.0.0.1:8000',
// '--suite', 'login',
// '--params.environment', 'test'
]
}))
.on('error', function(e) { throw e })
});
protractor.conf.js
exports.config = {
seleniumServerJar: './node_modules/webdriver-manager/selenium/selenium-server-standalone-3.9.0.jar',
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'chrome',
},
};
(using URL for selenium server is impotant)
Launch command:
gulp e2e

Protractor pointing to Sauce Labs Selenium Server

I'm trying to integrate Protractor with Sauce Labs from Travis. I can get the sauce_connect server running correctly but am unable to get Travis to point to that particular remote server.
Travis will get to the point where it initiates sauce_connect but when I run "protractor:analytics" it doesn't point to the correct server and fails.
Travis.yml:
language: python
python:
- 3.2_with_system_site_packages
branches:
only:
- develop
before_install:
- sudo apt-get update -qq
- sudo apt-get install python-numpy
install:
- cd lib && python setup.py install
- cd .. && pip install -r requirements/travis_requirements.txt
- npm install
script:
- grunt karma:single
- grunt protractor:analytics
env:
global:
- secure: <string>
- secure: <string>
sauce_connect: true
Gruntfile:
protractor: {
options: {
configFile: './webapp/static/test/e2e/protractor.conf.js',
keepAlive: true
},
singlerun: {},
analytics: {
options: {
//debug : true,
args:{
specs: ['./webapp/static/test/e2e/analytics_spec.js']
}
}
},
},
Protractor Conf:
exports.config = {
chromeOnly: false,
seleniumArgs: [],
// If sauceUser and sauceKey are specified, seleniumServerJar will be ignored.
// The tests will be run remotely using SauceLabs.
sauceUser: process.env.SAUCE_USER,
sauceKey: process.env.SAUCE_KEY,
baseUrl: 'http://localhost:8000',
specs: [
'./*_spec.js',
],
// Patterns to exclude.
exclude: [],
multiCapabilities: [],
// ----- More information for your tests ----
//
// A base URL for your application under test. Calls to protractor.get()
// with relative paths will be prepended with this.
baseUrl: process.env.SN_BASE_URL,
// Selector for the element housing the angular app - this defaults to
// body, but is necessary if ng-app is on a descendant of <body>
rootElement: 'body',
// A callback function called once protractor is ready and available, and
// before the specs are executed
// You can specify a file containing code to run by setting onPrepare to
// the filename string.
onPrepare: function() {
// At this point, global 'protractor' object will be set up, and jasmine
// will be available. For example, you can add a Jasmine reporter with:
// jasmine.getEnv().addReporter(new jasmine.JUnitXmlReporter(
// 'outputdir/', true, true));
},
// The params object will be passed directly to the protractor instance,
// and can be accessed from your test. It is an arbitrary object and can
// contain anything you may need in your test.
// This can be changed via the command line as:
// --params.login.user 'Joe'
params: {
login: {
user: process.env.SN_TEST_USERNAME,
password: process.env.SN_TEST_PASSWORD
}
},
framework: 'jasmine',
// ----- Options to be passed to minijasminenode -----
//
// See the full list at https://github.com/juliemr/minijasminenode
jasmineNodeOpts: {
// onComplete will be called just before the driver quits.
onComplete: null,
// If true, display spec names.
isVerbose: false,
// If true, print colors to the terminal.
showColors: true,
// If true, include stack traces in failures.
includeStackTrace: true,
// Default time to wait in ms before a test fails.
defaultTimeoutInterval: 30000
},
onCleanUp: function() {}
};
If I did understand well : Sauce connect tool is not used by protractor/selenium when running a test suite.
Well I had this problem, travis requires sauce credentials and protractor requires those credentials and a tunnel id:
.travis.yml:
addons:
sauce_connect:
username: xxx
access_key: xxx
protractor.conf.js:
exports.config = {
...
sauceUser: process.env.SAUCE_USERNAME,
sauceKey: process.env.SAUCE_ACCESS_KEY,
capabilities: {
...
'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER,
}
}