rembrembdocs

pgTAP: Unit Testing


pgTAP is a unit testing extension for Postgres.

Overview#

Let's cover some basic concepts:

Enable the extension#

  1. Go to the Database page in the Dashboard.
  2. Click on Extensions in the sidebar.
  3. Search for pgtap and enable the extension.

Testing tables#

1begin;2select plan( 1 );34select has_table( 'profiles' );56select * from finish();7rollback;

API:

Testing columns#

1begin;2select plan( 2 );34select has_column( 'profiles', 'id' ); -- test that the "id" column exists in the "profiles" table5select col_is_pk( 'profiles', 'id' ); -- test that the "id" column is a primary key67select * from finish();8rollback;

API:

Testing RLS policies#

1begin;2select plan( 1 );34select policies_are(5  'public',6  'profiles',7  ARRAY [8    'Profiles are public', -- Test that there is a policy called  "Profiles are public" on the "profiles" table.9    'Profiles can only be updated by the owner'  -- Test that there is a policy called  "Profiles can only be updated by the owner" on the "profiles" table.10  ]11);1213select * from finish();14rollback;

API:

You can also use the results_eq() method to test that a Policy returns the correct data:

1begin;2select plan( 1 );34select results_eq(5    'select * from profiles()',6    $$VALUES ( 1, 'Anna'), (2, 'Bruce'), (3, 'Caryn')$$,7    'profiles() should return all users'8);91011select * from finish();12rollback;

API:

Testing functions#

1prepare hello_expr as select 'hello'23begin;4select plan(3);5-- You'll need to create a hello_world and is_even function6select function_returns( 'hello_world', 'text' );                   -- test if the function "hello_world" returns text7select function_returns( 'is_even', ARRAY['integer'], 'boolean' );  -- test if the function "is_even" returns a boolean8select results_eq('select * from hello_world()', 'hello_expr');          -- test if the function "hello_world" returns "hello"910select * from finish();11rollback;

API:

Resources#