Thursday, January 29, 2015

Facebook login & Logout using Selenium python


from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("https://facebook.com")

email = "email"
password = "pass"
login="loginbutton"
emailelement = driver.find_element_by_name(email)
passwordelement = driver.find_element_by_name(password)
emailelement.send_keys("##username###")
passwordelement.send_keys("##password###")
loginelement = driver.find_element_by_id(login)
loginelement.click()
drop="userNavigationLabel"
dropelement = driver.find_element_by_id(drop)
dropelement.click()
logout="uiLinkButtonInput"
logoutelement = driver.find_element_by_class_name(logout)
logoutelement.click()

Wednesday, January 28, 2015

Sipp call generator UI application using python

Sipp call generator UI applicaion using python

Before proceeding, check the post "Sipp call generator UI application using python wxpython module"

Application:



Sipp call generator UI application using python




#-------------------------------------------------------------------------------
# Name:             CallGenerator
# Purpose:          To initate call generator using SIPp
#
# Author:           vallikkv
#
# Created:           02-11-2014
# Last Modified:     10-11-2014
# Copyright:        (c) vallikkv 2014
# Licence:           V2.0
#-------------------------------------------------------------------------------

import wx
import subprocess
import threading
import fileinput, socket, os

class MyFrame(wx.Frame):
    """ Dervice new class of Frame"""
    def __init__ (self, parent, title):
         wx.Frame.__init__(self,parent,title=title,size=(410,355))
         panel = wx.Panel(self)


         # CreatingTextbox for Extension/Queue number input
         self.filename = wx.TextCtrl(panel,pos=(175,50),size=(100,25))
         self.serveraddress = wx.TextCtrl(panel,pos=(175,90),size=(100,25))
         self.calltime = wx.TextCtrl(panel, pos=(175,130),size=(100,25))
         self.callerNum = wx.TextCtrl(panel, pos=(175,10),size=(100,25))

         #Label
         callerlabel = wx.StaticText(panel, label="Caller ID: ", pos =(55,15))
         labelname = wx.StaticText(panel, label="Queue Number: ", pos =(55,55))
         serverlabel = wx.StaticText(panel, label="Server IP: ", pos =(55,95))
         Calls = wx.StaticText(panel, label="Call timeout in secs: ", pos =(55,135))

         # Creating button which collects the Queuenumber and written it in the csv file and start the sipp.
         startbutton = wx.Button(panel, label="Start", pos=(100,200), size=(80,25)) #Creating Start button
         self.Bind(wx.EVT_BUTTON,self.StartClicked, startbutton) #Binding Start button with Startclicked  method

         closebutton = wx.Button(panel, label="Close",pos=(250,200),size=(80,25)) #Creating Close button to close the app
         self.Bind(wx.EVT_BUTTON, self.OnCloseMe, closebutton)
         self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

         self.Queueinput1 = str(self.filename.GetValue())


    def OnCloseMe(self, event):
        self.Close(True)

    def OnCloseWindow(self, event):
        self.removefiles()
        self.Destroy()

    def csvfilecreation(self):
        print "Calling csvfilecreation method"
        self.Queueinput = str(self.filename.GetValue())
        self.serverip = str(self.serveraddress.GetValue())
        self.callerid = str(self.callerNum.GetValue())
        #Creating CSV File based on the queue
        queuefile=open(r"C:\Program Files (x86)\Sipp_3.1\Sample"+self.Queueinput+".csv", 'w+')
        queuefile.write("SEQUENTIAL\n"+self.callerid+";"+self.serverip+";[authentication username="+self.callerid+" password=connect];"+self.Queueinput+";")
        queuefile.close

    def InputQueue(self):
        self.inputvalue = str(self.filename.GetValue())
        return self.inputvalue

    def updatetimeincsv(self):
        print "Updating timeout in xml"
        oldxml=open(r"C:\Program Files (x86)\Sipp_3.1\xml.xml",'r')
        newxml=open(r"C:\Program Files (x86)\Sipp_3.1\Sample"+self.Queueinput+".xml", 'w+')
        for line in oldxml:
            newxml.write(line.replace('<pause milliseconds="60000" />','<pause milliseconds="'+str(int(self.Timeout)*1000)+'" />'))
        newxml.close()
        oldxml.close()

    def updatecsvfileinbat(self):
        os.chdir(r"C:\Program Files (x86)\Sipp_3.1")
        print "Calling updatecsvfileinbat method"
        self.hostip=socket.gethostbyname(socket.gethostname())
        updatecsv=open(r'C:\Program Files (x86)\Sipp_3.1\SampleCall'+self.Queueinput+'.bat','w+')
        updatecsv.write(":start\nsipp.exe "+self.serverip+" -sf Sample"+self.Queueinput+".xml -inf Sample"+self.Queueinput+".csv"+" -m 1  -l 1  -i "+self.hostip+"\nsleep 10\ngoto start")

    def StartClicked(self, event):
        print 'Calling StartClicked Method'
        MyFrame.calltimeout(self)
        MyFrame.csvfilecreation(self)
        MyFrame.updatecsvfileinbat(self)
        MyFrame.updatetimeincsv(self)
        MyFrame.ThreadStart(self)


    def ThreadStart(self):
        print "Calling Threadstart Method"
        #myinstance=The()
        Sippscript = threading.Thread(target=self.sippthread)
        Sippscript.daemon=True
        Sippscript.start()


    def stopthread(self):
        while self.threads:
            thread = self.thread[0]
            thread.stop()
            self.threads.remove(thread)

    def sippthread(self):
        """ New Child Thread for Sipp"""
        self.filepath=r'C:\Program Files (x86)\Sipp_3.1\SampleCall'+self.Queueinput+'.bat'
        print "Chile tread"
        print self.filepath
        os.startfile(self.filepath)

    def calltimeout(self):
        print "Calling calltimeout Method"
        self.Timeout= str(self.calltime.GetValue())
        print self.Timeout

    def clear(self):
        self.clear()

    def removefiles(self):
        os.chdir(r"C:\Program Files (x86)\Sipp_3.1")
        for file in os.listdir("."):
            if os.path.isfile(file) and file.startswith("Sample"):
                try:
                    os.remove(file)
                except Exception,e:
                    print e


if __name__ == '__main__':
    app = wx.App()
    frame = MyFrame(None, "CallGenerator")
    frame.Show()
    app.MainLoop()


Monday, January 26, 2015

Python unittest with two different testcases

Python unittest with two different testcases:

Main file contains:

import unittest
from my_math import product
from dbtest import Dbquery

class Test(unittest.TestCase):
    """Tests for Product"""

    def test_product(self):
        try:
            self.failUnlessEqual(product(2,3),6,"Product Testcase")
        except AssertionError:
            print "Assertion Error, Check the Values"

    def test_mysql(self):
        try:
            check = str("(1, u'Vallinayagam.K', u'Welcome to DB World')")
            self.failUnlessAlmostEqual(str(Dbquery("SELECT * FROM name")),check)
        except AssertionError:
            print "Assertion Error"


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


my_math file contains:

def product(a,b):
    return a*b

dbtest file contains:

import mysql.connector

def Dbquery(query):
    try:
        conn = mysql.connector.connect(user="root", password="admin",host="127.0.0.1",database="test")
        cursor = conn.cursor()
        cursor.execute(query)
        for (id,username,tweet) in cursor:
            return id,username,tweet
        cursor.close()
        conn.close()
    except mysql.connector.Error as err:
        print "Error " + format(err)



Output:





Python unittest with multiple test data's

Python sample script for unitest with multiple test data's

import unittest
from my_math import product

data = [(2,3,6),(3,3,9),(4,3.5,11)]

class Test(unittest.TestCase):
    """Tests for Product"""
    def test_product(self):
        try:
            for a,b,expected in data:
                self.failUnlessEqual(product(a,b),expected,"Product Testcase")
                print "Expected is ",expected
        except AssertionError:
            print "Assertion Error, Check the Values"


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


my_math.py file contains:

#__author__ = 'valli'
def product(a,b):
    return a*b