Wednesday, December 28, 2011

pyserial port scan

if you are using pyserial module to read the communication from your device on UART , you will have to know which port the is your system connected to.

the following is a simple code to scan through all the COM ports and find out which com port is in opened. at the end of the program , you will see the serial uart that is in use being printed

import pyserial
for i in range(256):
try:
s = serial.Serial(i)
available.append( (i, s.portstr))
port = i
s.close()
except serial.SerialException:
pass

ser = serial.Serial(port, 115200,timeout=1)
print ser.portstr


happy scripting!

Tuesday, December 27, 2011

Process kill

In python if we need to kill a running process we need to run the following command.

import os
os.system("taskkill /im "process_name" /f")

just give the name of the process that is running and it should kill it. we need this kind of setup when we try to kill all the existing process before launching a one.

Thursday, December 22, 2011

Python File Operations

Alright ,it is time for python file operation related examples. there could be a variety of things that you would like to do with a file. I am sharing a simple example below.

old_file= open ("file_Path","r")
new_file = open ("file_Path","w")

for line in old_file:
if "" in line:
new_file.write(line.replace("oldtext","newtext"))
else:
new_file.write(line)

In the above example we are opening a file in read and write mode and performing some basic operations.

Based on a condition we are trying to replace some content in the file and writing the new thing in a different file.

this code works as is , you just have to give the appropriate values. sys is the only module you will be needing.

Tuesday, December 20, 2011

Python with HP Quality center

As promised, check the code below will let you connect to QC
the below walks you through the test tree and updates the status of test cases.
you can use this as a function can call it in python script to update.
this was pretty useful to me , hops is the same case with you.

import win32com
from win32com.client import Dispatch

qcServer = "http://xxxxxxxxx/qcbin/"
qcUser = "xxxxx"
qcPassword = "xxxxx"
qcDomain = "xxxx"
qcProject = "xxxx"

t = win32com.client.Dispatch("TDApiOle80.TDConnection.1")
t.InitConnectionEx(qcServer)
t.Login(qcUser,qcPassword)
t.Connect(qcDomain,qcProject)

print "Logged in"

mg=t.TreeManager
npath="Root\xxxxxx"
tsFolder = t.TestSetTreeManager.NodeByPath(npath)
print tsFolder
tfactory=tsFolder.TestSetFactory
td_tsff=tfactory.Filter
td_testset=td_tsff.NewList()

for otest in td_testset:
print otest.Name
td_TSTestSetFactory = otest.TSTestFactory
td_tstsff = td_TSTestSetFactory.NewList("")


for otestitem in td_tstsff:
print otestitem.Name
td_RunFactory = otestitem.RunFactory
obj_theRun = td_RunFactory.AddItem("testrun")
obj_theRun.Status = "Passed"
otestitem.Status= "Passed"
obj_theRun.Post()
print otestitem.Status
next
next

tsFolder = None
tfactory = None
td_testset = None
td_TSTestSetFactory = None
td_RunFactory = None
obj_theRun = None
t.logout
t = None

print "done"

Monday, December 19, 2011

Python with Quality center

We fall back to the topic of test management . we can use all the scripting languages in the world but it boils down to the point on how will you report the status of the testing to your management . well that is true for almost every testing activity manual or automation.

I was wondering what to use , could it be a custom python script to prepare a report or off the shelf product . after going through a bunch of processes , Proof of concepts I came to a conclusion that we can write something in relatively less time but maintaining it is a problem. when I looked at any test management tool that supports python , I came across Quality Center. they have a OTA framework which makes is relatively simple to access their APIs. I spent time on it and found relatively simple to connect with the com objects.

my suggestion , if you have access to QC in your company , give it a shot , should be simple and straight forward for you to use.

I will be posting how to connect to QC from a python script pretty soon.

Tuesday, December 6, 2011

PyAuto

Today , i wanted to share about a module that you can use for testing windows application.
you reach a point where , you will have to use windows based application testing and you will run after tools which support them , the good thing about python is it has a pyauto module which you can use for the same . This module helps us running all the ui related tests . you might question "what is the advantage?" the answer is if you are truly comparing it with any ui automation tool "Nothing" . having said that , we all reach a point where , we will have to use scripting language across the board and you will have to have multiple tools being used. python has it all , so be it ui , embedded or application , this does it all !

so before you choose , give it a thought :)

Friday, December 2, 2011

Escape characters python

The one place everybody who starts scripting gets stuck is escape characters . this is about the point where you will have to give either a absolute or relative path from where you will have to open a file , exe etc.

one aspect which i was particularly glad about in python is , python has a inbuilt function to do this (kewl right! )

re.escape(string)

Example : print re.escape("www.example.com")

www\\.example\\.com is your ouput

Wednesday, November 30, 2011

Python String replace

I came across a point where the incoming user string had to be replaced with something i desire . Considering the simplicity of the activity i expected python to have some user defined function . might be a simple thing , but really useful...

replace( old , new, [max count]).
if you have the below
Code :
sample = "this is a test string"
print sample.replace("test" , "long test")
the result will look like this
"this is a long test string"
you dont have to import any library in specific.
the "max" from the syntax constitutes to the number of times the string has to be replaced.

Tuesday, November 29, 2011

Scan for bluetooth devices using python

scan for bluetooth devices using a python script. the below script can be used for performing the same. remember , you will have to install pybluez module (it is available for both windows and linux). now for the script , here you go!

import bluetooth

print "performing inquiry..."

nearby_devices = bluetooth.discover_devices(lookup_names = True)

print "found %d devices" % len(nearby_devices)

for addr, name in nearby_devices:
print " %s - %s" % (addr, name)


this will print the number of devices , address and name . this can be used as test script for a variety for reasons .

Tuesday, November 8, 2011

Open EXE with Python

I guess we all reach a point in our scripting space when we end up with opening an exe file from the script. Well , here the code for it . just replace the contents with the values you desire

import subprocess
import os
from win32api import ShellExecute
ShellExecute(0, "open","C:\\XXXX\\XXXX.exe","" , "C:\\XXX", 1)

There might be other ways of doing it , but i believe this one is simple enough for you to try.


Monday, November 7, 2011

AT Commands Python

You can send AT commands to phone when connected to pc via the below progaram . i was able send the commands successfully. Remember most of the phones will have the DUN port open , if you don't connect the machine to a Linux box and run hciconfig command to see the configurations. if you dont have a linux box , just use a virtual box application and download ubuntu which is free of cost

in the case of a android phone , i made use of an application called padNEt 3.02 which helps you turn on the DUN port.

you can use the below mentioned code to send AT commands over bluetooth too. identify the appropriate profile and sent id accordingly.

#!/usr/bin/env python

# ATsend.py
#
# Turn the phone bluetooth off and on each time you
# send the At commands to free up the DUN port
#
# Requires Pybluez from Google
# http://pybluez.googlecode.com
# PyBluez works on GNU/Linux and Windows XP (Microsoft and Widcomm Bluetooth stacks)
#
# Send At commands to mobile device via DUN
#
# Some code to show how to dial a number with
# AT commands also shown below
#

import sys
import bluetooth
from bluetooth import * #Pybluez http://pybluez.googlecode.com

deviceName = []
deviceAddress = None
foundDevices = bluetooth.discover_devices()
if len(foundDevices) == 0:
print "No Bluetooth device found"
exit(0)
count = 0
while count == 0:
for bdaddr in foundDevices:
deviceName.append(bluetooth.lookup_name( bdaddr ))
deviceAddress = bdaddr
print "%2d %-16s Address: %s" % (count +1, deviceName[count], deviceAddress)
count += 1
choice = raw_input("Choose Device or 0 to repeat scan")

# Repeat scan to get more device names
if (choice.isdigit() and int(choice) <= len(foundDevices)):
count = int(choice)
else:
print "Invalid Choice - Please rerun the program"
exit(0)
# choice = raw_input("Choose Device or 0 to repeat scan")
# if (choice.isdigit() and int(choice) <= len(foundDevices)):
# count = int(choice)
#if choice == 0:
# while count == 0:
# for bdaddr in foundDevices:
# deviceName.append(bluetooth.lookup_name( bdaddr ))
# deviceAddress = bdaddr
# print "%2d %-16s Address: %s" % (count +1, deviceName[count], deviceAddress)
# count += 1
# choice = raw_input("Choose Device or 0 to repeat scan")

selected = deviceName[count -1]
deviceAddress = foundDevices[count -1]

if deviceAddress is not None:
print "Identifying the services for the selected devices ....."
else:
print "Could not find a Bluetooth device"
exit(0)

services = bluetooth.find_service(address=deviceAddress)
devicename = bluetooth.lookup_name(deviceAddress, timeout=10)
showProfiles = None

if len(services) > 0:
print "Found %d services on %s\n" % (len(services), deviceAddress)
#
else:
print "No device found at address: %s" % deviceAddress
print
print "Did you turn on bluetooth?"
print "Did you accept/authorize the connection?"
print
sys.exit(3)

dunPort = 0 # Not found yet
# Get Service Details
# global showProfiles
showProfiles = raw_input("Show Bluetooth Profiles supported? y|n")
for svc in services:
# Look for DUN port
if svc["name"] == "Dial-up networking (DUN)":
dunPort = svc["port"]
if showProfiles == "y":
print "BT Profile: %s" % svc["name"]
print " Host: %s" % svc["host"]
print " Description: %s" % svc["description"]
print " Provided By: %s" % svc["provider"]
print " Protocol: %s" % svc["protocol"]
print " channel/PSM: %s" % svc["port"]
print " svc classes: %s "% svc["service-classes"]
print " profiles: %s "% svc["profiles"]
print " service id: %s "% svc["service-id"]
print

if dunPort != 0:
print "Found Dial-Up Networking port = %d\n" % (dunPort)

#s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
#conn = s.connect((deviceAddress, dunPort))
sock=BluetoothSocket( RFCOMM )
sock.connect(("78:47:1D:B6:01:B2", dunPort))
print "socket connected"
# A semicolon ";" at the of the number dialed
# is necessary to make a voice call
# with out the ";" this command will try to
# make a data call

# Example to Dial a number using AT command

#s.send('AT#QAS\r'),
#print s.recv(1024),


# This next section has to expect the correct number of returns
# The first command "ATE1" gets a single "OK" response with a carrage return
# The next commands expects 2 lines returned.
# Each line return ends with \r
# The correct send/expect sequence must be followedd or you will get
# a hang or no response.

#s.send("ATE1\r")
#print s.recv(1024),
s.send("AT\r")
print s.recv(1024)

#s.send("AT+CMGF=1\r")
#print s.recv(1024)
#print s.recv(1024)

#s.send('AT+CMGS="0784XXXXXXX"\r')
#print s.recv(1024)
#s.send("This is freds test!"+chr(26))
#print s.recv(1024)
#print s.recv(1024)

#s.send("AT+GMI\r")
#print s.recv(1024),
#print s.recv(1024),

#s.send("AT+CGMI\r")
#print s.recv(1024),
#print s.recv(1024),

#s.send("AT+GMM\r")
#print s.recv(1024),
#print s.recv(1024),

#s.send("AT+CGMM\r")
#print s.recv(1024),
#print s.recv(1024),

s.close
sys.exit(0)

else :
print "Could not find Dial Up Networking port."
print "Or DUN port is busy."
print "Switch the target's Bluetooth off then on and retry"
sys.exit(4)

Friday, November 4, 2011

pylbuez SDP

We have seen that Bluetooth devices can locate other nearby devices, those that are in discovery mode. Rather than connecting by the address and port of a device and application, devices can discover the address and port by the service names.

The following version performs the same function but using SDP. On the server-side, the primary use of SDP to advertise the helloService as a serial port or RFCOMM protocols.

The client first finds a list of devices that provide the helloService (in reality, more than just helloService is returned). The list is then searched for the helloService, when found, the associated host address and port are used to connect to the service.

Client Code:


from bluetooth import *

services=find_service(name="helloService",
uuid=SERIAL_PORT_CLASS)

for i in range(len(services)):
match=services[i]
if(match["name"]=="helloService"):
port=match["port"]
name=match["name"]
host=match["host"]

print name, port, host

client_socket=BluetoothSocket( RFCOMM )

client_socket.connect((host, port))

client_socket.send("Hello world")

client_socket.close()

break


Server Code:

import bluetooth

server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )

server_sock.bind(("",bluetooth.PORT_ANY))
server_sock.listen(1)

bluetooth.advertise_service(server_sock, "helloService",
service_classes=[bluetooth.SERIAL_PORT_CLASS],
profiles=[bluetooth.SERIAL_PORT_PROFILE])

client_sock, address = server_sock.accept()
print "Accepted connection from ",address

data = client_sock.recv(1024)
print "received [%s]" % data

client_sock.close()
server_sock.close()

Thursday, November 3, 2011

pybluez bluetooth inquiry

In my yesterday's blog i was talking about pyserial module . today's post i wanted to share a test code for pybluez module which is a python wrapper around the Bluetooth stack. in this sample code below , we will perform a inquiry of all the Bluetooth devices nearby and list them.

from bluetooth import *
print "performing inquiry..."
nearby_devices = discover_devices(lookup_names = True)
print "found %d devices" % len(nearby_devices)
for name, addr in nearby_devices:
print " %s - %s" % (addr, name)


don't forget to download the pybluez module before you try this. this will be an important step.
you will end up getting errors that the bluetooth module is not available if you try to run the program as is.

happy testing!

Wednesday, November 2, 2011

pyserial

pyserial module is really useful . i have been using it for perfroming uart related communication.
there a lot of sites which provides this pyserial downloads.
import serial
ser = serial.Serial(0) # open serial port
print ser.portstr # prints the used port
ser.write("hello") # write a string
ser.close()
you can use the above code as a test program for performing a pyserial communication from windows.

Friday, October 28, 2011

Trace32 API Config

like i posted in my previous blog , we need to have the application up and running . i will detail out the ways of configuring now . once you install the trace on your machine you will notice a c:/t32 folder listed ( if you choose to install it else where , find the t32 folder on your machine) . when you launch the trace32marm.exe it generally picks up the configuration from config file (categorized as t32 file ) . open the file ( any ide is fine or even a notepad ) and enter the below value .

RCL=NETASSIST
PACKLEN=1024
PORT=xxxx

you can choose to provide any port number available on your computer . this runs a udp port on your computer , you can check the list of open ports to see if it did pick the correct configuration.

this will be the port number that you will have to use to open a port from scripting language. this will open up the trace32 for subsequent actions

Thursday, October 27, 2011

Trace32 API

with Trace32 lauterbach provides a bunch of APIs . These APIs dont provide access to Trace32 directly , rather , it provides access to the trace32 User interface ( i know what you are thinking :)).
So , this means that for you to access the trace32 Hardware , you will have to have the trace32 software open on the system . The config file of the trace installation folder is the key . i will share some more code and inputs shortly

Friday, July 15, 2011

Python - lauterbach

it is interesting to notice that with lauterbach you dont get a wrapper for scripting languages.
i am not saying that they will have to :) , but i would assume from a testing standpoint it will be great to have a scripting language interface to the same.

Lauterbach - trace32 is a really powerful tool . i am going to start using python scrpiting language with latuerbach. fortunately they provide a trace32 api that i can use.

we will have to see how things go by :) . atleast the idea for now when i am writing this blog is , you dont have python wrapper for lauterbach and i am trying to findout what we can do about it.

Wednesday, July 13, 2011

pybluez - bluetooth

For all who have been using python or who wanted to use python,
we can access RFCOMM profile via pybluez.
pybluez is the software supplied at code.google.com is a python wraper for bluetooth testing.
for now all the profiles are not supported ( read bluetooth related books/ postings for you to understand what profiles mean) . it supports only RFCOMM and L2CAP.
you can download it from the below.

http://code.google.com/p/pybluez

Monday, July 11, 2011

Python: AttributeError: 'module' object has no attribute

if you are getting the AttributeError: ' Module' object has no attribute do the following.

1. don't give the same name to your python script as that of library that you have imported.
python will import your script file instead of the orginal librarby file.
2. check the import file definition (if you are using a ide, just right click and say go to definiton )
to see if it has the attribute that you are trying to use . in simple , just do a ctrl-f and search the parameter that you are looking for.

Saturday, July 9, 2011

Active state python

There are quite a few sites where python downloads are available.
one such is activestate python. you can download the different versions/releases of python . be sure you are downloading the version that suits your operating system and needs.


brief note : active state supplies executable for lot of scripting languages. the above url is for python.

Also, if you are first time user of python , i strongly recommend using one of the editors for python. i have used activate state python komodo ide ( trial version) . looks powerful and simple.
it supports a lot of scripting languages too. i have also used editplus , pythonwin, eclipse too.
i don't have a preference , it just helps you find flaws with your syntax and easy to check the definitions for the files that you are importing .


if you want more information about other ide just drop me a email. i will reply.

Note : i have windows7 (64 bit) and python64 bit did not go well with it , so just download 32 bit python , it works for both 64 bit and 32 bit operating systems as well.



Active state python

There are quite a few sites where python downloads available.
one such is activestate python. you can download the different versions of python available for download. be sure you are downloading the version that suits your operating system and needs.


brief note : active state supplies executable for lot of scripting languages. the above url is for python.

Also, if you are first time user of python , i strongly recommend using one of the editors for python. i have used activate state python komodo ide ( trial version) . looks powerful and simple.
it supports a lot of scripting languages too. i have also used editplus , pythonwin, eclipse too.
i don't have a preference , it just helps you find flaws with your syntax and easy to check the definitions for the files that you are importing .


if you want more information about other ide just drop me a email. i will reply.

Note : i have windows7 (64 bit) and python64 bit did not go well with it , so just download 32 bit python , it works for both 64 bit and 32 bit operating systems as well.



Friday, July 8, 2011

Download Python

you can download python from the below site

www.python.org/getit

Make sure you choose the right version depending on what operating system that you will be supporting