Showing posts with label node. Show all posts
Showing posts with label node. Show all posts

Thursday, 15 February 2018

Selenium Grid -> Get Node Ip address

public  void getNodeIpAddress(){
        try {
            URL url = new URL("http://hub-ip:4444//grid/api/testsession?session="+((RemoteWebDriver) driver).getSessionId().toString());
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", url.toExternalForm());
            DefaultHttpClient client = new DefaultHttpClient();
            HttpHost host = new HttpHost(url.getHost(), url.getPort());
            HttpResponse response = client.execute(host, request);           
            String responseBody=EntityUtils.toString(response.getEntity());
            System.out.println(responseBody);
//Here you can find ip addr of the node machine at ProxyId parameter
            //  URL nodeUrl = new URL(object.getString("proxyId"));
            //return nodeUrl.getHost();
        } catch (Exception e){
        }

Wednesday, 20 September 2017

WebdriverJs - Sample programme | Mocha | chai | Javascript

Here is the selenium web automaton sample code , using java script bindings.


Software Setup:
1.Install Node.js & npm
 Node.js from https://nodejs.org/en/download/ ( latest version and please install it )
- Node installs npm software by deault

verification: open command window and type
> node -v
7.2.1
>npm -v
3.10.10

2. Installing selenium :
Create a folder called "webdriver-js" any where and open a command window from the newly cerated folder "webdriver-js" and install selenium

>npm install --save--dev selenium-webdriver


3. install testing framework chai and mocha ( globally )
>npm install chai mocha -g


4. Download chromedriver.exe 
download and place the chromedriver.exe file here ( webdriver-js folder )
https://sites.google.com/a/chromium.org/chromedriver/downloads





5. Sample Script ( save as 'test-with-assert.js' in the same folder)


-------------------------------------


// Require chai.js expect module for assertions
var chai = require('chai');
var assert = require('chai').assert;

// URL
var url = 'http://www.google.com';

// Official selenium webdriver testing setup
var selenium = require('selenium-webdriver');

describe('Google.com Application test suite', function () {
    var driver;
    beforeEach(function(){
        // Start of test use this
        driver = new selenium.Builder().
        withCapabilities(selenium.Capabilities.chrome()).
        build();
        console.log("Selenium Webdriver Chrome Started");
    });

it('test#1 : verify google.com title', function (done) {      
        driver.get(url);
this.timeout(50000);
driver.getTitle().then(function(title) {
            assert.equal(title,'Google');
done();
            console.log("Selenium Webdriver Chrome Shutdown");
        })

    });

it('test#2 : verify google.com title when we searched for a text', function (done) {
        driver.get(url);
driver.findElement(selenium.By.name('q')).sendKeys("selenium");
driver.findElement(selenium.By.name('btnK')).click();
this.timeout(50000);
        driver.getTitle().then(function(title) {
            assert.equal(title,'selenium - Google Search');
            done();
            console.log("Selenium Webdriver Chrome Shutdown");
        })
    });

it('test#3 : verify that page is navigated to gmail on gmail link clicked', function (done) {
        driver.get(url);
driver.findElement(selenium.By.linkText('Gmail')).click();
this.timeout(50000);
        driver.getTitle().then(function(title) {
            assert.equal(title,'Gmail');
            done();
            console.log("Selenium Webdriver Chrome Shutdown");
        })
    });

    afterEach(function(){      
        driver.quit();
console.log("Selenium Webdriver Chrome Stopped");
    });

 
});



-------------------------------------



6.Run
>mocha test-with-assert.js

That's all .




with different way assertions : expect

------------------------
// Require chai.js expect module for assertions
var chai = require('chai');
var expect = require('chai').expect;

// URL
var url = 'http://www.google.com';

// Official selenium webdriver testing setup
var selenium = require('selenium-webdriver');

describe('Google.com Application test suite', function () {
    var driver;
    beforeEach(function(){
        // Start of test use this
        driver = new selenium.Builder().
        withCapabilities(selenium.Capabilities.chrome()).
        build();
        console.log("Selenium Webdriver Chrome Started");
    });

it('test#1 : verify google.com title', function (done) {
        driver.get(url);
        this.timeout(50000);
        driver.getTitle().then(function(title) {
            expect(title).to.equal('Google');
            done();
            console.log("Selenium Webdriver Chrome Shutdown");
        })
    });

it('test#2 : verify google.com title when we searched for a text', function (done) {
        driver.get(url);
driver.findElement(selenium.By.name('q')).sendKeys("selenium");
driver.findElement(selenium.By.name('btnK')).click();
this.timeout(50000);
        driver.getTitle().then(function(title) {
            expect(title).to.equal('selenium - Google Search');
            done();
            console.log("Selenium Webdriver Chrome Shutdown");
        })
    });

it('test#3 : verify that page is navigated to gmail on gmail link clicked', function (done) {
        driver.get(url);
driver.findElement(selenium.By.linkText('Gmail')).click();
this.timeout(50000);
        driver.getTitle().then(function(title) {
            expect(title).to.equal('Gmail');
            done();
            console.log("Selenium Webdriver Chrome Shutdown");
        })
    });

    afterEach(function(){      
        driver.quit();
console.log("Selenium Webdriver Chrome Stopped");
    });

 

});
-----------------------------------

Tuesday, 14 February 2017

Read xml file content


import java.io.*;
import java.nio.charset.Charset;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;

import org.w3c.dom.NodeList;

public class NewTest {

    public static void main(String[] args) throws IOException, SOAPException {

        String xmlInput = getTexFromXML("C:\\Inboud_testfile_before.xml");
        MessageFactory factory = MessageFactory.newInstance();
        SOAPMessage message = factory.createMessage(
                new MimeHeaders(),
                new ByteArrayInputStream(xmlInput.getBytes(Charset
                        .forName("UTF-8"))));
        SOAPBody body = message.getSOAPBody();
        getValue(body,"REC_MEME","MEME_CK",0);
    }

    private static String getTexFromXML(String xmlPath) {
        String xmlInput;
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(new File(xmlPath)));

            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line.trim());
            }
            xmlInput = sb.toString();
            return xmlInput;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return xmlPath;
    }

    public static void getValue(SOAPBody body, String parentNode, String childNode, Integer position)
    {
        NodeList returnList = body.getElementsByTagName(parentNode);
        for (int k = 0; k < returnList.getLength(); k++) {
            if(position==k) {
                NodeList innerResultList = returnList.item(k).getChildNodes();
                for (int l = 0; l < innerResultList.getLength(); l++) {
                    if (innerResultList.item(l).getNodeName()
                            .equalsIgnoreCase(childNode)) {
                        System.out.println(Integer.valueOf(innerResultList.item(l)
                                .getTextContent().trim()));
                    }
                }
            }
        }
    }
}

Friday, 3 June 2016

Node Require and Exports

A module encapsulates related code into a single unit of code. When creating a module, this can be interpreted as moving all related functions into a file.

---misc.js------
var x = 5;
var addX = function(value) {
  return value + x;
};

Now, before we look at how to expose things out of a module, let's look at loading a module. This is where require comes in. require is used to load a module, which is why its return value is typically assigned to a variable:

var misc = require('./misc');

as long as our module doesn't expose anything, the above isn't very useful. To expose things we use module.exports and export everything we want:

---misc.js------
var x = 5;
var addX = function(value) {
  return value + x;
};
module.exports.x = x;
module.exports.addX = addX;

--usage--
var misc = require('./misc');
console.log("Adding %d to 10 gives us %d", misc.x, misc.addX(10));


There's another way to expose things in a module:

var User = function(name, email) {
  this.name = name;
  this.email = email;
};
module.exports = User;

the last thing to consider is what happens when you directly export a function:

var powerLevel = function(level) {
  return level > 9000 ? "it's over 9000!!!" : level;
};
module.exports = powerLevel;
When you require the above file, the returned value is the actual function. This means that you can do:

require('./powerlevel')(9050);
Which is really just a condensed version of:

var powerLevel = require('./powerlevel')
powerLevel(9050);
Hope that helps!

Monday, 18 April 2016

Selenium Question


-          Assume, given web application is accessible in one Machine ( IP : 10.10.10.10)
-          You need to write selenium tests and run.
-          You are not allowed to install / download any software except browser in IP: 10.10.10.10.
How you do you achieve this?                                                 
Analysis:
-          We can start coding in our local laptop , later we can think about executing tests.
-          To find out locators ( xpaths / css / etc) , connect to the machine IP 10.10.10.10 via remote desktop and fetch as much info as needed.
Now Execution part,
-          When we execute our test in local, tests should run in the IP 10.10.10.10.
-          This can be achieved via selenium GRID.
-          Create a node in IP 10.10.10.10 and connect to a HUB ( either in your laptop / IP 10.10.10.10)
-          Write Remote web driver code instead of plain webdriver.

Just hit run. That’s all.

Selenium Grid (Advanced)

Selenium Grid distributes our tests across multiple machines so that we can run them in parallel, cutting down the time required for running tests.

The selenium-server-standalone package includes the Hub, WebDriver, and Selenium RC .

Setting up Hub: (Simple)
java -jar selenium-server-standalone-2.53.0.jar -port 4444 -role hub

Setting up Node:(Simple)
java -jar selenium-server-standalone-2.53.0.jar -role webdriver -hub http://xx.xx.xx.xx:4444/grid/register –port 8989

Setting up Node:(Complex)
If you want to setup a node with only IE browsers

Option1: via Command Text
java -jar selenium-server-standalone-2.53.0.jar -role webdriver -browser "browserName=internet explorer,version=11,maxinstance=1,platform=WINDOWS" -hub http://xx.xx.xx.xx:4444/grid/register –port 8989

Option2: via Json file

Save below Json as selenium-node-win-ie11-cfg.json

{
           "class": "org.openqa.grid.common.RegistrationRequest",

           "capabilities":
                              [
                                 { "seleniumProtocol": "WebDriver", 
                                    "browserName": "internet explorer",
                                    "version": "11",
                                    "maxInstances": 1,
                                    "platform" : "WINDOWS"
                                 }
                              ],

          "configuration":
                      {
                           "port": 8989,
                           "register": true,
                           "host": "xx.xx.xx.100", 
                           "proxy": "org.openqa.grid.selenium.proxy. DefaultRemoteProxy", 
                           "maxSession": 2,
                          "hubHost": "xx.xx.xx.100",
                          "role": "webdriver",
                          "registerCycle": 5000,
                          "hub": "http://xx.xx.xx.100:4444/grid/register",
                          "hubPort": 4444,
                          "remoteHost": "http://xx.xx.xx.101:8989"
                       }
}


one more json:


{
  "capabilities":
      [
        {
          "browserName": "chrome",
          "maxInstances": 5
        },
        {
          "browserName": "firefox",
          "maxInstances": 5
        },
        {
          "browserName": "internet explorer",
          "maxInstances": 5
        },
        {
          "browserName": "safari",
          "maxInstances": 5
        }
      ],
    "configuration":
        {
"_comment": "Configuration for Node",
        "nodeTimeout":120,
        "port":5555,
        "hubPort":4444,
        "hubHost":"hubIpAddress",
        "nodePolling":2000,
        "registerCycle":10000,
        "register":true,
        "cleanUpCycle":2000,
        "timeout":30000,
        "maxSession":5,
        }
}


Command Text:

java -jar selenium-server-standalone-53.jar -role webdriver -nodeConfig selenium-node-win-ie11-cfg.json


Selenium Remote WebDriver code:

DesiredCapabilities cap = new DesiredCapabilities();  
                                cap.setBrowserName("firefox");
                                cap.setPlatform(org.openqa.selenium.Platform.WINDOWS);


WebDriver driver = new RemoteWebDriver(new URL("http://xx.xx.xx.xx:4444/wd/hub"),cap);



Suite.
xml:

<suite name="Parallel Tests" verbose="1" thread-count="4"
parallel="tests">

</suite>

thread-count=“4” describes the maximum number of threads to be executed in parallel.


---------------------------------------------------------------------------------------------------------------------------------

Each node contains  
5 Chrome, 5 Firefox and 1 IE browser under Browser section like below.




Do you want only one IE browser?

java -jar selenium-server-standalone-2.41.0.jar -role webdriver -hub
http://localhost:4444/grid/register -port 5556 -browser browserName=iexplore




You want one browser per each type?

java -jar selenium-server-standalone-2.41.0.jar -role webdriver -hub
http://localhost:4444/grid/register -port 5556 -browser browserName=iexplore
-browser browserName=firefox -browser browserName=chrome




maxInstances:

maxInstance is used to limit the number of browser initialization in a node.
For example if you want to work with 2 Firefox and 2 IE then you can start the node using maxInstance.
java -jar selenium-server-standalone-2.41.0.jar -role webdriver -hub 
http://localhost:4444/grid/register -port 5556 -browser browserName=firefox,maxInstance=3


maxSession:
maxSession is used to configure how many number of browsers can be used parallel in the remote system.
java -jar selenium-server-standalone-2.41.0.jar -role webdriver -hub http://localhost:4444/grid/register -port 5556 -browser browserName=chrome,maxInstance=3 -browser browserName=firefox,maxInstance=3 –maxSession 3



Selenium Grid ( Simple )

Selenium Grid distributes our tests across multiple machines so that we can run them in parallel, cutting down the time required for running tests.

The selenium-server-standalone package includes the Hub, WebDriver, and Selenium RC needed to run the grid.

Setting up Hub: (Simple)
java -jar selenium-server-standalone-2.53.0.jar -port 4444 -role hub

Setting up Node:(Simple)
java -jar selenium-server-standalone-2.53.0.jar -role webdriver -hub http://xx.xx.xx.xx:4444/grid/register –port 8989 -Dwebdriver.chrome.driver=path/to/chromedriver.exe


Selenium Remote WebDriver code:

DesiredCapabilities cap = new DesiredCapabilities(); 
                                cap.setBrowserName("firefox");
                                cap.setPlatform(org.openqa.selenium.Platform.WINDOWS);


WebDriver driver = new RemoteWebDriver(new URL("http://xx.xx.xx.xx:4444/wd/hub"),cap);


Thats all.