SlideShare a Scribd company logo
1 of 24
Pgtap
Unit testing for Postgresql

Lucio Grenzi
l.grenzi@gmail.com

PGDay.IT 2013 – 25 Ottobre 2013 - Prato

1 di 24
Who I am
Delphi developer since 1999
IT Consultant
Front end web developer
Postgresql addicted
Nonantolando.blogspot.com
lucio.grenzi
lucio grenzi

PGDay.IT 2013 – 25 Ottobre 2013 - Prato

2 di 24
Agenda
PgTap: introduction
Why use this tool
Best practices
Q&A

PGDay.IT 2013 – 25 Ottobre 2013 - Prato

3 di 24
Question before starting

Why would you want to unit
test your database?

PGDay.IT 2013 – 25 Ottobre 2013 - Prato

4 di 24
Why use pgTap
Backend application development
Test schema object validation
Module development
Continuos integration

PGDay.IT 2013 – 25 Ottobre 2013 - Prato

5 di 24
Tap protocol
The Test Anything Protocol (TAP) is a protocol to allow
communication between unit tests and a test harness. It
allows individual tests (TAP producers) to communicate
test results to the testing harness in a language-agnostic
way. Originally developed for unit testing of the Perl
interpreter in 1987, producers and parsers are now
available for many development platforms.
-wikipedia-

PGDay.IT 2013 – 25 Ottobre 2013 - Prato

6 di 24
PgTap

pgTAP is a unit testing framework for PostgreSQL written
in PL/pgSQL and PL/SQL. It includes a comprehensive
collection of TAP-emitting assertion functions, as well as
the ability to integrate with other TAP-emitting test
frameworks. It can also be used in the xUnit testing style.
-http://pgtap.org/-

PGDay.IT 2013 – 25 Ottobre 2013 - Prato

7 di 24
PgTap now
www.pgtap.org
Latest version is 0.93.0
Already packaged for the most important linux
distributions
make
make installcheck
make install

PGDay.IT 2013 – 25 Ottobre 2013 - Prato

8 di 24
Requirements
PostgreSQL 8.1 or higher
with 8.4 or higher recommended for full use of its API

PL/pgSQL
On Windows servers is necessary to install Perl
Perl on Linux is no more necessary but it is required by
pg_prove

PGDay.IT 2013 – 25 Ottobre 2013 - Prato

9 di 24
Adding PgTap to a database
Install pgtap in a database
psql -d dbname -f pgtap.sql

include the call to pgtap.sql in your script with
/pgtap.sql

i

remove pgtap from a database
psql -d dbname -f uninstall_pgtap.sql

PGDay.IT 2013 – 25 Ottobre 2013 - Prato

10 di 24
Tap in practice
Test output is easy to understand
BEGIN;
SELECT plan(); ---- how many test?
…put your tests here…
SELECT * FROM finish(); ---- test finished, print report
ROLLBACK;

PGDay.IT 2013 – 25 Ottobre 2013 - Prato

11 di 24
PgTap functions - compare
ok()
is()
isnt()
matches()
doesnt_match()
alike()
unalike()
cmp_ok()
pass()
fail()

SELECT ok( :boolean, :description );
SELECT is ( :have, :want, :description);
SELECT isnt(:have, :want, :description);
SELECT matches( :have, :regex, :description );
SELECT doesnt_match( :have, :regex, :description );
SELECT alike( :this, :like, :description );
SELECT unalike( :this, :like, :description );
SELECT cmp_ok( :have, :op, :want, :description );
SELECT pass( :description );
SELECT fail( :description );

PGDay.IT 2013 – 25 Ottobre 2013 - Prato

12 di 24
PgTap functions – test failures
throws_ok()
throws_like()
throws_matching()
lives_ok()
performs_ok()

SELECT throws_ok( :sql, :errcode, :ermsg,
:description );

PGDay.IT 2013 – 25 Ottobre 2013 - Prato

13 di 24
PgTap functions – test objects
tablespaces_are()
schemas_are()
tables_are()
views_are()
sequences_are()
columns_are()
indexes_are()
triggers_are()
functions_are()
roles_are()
users_are()

groups_are()
languages_are()
opclasses_are()
rules_are()
types_are()
domains_are()
enums_are()
casts_are()
operators_are()

PGDay.IT 2013 – 25 Ottobre 2013 - Prato

14 di 24
PgTap basics
set ON_ERROR_ROLLBACK 11
set ON_ERROR_ROLLBACK
set ON_ERROR_STOP true
set ON_ERROR_STOP true
set QUIET 11
set QUIET
BEGIN;
BEGIN;
SELECT plan(1);
SELECT plan(1);
SELECT pass( 'Hello PgDayit !'!');
SELECT pass( 'Hello PgDayit );
SELECT **FROM finish();
SELECT FROM finish();
ROLLBACK;
ROLLBACK;
save this as HelloPgDayit.txt and type: psql -U postgres -f HelloPgDayit.txt

1..1
1..1
ok 11- -Hello PgDayit ! !
ok
Hello PgDayit

PGDay.IT 2013 – 25 Ottobre 2013 - Prato

15 di 24
Let's create some tables
BEGIN;
i ./pgtap.sql
-- create two tables with referential constraint
create table table1 (id integer not null, t_text varchar(100), dt timestamp default now(), CONSTRAINT table1_pkey
PRIMARY KEY (id));
create table table2 (id integer not null, t_text varchar(100), id_ref integer, CONSTRAINT id_ref FOREIGN KEY
(id_ref) REFERENCES table1 (id));
insert into table1 (id,t_text) values (1,'test one');
insert into table1 (id,t_text) values (2,'test two');
insert into table1 (id,t_text) values (3,'test three');
insert into table2 (id,t_text,id_ref) values (1,'ref test one', 1);
insert into table2 (id,t_text,id_ref) values (2,'ref test two', 2);
insert into table2 (id,t_text,id_ref) values (3,'ref test three', 3);
SELECT plan(6);
## type tests here##
## get results here##
SELECT * FROM finish();
ROLLBACK;

PGDay.IT 2013 – 25 Ottobre 2013 - Prato

16 di 24
Test samples
PREPARE ids_fetched AS
PREPARE ids_fetched AS
select id from table1 where id in (1,2,3) order by id asc;
select id from table1 where id in (1,2,3) order by id asc;
PREPARE ids_expected AS VALUES (1),(2),(3);
PREPARE ids_expected AS VALUES (1),(2),(3);
SELECT results_eq( 'ids_fetched', 'ids_expected',
SELECT results_eq( 'ids_fetched', 'ids_expected',
'fetched the expected ids from table1');
'fetched the expected ids from table1');
PREPARE ids_fetched1 AS select id
PREPARE ids_fetched1 AS select id
from table1 where id in (1,2,3) order by id asc;
from table1 where id in (1,2,3) order by id asc;
PREPARE ids_fetched2 AS select id
PREPARE ids_fetched2 AS select id
from table2 where id in (1,2,3) order by id asc;
from table2 where id in (1,2,3) order by id asc;
SELECT results_eq( 'ids_fetched1', 'ids_fetched2');
SELECT results_eq( 'ids_fetched1', 'ids_fetched2');
PREPARE throw_error AS
PREPARE throw_error AS
insert into table1 (id,t_text)
insert into table1 (id,t_text)
values (1,'duplicate key error');
values (1,'duplicate key error');
SELECT throws_ok('throw_error','23505',NULL,
SELECT throws_ok('throw_error','23505',NULL,
'duplicated key found (id)');
'duplicated key found (id)');

PGDay.IT 2013 – 25 Ottobre 2013 - Prato

17 di 24
pg_prove
command-line application to run one or more pgTAP
tests in a PostgreSQL database
output of the tests is processed by TAP::Harness in
order to summarize the results
Tests can be written as:
SQL scripts
xUnit-style database functions

PGDay.IT 2013 – 25 Ottobre 2013 - Prato

18 di 24
pg_prove output
% pg_prove ­U postgres tests/
% pg_prove ­U postgres tests/
tests/coltap.....ok
tests/coltap.....ok
tests/hastap.....ok
tests/hastap.....ok
tests/moretap....ok
tests/moretap....ok
tests/pg73.......ok
tests/pg73.......ok
tests/pktap......ok
tests/pktap......ok
All tests successful.
All tests successful.
Files=5, Tests=100,  1 wallclock secs 
Files=5, Tests=100,  1 wallclock secs 
( 0.06 usr  0.02 sys +  0.08 cusr  0.07 csys =  0.23 CPU)
( 0.06 usr  0.02 sys +  0.08 cusr  0.07 csys =  0.23 CPU)
Result: PASS
Result: PASS

PGDay.IT 2013 – 25 Ottobre 2013 - Prato

19 di 24
pg_prove - xUnit Test Functions

EATE OR REPLACE FUNCTION setup_insert(
REATE OR REPLACE FUNCTION setup_insert(
RETURNS SETOF TEXT AS $$
 RETURNS SETOF TEXT AS $$
  RETURN NEXT is( MAX(lucio), NULL, 'Should have no users') FROM speakers;
   RETURN NEXT is( MAX(lucio), NULL, 'Should have no users') FROM speakers;
  INSERT INTO speakers (lucio) VALUES ('theory');
   INSERT INTO speakers (lucio) VALUES ('theory');
 LANGUAGE plpgsql;
$ LANGUAGE plpgsql;

eate OR REPLACE FUNCTION test_user(
reate OR REPLACE FUNCTION test_user(
RETURNS SETOF TEXT AS $$
 RETURNS SETOF TEXT AS $$
  SELECT is( lucio, 'theory', 'Should have nick') FROM speakers;
   SELECT is( lucio, 'theory', 'Should have nick') FROM speakers;
D;
ND;
 LANGUAGE sql;
$ LANGUAGE sql;
% pg_prove ­­dbname pgdayit ­­runtests
% pg_prove ­­dbname pgdayit ­­runtests
runtests()....ok
runtests()....ok
All tests successful.
All tests successful.
Files=1, Tests=16,  0 wallclock secs 
Files=1, Tests=16,  0 wallclock secs 
( 0.02 usr  0.01 sys +  0.01 cusr  0.00 csys =  0.04 CPU)
( 0.02 usr  0.01 sys +  0.01 cusr  0.00 csys =  0.04 CPU)
Result: PASS
Result: PASS

PGDay.IT 2013 – 25 Ottobre 2013 - Prato

20 di 24
Conclusions
There are functions for almost everything in your
postgresql db
Triggers, Functions, Schemas, Tablespaces, ….
It is possible create relationships of, or better conditional,
tests

Stable

PGDay.IT 2013 – 25 Ottobre 2013 - Prato

21 di 24
Risorse
Citare tutte le risorse utili:
www.pgtap.org
https://github.com/theory/pgtap

PGDay.IT 2013 – 25 Ottobre 2013 - Prato

22 di 24
Questions

PGDay.IT 2013 – 25 Ottobre 2013 - Prato

23 di 24
PGDay.IT 2013 – 25 Ottobre 2013 - Prato

24 di 24

More Related Content

What's hot

Isolating GPU Access in its Own Process
Isolating GPU Access in its Own ProcessIsolating GPU Access in its Own Process
Isolating GPU Access in its Own ProcessPatricia Aas
 
VHDL PROGRAMS FEW EXAMPLES
VHDL PROGRAMS FEW EXAMPLESVHDL PROGRAMS FEW EXAMPLES
VHDL PROGRAMS FEW EXAMPLESkarthik kadava
 
Les race conditions, nos très chères amies
Les race conditions, nos très chères amiesLes race conditions, nos très chères amies
Les race conditions, nos très chères amiesPierre Laporte
 
Software Vulnerabilities in C and C++ (CppCon 2018)
Software Vulnerabilities in C and C++ (CppCon 2018)Software Vulnerabilities in C and C++ (CppCon 2018)
Software Vulnerabilities in C and C++ (CppCon 2018)Patricia Aas
 
The Ring programming language version 1.10 book - Part 95 of 212
The Ring programming language version 1.10 book - Part 95 of 212The Ring programming language version 1.10 book - Part 95 of 212
The Ring programming language version 1.10 book - Part 95 of 212Mahmoud Samir Fayed
 
Unit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon GaliciaUnit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon GaliciaRobot Media
 
Maximizing SQL Reviews and Tuning with pt-query-digest
Maximizing SQL Reviews and Tuning with pt-query-digestMaximizing SQL Reviews and Tuning with pt-query-digest
Maximizing SQL Reviews and Tuning with pt-query-digestPythian
 
PgTAP Best Practices
PgTAP Best PracticesPgTAP Best Practices
PgTAP Best PracticesDavid Wheeler
 
The Ring programming language version 1.6 book - Part 83 of 189
The Ring programming language version 1.6 book - Part 83 of 189The Ring programming language version 1.6 book - Part 83 of 189
The Ring programming language version 1.6 book - Part 83 of 189Mahmoud Samir Fayed
 
Meg bernal insight2014 4219
Meg bernal insight2014 4219Meg bernal insight2014 4219
Meg bernal insight2014 4219Peter Schouboe
 
TDD CrashCourse Part4: Improving Testing
TDD CrashCourse Part4: Improving TestingTDD CrashCourse Part4: Improving Testing
TDD CrashCourse Part4: Improving TestingDavid Rodenas
 
JAVA AND MYSQL QUERIES
JAVA AND MYSQL QUERIES JAVA AND MYSQL QUERIES
JAVA AND MYSQL QUERIES Aditya Shah
 
Introduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxIntroduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxDavid Rodenas
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockRobot Media
 
Quickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop ApplicationsQuickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop ApplicationsClare Macrae
 
Inside PyMongo - MongoNYC
Inside PyMongo - MongoNYCInside PyMongo - MongoNYC
Inside PyMongo - MongoNYCMike Dirolf
 
Fnt software solutions placement paper
Fnt software solutions placement paperFnt software solutions placement paper
Fnt software solutions placement paperfntsofttech
 
Digital_Logic_FinalProj
Digital_Logic_FinalProjDigital_Logic_FinalProj
Digital_Logic_FinalProjSpencer Minder
 

What's hot (20)

Isolating GPU Access in its Own Process
Isolating GPU Access in its Own ProcessIsolating GPU Access in its Own Process
Isolating GPU Access in its Own Process
 
Praktek ARDUINO
Praktek ARDUINOPraktek ARDUINO
Praktek ARDUINO
 
VHDL PROGRAMS FEW EXAMPLES
VHDL PROGRAMS FEW EXAMPLESVHDL PROGRAMS FEW EXAMPLES
VHDL PROGRAMS FEW EXAMPLES
 
Les race conditions, nos très chères amies
Les race conditions, nos très chères amiesLes race conditions, nos très chères amies
Les race conditions, nos très chères amies
 
Software Vulnerabilities in C and C++ (CppCon 2018)
Software Vulnerabilities in C and C++ (CppCon 2018)Software Vulnerabilities in C and C++ (CppCon 2018)
Software Vulnerabilities in C and C++ (CppCon 2018)
 
The Ring programming language version 1.10 book - Part 95 of 212
The Ring programming language version 1.10 book - Part 95 of 212The Ring programming language version 1.10 book - Part 95 of 212
The Ring programming language version 1.10 book - Part 95 of 212
 
Unit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon GaliciaUnit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon Galicia
 
Maximizing SQL Reviews and Tuning with pt-query-digest
Maximizing SQL Reviews and Tuning with pt-query-digestMaximizing SQL Reviews and Tuning with pt-query-digest
Maximizing SQL Reviews and Tuning with pt-query-digest
 
PgTAP Best Practices
PgTAP Best PracticesPgTAP Best Practices
PgTAP Best Practices
 
The Ring programming language version 1.6 book - Part 83 of 189
The Ring programming language version 1.6 book - Part 83 of 189The Ring programming language version 1.6 book - Part 83 of 189
The Ring programming language version 1.6 book - Part 83 of 189
 
Meg bernal insight2014 4219
Meg bernal insight2014 4219Meg bernal insight2014 4219
Meg bernal insight2014 4219
 
TDD CrashCourse Part4: Improving Testing
TDD CrashCourse Part4: Improving TestingTDD CrashCourse Part4: Improving Testing
TDD CrashCourse Part4: Improving Testing
 
JAVA AND MYSQL QUERIES
JAVA AND MYSQL QUERIES JAVA AND MYSQL QUERIES
JAVA AND MYSQL QUERIES
 
Ip project
Ip projectIp project
Ip project
 
Introduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxIntroduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicox
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
 
Quickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop ApplicationsQuickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop Applications
 
Inside PyMongo - MongoNYC
Inside PyMongo - MongoNYCInside PyMongo - MongoNYC
Inside PyMongo - MongoNYC
 
Fnt software solutions placement paper
Fnt software solutions placement paperFnt software solutions placement paper
Fnt software solutions placement paper
 
Digital_Logic_FinalProj
Digital_Logic_FinalProjDigital_Logic_FinalProj
Digital_Logic_FinalProj
 

Viewers also liked (8)

Jenkins djangovillage
Jenkins djangovillageJenkins djangovillage
Jenkins djangovillage
 
GeoDjango
GeoDjangoGeoDjango
GeoDjango
 
Geodjango
GeodjangoGeodjango
Geodjango
 
Introduction to GeoDjango
Introduction to GeoDjangoIntroduction to GeoDjango
Introduction to GeoDjango
 
PLV8 - The PostgreSQL web side
PLV8 - The PostgreSQL web sidePLV8 - The PostgreSQL web side
PLV8 - The PostgreSQL web side
 
Geodjango and HTML 5
Geodjango and HTML 5Geodjango and HTML 5
Geodjango and HTML 5
 
POSTGIS - Uso de datos espaciales con el buen PostgreSQL
POSTGIS - Uso de datos espaciales con el buen PostgreSQLPOSTGIS - Uso de datos espaciales con el buen PostgreSQL
POSTGIS - Uso de datos espaciales con el buen PostgreSQL
 
Postgrest: the REST API for PostgreSQL databases
Postgrest: the REST API for PostgreSQL databasesPostgrest: the REST API for PostgreSQL databases
Postgrest: the REST API for PostgreSQL databases
 

Similar to Pg tap

SCALE 15x Minimizing PostgreSQL Major Version Upgrade Downtime
SCALE 15x Minimizing PostgreSQL Major Version Upgrade DowntimeSCALE 15x Minimizing PostgreSQL Major Version Upgrade Downtime
SCALE 15x Minimizing PostgreSQL Major Version Upgrade DowntimeJeff Frost
 
Python And GIS - Beyond Modelbuilder And Pythonwin
Python And GIS - Beyond Modelbuilder And PythonwinPython And GIS - Beyond Modelbuilder And Pythonwin
Python And GIS - Beyond Modelbuilder And PythonwinChad Cooper
 
GDSC Flutter Forward Workshop.pptx
GDSC Flutter Forward Workshop.pptxGDSC Flutter Forward Workshop.pptx
GDSC Flutter Forward Workshop.pptxGDSCVJTI
 
An Overview of SystemVerilog for Design and Verification
An Overview of SystemVerilog  for Design and VerificationAn Overview of SystemVerilog  for Design and Verification
An Overview of SystemVerilog for Design and VerificationKapilRaghunandanTrip
 
Sydney Oracle Meetup - execution plans
Sydney Oracle Meetup - execution plansSydney Oracle Meetup - execution plans
Sydney Oracle Meetup - execution planspaulguerin
 
Getting by with just psql
Getting by with just psqlGetting by with just psql
Getting by with just psqlCorey Huinker
 
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
Tony jambu   (obscure) tools of the trade for tuning oracle sq lsTony jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony jambu (obscure) tools of the trade for tuning oracle sq lsInSync Conference
 
Eff Plsql
Eff PlsqlEff Plsql
Eff Plsqlafa reg
 
A brief introduction to PostgreSQL
A brief introduction to PostgreSQLA brief introduction to PostgreSQL
A brief introduction to PostgreSQLVu Hung Nguyen
 
Sqladria 2009 SRC
Sqladria 2009 SRCSqladria 2009 SRC
Sqladria 2009 SRCtepsum
 
Tests unitaires pour PostgreSQL avec pgTap
Tests unitaires pour PostgreSQL avec pgTapTests unitaires pour PostgreSQL avec pgTap
Tests unitaires pour PostgreSQL avec pgTapRodolphe Quiédeville
 
PostgreSQL 8.4 TriLUG 2009-11-12
PostgreSQL 8.4 TriLUG 2009-11-12PostgreSQL 8.4 TriLUG 2009-11-12
PostgreSQL 8.4 TriLUG 2009-11-12Andrew Dunstan
 

Similar to Pg tap (20)

Pro PostgreSQL
Pro PostgreSQLPro PostgreSQL
Pro PostgreSQL
 
SCALE 15x Minimizing PostgreSQL Major Version Upgrade Downtime
SCALE 15x Minimizing PostgreSQL Major Version Upgrade DowntimeSCALE 15x Minimizing PostgreSQL Major Version Upgrade Downtime
SCALE 15x Minimizing PostgreSQL Major Version Upgrade Downtime
 
Python And GIS - Beyond Modelbuilder And Pythonwin
Python And GIS - Beyond Modelbuilder And PythonwinPython And GIS - Beyond Modelbuilder And Pythonwin
Python And GIS - Beyond Modelbuilder And Pythonwin
 
GDSC Flutter Forward Workshop.pptx
GDSC Flutter Forward Workshop.pptxGDSC Flutter Forward Workshop.pptx
GDSC Flutter Forward Workshop.pptx
 
An Overview of SystemVerilog for Design and Verification
An Overview of SystemVerilog  for Design and VerificationAn Overview of SystemVerilog  for Design and Verification
An Overview of SystemVerilog for Design and Verification
 
Noinject
NoinjectNoinject
Noinject
 
Sydney Oracle Meetup - execution plans
Sydney Oracle Meetup - execution plansSydney Oracle Meetup - execution plans
Sydney Oracle Meetup - execution plans
 
Getting by with just psql
Getting by with just psqlGetting by with just psql
Getting by with just psql
 
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
Tony jambu   (obscure) tools of the trade for tuning oracle sq lsTony jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
 
Eff Plsql
Eff PlsqlEff Plsql
Eff Plsql
 
A brief introduction to PostgreSQL
A brief introduction to PostgreSQLA brief introduction to PostgreSQL
A brief introduction to PostgreSQL
 
All things that are not code
All things that are not codeAll things that are not code
All things that are not code
 
Sqladria 2009 SRC
Sqladria 2009 SRCSqladria 2009 SRC
Sqladria 2009 SRC
 
Oracle GoldenGate
Oracle GoldenGateOracle GoldenGate
Oracle GoldenGate
 
Explain this!
Explain this!Explain this!
Explain this!
 
DataBase Management System Lab File
DataBase Management System Lab FileDataBase Management System Lab File
DataBase Management System Lab File
 
PHP tips by a MYSQL DBA
PHP tips by a MYSQL DBAPHP tips by a MYSQL DBA
PHP tips by a MYSQL DBA
 
Bluespec @waseda
Bluespec @wasedaBluespec @waseda
Bluespec @waseda
 
Tests unitaires pour PostgreSQL avec pgTap
Tests unitaires pour PostgreSQL avec pgTapTests unitaires pour PostgreSQL avec pgTap
Tests unitaires pour PostgreSQL avec pgTap
 
PostgreSQL 8.4 TriLUG 2009-11-12
PostgreSQL 8.4 TriLUG 2009-11-12PostgreSQL 8.4 TriLUG 2009-11-12
PostgreSQL 8.4 TriLUG 2009-11-12
 

More from Lucio Grenzi

How to use Postgresql in order to handle Prometheus metrics storage
How to use Postgresql in order to handle Prometheus metrics storageHow to use Postgresql in order to handle Prometheus metrics storage
How to use Postgresql in order to handle Prometheus metrics storageLucio Grenzi
 
Building serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformBuilding serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformLucio Grenzi
 
Patroni: PostgreSQL HA in the cloud
Patroni: PostgreSQL HA in the cloudPatroni: PostgreSQL HA in the cloud
Patroni: PostgreSQL HA in the cloudLucio Grenzi
 
Use Ionic Framework to develop mobile application
Use Ionic Framework to develop mobile applicationUse Ionic Framework to develop mobile application
Use Ionic Framework to develop mobile applicationLucio Grenzi
 
Rabbitmq & Postgresql
Rabbitmq & PostgresqlRabbitmq & Postgresql
Rabbitmq & PostgresqlLucio Grenzi
 
node.js e Postgresql
node.js e Postgresqlnode.js e Postgresql
node.js e PostgresqlLucio Grenzi
 

More from Lucio Grenzi (8)

How to use Postgresql in order to handle Prometheus metrics storage
How to use Postgresql in order to handle Prometheus metrics storageHow to use Postgresql in order to handle Prometheus metrics storage
How to use Postgresql in order to handle Prometheus metrics storage
 
Building serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformBuilding serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platform
 
Patroni: PostgreSQL HA in the cloud
Patroni: PostgreSQL HA in the cloudPatroni: PostgreSQL HA in the cloud
Patroni: PostgreSQL HA in the cloud
 
Full slidescr16
Full slidescr16Full slidescr16
Full slidescr16
 
Use Ionic Framework to develop mobile application
Use Ionic Framework to develop mobile applicationUse Ionic Framework to develop mobile application
Use Ionic Framework to develop mobile application
 
Rabbitmq & Postgresql
Rabbitmq & PostgresqlRabbitmq & Postgresql
Rabbitmq & Postgresql
 
Yui app-framework
Yui app-frameworkYui app-framework
Yui app-framework
 
node.js e Postgresql
node.js e Postgresqlnode.js e Postgresql
node.js e Postgresql
 

Recently uploaded

Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 

Recently uploaded (20)

Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 

Pg tap

  • 2. Who I am Delphi developer since 1999 IT Consultant Front end web developer Postgresql addicted Nonantolando.blogspot.com lucio.grenzi lucio grenzi PGDay.IT 2013 – 25 Ottobre 2013 - Prato 2 di 24
  • 3. Agenda PgTap: introduction Why use this tool Best practices Q&A PGDay.IT 2013 – 25 Ottobre 2013 - Prato 3 di 24
  • 4. Question before starting Why would you want to unit test your database? PGDay.IT 2013 – 25 Ottobre 2013 - Prato 4 di 24
  • 5. Why use pgTap Backend application development Test schema object validation Module development Continuos integration PGDay.IT 2013 – 25 Ottobre 2013 - Prato 5 di 24
  • 6. Tap protocol The Test Anything Protocol (TAP) is a protocol to allow communication between unit tests and a test harness. It allows individual tests (TAP producers) to communicate test results to the testing harness in a language-agnostic way. Originally developed for unit testing of the Perl interpreter in 1987, producers and parsers are now available for many development platforms. -wikipedia- PGDay.IT 2013 – 25 Ottobre 2013 - Prato 6 di 24
  • 7. PgTap pgTAP is a unit testing framework for PostgreSQL written in PL/pgSQL and PL/SQL. It includes a comprehensive collection of TAP-emitting assertion functions, as well as the ability to integrate with other TAP-emitting test frameworks. It can also be used in the xUnit testing style. -http://pgtap.org/- PGDay.IT 2013 – 25 Ottobre 2013 - Prato 7 di 24
  • 8. PgTap now www.pgtap.org Latest version is 0.93.0 Already packaged for the most important linux distributions make make installcheck make install PGDay.IT 2013 – 25 Ottobre 2013 - Prato 8 di 24
  • 9. Requirements PostgreSQL 8.1 or higher with 8.4 or higher recommended for full use of its API PL/pgSQL On Windows servers is necessary to install Perl Perl on Linux is no more necessary but it is required by pg_prove PGDay.IT 2013 – 25 Ottobre 2013 - Prato 9 di 24
  • 10. Adding PgTap to a database Install pgtap in a database psql -d dbname -f pgtap.sql include the call to pgtap.sql in your script with /pgtap.sql i remove pgtap from a database psql -d dbname -f uninstall_pgtap.sql PGDay.IT 2013 – 25 Ottobre 2013 - Prato 10 di 24
  • 11. Tap in practice Test output is easy to understand BEGIN; SELECT plan(); ---- how many test? …put your tests here… SELECT * FROM finish(); ---- test finished, print report ROLLBACK; PGDay.IT 2013 – 25 Ottobre 2013 - Prato 11 di 24
  • 12. PgTap functions - compare ok() is() isnt() matches() doesnt_match() alike() unalike() cmp_ok() pass() fail() SELECT ok( :boolean, :description ); SELECT is ( :have, :want, :description); SELECT isnt(:have, :want, :description); SELECT matches( :have, :regex, :description ); SELECT doesnt_match( :have, :regex, :description ); SELECT alike( :this, :like, :description ); SELECT unalike( :this, :like, :description ); SELECT cmp_ok( :have, :op, :want, :description ); SELECT pass( :description ); SELECT fail( :description ); PGDay.IT 2013 – 25 Ottobre 2013 - Prato 12 di 24
  • 13. PgTap functions – test failures throws_ok() throws_like() throws_matching() lives_ok() performs_ok() SELECT throws_ok( :sql, :errcode, :ermsg, :description ); PGDay.IT 2013 – 25 Ottobre 2013 - Prato 13 di 24
  • 14. PgTap functions – test objects tablespaces_are() schemas_are() tables_are() views_are() sequences_are() columns_are() indexes_are() triggers_are() functions_are() roles_are() users_are() groups_are() languages_are() opclasses_are() rules_are() types_are() domains_are() enums_are() casts_are() operators_are() PGDay.IT 2013 – 25 Ottobre 2013 - Prato 14 di 24
  • 15. PgTap basics set ON_ERROR_ROLLBACK 11 set ON_ERROR_ROLLBACK set ON_ERROR_STOP true set ON_ERROR_STOP true set QUIET 11 set QUIET BEGIN; BEGIN; SELECT plan(1); SELECT plan(1); SELECT pass( 'Hello PgDayit !'!'); SELECT pass( 'Hello PgDayit ); SELECT **FROM finish(); SELECT FROM finish(); ROLLBACK; ROLLBACK; save this as HelloPgDayit.txt and type: psql -U postgres -f HelloPgDayit.txt 1..1 1..1 ok 11- -Hello PgDayit ! ! ok Hello PgDayit PGDay.IT 2013 – 25 Ottobre 2013 - Prato 15 di 24
  • 16. Let's create some tables BEGIN; i ./pgtap.sql -- create two tables with referential constraint create table table1 (id integer not null, t_text varchar(100), dt timestamp default now(), CONSTRAINT table1_pkey PRIMARY KEY (id)); create table table2 (id integer not null, t_text varchar(100), id_ref integer, CONSTRAINT id_ref FOREIGN KEY (id_ref) REFERENCES table1 (id)); insert into table1 (id,t_text) values (1,'test one'); insert into table1 (id,t_text) values (2,'test two'); insert into table1 (id,t_text) values (3,'test three'); insert into table2 (id,t_text,id_ref) values (1,'ref test one', 1); insert into table2 (id,t_text,id_ref) values (2,'ref test two', 2); insert into table2 (id,t_text,id_ref) values (3,'ref test three', 3); SELECT plan(6); ## type tests here## ## get results here## SELECT * FROM finish(); ROLLBACK; PGDay.IT 2013 – 25 Ottobre 2013 - Prato 16 di 24
  • 17. Test samples PREPARE ids_fetched AS PREPARE ids_fetched AS select id from table1 where id in (1,2,3) order by id asc; select id from table1 where id in (1,2,3) order by id asc; PREPARE ids_expected AS VALUES (1),(2),(3); PREPARE ids_expected AS VALUES (1),(2),(3); SELECT results_eq( 'ids_fetched', 'ids_expected', SELECT results_eq( 'ids_fetched', 'ids_expected', 'fetched the expected ids from table1'); 'fetched the expected ids from table1'); PREPARE ids_fetched1 AS select id PREPARE ids_fetched1 AS select id from table1 where id in (1,2,3) order by id asc; from table1 where id in (1,2,3) order by id asc; PREPARE ids_fetched2 AS select id PREPARE ids_fetched2 AS select id from table2 where id in (1,2,3) order by id asc; from table2 where id in (1,2,3) order by id asc; SELECT results_eq( 'ids_fetched1', 'ids_fetched2'); SELECT results_eq( 'ids_fetched1', 'ids_fetched2'); PREPARE throw_error AS PREPARE throw_error AS insert into table1 (id,t_text) insert into table1 (id,t_text) values (1,'duplicate key error'); values (1,'duplicate key error'); SELECT throws_ok('throw_error','23505',NULL, SELECT throws_ok('throw_error','23505',NULL, 'duplicated key found (id)'); 'duplicated key found (id)'); PGDay.IT 2013 – 25 Ottobre 2013 - Prato 17 di 24
  • 18. pg_prove command-line application to run one or more pgTAP tests in a PostgreSQL database output of the tests is processed by TAP::Harness in order to summarize the results Tests can be written as: SQL scripts xUnit-style database functions PGDay.IT 2013 – 25 Ottobre 2013 - Prato 18 di 24
  • 20. pg_prove - xUnit Test Functions EATE OR REPLACE FUNCTION setup_insert( REATE OR REPLACE FUNCTION setup_insert( RETURNS SETOF TEXT AS $$  RETURNS SETOF TEXT AS $$   RETURN NEXT is( MAX(lucio), NULL, 'Should have no users') FROM speakers;    RETURN NEXT is( MAX(lucio), NULL, 'Should have no users') FROM speakers;   INSERT INTO speakers (lucio) VALUES ('theory');    INSERT INTO speakers (lucio) VALUES ('theory');  LANGUAGE plpgsql; $ LANGUAGE plpgsql; eate OR REPLACE FUNCTION test_user( reate OR REPLACE FUNCTION test_user( RETURNS SETOF TEXT AS $$  RETURNS SETOF TEXT AS $$   SELECT is( lucio, 'theory', 'Should have nick') FROM speakers;    SELECT is( lucio, 'theory', 'Should have nick') FROM speakers; D; ND;  LANGUAGE sql; $ LANGUAGE sql; % pg_prove ­­dbname pgdayit ­­runtests % pg_prove ­­dbname pgdayit ­­runtests runtests()....ok runtests()....ok All tests successful. All tests successful. Files=1, Tests=16,  0 wallclock secs  Files=1, Tests=16,  0 wallclock secs  ( 0.02 usr  0.01 sys +  0.01 cusr  0.00 csys =  0.04 CPU) ( 0.02 usr  0.01 sys +  0.01 cusr  0.00 csys =  0.04 CPU) Result: PASS Result: PASS PGDay.IT 2013 – 25 Ottobre 2013 - Prato 20 di 24
  • 21. Conclusions There are functions for almost everything in your postgresql db Triggers, Functions, Schemas, Tablespaces, …. It is possible create relationships of, or better conditional, tests Stable PGDay.IT 2013 – 25 Ottobre 2013 - Prato 21 di 24
  • 22. Risorse Citare tutte le risorse utili: www.pgtap.org https://github.com/theory/pgtap PGDay.IT 2013 – 25 Ottobre 2013 - Prato 22 di 24
  • 23. Questions PGDay.IT 2013 – 25 Ottobre 2013 - Prato 23 di 24
  • 24. PGDay.IT 2013 – 25 Ottobre 2013 - Prato 24 di 24