Wednesday, July 15, 2015

Eval & Execute

 

Difference between Eval & Execute

In the syntax above, both expression and statement arguments are string statements. Both expressions can be derived from VBScript or QTP code; the difference lies in the fact that Eval will always return the result of the string evaluation whereas Execute will execute a string statement for execution and will not retrieve the result (but there are workarounds). The following example demonstrates the main difference between the 2 functions:
x = 9
y = 10
 
bIsEqual = Eval("x = y")
Execute "x = y"
 
MsgBox "bIsEqual: " & bIsEqual
MsgBox "X is no longer 9. It is: " & x
bIsEqual
Eval Function
New x
Execute Statement
Note that Eval returned a Boolean value whereas Execute function performed a variable assignment. This article will cover the usage of both techniques in depth through both VBS and QTP code.
You must be wondering why the syntax for Eval and Execute is different. The reason is that, Eval is a function. Execute is not. That means, the following statement for Eval: bIsEqual = Eval("x = y"), when written for Execute will return a Null value for bResult (but assignment will be performed for x):
bResult = Execute("x = y")
MsgBox bResult
MsgBox "x: " & x
Null Output
Null Output
Value Assigned
X = 10
With that said, let me share the workaround that can be used with Execute to return the evaluation just like we did with Eval. Here’s how:
x = 9
y = 10
 
Execute "z = (x = y)"
MsgBox "z: " & z   ' how come its evaluating the 
Return Z (False)
Return Z (False)
More on this concept will be covered in the section Evaluating Statements.

Thursday, July 9, 2015

Miscelleneous

- Option Explicit

- Loops:
1. For Loop
2. Do While Loop
3. While Wend  ---Wend - while end

- Array
UBound(), LBound()

- String Functions:

1. TRIM()
2. RTRIM()
3. LTRIM()
4. LEN()
5. MID()
6. INSTR()   -returns position

7. SPLIT()


 - .Exist

Is used to find whether objects exists or not.

- .value

Without mentioning the .value method, we can use GetROProperty to retreive value of the property of object.
 - If you do not want to use Browser and Page all the time, create object and use it when ever needed, instead.

Set obj = Browser("<name>").Page("<name>")

obj.WebEdit("c").set = "a"

- Syntax checker -- Is small utility in menu bar, is used to find the syntax of your script.

Go to Design->Check Syntax

- Understand the methods: Select  the method and click on F1, it will direct you the description of the method.

- SystemUtil.Run

Object spy on browser bar revealed that it was being recognized as window instead of browser! Some more R & D and I discovered that the problem lies with the SystemUtil.Run method. I was using SystemUtil.Run “explorer”, <URL>. When I changed that to SystemUtil.Run “iexplore”, <URL> script started running fine. I guess while using explorer, QTP expects a file path and not a HTTP path on it. Having said that, I am still not sure how it ran fine for the first few times.

- RunAction  -------
Runs a specific action from the open test and creates results in the specified file or ALM path.
Syntax –
object.RunAction Name, [ResultsOptions], [WaitOnReturn], [Parameters]

Issues:

- Can we have the code:  Half of the statement with descriptive programming another half with Object Respository? ---- Not Solved
- In most of the scenarios I have worked with, script worked when I stored Objects in OR and started the script, but when I do descriptive programming the same script fails.
And another issue is script is not consistent, it will work in first run and fails in second run. --- Not Solved.


Code:

-  Not sure how the function got called here??? --- Not Solved


Function GetHoverColor(oLink)
    Setting.WebPackage("ReplayType") = 2
        oLink.FireEvent "onMouseOver"
        GetHoverColor = oLink.Object.currentStyle.color
    Setting.WebPackage("ReplayType") = 1
End Function
 
RegisterUserFunc "Link", "GetHoverColor", "GetHoverColor"
Now, whenever the link color is to be retrieved, you can simply call the “GetHoverColor” function as you would normally use the Click event:
MsgBox Browser("Browser").Page("Page").Link("Link").GetHoverColor
 -  Whole code looks different:   ????? -- Not Solved

Sub My_MouseOver(objSender) //how objSender variable is passed
    Dim absX : absX = objSender.GetROProperty("abs_x")
    Dim absY : absY = objSender.GetROProperty("abs_y")
    Dim width : width = objSender.GetROProperty("width")
    Dim height : height = objSender.GetROProperty("height")
    Dim x : x = (absX + (width / 2))
    Dim y : y = (absY + (height / 2))
    Dim deviceReplay : Set deviceReplay = CreateObject("Mercury.DeviceReplay")
    deviceReplay.MouseMove x, y

    Reporter.ReportEvent micDone, "A step name", "A useful step description"
End Sub
RegisterUserFunc "Link", "MouseOver", "My_MouseOver"      //MouseOver method is registered
RegisterUserFunc "WebButton", "MouseOver", "My_MouseOver" //MouseOver method is registered 
Browser(<>").Page("<>").Link("<>").MouseOver //My_MouseOver function is called
Browser(<>").Page("<>").WebButton("<>").MouseOver //My_MouseOver function is called

- Issue with a browser, QTP detects two browsers but only one exist? --- Solved
Please check your Task Manager, UFT must be identifying any open instances of IE. 
Use “CloseProcessByName” function to kill any open IE instances in your code to rectify 
this.



Reporting Object or output

7/9/2015 -- notes of webex training

Reporter object is used to Report something on the result.

- Reporter.ReportEvent ----- this is used to report

Reporter.ReportEvent micPass, "<Expected value>", "<Actual value>"

or

Reporter.ReportEvent micFail, "<Expected value>","<Actual value>"


-  Report each every step in a script is possible through Reporter.ReportEvent

- EX:
if(Browser("<>").Page("<>").WebEdit("<>").Exist(2)) then

Reporter.ReportEvent micPass, "WebEdit should exist", "WebEdit exist"

else

Reporter.ReportEvent micFail, "WebEdit should exist", "WebEdit does not exist"

end if


- For Screenshot we can use the below:

- Screenshot

1.  Manually capture the screen
CaptureBitmap("<path>")
Desktop.CaptureBitmap("<path>")

Ex: Browser("<name>").Page("<name>").CaptureBitmap("<path where screenshot needs to be saved")

2. Update settings to capture the screen
Go to Tools->Options->Run -> Screen Capture

We can also capture movies here.


-

Handle Excel Workbook with QTP


-          Handling Excel:


Set obj = CreateObject(“Excel.Application”)

 

UsedRange.Columns.Count  ‘--to find the number of columns used

     UsedRange.Rows.Count ‘--- to find number of rows used

Handling XML's with QTP


-          Handling XML:

http://www.qtpworld.com/index.php?cid=86
 
set obj = CreateObject(“Microsoft.XMLDOM”)
 
Reading/Writing XML:
Load
SelectNodes
Nodes.length
NodeValue




How API testing is done using QTP??
Open test as API
Load WSDL(get it from the website)
Methods are displayed in explorer
drag the methods to canvas
you could see xml(Request and response parameters) on the right side - properties window
Give the input values to the xml in the request xml
Run the tool
You could see result in response xml tags on the right side window
In the result you could clearly see request and response xmls.
Note - Web Service url- WSDL file
Note: Authorization error when you try to import the WSDL file to UFT??

Wednesday, July 8, 2015

WebTable object and ChildItem Method


WebEx training notes:
-          WebTable :  WebTable is the web class in the web application. It plays major role in Web Page because table has multiple rows and columns. It would be very difficult to find some cell( row or column) in a web page because it will be too much for the object repository to hold properties of all cells.


As it becomes unrealistic to find Web Table cells using object Repository(as it fills the OR), so we use ChildItem(<row>,<column>,<classname>,<index>) .


Set obj = Browser(“<name>”).Page(“<name>”).WebTable(“<name>”). ChildItem(<row>,<column>,<mic classname>,<index>)


Obj.Set “<text to be entered, if class is web Element>”


- Mostly used methods with WebTable
RowCount
ColumnCount(<Row Number>) --- gives the number of columns in that Row Number
GetCellData(1,1)
ChildItem



Miscelleneous:


- How to identify that which web element lies in which row and column.(having difficulty with mycontactform.com)  ---- Solved(but try this technique once)

Use the Exist method and if condition to find if the value is "Nothing".

And you could use  RowCount and ColumnCount methods to navigate to each element.

And you could set value to the each type of element, by using ChildItem(row1,col1,"WebCheckBox",0).set "ON"   '---sets all checks all checkboxes
ChildItemCount(row1,col1,"WebEdit",0).set "srikanth"  '----insert "srikanth" to all webedits

Use F12 in IE to find the tr,td details.

- How to get the syntax of each method in UFT -- Solved

You will get it from the help document UFT has in help menu. It clearly gives syntax and description of methods.

Scripts:

- msgbox Browser("Sample Email Forms - myContact").Page("Sample Email Forms - myContact").WebTable("Send To: * Marketing Departmen").ChildItemCount   ----- this one throws error saying wrong arguments assignment  --- Solved

Yes because WebTable accepts only 4 methods RowCount, ColumnCount, GetCellData, ChildItem

- Set obj = Browser("Sample Email Forms - myContact").Page("Sample Email Forms - myContact").WebTable("Send To: * Marketing Departmen").ChildObjects

MsgBox obj.Count  --- Solved
The above code does not work as ChildObjects method does not work with WebTable
- Set obj = Browser("Sample Email Forms - myContact").Page("Sample Email Forms - myContact").WebTable("Send To: * Marketing Departmen").ChildObjects("WebCheckbox") --- throws error --- Solved
The above code does not work as ChildObjects method does not work with WebTable


- 
-

- 

Thursday, July 2, 2015

Handling Files with QTP

 
Source from: http://qeworks.com/scripts-to-handle-folder-structure/

File system object in QTP

Written by

QTP provides various features and built-in functions to handle the folder structure. By using “filesystemobject ” you can easily work on folders and files.this is commonly used object for parameterization
there are several methods provided with fileobjectsystem in this post we will see some commonly used method with the example

Methods:

BuildPath Method
Appends a name to an existing path. The BuildPath method inserts an additional path separator between the existing path and the name, only if necessary
Function GetBuildPath(path)
Dim fso, newpath
Set fso = CreateObject("Scripting.FileSystemObject")
newpath = fso.BuildPath(path, "Sub Folder") 
GetBuildPath = newpath
End Function
Close Method
This method is used to close the open TextStream file. if you open any file for reading for writing purpose then you should close it once you complete with the operation.
object.Close( );
Sub CreateAFile
   Dim fso, MyFile
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set MyFile = fso.CreateTextFile("c:testfile.txt", True)
   MyFile.WriteLine("This is a test.")
   MyFile.Close
End Sub
Copy Method
This is one of useful method used. it Copies a specified file or folder from one location to another.
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.CreateTextFile("c:testfile.txt", True)
MyFile.WriteLine("This is a test.")
MyFile.Close
Set MyFile = fso.GetFile("c:testfile.txt")
MyFile.Copy ("c:windowsdesktoptest2.txt")
CopyFile Method
Copies one or more files from one location to another.
FileSystemObject.CopyFile "c:mydocumentsletters*.doc", "c:tempfolder"
this code will copy all docs file to desired location.
CopyFolder Method
Recursively copies a folder from one location to another.
FileSystemObject.CopyFolder "c:mydocumentsletters*", "c:tempfolder"
this code will copy all folders from letters folder to tempfolder.
CreateFolder Method
following code use to Creates a folder in desired location.
Function CreateFolderDemo
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.CreateFolder("c:New Folder")
   CreateFolderDemo = f.Path
End Function
CreateTextFile Method
Creates a specified file name and returns a TextStream object that can be used to read from or write to the file.
Sub CreateAfile
   Dim fso, MyFile
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set MyFile = fso.CreateTextFile("c:testfile.txt", True)
   MyFile.WriteLine("This is a test.")
   MyFile.Close
End Sub
Delete Method
Deletes a specified file or folder.
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.CreateTextFile("c:testfile.txt", True)
MyFile.WriteLine("This is a test.")
MyFile.Close
Set MyFile = fso.GetFile("c:testfile.txt")
MyFile.Delete
DeleteFile Method
Deletes a specified file.
Sub DeleteAFile(filespec)
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   fso.DeleteFile(filespec)
End Sub
DeleteFolder Method
Deletes a specified folder and its contents.
Sub DeleteAFolder(filespec)
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   fso.DeleteFolder(filespec)
End Sub
DriveExists Method
Returns true if the specified drive exists; false if it does not.
Function ReportDriveStatus(drv)
   Dim fso, msg
   Set fso = CreateObject("Scripting.FileSystemObject")
   If fso.DriveExists(drv) Then
      msg = ("Drive " & UCase(drv) & " exists.")
   Else
      msg = ("Drive " & UCase(drv) & " doesn't exist.")
   End If
   ReportDriveStatus = msg
End Function
Exists Method
Returns true if a specified key exists in the Dictionary object, false if it does not.
Function KeyExistsDemo
   Dim d, msg   ' Create some variables.
   Set d = CreateObject("Scripting.Dictionary")
   d.Add "a", "Athens"   ' Add some   keys and items.
   d.Add "b", "Belgrade"
   d.Add "c", "Cairo"
   If d.Exists("c") Then
      msg = "Specified key exists."
   Else
      msg = "Specified key doesn't exist."
   End If
   KeyExistsDemo = msg
End Function
FileExists Method
Returns true if a specified file exists; false if it does not.
Function ReportFileStatus(filespec)
   Dim fso, msg
   Set fso = CreateObject("Scripting.FileSystemObject")
   If (fso.FileExists(filespec)) Then
      msg = filespec & " exists."
   Else
      msg = filespec & " doesn't exist."
   End If
   ReportFileStatus = msg
End Function
FolderExists Method
Returns true if a specified folder exists; false if it does not.
Function ReportFolderStatus(fldr)
   Dim fso, msg
   Set fso = CreateObject("Scripting.FileSystemObject")
   If (fso.FolderExists(fldr)) Then
      msg = fldr & " exists."
   Else
      msg = fldr & " doesn't exist."
   End If
   ReportFolderStatus = msg
End Function
GetFile Method
Returns a File object corresponding to the file in a specified path.
Function ShowFileAccessInfo(filespec)
   Dim fso, f, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFile(filespec)
   s = f.Path & "<br>"
   s = s & "Created: " & f.DateCreated & "<br>"
   s = s & "Last Accessed: " & f.DateLastAccessed & "<br>"
   s = s & "Last Modified: " & f.DateLastModified   
   ShowFileAccessInfo = s
End Function
GetFileName Method
Returns the last component of specified path that is not part of the drive specification.
Function GetAName(DriveSpec)
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   GetAName = fso.GetFileName(DriveSpec)
End Function
GetFolder Method
Returns a Folder object corresponding to the folder in a specified path.
Sub AddNewFolder(path, folderName)
   Dim fso, f, fc, nf
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFolder(path)
   Set fc = f.SubFolders
   If folderName <> "" Then
      Set nf = fc.Add(folderName)
   Else
      Set nf = fc.Add("New Folder")
   End If
End Sub
GetSpecialFolder Method
Returns the special folder object specified.
Dim fso, tempfile
Set fso = CreateObject("Scripting.FileSystemObject")

Function CreateTempFile 
   Dim tfolder, tname, tfile
   Const TemporaryFolder = 2
   Set tfolder = fso.GetSpecialFolder(TemporaryFolder)
   tname = fso.GetTempName   
   Set tfile = tfolder.CreateTextFile(tname)
   Set CreateTempFile = tfile
End Function

Set tempfile = CreateTempFile
tempfile.WriteLine "Hello World"
tempfile.Close
GetTempName Method
Returns a randomly generated temporary file or folder name that is useful for performing operations that require a temporary file or folder.
Dim fso, tempfile
Set fso = CreateObject("Scripting.FileSystemObject")

Function CreateTempFile 
   Dim tfolder, tname, tfile
   Const TemporaryFolder = 2
   Set tfolder = fso.GetSpecialFolder(TemporaryFolder)
   tname = fso.GetTempName    
   Set tfile = tfolder.CreateTextFile(tname)
   Set CreateTempFile = tfile
End Function

Set tempfile = CreateTempFile
tempfile.WriteLine "Hello World"
tempfile.Close
OpenAsTextStream Method
Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file.
The iomode argument can have any of the following settings:
Constant Value Description
ForReading 1 Open a file for reading only. You can’t write to this file.
ForWriting 2 Open a file for writing. If a file with the same name exists, its previous contents are overwritten.
ForAppending 8 Open a file and write to the end of the file.
The format argument can have any of the following settings:
Constant Value Description
TristateUseDefault -2 Opens the file using the system default.
TristateTrue -1 Opens the file as Unicode.
TristateFalse 0 Opens the file as ASCII.
Code :
Function TextStreamTest
   Const ForReading = 1, ForWriting = 2, ForAppending = 8
   Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
   Dim fso, f, ts
   Set fso = CreateObject("Scripting.FileSystemObject")
   fso.CreateTextFile "test1.txt"   ' Create a file.
   Set f = fso.GetFile("test1.txt")
   Set ts = f.OpenAsTextStream(ForWriting, TristateUseDefault)
   ts.Write "Hello World"
   ts.Close
   Set ts = f.OpenAsTextStream(ForReading, TristateUseDefault)
   TextStreamTest = ts.ReadLine
   ts.Close
End Function
OpenTextFile Method
Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file.
Sub OpenTextFileTest
   Const ForReading = 1, ForWriting = 2, ForAppending = 8
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile("c:testfile.txt", ForWriting, True)
   f.Write "Hello world!"
   f.Close
End Sub
Read Method
Reads a specified number of characters from a TextStream file and returns the resulting string.
Function ReadTextFileTest
   Const ForReading = 1, ForWriting = 2, ForAppending = 8
   Dim fso, f, Msg
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile("c:testfile.txt", ForWriting, True)
   f.Write "Hello world!"
   Set f = fso.OpenTextFile("c:testfile.txt", ForReading)
   ReadTextFileTest = f.Read(5)
End Function
ReadAll Method
Reads an entire TextStream file and returns the resulting string.
Function ReadAllTextFile
   Const ForReading = 1, ForWriting = 2
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile("c:testfile.txt", ForWriting, True)
   f.Write "Hello world!"
   Set f = fso.OpenTextFile("c:testfile.txt", ForReading)
   ReadAllTextFile =   f.ReadAll
End Function
ReadLine Method
Reads an entire line (up to, but not including, the newline character) from a TextStream file and returns the resulting string.
Function ReadLineTextFile
   Const ForReading = 1, ForWriting = 2
   Dim fso, MyFile
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set MyFile = fso.OpenTextFile("c:testfile.txt", ForWriting, True)
   MyFile.WriteLine "Hello world!"
   MyFile.WriteLine "The quick brown fox"
   MyFile.Close
   Set MyFile = fso.OpenTextFile("c:testfile.txt", ForReading)
   ReadLineTextFile = MyFile.ReadLine    ' Returns "Hello world!"
End Function
Write Method
Writes a specified string to a TextStream file.
Function WriteToFile
   Const ForReading = 1, ForWriting = 2
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile("c:testfile.txt", ForWriting, True)
   f.Write "Hello world!" 
   Set f = fso.OpenTextFile("c:testfile.txt", ForReading)
   WriteToFile =   f.ReadLine
End Function
WriteBlankLines Method
Writes a specified number of newline characters to a TextStream file.
Function WriteBlankLinesToFile
   Const ForReading = 1, ForWriting = 2
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile("c:testfile.txt", ForWriting, True)
   f.WriteBlankLines 2 
   f.WriteLine "Hello World!"
   Set f = fso.OpenTextFile("c:testfile.txt", ForReading)
   WriteBlankLinesToFile = f.ReadAll
End Function
WriteLine Method
Writes a specified string and newline character to a TextStream file.
Function WriteLineToFile
   Const ForReading = 1, ForWriting = 2
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile("c:testfile.txt", ForWriting, True)
   f.WriteLine "Hello world!" 
   f.WriteLine "VBScript is fun!"
   Set f = fso.OpenTextFile("c:testfile.txt", ForReading)
   WriteLineToFile = f.ReadAll
End Function



7/9/15
Webex notes:


-          Handling files with QTP:

VB script concept – handle any files use file System object.

1. Flat file(if a batch is producing, file with delimeters in its content). Delimeter text file.

 2. Fixed Layout: Each record in a file follows a layout.

Nicely explained: As per the trainer)


 

To access any methods of DLL, we need to create an object. So use set <object name> for the FileSysteObject method.
 
Except excel and XML we cannot use FileSystemObject method.
 
->  Readall does not work if the file is very big, so go with ReadLine and use loop and AtEndofStream to rech end of line.
 

  • 1- Read, 2 – Write, 8 – Append(append some data end of the file).
  •  For batch file and flat file, this is very usefull
  • For Reading a file, we need the file to be opened, or use OpenTextfile before reading it.
  • Exercise: Compare the contents of two files. And print the difference in the data table
  • Exercise: Compare the two fixed length source target file

File template(with no delimeter):

First name 10

Last name 10

Empid 6
             Design 10
 
            Ex: Srikanth     Kulkarni      175146               Manager

When you compare the files, how will you check the difference in first, last, emp id etc….instead of comparing everything.???

Ans: Use the below for the above scenario:

Method: Read
 
            Description: Reads a specified number of characters from a TextStream file and returns the    resulting string.
 
            Syntax: strChars = objTso.Read(numCharacters)