Sie sind auf Seite 1von 63

Mary R.

Sweeney
msweeney@sammamishsoftware.com

Copyright Sammamish Software


Services 2003. All rights reserved. 1
 Class files and resources
 Prerequisites
 Knowledge of:
 fundamental programming,
 basic ANSI SQL, relational database design
 testing concepts

Copyright Sammamish Software


Services 2003. All rights reserved. 2
 Module 1: Creating and testing basic stored
procedures
 Module 2: Testing stored procedures using
SQL
 Module 3: Using stored procedures for
testing
 Module 4 : Introduction to database triggers
 Module 5 : Testing for database hacks: the
SQL Injection attack

Copyright Sammamish Software


Services 2003. All rights reserved. 3
Creating and testing basic
stored procedures

Copyright Sammamish Software


Services 2003. All rights reserved. 4
 What are stored procedures?
 Why do developer’s use them?
 Performance optimization by the DBMS
 Security: access can be limited
 Robustness against hacks
 Why test stored procedures?
 Aren’t there test tools out there that can
handle this?

Copyright Sammamish Software


Services 2003. All rights reserved. 5
 Data access routines reside within the
application source
Routines for
accessing
App source code data
C++, Java, etc.

Copyright Sammamish Software


Services 2003. All rights reserved. 6
 Data access routines are Routines for
moved to the database accessing
data
backend

App source code


C++, Java, etc.

Copyright Sammamish Software


Services 2003. All rights reserved. 7
A. Debugging Stored White box – access to code.
Procedures (Largely a development
effort.)
B. Testing an app’s White box (Unit Test).
Stored Procedures in the
DB Backend
C. Creating and using Black or white box.
Stored Procedures for
Testing
Copyright Sammamish Software
Services 2003. All rights reserved. 8
create procedure UpdateProducts
as
update products
set unitprice = unitprice * 1.1;

Copyright Sammamish Software


Services 2003. All rights reserved. 9
Create procedure uspValidateUser
(@userName varchar(50),
@userPass varchar(20))
as
select * from users
where userName = @userName and
userPass=@userPass;
Copyright Sammamish Software
Services 2003. All rights reserved. 10
create PROCEDURE CustOrderHist2 @CustomerID nchar(5)
AS
if exists (select customerid from customers
where @customerid = customerid)
begin
SELECT ProductName, SUM(Quantity) as Total
FROM Products P join [Order Details] OD
on p.productid = od.productid
join orders o
on O.OrderID = OD.OrderID
join customers c
on C.CustomerID = O.CustomerID
where c.customerid = @customerid
GROUP BY ProductName
end
Copyright Sammamish Software
Services 2003. All rights reserved. 11
Create Procedure procedurename as
Begin
SQL-Statements
End;

Copyright Sammamish Software


Services 2003. All rights reserved. 12
SELECT text FROM USER_SOURCE
WHERE name = 'INPUTCOMMERCIAL2';
 You can also check the status of the stored
procedure, such as whether or not it compiled
properly and is runnable by using this statement:
SELECT object_name, object_type,
status
FROM user_objects
WHERE object_name ='INPUTCOMMERCIAL2';
Copyright Sammamish Software
Services 2003. All rights reserved. 13
T-SQL:
EXEC SP_HELPTEXT INPUTCOMMERCIAL;

Copyright Sammamish Software


Services 2003. All rights reserved. 14
CREATE Procedure procedurename
(parametername datatype, …)
as
Begin
SQL-Statements
End;

Copyright Sammamish Software


Services 2003. All rights reserved. 15
SQL> execute inputCommercial2
(&propid, &propname, &propdesc,
&loan);
Enter value for propid: 99
Enter value for propname: 'prop1'
Enter value for propdesc: 'desc'
Enter value for loan: 50000

Copyright Sammamish Software


Services 2003. All rights reserved. 16
declare
cursor get_prop_data is
SELECT id, name, description
from COMMERCIAL_PROPERTY;

for cl_rec in get_prop_data loop


/* code goes here */
end loop
Copyright Sammamish Software
Services 2003. All rights reserved. 17
 Demo 1: Creating and testing a Simple Stored
Procedure

Copyright Sammamish Software


Services 2003. All rights reserved. 18
Testing stored
procedures using
SQL

Copyright Sammamish Software


Services 2003. All rights reserved. 19
 Set up a test harness/ test bed which bypasses
the front End

GUI or Web
Front End
SQL Harness/
Test Bed

Copyright Sammamish Software


Services 2003. All rights reserved. 20
Creating Test harnesses for
Ad hoc testing
 You can set up your tests for database values and
objects using Structured Query Language within the
SQL*Plus and/or Query Analyzer environments.
 To do this you create independent SQL statements.
 In PL/SQL these are called anonymous, or unnamed, blocks.

Copyright Sammamish Software


Services 2003. All rights reserved. 21
 Using nocount:

 Set nocount on|off


 Stops the message indicating the
number of rows affected by a
Transact-SQL statement from being
returned as part of the results.

Copyright Sammamish Software


Services 2003. All rights reserved. 22
set nocount on
select 'Starting Tests: ',
current_timestamp;
delete commercial_property;
exec inputCommercial2 10, ‘TestProp1',
‘Test Description1', 22;
select * from Commercial_Property;
select 'Ending Tests: ',
current_timestamp;
set nocount off

Copyright Sammamish Software


Services 2003. All rights reserved. 23
 Using the declare statement:
In PL/SQL variables are declared like this:
Declare
e_empno NUMBER := &Empnum;
e_exists varchar2(3) := 'NO ';

 T-SQL:
declare @e_expected char(3),
@e_exists char(3) ;
set @e_expected = 'YES';
set @e_exists = 'NO ';
Copyright Sammamish Software
Services 2003. All rights reserved. 24
Declare
/* variable declarations */
Begin
/* code */
End;

Copyright Sammamish Software


Services 2003. All rights reserved. 25
if exists
(select * from COMMERCIAL_PROPERTY
where ID = 192)
select 'Test Pass: Property exists ';
else
select 'Test Fail: Property doesn’’t exist ';

Copyright Sammamish Software


Services 2003. All rights reserved. 26
 SQL 2000’s T-SQL does not include exception
handling however you can check for system errors
using the @@Error global variable.
 If a system error is generated during a test, the
@@Error variable is automatically loaded with the
error number.
 You can check this value and take appropriate action
such as roll back a transaction, if necessary.
 For testers this allows you to check for certain
expected kinds of errors.

Copyright Sammamish Software


Services 2003. All rights reserved. 27
inputCommercial2 10, 'Yet another property', 'a
description', 22;

if @@error = 2627
select 'Test failure: Duplicate PK not handled by
Proc'

Copyright Sammamish Software


Services 2003. All rights reserved. 28
Declare

Begin
/* code */
Exception
when NO_DATA_FOUND then
/* code */
End;

Copyright Sammamish Software


Services 2003. All rights reserved. 29
SQL> spool emptestresults.txt
SQL> select * from emp;
SQL> spool off
SQL>

Copyright Sammamish Software


Services 2003. All rights reserved. 30
 Demo 2: Testing stored procedures using a SQL
script

Copyright Sammamish Software


Services 2003. All rights reserved. 31
Using stored procedures
for testing

Copyright Sammamish Software


Services 2003. All rights reserved. 32
 Can be stored within the target database or
within a linked database
 Can use test data stored within the database
for a data driven test

Stored
Procedure
tests

Copyright Sammamish Software


Services 2003. All rights reserved. 33
 Simply preface your existing tests with
a Stored procedure Create statement:

Create Procedure
Tst_InputCommercial2
As
/* your test code goes here! */

Copyright Sammamish Software


Services 2003. All rights reserved. 34
SQL cursors:
DECLARE tnames_cursor CURSOR
FOR
SELECT au_lname FROM authors
OPEN tnames_cursor
DECLARE @authname varchar(40)
FETCH NEXT FROM tnames_cursor INTO
@authname

Copyright Sammamish Software


Services 2003. All rights reserved. 35
/*testing using testdata table
values: */

for test_rec in get_test_data


loop
inputCommercial2
(test_rec.id, test_rec.name,
test_rec.description,
test_rec.primary_loan_id);
end loop;
Copyright Sammamish Software
Services 2003. All rights reserved. 36
 Demo 3:
 Testing a stored procedure with a stored procedure

Copyright Sammamish Software


Services 2003. All rights reserved. 37
 Basic functionality: Test input and output parameters using
standard techniques (boundary analysis, parameter
validation, etc.)
 Should have error-handling and existence checks
 Triggered stored procedure functionality
 Stored procedures which include queries that cover the
entire table i.e., table scans (performance)
 SPs which return nothing (performance)
 System/application errors returned to the user (Incomplete
or ineffective or no error-handling)
 Corrupt data results
Copyright Sammamish Software
Services 2003. All rights reserved. 38
Tester’s checklist:
What to look for (cont)
 No use of transactions
 Excess use of temp tables and cursors
 No data validation for required
parameters
 No return of status
 Parameters:
 Precision mismatches;
 lack of default values
 Susceptibility to deliberate, destructive
attacks, such as SQL Injection attacks
Copyright Sammamish Software
Services 2003. All rights reserved. 39
 DevPartner by CompuWare (DB2, Oracle,
SQL Server)
 Visual Studio .Net (for SQL Server)
 SQL Navigator by Quest (for Oracle)
 Quest “Code Tester” (Steven Feuerstein)
 NUnit(Windows) JUnit (Unix) csUnit
 DbUnit

Copyright Sammamish Software


Services 2003. All rights reserved. 40
 Scripting languages can be effectively utilized
to exercise stored procedures.
 VBScript
 Perl
 Ruby
 Javascript/Jscript
 Data access languages: PHP or ADO

Copyright Sammamish Software


Services 2003. All rights reserved. 41
 they typically have a light footprint, i.e., are easy
on the test system.
 they can directly and quickly emulate the calls
being used by the application, especially if you
use the same scripting language as the
application! (Be careful to avoid replicating
application development.)
 test scripts are smaller, more focused and are
able to isolate bugs better than using the
application to do the test.
Copyright Sammamish Software
Services 2003. All rights reserved. 42
Dim conn, rsTestData, i, strMsg
Set conn = CreateObject("ADODB.Connection")
conn.Open
"Provider=MSDAORA.1;Password=tiger;User
ID=scott"
Set rsTestData =
CreateObject("ADODB.Recordset")
rsTestData.CursorType = 1
rsTestData.Open "select * from EMP", conn
rsTestData.MoveFirst
Copyright Sammamish Software
Services 2003. All rights reserved. 43
<Job ID="PerlTest1">
<script language=PerlScript runat=server>
my $conn =
$Wscript->CreateObject('ADODB.Connection');
$conn->Open('NWDsn');
if($conn->{State} == 1) {
$WScript->Echo("Connection Successful!")}
else {$WScript->Echo("Connection Failed");}
my $adOpenKeySet_CursorType = 1;
my $rst = $WScript->CreateObject('ADODB.Recordset');
my $rst2 = $WScript->CreateObject('ADODB.Recordset');
$rst->Open('SELECT * FROM TestData', $conn,
$adOpenKeySet_CursorType);
$WScript->Echo("There are ".$rst->{RecordCount}."
records in the Recordset");

Copyright Sammamish Software


Services 2003. All rights reserved. 44
 Php/Perl:  ADO/VBScript
 Open source software  Runs only on all
 Can run on Linux, Windows OS
Windows, Unix  Freely downloadable;
systems pre-installed on
 Widely used; lots of Windows
documentation  Widely used; lots of
 Perl Oracle module documentation
has issues  My best choice for
Windows

Copyright Sammamish Software


Services 2003. All rights reserved. 45
Introduction to database
Triggers

Copyright Sammamish Software


Services 2003. All rights reserved. 46
 Triggers are a special type of stored procedure
that is applied to tables.
 Complex procedural data integrity methods and
business logic can be added to a database using
triggers.
 A trigger is a set of actions that execute
automatically whenever a specified event occurs
to a specified table.
 Events can be an insert, update, delete, or read operation.
The trigger can run before or after the event.

Copyright Sammamish Software


Services 2003. All rights reserved. 47
 Referential Integrity Constraints should be
used before Triggers
 Complex procedural data integrity methods
and business logic can be added to a database
using triggers.
 A single trigger can run multiple actions, and it
can be fired by more than one event. For
example, you can create a single trigger that
runs when any valid event, INSERT, UPDATE,
or DELETE occurs.

Copyright Sammamish Software


Services 2003. All rights reserved. 48
 Triggers cannot be fired manually.

 An important feature of triggers is that


unsuccessful transactions are automatically
rolled back.

Copyright Sammamish Software


Services 2003. All rights reserved. 49
CREATE TRIGGER reminder
ON Orders
FOR UPDATE
AS
select 'A row was just modified in the Orders
table';

Copyright Sammamish Software


Services 2003. All rights reserved. 50
The main clauses in a CREATE TRIGGER statement can be
summarized as follows:

CREATE TRIGGER trigger_name


ON table_name or v
FOR trigger_class and trigger_type(s)
AS SQL statements

Copyright Sammamish Software


Services 2003. All rights reserved. 51
 Triggers are an important way that business
logic is implemented in a database
 Triggers have automatic behavior that can be
complex and can cause significant damage if
incorrect
 Triggers are “expensive” and should be used
judiciously

Copyright Sammamish Software


Services 2003. All rights reserved. 52
 Graph trigger effects
 Trigger effect graph
Table Trigger Events Affected Affected
Customers trgOrdUpd U Orders
trgCustLog U, D, I CustLogtbl
Orders trgOrdLog U, D, I OrdLogtbl

 Design Test cases for each trigger effect


 Customer table test cases:
 TC1: Add record to cust; Check custlog
 TC2: Update cust record; Check custlog; check Orders
table
 TC3?

Copyright Sammamish Software


Services 2003. All rights reserved. 53
 Map out trigger effects
 Trigger effect map

Customers
table Orders
Table
TrgOrdUp
d TrgOrdLog
TrgCustLog

Custome Orders
r log
log table
table

Copyright Sammamish Software


Services 2003. All rights reserved. 54
 Create a log table to track trigger effects
 Encourage developers to do this if you don’t have
permission:
Create Table Custlogtbl
(Eventtime DATETIME not null, SQL Server
Eventtype VARCHAR(20) not null,
CustID varchar(5));
Create Table Custlogtbl
(Eventtime DATE not null,
Eventtype VARCHAR2(255) not null, Oracle
CustID varchar(5));

Copyright Sammamish Software


Services 2003. All rights reserved. 55
Sweeney:
Sweeney:
Demo
Demo
triggerlogexample.sql
triggerlogexample.sql

 A trigger for logging table changes:

Create Trigger trgCustLog


on Customers
after update
as
begin
insert into custlogtbl
select current_timestamp, 'Updated', customerid from
deleted;
end;
Copyright Sammamish Software
Services 2003. All rights reserved. 56
 Triggers can be tested manually and/or
tracked by using log tables
 Add the Trigger effect graph and Trigger effect
map to your documentation artifacts

Copyright Sammamish Software


Services 2003. All rights reserved. 57
Database Security: Testing
for database hacks

Copyright Sammamish Software


Services 2003. All rights reserved. 58
ABC Corp. Login Form:

Username: ‘or 1=1; drop table user; --

Password:
Turns this query:
Select username from user where username = ‘someuser’
and pass = ‘somepass’
Into this query:
Select username from user where username = ‘’ or 1 = 1;
drop table user; -- and pass = ‘’
Copyright Sammamish Software
Services 2003. All rights reserved. 59
 Demo 5:
 Develop at least two test cases to test for a SQL Injection
attack

Copyright Sammamish Software


Services 2003. All rights reserved. 60
Review
Where do we go from here?

Copyright Sammamish Software


Services 2003. All rights reserved. 61
 Module 1: Creating and testing basic stored
procedures
 Module 2: Testing stored procedures using
SQL
 Module 3: Using stored procedures for
testing
 Module 4 : Introduction to Triggers
 Module 5 : Testing for database hacks: the
SQL Injection attack
Copyright Sammamish Software
Services 2003. All rights reserved. 62
 Course on scripting language
 Advanced RDBMS courses
 Resources in Appendix A
 STQE www.sqe.com
 QA forums
 Yahoo group: Agile databases

Copyright Sammamish Software


Services 2003. All rights reserved. 63

Das könnte Ihnen auch gefallen