How to add cookie to Selenium IDE test running in grid via selenium-side-runner for Zalenium messages - selenium

I've recorded a test using Selenium IDE and am submitting the generated .side file to selenium-side-runner to run on a Selenium Grid built using Zalenium. Is it possible to run a command that calls driver.manage().addCookie() from the test that was submitted to selenium-side-runner? I want to do this to send messages back to Zalenium with test progress and status
I added a command executeScript to the Selenium IDE editor with a target of driver.manage().addCookie({name: 'test', value: 'test'})
I see that the command that selenium-side-runner generated in commons.js was
await driver.executeScript(`driver.manage().addCookie({name:'test', value: 'test'});`);
Doing this causes the browser to report an error JavascriptError: javascript error: driver is not defined
I think what I need is the code to be generated without the driver.executeScript wrapper. Is there a way to accomplish this without exporting my Selenium IDE test to NUnit?

I was able to make this functionality work by crudely modifying the selenium-side-runner package on my Windows dev machine
In file ~\node_modules\selenium-side-runner\node_modules\selianize\dist\selianize.cjs.js
Change
function generateScript(script, isExpression = false) {
return `await driver.executeScript(\`${isExpression ? `return (${script.script})` : script.script}\`${script.argv.length ? ',' : ''}${script.argv.map(n => `vars["${n}"]`).join(',')});`;
}
to
function generateScript(script, isExpression = false) {
if (script.script.indexOf('zalenium') > -1)
{
return script.script;
} else
{
return `await driver.executeScript(\`${isExpression ? `return (${script.script})` : script.script}\`${script.argv.length ? ',' : ''}${script.argv.map(n => `vars["${n}"]`).join(',')});`;
}
}
Now when running a test with selenium-side-runner, calling "executeScript" with any value that contains zalenium will generate the command verbatim in the test script

Related

chrome:headless (MacOS) results with ' 1) AssertionError: expected 'about:blank' to include $target page'

I am using TestCafe in combination with gherkinTestcafe (steps) / cucumber.
I am also using environment variables so that i can run my tests on 2 different environments.
My code is as follows, although through debugging, i don't believe this is something strictly code related, as much as it is related to:
chrome:headless
environment
version of chrome / MacOS
import Enviorments from "../../../../../../AEM_Engine/Enviorment/Enviorments";
import { Helper } from "../../../../../TestActions/Test_specific/Career_helper";
import {AddAuthCredentialsHook} from "../../../../../TestActions/BasicAuth";
const {Before, Given, Then} = require('cucumber');
let publisher = new Publish();
let aemEnv = new Enviorments();
let helper = new Helper;
let careersPage = '/career';
Before('#basicAuth', async testController => {
const addAuthCredentialsHook = new AddAuthCredentialsHook('$someUserName', '$somePassword');
await testController.addRequestHooks(addAuthCredentialsHook);
});
Before('#disableCookie', async testController => {
await testController.addRequestHooks(publisher.mockCookieResponse);
});
Given('I am at Careers page', async testController => {
await publisher.Navigate(testController, aemEnv.frontEndURL + careersPage);
await publisher.verifyURL(testController, aemEnv.frontEndURL + careersPage);
});
.
.
.
When i wait for the script to run i have
1) AssertionError: expected 'about:blank' to include $expectedPage
As i mentioned, i don't believe the problem is in the code. Even if i remove the step for verifying the current URL location, the test fails on the next step after.
Tests pass on
Chrome (with UI shell)
Other browsers (firefox, safari), headless or with UI shell
Second (staging) environment
When Tests are run and TestCafe starts, i get the following info
Running tests in:
- HeadlessChrome 99.0.4844 / Mac OS X 10.15.7
Feature: Careers Page Available
(node:87344) Warning: Setting the NODE_TLS_REJECT_UNAUTHORIZED environment variable to '0' makes TLS connections and HTTPS requests insecure by disabling certificate verification.
I tried re-installing some packages, re-writing some of the steps, adding some flags to clear cache, change chrome port or similar, but nothing worked.
Any thoughts on what might be causing this and how to solve it?

Karate UI: How to initialize a new driver in JS [duplicate]

I was trying to find a way to launch all features in Karate testing through maven using an external variable to set up the browser (with a local webdriver or using a Selenium grid).
So something like:
mvn test -Dbrowser=chrome (or firefox, safari, etc)
or using a Selenium grid:
mvn test -Dbrowser=chrome (or firefox, safari, etc) -Dgrid="grid url"
With Cucumber and Java this was quite simple using a singleton for setting up a global webdriver that was then used in all tests. In this way I could run the tests with different local or remote webdrivers.
In Karate I tried different solution, the last was to:
define the Karate config file a variable "browser"
use the variable "browser" in a single feature "X" in which I set up only the Karate driver
from all the other features with callonce to re-call the feature "X" for using that driver
but it didn't work and to be honest it doesn't seem to me to be the right approach.
Probably being able to set the Karate driver from a Javascript function inside the features is the right way but I was not able to find a solution of that.
Another problem I found with karate is differentiating the behavior using a local or a remote webdriver as in the features files they're set in different ways.
So does anyone had my same needs and how can I solve it?
With the suggestions of Peter Thomas I used this karate-config.js
function fn() {
// browser settings, if not set it takes chrome
var browser = karate.properties['browser'] || 'chrome';
karate.log('the browser set is: ' + browser + ', default: "chrome"');
// grid flag, if not set it takes false. The grid url is in this format http://localhost:4444/wd/hub
var grid_url = karate.properties['grid_url'] || false;
karate.log('the grid url set is: ' + grid_url + ', default: false');
// configurations.
var config = {
host: 'http://httpstat.us/'
};
if (browser == 'chrome') {
if (!grid_url) {
karate.configure('driver', { type: 'chromedriver', executable: 'chromedriver' });
karate.log("Selected Chrome");
} else {
karate.configure('driver', { type: 'chromedriver', start: false, webDriverUrl: grid_url });
karate.log("Selected Chrome in grid");
}
} else if (browser == 'firefox') {
if (!grid_url) {
karate.configure('driver', { type: 'geckodriver', executable: 'geckodriver' });
karate.log("Selected Firefox");
} else {
karate.configure('driver', { type: 'geckodriver', start: false, webDriverUrl: grid_url });
karate.log("Selected Firefox in grid");
}
}
return config;
}
In this way I was able to call the the test suite specifying the browser to use directly from the command line (to be used in a Jenkins pipeline):
mvn clean test -Dbrowser=firefox -Dgrid_url=http://localhost:4444/wd/hub
Here are a couple of principles. Karate is responsible for starting the driver (the equivalent of the Selenium WebDriver). All you need to do is set up the configure driver as described here: https://github.com/intuit/karate/tree/master/karate-core#configure-driver
Finally, depending on your environment, just switch the driver config. This can easily be done in karate-config.js actually (globally) instead of in each feature file:
function fn() {
var config = {
baseUrl: 'https://qa.mycompany.com'
};
if (karate.env == 'chrome') {
karate.configure('driver', { type: 'chromedriver', start: false, webDriverUrl: 'http://somehost:9515/wd/hub' });
}
return config;
}
And on the command-line:
mvn test -Dkarate.env=chrome
I suggest you get familiar with Karate's configuration: https://github.com/intuit/karate#configuration - it actually ends up being simpler than typical Java / Maven projects.
Another way is to set variables in the karate-config.js and then use them in feature files.
* configure driver = { type: '#(myVariableFromConfig)' }
Keep these principles in mind:
Any driver instances created by a "top level" feature will be available to "called" features
You can even call a "common" feature, create the driver there, and it will be set in the "calling" feature
Any driver created will be closed when the "top level" feature ends
You don't need any other patterns.
EDIT: there's some more details in the documentation: https://github.com/intuit/karate/tree/develop/karate-core#code-reuse
And for parallel execution or trying to re-use a single browser for all tests, refer: https://stackoverflow.com/a/60387907/143475

selenium-server won't `setValue`

I'm using selenium-server version 3.0.1 and nightwatch version ^0.9.12 on node 8.9.0. My e2e test do run, clicks work, and reading the DOM works, but setValue just doesn't.
For example, the following test:
browser
.url("...")
.waitForElementPresent('select[name=foo]', 5000)
.click('select[name=foo] option:nth-child(2)')
.waitForElementPresent('input[name=bar]', 5000)
.setValue('input[name=bar]', "hello world")
.getValue('input[name=bar]', function(input) {
this.assert.equal(input.value, "hello world");
})
.end();
will open the url, wait for foo and click the second option. It will wait for bar, then fails:
Running: test
✔ Element <select[name=foo]> was present after 24 milliseconds.
✔ Element <input[name=bar]> was present after 28 milliseconds.
✖ Failed [equal]: ('' == 'hello world') - expected "hello world" but got: ""
at Object.<anonymous> (/test/e2e/specs/test.js:49:21)
FAILED: 1 assertions failed and 2 passed (4.692s)
_________________________________________________
TEST FAILURE: 1 assertions failed, 2 passed. (4.9s)
✖ test
- run through apply process (4.692s)
Failed [equal]: ('' == 'hello world') - expected "hello world" but got: ""
If I replace the setValue with a delay and enter a value by hand, the test will pass, so getValue is working.
This does run, and pass, on other systems, but I can't get it working on my own so I think it's a selenium-server issue.
I've tried a lot of the 101 fixes, clearing the npm cache, re-running an npm install, etc. But with no errors other than the failure, how do I debug this?
Assuming you are trying to test using Chrome, you need to update your ChromeDriver.
Chrome 65 was released recently and older ChromeDriver versions are apparently incompatible with it.
Download the latest one from the downloads page.
Make Nightwatch use it, nightwatch.json -
{
...
"selenium": {
...
"cli_args": {
"webdriver.chrome.driver": "path/to/chromedriver.exe"
Assuming Nightwatch uses it (you can see which one it uses using the Windows Task Manager - assuming you are using Windows - look for the command line of chromedriver.exe), setValue should now work again.
The error says it all :
Failed [equal]: ('' == 'hello world') - expected "hello world" but got: ""
In your code block you have induced wait for the WebElement identified as 'input[name=bar]' and next invoked setValue() which is successful as follows :
.waitForElementPresent('input[name=bar]', 5000)
.setValue('input[name=bar]', "hello world")
Now the JavaScript associated with this WebElement identified as 'input[name=bar]' will require some time to render the value within the HTML DOM. But in you code block you are trying to access the entered value (in the previous step) too early. Hence your script finds <null> as the value.
Solution
You need to induce a waiter i.e. expect clause for the value to be rendered within the HTML DOM through the associated JavaScript as follows :
.waitForElementPresent('input[name=bar]', 5000)
.setValue('input[name=bar]', "hello world")
.expect.element('input[name=bar]').to.have.value.that.equals('hello world');
.getValue('input[name=bar]', function(input) {
this.assert.equal(input.value, "hello world");
})

Selenium test fails when running phantomjs

I using nightwatch framework for running End-to-End test. I am able to run all the test cases successfully in chrome and IE but few tests fails for phantomjs. Test cases below error out
'Search' : function(browser) {
browser
.url('http://localhost:8001/index.html')
browser
.setValue('input[id=SearchInput-inner]', 'abc')
.click('button[id=nsnButton]')
.pause('1000')
.verify.attributeEquals('#nsnButton', 'disabled', 'true')
},
Error I get is
Testing if attribute disabled of <#nsnButton> equals "true". Element does not have a disabled attribute. - expected "true" but got: "null"
other test that fails is
.getCssProperty('#SearchInput-inner', 'border-color', function(result) {
this.verify.equal(result.value, '#ee0000');
})
Error I get is Failed [equal]: ('rgb(238, 0, 0)' == '#ee0000') - expected "#ee0000" but got: "rgb(238, 0, 0)"
How Can I handle this situation where same test works for ie and chrome but fails for phantomjs.
Thanks

Selenium-rc window causes permission denied message in IE

I am testing with Selenium-rc 1.0.3 and I am getting a Permission denied error message in IE when I run my IDE script from the command line.
I am trying to run an IDE script in Internet explorer using the selenium control RC 1.0.3
from the command line:
java -jar selenium-server.jar -htmlsuite "*iexploreproxy" "url
address/where" "C:\Users\sat\Documents\selenium\suite.html"
"C:\Users\sat\Documents\selenium scripts\results.htm" at this point
The IE window pops up saying as below
I get a security warning saying "Do you want to view only the webpage content that was delivered securely?" I hit Yes and I see this error in the test runner window:
Webpage error details
Message: Access is denied.
Line: 177
Char: 9
Code: 0
URI: xx.xx.xx.xxx/selenium-server/core/scripts/selenium-testrunner.js
UPDATE:
I looked at the line 177 and char :9 in the script and it points to
var runInterval = 0;
/** SeleniumFrame encapsulates an iframe element */
var SeleniumFrame = classCreate();
objectExtend(SeleniumFrame.prototype, {
initialize : function(frame) {
this.frame = frame;
addLoadListener(this.frame, fnBind(this._handleLoad, this));
},
getWindow : function() {
return this.frame.contentWindow;
},
getDocument : function() {
return this.frame.contentWindow.document; - line 177 char 9
},
_handleLoad: function() {
this._attachStylesheet();
this._onLoad();
if (this.loadCallback) {
this.loadCallback();
}
Do you know what the error is about? Why do I get that? I see my test cases and everything in the test runner window, but I can't run them in the IE browser. I searched the web with no avail.
I do not have much experience with running the test from CLI, but have you tried starting Selenium RC with administrator permission?
Any particular reason for not using the new Selenium 2 IWebDriver and a test framework?
The error might be caused by the use of iframe/frameset and IE's security settings. Default settings are that, if a site uses iframe/frameset and the frame content originates from 2 different root domains, then this is a security risk. Try is add the sites to your list thrusted site for IE. Have you tried to ude the firefox driver instead (will not have this security restriction).