pgTAP: Unit Testing
pgTAP
is a unit testing extension for PostgreSQL.
Overview
Let's cover some basic concepts:
- Unit tests: allow you to test small parts of a system (like a database table!).
- TAP: stands for Test Anything Protocol. It is an framework which aims to simplify the error reporting during testing.
Enable the extension
- Go to the Database page in the Dashboard.
- Click on Extensions in the sidebar.
- Search for "pgtap" and enable the extension.
Testing tables
API:
has_table()
: Tests whether or not a table exists in the databasehas_index()
: Checks for the existence of a named index associated with the named table.has_relation()
: Tests whether or not a relation exists in the database.
Testing columns
API:
has_column()
: Tests whether or not a column exists in a given table, view, materialized view or composite type.col_is_pk()
: Tests whether the specified column or columns in a table is/are the primary key for that table.
Testing RLS policies
API:
policies_are()
: Tests that all of the policies on the named table are only the policies that should be on that table.policy_roles_are()
: Tests whether the roles to which policy applies are only the roles that should be on that policy.policy_cmd_is()
: Tests whether the command to which policy applies is same as command that is given in function arguments.
You can also use the results_eq()
method to test that a Policy returns the correct data:
API:
Testing functions
API:
function_returns()
: Tests that a particular function returns a particular data typeis_definer()
: Tests that a function is a security definer (i.e., a “setuid” function).
Resources
- Official
pgTAP
documentation