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

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
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
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 

Recently uploaded (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
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
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 

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