Tuesday, June 29, 2010

Vbscripting with Classes

Classess in VB script

Class Customer

     Private m_CustomerName
     Private m_OrderCount
    
Private Sub Class_Initialize
     m_CustomerName = ""
     m_OrderCount = 0
End Sub



' CustomerName property.

Public Property Get CustomerName
      CustomerName = m_CustomerName
End Property

Public Property Let CustomerName(custname)
     m_CustomerName = custname
End Property

' OrderCount property (read only).

Public Property Get OrderCount
     OrderCount = m_OrderCount
End Property

' Methods.

Public Sub IncreaseOrders(valuetoincrease)
     m_OrderCount = m_OrderCount + valuetoincrease
End Sub

End Class

Dim c

Set c = New Customer
c.CustomerName = "Fabrikam, Inc."
MsgBox (c.CustomerName)
c.IncreaseOrders(5)
c.IncreaseOrders(3)
MsgBox (c.OrderCount)

Property in Class

Class User
' declare private class variable

     Private m_userName
     Private m_Test
' declare the property

Public Property Get UserName
     UserName = m_userName
End Property

Public Property Let UserName (strUserName)
     m_userName = strUserName
End Property

Public Property Get Test
     Test = m_Test
End Property

Public Property Let Test (sTest)
     m_Test = srTest
End Property

' declare and define the method

Sub DisplayUserName
     WScript.Echo UserName
     WScript.Echo Test
End Sub

End Class

Dim objUser
Set objUser = New User
' set the UserName property
objUser.UserName = "The Guru"
objUser.Test = "Test value"
' call the DisplayUserName method to print the user name
objUser.DisplayUserName


Shared Class

Class Test
     Public InstanceValue As String
     Public Shared SharedValue As String
Public Shared

Sub ShareMethod()
     MsgBox("This is a shared method.")
End Sub

End Class


Sub TestShared()
     Dim Shared1 As New Test() ' Create an instance of the class.
     Dim Shared2 As New Test() ' Create an instance of the class.
     Shared1.SharedValue = "Share Value 1" ' Set the value of a shared field.
     Shared2.SharedValue = "Share Value 2" ' Overwrite the first value.
     MsgBox("The value of the shared field in the first instance" & _
      "is: " & Shared1.SharedValue)
     MsgBox("The value of the shared field in the second instance" & _
      is: " & Shared2.SharedValue)
'    Call a method on the class without creating an instance.
     Test.ShareMethod()
End Sub

Object Drive using Class

Dim filesys
set filesys = CreateObject("Scripting.FileSystemObject")
Set drv = filesys.GetDrive("e")

select case drv.DriveType
     Case 0: drtype = "Unknown"
     Case 1: drtype = "Removable"
     Case 2: drtype = "Fixed"
     Case 3: drtype = "Network"
     Case 4: drtype = "CD-ROM"
    Case 5: drtype = "RAM Disk"
End Select

WScript.Echo "The specified drive is a " & drtype & " type disk."
WScript.Echo " "
WScript.Echo "Total size is " & drv.TotalSize & ". "
WScript.Echo "Available space is " & drv.AvailableSpace & ". "
WScript.Echo "Type is " & drv.DriveType & " "
WScript.Echo "Path is " & drv.Path & " "

Dim filesyst, drive
Set filesyst = CreateObject("Scripting.FileSystemObject")
WScript.Echo "Before Condtion"
drive = filesyst.DriveExists("z")
WScript.Echo drive

If filesyst.DriveExists("z") Then
     WScript.Echo("The specified drive does exist.")
Else
     WScript.Echo("The specified drive does not exist.")
End If

WScript.Echo "After Condtion"

Sunday, June 27, 2010

Time and date function in Vbscript

Time and date in Vbscript

'MsgBox (Date ())

WScript.Echo (Date ())
WScript.Echo (Time ())
WScript.Echo Now ()
WScript.Echo Hour (Time)
WScript.Echo Month (Date)
WScript.Echo (Time ())
WScript.Echo MonthName (1)
WScript.Echo MonthName (12)
WScript.Echo second (time)
WScript.Echo Timer ()
WScript.Echo TimeSerial (13,56,8)
WScript.Echo Timevalue (Time)
WScript.Echo Weekday (Date)
WScript.Echo WeekdayName(Weekday(2))
WScript.Echo





Playing with string in Vbscript

Manipulating String

Dim var
var = " hello Word "
MsgBox var
temp = Trim (var)
MsgBox temp
MsgBox var
temp1 = UCase(Trim (var))
MsgBox temp1
temp2 = LCase(temp1)
MsgBox temp2


Few more function for string

Dim temp
temp = "12 3456781 "

MsgBox (temp)
MsgBox (Len (temp))
MsgBox (Left (temp, 3))
MsgBox (right (temp, 3))
MsgBox (Mid (temp,2,3))
MsgBox (Mid (temp,1,3))
MsgBox (Mid (temp,5,2))
MsgBox (Trim (temp))
MsgBox (StrComp ("YES","yes",(0))) ' 0 is a case sensitive option
MsgBox (StrComp ("yes","ye",(1)))
MsgBox (String (34,"*"))
WScript.Echo (String (34,"*")) ' Run with both wscript n script option in CMD '
MsgBox (StrReverse ("HEllo"))

Thursday, June 24, 2010

Debug vbscript & Jscript from Command prompt

How to debug Windows Script Host (WSH) scripts, which can be written in any ActiveX script language (as long as the proper language engine is installed), but which, by default, are written in VBScript and JScript.
There are certain flags in the registry and, depending on the debugger used, certain required procedures to enable debugging.
To debug WSH scripts in Microsoft Visual InterDev, the Microsoft Script Debugger, or any other debugger, use the following command-line syntax to start the script:

               wscript.exe //d

This code informs the user when a runtime error has occurred and gives the user a choice to debug the application. Also, the //x flag can be used, as follows, to throw an immediate exception, which starts the debugger immediately after the script starts running:
               wscript.exe //d //x 

After a debug condition exists, the following registry key determines which debugger will be used:

HKEY_CLASSES_ROOT\CLSID\{834128A2-51F4-11D0-8F20-00805F2CD064}\LocalServer32

The script debugger should be Msscrdbg.exe, and the Visual InterDev debugger should be Mdm.exe.

If Visual InterDev is the default debugger, make sure that just-in-time (JIT) functionality is enabled. To do this, follow these steps:
  1. Start Visual InterDev.
  2. On the Tools menu, click Options.
  3. Click Debugger, and then ensure that the Just-In-Time options are selected for both the General and Script categories.
Additionally, if you are trying to debug a .wsf file, make sure that the following registry key is set to 1:

HKEY_CURRENT_USER\Software\Microsoft\Windows Script\Settings\JITDebug

Thursday, June 17, 2010

Structure outline of Automation Framework


Hi All,

Generic structure for Keyword Driven Framework:

·         Test case                                                             (Excel OR XML OR ELSE)
·         Driver script
·         Data script                                                           ( To collect & Validate the test data & Keyword from test case excel )
·         Common Functional Library                        (Common for all the test)
·         Business function & procedure                  (Can be specific to test)
·         Supportive library                                           (Application Independent)
·         Scripts                                                                   ( Specific to test  - only if required)
·         Test result
Configuration files which contain following thing: 

1.       File 1:  Contain the variable to make debug mode enable/disable.
a.       Can also include flag to install\Uninstall application.
b.      Point to re-configure the test environment.
c.       Flag to make different level of validation\Check point before executing test.
2.       File 2 :  Which contain all the required path of files. (Application, result, etc)
3.       File 3 : which contain global variable & QTP environment variable  used as reference for validation,  to invoke QTP & set the test environment.
Optional Feature:

1.       Maintaining result history separately, which can be maintain in such way that we can extract history detail of each test/module.
2.       Generating mail at completion of each scheduled run with result & important messages of failure.

Wednesday, June 16, 2010

Environment variables in QTP

Environment variables in QTP:

Environment variables in QTP are like global variables in other programming languages which can be accessed through any part of the script.

·         The values of these variables remain same irrespective of the number of iterations (unless you change them through scripting).
·         These variables can prove to be very useful when you want a variable to be shared across various reusable actions.

There are two types of environment variables:

1.       Built-In:
2.       User-Defined:

Build IN:
·         These are the internal variables that are provided by QTP.
·         Contain information like the path of the folder where test is located, the path of the results folder, the name of the action iteration or the OS version.
·         You can simply type in Environment.Value(“OSVersion”) to get the OS version

User-Defined:

These can be further defined into two types.
·         User defined Internal
o   Define within the test.
o   These variables are saved with the test and are accessible only within the test in which they were defined.
o   So how can we define and use them?

To define them: Environment.Value(“name”)= “Ankur Jain”
To call them: msgbox Environment.Value(“name”)

·         User defined External
·         These are the variables that we predefine in the active external environment variables file.
·         These can be created using a list of variable-value pairs in an external file in .xml format or any other

For e.g.

‘ Load an INI file with user-defined parameters
App.Test.Environment.LoadFromFile “C:\Test_Params\environment_file1.ini”

‘ Set the value of a specific user-defined Environment variable
App.Test.Environment.Value(“newvariable”) = “new value”

As you can see from the example, the Environment variable file is actually an .ini file. The structure would be:
[Environment]
var1=value1
var2=value2


How to run qtp from CMD

Write the Vbs script and execute it from CMD using cscript orWscript

Sample Vbscript as follow

Set qtApp= CreateObject("QuickTest.Application")
qtApp.Launch
qtApp.Visible = True

'And then call your scripts one after another
qtApp.Open "Enter Complete path for script here"
qtApp.Test.Run
'and once you are done then close the QTP with the following :

qtApp.Quit

Monday, June 14, 2010

Vbscript to get detail information of any file

 Vbscript to get detail information of any file

Dim filesys, demofile, createdate
Set filesys = CreateObject("Scripting.FileSystemObject")


Set demofile = filesys.GetFile("e:\TEST.xls")
createdate = demofile.DateCreated
WScript.Echo (createdate)
strHomeFolder = "E:\QTP"
Set objShell = CreateObject("Wscript.Shell")
Set filesys = CreateObject("Scripting.FileSystemObject")
If filesys.FolderExists (strHomeFolder) Then
' Assign user permission to home folder.
intRunError = objShell.Run("%COMSPEC% /c Echo Y| cacls " & strHomeFolder & " /t /c /g Administrators:F ", 2, True)
WScript.Echo (intRunError)
   If intRunError <> 0 Then
   Wscript.Echo "Error assigning permissions for user " & strUser & " to home folder " & strHomeFolder
   Else
   Wscript.Echo "In inner loop"
   End If
Else
Wscript.Echo "In Outer loop"
End If


WScript.Echo (demofile.Attributes)
'WScript.Echo (demofile.Type)
'WScript.Echo "Date created: " & demofile.DateCreated
'Wscript.Echo "Date last accessed: " & demofile.DateLastAccessed
'Wscript.Echo "Date last modified: " & demofile.DateLastModified
'Wscript.Echo "Drive: " & demofile.Drive
'Wscript.Echo "Name: " & demofile.Name
'Wscript.Echo "Parent folder: " & demofile.ParentFolder
'Wscript.Echo "Path: " & demofile.Path
'Wscript.Echo "Short name: " & demofile.ShortName
'Wscript.Echo "Short path: " & demofile.ShortPath
'Wscript.Echo "Size: " & demofile.Size
'Wscript.Echo "Type: " & demofile.Type




WScript.Quit

Sunday, June 13, 2010

Sample of VB script with class

Class Hello_World

Public Sub Say_Hello(Name)
MsgBox "Hello, " & Name & ", welcome to " & Garden & "."
End Sub
Public Garden
End Class

Dim MyHello_World

Set MyHello_World = New Hello_World

MyHello_World.Garden = "Fountain"
MyHello_World.Say_Hello "Sachin"
MyHello_World.Garden = "Foun" 

VB scripts to play with file

Script to read a file using while loop.

#!/usr/local/ActivePerl-5.8/bin/perl
if (open(MYFILE, "file1")) {
$line = ;
while ($line ne "") {
print ($line);
$line = ;
}
}

Script to write in a file

#!/usr/local/bin/perl
open (MYPIPE, "cat >hello");
print MYPIPE ("Hi, Dave! Your Perl program sent this!\n");

close (MYPIPE); 


Script to search specific word from the file.

#!/usr/local/bin/perl
print ("Word to search for $ARGV[0]\n");
$filecount = 1;
$totalwordcount = 0;

while ($filecount <= @ARGV-1) {
unless (open (INFILE, $ARGV[$filecount]))
{
die ("Can't open input file $ARGV[$filecount]\n");
            }
            $wordcount = 0;
            while ($line = )
            {
                        chop ($line);
                        print ("Before split : $line\n");
                        @words = split(/ /, $line);
                        print ("Content is : @words\n");
                        $w = 1;
                        while ($w <= @words) {
                                    if ($words[$w-1] eq $ARGV[0]) {
                                                $wordcount += 1;
                                    }
                                    $w++;
                                    }
            }         
}

print ("total number of occurrences $totalwordcount\n");

' Script to create a instant of existing file and list out the complete information of the same

Dim filesys, demofile, createdate

Set filesys = CreateObject("Scripting.FileSystemObject")
Set demofile = filesys.GetFile("e:\TEST.xls")

createdate = demofile.DateCreated
WScript.Echo (createdate)

strHomeFolder = "E:\QTP"

Set objShell = CreateObject("Wscript.Shell")
Set filesys = CreateObject("Scripting.FileSystemObject")

If filesys.FolderExists (strHomeFolder) Then
            ' Assign user permission to home folder.
            intRunError = objShell.Run("%COMSPEC% /c Echo Y
            cacls " & strHomeFolder & " /t /c /g Administrators:F ", 2, True)
            WScript.Echo (intRunError)

            If intRunError <> 0 Then
                               Wscript.Echo "Error assigning permissions for user " & strUser & " to home folder " & strHomeFolder
            Else
       Wscript.Echo "In inner loop"
            End If
End if



WScript.Echo (demofile.Attributes)
WScript.Echo (demofile.Type)
WScript.Echo "Date created: " & demofile.DateCreated
Wscript.Echo "Date last accessed: " & demofile.DateLastAccessed
Wscript.Echo "Date last modified: " & demofile.DateLastModified
Wscript.Echo "Drive: " & demofile.Drive
Wscript.Echo "Name: " & demofile.Name
Wscript.Echo "Parent folder: " & demofile.ParentFolder
Wscript.Echo "Path: " & demofile.Path
Wscript.Echo "Short name: " & demofile.ShortName
Wscript.Echo "Short path: " & demofile.ShortPath
Wscript.Echo "Size: " & demofile.Size
Wscript.Echo "Type: " & demofile.Type

WScript.Quit

' Script to write in the file and read using loop
' Also to get the version detail of vbscript.

Dim filesys, text, readfile, contents

set filesys = CreateObject("Scripting.FileSystemObject")
Set text = filesys.CreateTextFile("c:\test.txt")

text.Write "Find the last character in the text file"
text.Write " '
text.Write "Find the last character in the text fil"
text.Close

Set readfile = filesys.OpenTextFile("c:\somefile2.txt", 1, false)
Do while readfile.AtEndOfLine <> true 'Condition to get end letter of first line'

'Do while readfile.AtEndOfStream <> true 'Condition to get end letter of file'
        contents = readfile.Read(1)
'WScript.Echo contents 'Print all the letter for file'
Loop
readfile.close

'Response.Write "The last character in the text file is '" & contents & "."
WScript.Echo "The last character in the text file is '" & contents & "."
WScript.Echo ScriptEngine
WScript.Echo ScriptEngineBuildVersion
WScript.Echo ScriptEngineMajorVersion
WScript.Echo ScriptEngineMinorVersion
WScript.Echo Second(Time)
WScript.Echo Tan(55.0)

Perl Script to send mail

#!E:\Perl\bin -w
use MIME::Lite;
MIME::Lite->send('smtp', "mailtesthub.gmail.com", Timeout=>90);

my $MailFrom = 'test@gmail.com';
my $to_list = 'john@gmail.com';
my $cc_list = 'frank@yahoo.com';
my $subject = "hello test";
my $message = "This email was generated automatically.";

my $msg = MIME::Lite->new(
From => $MailFrom,
To => $to_list,
Cc => $cc_list,
Subject => $subject,
Type => 'TEXT',
Encoding => '7bit',
Data => $message,
);


$msg->send()

Friday, June 11, 2010

How to specify the environment variables to be loaded when QTP is started

You can either define individual values in the .vbs file or specify an environment file to load.

Example:
Here is what the .vbs file could look like:

Dim App ‘As Application
‘ Launch QTP
Set App = CreateObject(“QuickTest.Application”)
App.Launch
App.Visible = True

‘ Load an INI file with user-defined parameters
App.Test.Environment.LoadFromFile “C:\Test_Params\environment_file1.ini”

‘ Set the value of a specific user-defined Environment variable
App.Test.Environment.Value(“newvariable”) = “new value”

As you can see from the example, the Environment variable file is actually an .ini file. The structure would be:
[Environment]
var1=value1
var2=value2

Wednesday, June 2, 2010

30 Basic Question for QTP Certification

I have not given answer here because I want you to find answers and have idea what kind of question can be in Certification.

Best of luck

1) Identify the recording mode, by which you can record the non-standard object in
QTP
A) Standard recording
B) Analog recording
C) Low level recording
D) None

2) By default, how many no of tables would be there in a script?

a) One
b) Two
c) Three
d) Four

3) By default, how many no of actions would be there in a script?

a) One
b) Two
c) Three
d) Four

4) The file extension of Local object repository file is

a) .MTR
b) .TSR
c) .QRS
d) None

5) The file extension of Shared object repository file is

a. .MTR
b. .TSR
c. .QRS
d. None

6) When a procedure is created in the Function Library editor, what is the extension of the file?

A. .INI
B. .TXT
C. .QFL
D. .VBS

7) What are the categories in the Step Generator?

E. Object, Operation, Value
F. Library, Built-in, Local Script
G. Operation, Arguments, Return Value
H. Test Objects, Utility Objects, Functions

8) In Test Settings -> Run the Data Table iteration options are for which data sheet?

I. Local
J. Global
K. Run-time Data Table
L. Design-time Data Table

9) What can you use to handle unpredictable testing exceptions?

M. A Do Loop
N. Recovery Scenario
O. IF Then statement
P. Select Case statement

10) In which command can you associate a function library to a test?

Q. Run Options
R. Test Settings
S. View Options
T. Function Definition Generator

11) To invoke the function which does not return any value, we can use

a. call function name
b. function name
c. Both A & B
d. None

12) The result of the checkpoints can be stored in a variable

a. True
b. False


13) Parameterization generally involves

a. Data table
b. Random number
c. Environment
d. Both A & B
e. Both A, B & C

14) The file which is used for recovering from the run time errors known as

i. QRS
ii. TSR
iii. PNG
iv. DAT

15) Among the following recording modes, which method uses both the objects and
mouse coordinates

a. Normal
b. Low level
c. Analog
d. All of the above

16) Where do you set the action iterations for a specified action?

a. Action Settings
b. Action Properties
c. Action Run Properties
d. Action Call Properties

17) Where do you mark an action as reusable?
a. Action Settings
b. Action Properties
c. Action Run Properties
d. Action Call Properties

18) After running a test that contains both input and output parameters, where can the results of an output parameter be found?

a. Local Data Sheet
b. Global Data Sheet
c. Run-time Data Table
d. Design-time Data Table


19) If you have a Virtual Object Collection stored on your machine, and you don’t want to use it what you must do?

a. Disable Virtual Objects in Test Settings
b. Remove the Collection from your machine
c. Disable Virtual Objects in General Options
d. Remove the Collections from the Resources list

20) Which method for the Data Table utility object will allow you to retrieve information from the Data Table during a test run?

a. Value
b. Import
c. GetCell
d. GetValue

21) Statement to return the value from the function

i. Return (return value)
ii. Exit (Return value)
iii. Function name = Return value
iv. None

22) constant “2” with the reporter statement returns

a. Pass
b. Fail
c. Done
d. Warning

23) The standard timing delay for windows application is

i. 20 seconds
ii. 60 seconds
iii. Infinite
iv. 100 seconds

24) The standard timing delay for web based application is

i. 20 seconds
ii. 60 seconds
iii. Infinite
iv. 100 seconds

25) In VB Script functions, which one is false among the following

a. Variables must be declared before use
b. Variables may not be declared before use
c. Variables may be declared without data types
None

26) What does the source property of a database checkpoint object represent?

A. The SQL query
B. The identification number of the database
C. The number of rows returned from the query
D. The connection string used to connect to the database

27) What is created, by default, with each new action?

A. Local Data Sheet, Global Data Sheet, Folder
B. Local Object Repository, Local Data Sheet, Folder
C. Global Data Sheet, Local Object Repository, Folder
D. Local Data Sheet, Global Data Sheet, Local Object Repository

28) What are the available environment variable types?

A. Built-in
B. User-defined
C. User-function
D. Built-in, User-defined
E. Built-in, User-function

29) If the Global Data sheet contains no data and the Local Datasheet contains two rows of data, how many times will the test iterate?

A. 1
B. 2
C. 3
D. 5

30) What is the first thing that must be defined in a Recovery Scenario?

A. Trigger
B. Recovery Operation
C. Recovery Scenario Name
D. The Function used in the scenario

Will update more soon
 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | JCpenney Printable Coupons