Wednesday, December 30, 2015

Python Interview questions

1. What is constructors in python?
2. How do inherit in python?
3. Name the types of datatypes in python?

Python has five standard data types:
1. Numbers
2. Strings
3. List
4. Tuple
5. Dictionary

Python supports four different numerical types:
1. int (signed integers)
2. long (long integers, they can also represented in octal and hexa decimal)
3. Float
4. Complex


4. Name the types of  variables in python? and how to configure the private, public variables and how to access them?

5. How do you reverse the string?


How do you login the webpage using python scripting without selenium web driver?

6. Write a class that keeps track of all the identifiers of objects created while instantiating?

7. Write a method that takes two dimensional list as argument and gives the transpose of the list
(Eg:)
def transpose(input_list):
    #Your Code here
    return output_list

a = [[1,2,3],[4,5,6]]


print transpose(a)
#Outputs[[1,4],[2,5],[3,6]]

8. Read a file and print only the strings from the file.

def Main():
        with open('word.txt','r') as f:
                for line in f:
                        for i in line.split(" "):
                                for x in i.rstrip("\n").split():
                                        if x.isalpha() == True:
                                                print x


if __name__ == "__main__":
        Main()


9. Write a class which implements method overloading?

10. What is the output of the following code?

def fun1(a=None):
    print "In the first function"

def fun1(a):
   print "In the second function"



Saturday, October 31, 2015

API testing: SoapUI property transfer using Groovy scripting

//Importing XML module of SoapUI tool
import com.eviware.soapui.support.XmlHolder



//Access the Get_Employee Response XML and get the value of name tag.
def response=context.expand('${GetEmployee#response}')
def xml=new XmlHolder(response)
def namenode = xml.getNodeValue("//ns:name")
log.info namenode
context.setProperty("name","$namenode")
log.info context.getProperty("name")

//Access the Delete Employee Request XML and store the value grabbed from the Get Employee Response
def requestt = context.expand('${DeleteEmployee#request}')
def xmlreq=new XmlHolder(requestt)
xmlreq.setNodeValue("//typ:guestName", namenode)

//Formatting the xml and put it in the Testcase, Teststeps level 
def dxml = xmlreq.getXml()
testRunner.testCase.testSteps["DeleteEmployee"].setPropertyValue("request",dxml)

Monday, October 26, 2015

Python requests and grab values from json response

__author__ = 'valli_000'

import requests

r = requests.get('http://api.fixer.io/latest?base=USD')
data = r.json()
dict = data['rates']
for key,value in dict.iteritems():
    print "US Dollar Conversion of " + str(key) + " is " + str(value)

Wednesday, October 14, 2015

Sikuli: check multiple of the same/duplicate images and choose the image to perform action

def by_y(match):

   return match.y


icons = findAll("Capture.PNG")



# sort the icons by their y coordinates and put them into a new variable sorted_icons

sorted_icons = sorted(icons, key=by_y)

# another shorter version is using lambda.

print sorted_icons[3]


# Iterate the images and hover it - To confirm

for icon in list(sorted_icons)[:2]:

    hover(icon)


#Click the 4th image from the list.

click(list(sorted_icons)[4])

Saturday, October 3, 2015

Groovy scripting: Class

Bank.log=log
log.info("Hello World!")
Bank obj1 = new Bank()
Bank obj2 = new Bank()

obj1.accountnumber=1235
obj1.accounttype="Savings"
obj2.accountnumber=54321
obj2.accounttype="Current"

//log.info obj1.accountnumber + " " + obj1.accounttype
//log.info obj2.accountnumber + "  " + obj2.accounttype
log.info obj1.printaccount()



class Bank{

def static log
def accountnumber
def accounttype

public void printaccount(){
log.info("Your account type is $accounttype and number is $accountnumber")
}
}


Output:

Sat Oct 03 15:54:38 IST 2015:INFO:Hello World!
Sat Oct 03 15:54:38 IST 2015:INFO:Your account type is Savings and number is 1235
Sat Oct 03 15:54:38 IST 2015:INFO:null

Friday, October 2, 2015

Python: Encapsulation

Sample program

class Animal:
    def __init__(self, Animalname):
        self.__Animalname = Animalname

    def name(self):
        return self.__Animalname



x = Animal("This")
print x.name()

t = Animal("Pet2")
print t.__Animalname


Output:

C:\Python27\python.exe E:/Scripts_to_learn/Scripts_to_learn/Encapsulation.py

This

Traceback (most recent call last):
  File "E:/Scripts_to_learn/Scripts_to_learn/Encapsulation.py", line 17, in <module>
    print t.__Animalname
AttributeError: Animal instance has no attribute '__Animalname'


Notes:

1. To make the attribute private, use "__". So that it can't be accessed from outside
2. To know/use the private attribute, create a method as above (Eg: Above 'name' method)



Python polymorphism

Note
http://stackoverflow.com/questions/3724110/practical-example-of-polymorphism

Example:

#__author__ = 'valli_000'


class Animal(object):
    def __init__(self, Animalname):
        self.Animalname = Animalname

    def talk(self):
        pass


class Dog(Animal):
    def __init__(self, Animalname):
        super(self.__class__, self).__init__(Animalname)

    def talk(self):
        print "Sound of Animal " + self.Animalname + " is Bow Bow !"


class cat(Animal):
    def __init__(self, Animalname):
        super(self.__class__, self).__init__(Animalname)

    def talk(self):
        print "Sound of Animal " + self.Animalname + " is Meow Meow !"


x = cat("Pet 1")
x.talk()

y = Dog("Pet 2")
y.talk()


output:
C:\Python27\python.exe C:/Users/valli_000/PycharmProjects/Selflearning/Polymorphism.py

Sound of Animal Pet 1 is Meow Meow !
Sound of Animal Pet 2 is Bow Bow !

Process finished with exit code 0

Python Inheritace (accessing the init variables of base class from child class)


>>> class Baseclass(object):
...     def __init__(self, number):
...             self.number = number
...
...
>>> class childclass(Baseclass):

...     def __init__(self, number, number2):
...             self.number2 = number2
...             super(self.__class__, self).__init__(number)
...     def add(self):
...             return self.number + self.number2

>>> c = childclass(2,3)
>>> c.add()
5

Here, Accessing the init variables of base class from inside the child class  (i.e use the values of base class inside the child class)


Reference: http://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods



Case 2:  (Here we are accessing the parent variables from the child object, not from the child class/methods)

class base:
...     var1 = "Base class"
...     def __init__(self, number):
...             self.number = 5
...

class child(base):
...     var2 = "child class"
...     def add(self):
...             pass



Output:

 y = child(3)
>>> y.number
5

Python: Method overriding

Python Method overriding:

Parent class:

class pclass:
...     var1="Im in parent class"
...     def add(self, number1, number2):
...             return number1 + number2


Child Class:


class cclass(pclass):
...     var1="Im in parent class"
...     def add(self, number1, number2, number3):

...             return number1 + number2+number3


Here, we override the "add" method of parent class in the child class. See the output


Output:

>> c = class()
>> c.add(1,2,3)
>> 6

So, it uses only the add method of the child class, not the parent class


Note: Child class is also called as sub class


Why overriding is required?

One reason for overriding parent's methods is because you may want special or different functionality in your subclass.

Saturday, September 26, 2015

Notes

Funkload
holmiumcore  - page object models

Saturday, September 12, 2015

Robot framework + SSH Library + Monitor a log file until a string matches using Jython

SSH library installation.

1. Download SSH library and install using "jython setup.py install" command
2. Download Trilead-ssh2-1.0.0-build217.jar file and put it in a folder
3. Add that folder in the "CLASSPATH"

Eg: E:\Robot\trilead-ssh2-1.0.0-build217.jar;C:\Python27\Lib\site-packages

4. Similarly add "robot" folder in the JYTHONPATH

Eg: C:\Python27\Lib\site-packages\robot;C:\Python27\Lib\site-packages

5. Execute command jython -c "import SSHLibrary" for verification

Sample SSH Robot script

*** Settings ***
Documentation  Open Notepad using Sikuli and Robotframework

Library    SSHLibrary

*** Variables ***
${HOST}                192.168.10.135
${USERNAME}            test
${PASSWORD}            test

*** Test Cases ***
Open Connection And Log In
    Open Connection    ${HOST}
    Login    ${USERNAME}    ${PASSWORD}

Execute and expect a new session
    ${OUT}=    Execute Command    timeout 5 tail -f -n 1 /var/log/messages | awk '/vallikkv/;/vallikkv/ { exit }'
    BuiltIn.Log to console    ${OUT}
    BuiltIn.Should Not Be Equal    ${OUT}    \  
    

Closing the connections
    BuiltIn.Log to console    Test
    Close All Connections


ButiltIn.Log to console -> This is how, use the inbuilt keywords of robot(python) in jython scripts

Shell command to monitor log file until specific "word" matches, if not exit the script in 5 seconds


timeout 5 tail -f -n 1 /var/log/messages | awk '/vallikkv/;/vallikkv/ { exit }'  







Wednesday, September 9, 2015

Jython remote library

Remote library for Jython/Jybot with sikuli

Machine 1:
1. Installed jython 2.5.2, Jybot, Sikuli
2. Install robot remote server using command "jython setup.py install"
       Note: Download robotremoteserver.tgz file and install
3. Own library for sikuli


Machine 2:
1.Robot framework, jython 2.5.2, jybot
2. Test scripts (Eg: Notepad.robot)

STEPS:

1. Run the sikuli library using command "jython <sikulilibrary>"

It will start the Remote library for the interface configured in the library file and exposed keywords

2.  Now run the robot script from any network machines using command

"jybot <Notepad.robot>"


The testresults will be available in the local machine (i.e Machine2)

Tuesday, September 8, 2015

Robot framework: Remote library

How to use simple remote library in robot framework? (Only for Python)

Pre-requisities:
1. Robot framework should be installed
2. Pybot command should work fine.

STEP 1:
Install robot remote server using command.

pip install robotremoteserver

Refer: https://github.com/robotframework/PythonRemoteServer

STEP 2:
Create a file as mentioned in the above link


from robotremoteserver import RobotRemoteServer
from mylibrary import MyLibrary

RobotRemoteServer(MyLibrary())

Remotelib.py:

if __name__ == '__main__':
    import sys
    from robotremoteserver import RobotRemoteServer
    from Example import test

    RobotRemoteServer(test(), host='192.168.10.104', port=8270, allow_stop=False)

192.168.10.104 - Remote machine ip where remote library exists


Here i have created a sample Example library with class "test"

Example.py

#!/usr/bin/env python

class test(object):
    """ Sample doc"""

    def add(self,x,y):
        self.x = int(x)
        self.y = int(y)
        return str(self.x + self.y)

STEP 3:
Start the Remoteserver  - command python Remotelib.py



STEP 4:
Sample Robot script


*Settings*
Documentation               This is just a tutorial for Remote library

Library    Remote    http://192.168.10.104:8270

*** Test Cases ***
Check Remote library first keyword
    [Documentation]         Check ADD keyword of remote library
    ${ANS}=    Add    1    6
    Should Be Equal    ${ANS}    7



STEP 5:
Test execution:






 

Thursday, August 20, 2015

Python Matrix Multiplication

def MatrixProduct(a, b):
    d=[]
    i=0
    while i<len(a):
        j=0
        e=[]
        while j<len(b[0]):
            k=0
            r=0
            while k<len(a[0]):
                r+=a[i][k]*b[k][j]
                k+=1
            j+=1
            e.append(r)
        d.append(e)
        i+=1
    return d

Wednesday, June 24, 2015

Sikuli Robotframework general libary + Robot testcase + Open a notepad

General sikuli robotframework library:

'''
Created on Jun 24, 2015

@author: vallikkv @ Vallinayagam.K
'''

from sikuli import *
from Screenshot import *


class SikuliLib(object):
    ROBOT_CONTINUE_ON_FAILURE = True
    myImagePath = "C:\\sikulix\\Images"
    addImagePath(myImagePath)

    def __init__(self):
        self.screen = Screenshot()

    def click_window(self, inputfile):
        self.inputfile = inputfile
        if exists(self.inputfile):
            find(self.inputfile)
            click(self.inputfile)
        else:
            self.screen.take_screenshot()
            raise AssertionError("Required screen to click is not available")

    def Type_and_enter(self, inputtotype, inputfile1):
        self.inputtotype = inputtotype
        self.inputfile1 = inputfile1
        if exists(self.inputfile1):
            find(self.inputfile1)
            type(self.inputtotype + Key.ENTER)
        else:
            self.screen.take_screenshot()
            raise AssertionError("Typing To inputfile is failed")

    def expected_screen(self, expectedfile):
        self.expectedfile = expectedfile
        if not exists(self.expectedfile):
            self.screen.take_screenshot()
            raise AssertionError("Error, Failed")
        else:
            pass



Robot Testcase using above library:

*** Settings ***
Documentation  Open Notepad using Sikuli and Robotframework

Library  Sikulilibrary.SikuliLib

*** Test Cases ***
Open a Notepad
    click window    windowicon.PNG
    click window    search.png
    Type and enter  notepad.exe    typerun.png
    expected screen  notepad.png

Failed Log:

By Giving wrong File name in the "Type and enter" keyword




Passed Log:







Sikuli + Robotframework + jybot - Execution with screenshot

Sample code:

Created on Jun 24, 2015

@author: vallikkv @ Vallinayagam.K
'''

from robot.api import *
import org.sikuli.basics.SikuliXforJython
from sikuli import *
from Screenshot import *

##Screenshot.py is copied and available in the location "C:\Python27\Lib\site-packages", or declare ##the path where screenshot.py is located.


class Notepad(object):
    ROBOT_CONTINUE_ON_FAILURE = True
    myImagePath = "C:\\sikuli\\Tests.sikuli\Notepad"
    addImagePath(myImagePath)

    def __init__(self):
        self.screen = Screenshot()

    def click_window(self):
        try:
            find("WindowsIcon.PNG")
            click("WindowsIcon.PNG")
        except Exception:
            print "Error in the click window"

    def Type_in_run_and_enter(self):
        try:
            wait("Runwindow.PNG", 5)
            type("notepad.exed"+ Key.ENTER)
        except Exception:
            print "Problem in second step"

    def verify_result(self):
        if not exists("Notepad.PNG"):
            self.screen.take_screenshot()
            raise AssertionError("Error, Failed")
        else:
            pass



Command used to execuet - jython C:\Python27\Lib\site-packages\robot\run.py C:\sikuli\Tests.sikuli\Notepad\Robot.txt


It will embeed screenshots when failed, I've used only for the verify_result method, It should be included for all the methods.

Tuesday, June 23, 2015

How to create Robot Framework Test library for Sikuli jython scripts: (Content Not yet Finalized: Warning)

1. Create Jython script, Filename -  Sample1.py

import org.sikuli.basics.SikuliXforJython
from sikuli import *


class Sample(object):

    def testing(self):
        print "testing"
        try:
            click("1.PNG")
            wait("1.PNG", FOREVER)
        except:
            print "Click windows icon is not occured - Failed "
        
       
#if __name__=='__main__':
#    test = Sample()
#    test.testing()
    
2.  Create Robot Library for the created script

*** Settings ***
Library    Sample1.Sample              

*** Test Cases ***
Sample testcase
    testing


3. Sikuliwrapper details: TO DO

4. Execute it as below





Monday, June 22, 2015

How to install sikuli for Jython?

How to install sikuli for Jython?

Before starting with sikuli installation, Install Jython 2.5.2 (In my windows 8.1, it not works with jython 2.5.3, So I used the earlier one). Refer my earlier post for jython installation

1. Download sikuli-setup.jar file and save it in a location: Eg: "C:\sikulix"

2. Now open the command prompt and go to the "C:\sikulix" location and execute command
      java -jar sikuli-setup.jar

3. It will generate a file named "runSetup.cmd" and available in the same location.

4. Now execute the command, it opens a installer window.

5. Choose the options for jython (2,4)

6. It will automatically download the required files from internet.

7. Once installation is completed, declare the following values in the system enviroment table




8. Now close the command prompt and open a new one

9. Open jython and import sikuli to verify everything works fine


Thursday, June 18, 2015

How to install jython in windows?

How to install jython in windows?

1. Download jython installer jar file from http://www.jython.org/downloads.html

          jython-installer-2.5.3.jar

2. Open command prompt and go to that downloaded location and execute

         java -jar jython-installer-2.5.3.jar

3. It will open a installer window, follow the instructions and install it.

4. Now open a  new command prompt and type "jython" and check it opens the interpreter window.


Note: To set path in environment variable, use path where the jython folder is available, in my case it's "C:\jython2.5.3"





Wednesday, June 17, 2015

Sikuli + Eclipse + java

How to execute sikuli script using Eclipse + java?

1. Download sikuli-setup.jar

2. Execute in cmd prompt "java -jar sikuli-setup.jar" file. It will generate runSetup.cmd in the same folder.

3. Execute it via cmd prompt.

4. It will lauch a window, choose the options "Download for IDE, eclipse" and for "windows, mac"

5. It will download sikuli-java.jar file.

6. Now open the eclipse, create a package -> create a project -> Add TestNG library and Sikuli-java.jar.

7. Save and reboot the pc (It requires a logout and login to activate)

8. Lauch eclipse and create a TestNG Class and write your code.(Note:- TestNG installation for eclipse is not covered here)

Sample code:

package sample_sikuli;

import org.sikuli.script.FindFailed;
import org.sikuli.script.Screen;
import org.testng.annotations.Test;

public class NewTest {
Screen s = new Screen();
  @Test
  public void Sample() {
 try {
s.click("C:/Users/USER/Desktop/1.png");
s.click("C:/Users/USER/Desktop/2.png");
s.click("C:/Users/USER/Desktop/3.png");
s.type("notepad.exe");
} catch (FindFailed e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
  }
}




Tuesday, June 16, 2015

Robotframework + Selenium2Library + Jenkins

Robotframework + Selenium2Library + Jenkins

How to run robotframework selenium testcases using jenkins - UI Based.

1. Download Jenkins.war file and start via cmd.



2.  Once its started, it can be accessible via 'http://localhost:8080'

3.  Install the  Robotframework plugin using Manage Jenkin -> Plugin option.

4. Once it's installed, it will be displayed in the "Installed" tab



5. Now create a job and Configure as below. (I explained here with having build management as None).




6. Once its created, You can start the job and see the robot output files in


Tuesday, April 7, 2015

Robotframework - Parallel test execution of two different testsuites on two different machines.

Robotframework - Parallel test execution of two different testsuites on two different machines.





Step 1:
Install the selenium server "http://docs.seleniumhq.org/download/" from the location.

Filename -  selenium-server-standalone-3.8.1.jar (Version will be different in your case)

Step 2:
From Machine1 command prompt, Go to the jar application location and launch it as 'hub' by giving commmand

java -jar selenium-server-standalone-3.8.1.jar -role hub

Step 3:
From Machine2 command prompt, Go to the jar application location and launch it as 'node' by giving command

java -jar selenium-server-standalone-3.8.1.jar -role node -hub http://<Machine 1 IP address>:4444/grid/register -port 5566

Test cases:

Open Browser    ${URL}    ${BROWSER}    None    http://<HUB Machine IP ADDRESS>:5566/wd/hub

Sunday, April 5, 2015

Robotframework: Customized library using python - How to

Robotframework: How to create a customized library using python to create a robot keyword

Below example shows the creating a robot keyword "Addition" using customized library

Step 1. Create the python script,

Addition.py - (Library name to be imported in RF)
-------------

from robot.api import logger
from robot.libraries.BuiltIn import BuiltIn


def add_two_numbers(number1, number2):
    """ Python function for adding two numbers """
    return int(number1) + int(number2)



add_two_numbers - Keyword to be used in test scripts

Step 2: Save the file in the folder "C:\Python27\Lib\site-packages"

Step 3: Robot test scripts

Filename - Addition.txt
Execution command - pybot Addition.txt


*** Settings ***
Documentation     Testing my own library

Library    Addition

*** Test Cases ***
Add two
    Add two numbers using own library


***Keywords***
Add two numbers using own library
    ${ADDITION}    Add two numbers    1    8
    Log to console    ${ADDITION}

 Execution Report


Robotframework: AutoIt Library installation steps

Robot Framework: AutoIT library installation steps

Step 1: Install python 2.7 (64 or 32 bit, based on the machine) and you can verify it by typing python in command prompt. you can see the version in the top of the console.
           

Step 2: Install robotframework using pip command: "pip install robotframework" and you can verify it by command "pybot --version"



Step 3: Install pywinauto (32 or 64 bit, based on the python version which you installed) and you can verify by importing the pywin module in the python or Install wxpython for corresponding python version.



Step 4: Install robotframework AutoIT library by downloading the package and install the setup.py file using the command "python setup.py install"

Note: To install AutoIT library, launch the command prompt in administrator mode.

Once the installation is successful, AutoIT library folder will be created in the location

"C:\RobotFramework\Extensions"

Note: Its better to install 32 bit windows of Python, pywin or Wxpython to avoid problems.


           

Tuesday, March 31, 2015

Robotframework Jmeter testcase example with assertion

*** Settings ***
Library           JMeterLib.py
Library           Collections

*** Test Cases ***
tc1_justRunJMeter
    run jmeter    C:/Users/USER/Desktop/apache-jmeter-2.12/apache-jmeter-2.12/bin/jmeter.bat    C:/Users/USER/Desktop/apache-jmeter-2.12/apache-jmeter-2.12/bin/vallikkv/Soap.jmx    E:/Robot/jmeter/log/output_tc1.jtl

tc2_analyseAndConvertExistingJtlLog
    ${result}    analyse Jtl convert    E:/Robot/jmeter/log/output_tc1.jtl
    log    ${result}
    : FOR    ${ELEMENT}    IN    @{result}
    \    log dictionary    ${ELEMENT}
    \    ${check}    Get From Dictionary    ${ELEMENT}    samplesSuccessRateInclAssert
    \    log to console    ${check}
    Should Be Equal As Integers    ${check}    100

tc3_runJMeterAndAnalyseAndConvertLog
    ${result}    run jmeter analyse jtl convert    C:/Users/USER/Desktop/apache-jmeter-2.12/apache-jmeter-2.12/bin/jmeter.bat    C:/Users/USER/Desktop/apache-jmeter-2.12/apache-jmeter-2.12/bin/vallikkv/Soap.jmx    E:/Robot/jmeter/log/output_tc3.jtl
    log    ${result}
    :FOR    ${ELEMENT}    IN    @{result}
    \    log dictionary    ${ELEMENT}

Thursday, March 26, 2015

Robot framework - Notes

Robot framework: To read datas from a row in excel sheet

Add more users
    Open Excel    ${Excel_File_Path}
    @{ROW1}    Get Row Values    Sheet1    0
    ${RUN}=    Get From List    ${ROW1}    0
    ${LIST}    Convert To List    ${RUN}
    log to console    ${LIST[1]}
 
Explanation

Get Row Values - Collects all values from row and assign it to ROW1
 @{ROW1}    Get Row Values    Sheet1    0 ->Output will be tuple -> Eg [(1,2),(3,4)]
 Get From List    ${ROW1}    0 -> To get the first value, i.e  (1,2)
To convert it as [1,2] -> use Convert to List keyword
 ${LIST[1]} - To access 2nd value from the list

Reading values from excel

Add more users
    Open Excel    ${Excel_File_Path}
    ${COLCOUNT}    Get Column Count    Sheet1
    @{ROW1}    Get Row Values    Sheet1    0
    ${RUN}=    Get From List    ${ROW1}    0
    ${LIST}    Convert To List    ${RUN}
    :FOR    ${COUNT}    IN RANGE    ${COLCOUNT}
    \    @{ROW1}    Get Row Values    Sheet1    ${COUNT}
    \    Fetch Column Data

Fetch Column Data
         :FOR    ${ColIndex}    IN RANGE    ${COLCOUNT}
         \    ${VarList}    Create List
         \    ${RUN}=    Get From List    ${ROW1}    ${ColIndex}
         \    ${LIST}    Convert To List    ${RUN}
         \    ${Value1}=    Get From List    ${List}    1   
         \    Insert Into List    ${VarList}    ${ColIndex}    ${Value1}
         \    Log to console    ${VarList}


Tuesday, March 24, 2015

Monday, March 23, 2015

Robot Framework

Installation







Read data from Excel


Manual Installation

To install robotframework-excellibrary manually, install all dependency libraries before installing robotframework-excellibrary.
1) Install Robot Framework installed.
2) Download source distributions (*.tar.gz / *.zip) for the library and its dependencies.
robotframework-excellibrary and dependencies:
Note: Internet Connection is required

command
python setup.py install


***Settings***
Library    ExcelLibrary

***Variables***
${Excel_File_Path}    C:\Test.xls

***Test Case***
Read Data from Excel and fill in text box Open Excel ${Excel_File_Path} ${username}= Read Cell Data By Name Sheet1 B1 ${password}= Read Cell Data By Name Sheet1 B2 Input Text id=Username ${username} Input Text id=Password ${password}

Tuesday, March 3, 2015

Robot framework - Selenium2Library test execution


*** Settings ***
Documentation  Test suite-2 Verify the connect webpage is logged in with valid logon credentials
Library  Selenium2Library

*** Variables ***
${HOMEPAGE}     http://192.168.10.132:8080/connectserver
${BROWSER}  FireFox
${DELAY}    1
${USERNAME}    admin
${PASSWORD}    connect


*** Test Cases ***
connect login
    open connect webpage
    enter login credentials
    click login

connect logout
    logout connect webgui


*** Keywords ***
Open connect webpage
    open browser    ${HOMEPAGE}    ${BROWSER}
    Maximize Browser Window
    Set Selenium Speed    ${DELAY}

enter login credentials
    Input Text    id=username    ${USERNAME}
    Input Text    id=password    ${PASSWORD}

click login
    Click Button    id=loginAction_login_submit

logout connect webgui
    Get Location
    Select Frame    xpath=//div[1][@class='ui-layout-north ui-layout-pane ui-layout-pane-north open']
    Click Button    xpath=//div[1]/table/tbody/tr/td[3]/table/tbody/tr[2]/td/a[@class='siLink1']

Monday, February 16, 2015

Nose framework test discovery

To discovers test by Nose, structure the folders as

Module
    --- test_script.1py
    -- -Test_Module2
             --- test_script1.py
          

Command to exeute all cases

 




--with-html for html output.


HTML output report will be generated for each test files.


Python selenium Nose test execution : HTML Report

To generate test execution status in HTML format in NOSE.

Step 1. Install 'nose-htmloutput' using pip command












Step 2: Once html output is installed, Execute the testscript with option "--with-html"


Thats it.

Step 3: HTML file output

















Step 4: HTMLfile output for failed cases




Python selenium test automation with Nose

Test file details:

from selenium import webdriver
import unittest

class TestUI(unittest.TestCase):
    ''' Test documentation '''

    driver = webdriver.Firefox()

    def test_case1(self):
        self.driver.maximize_window()

    def test_case2(self):
        self.driver.maximize_window()
        self.driver.get("<Web address>")
        self.driver.implicitly_wait(5)
        assert "<Title>" in self.driver.title

    def test_case3(self):
        uname1 = self.driver.find_element_by_id('username')
        pwd = self.driver.find_element_by_id("password")
        login = self.driver.find_element_by_id('loginAction_login_submit')
        uname1.send_keys("admin")
        pwd.send_keys("Password1")
        login.click()
        self.driver.implicitly_wait(5)

    def test_case4(self):
        configmgmt = self.driver.find_element_by_id("configuration")
        configmgmt.click()
        self.driver.implicitly_wait(5)
        mapgrps = self.driver.find_element_by_id("mapings")
        mapgrps.click()
        self.driver.switch_to_frame(self.driver.find_element_by_tag_name("iframe"))
        self.driver.implicitly_wait(5)

    def test_case5(self):
        mapping = self.driver.find_element_by_xpath("//form/table[2]/tbody/tr[2]/td/table/tbody/tr/td/div/table/tbody/tr/td/table/tbody/tr[2]/td[1]/input")
        if mapping.is_selected():
            pass
        else:
            mapping.click()
            self.driver.implicitly_wait(5)
            submit = self.driver.find_element_by_id("Operatorsubmit")
            submit.click()

    def test_case6(self):
        self.driver.switch_to_default_content()
        logout = self.driver.find_element_by_css_selector('font')
        logout.click()
        self.driver.implicitly_wait(3)
        self.driver.close()



if __name__ == '__main__':
    unittest.main()

How to execute using nose framework?