pgTAP:单元测试
pgTAP 是用于 Postgres 的单元测试扩展。
概览 #
🌐 Overview
本节涵盖基本概念:
🌐 This section covers basic concepts:
- 单元测试:让你可以测试系统的小部分(比如一个数据库表!)。
- TAP:代表测试任意协议。它是一个框架,旨在简化测试过程中的错误报告。
启用扩展 #
🌐 Enable the extension
- 在仪表板中转到数据库页面。
- 点击侧边栏的 扩展。
- 搜索
pgtap并启用这个扩展。
测试表格 #
🌐 Testing tables
1begin;2select plan( 1 );34select has_table( 'profiles' );56select * from finish();7rollback;API:
has_table():测试数据库中是否存在某个表has_index():检查与指定表关联的命名索引是否存在。has_relation():测试数据库中是否存在某个关系。
测试列 #
🌐 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:
has_column():测试给定表、视图、物化视图或复合类型中是否存在某列。[col_is_pk()](https://pgtap.org/documentation.html#col_is_pk):测试表中指定的列是否为该表的主键。
测试 RLS 策略 #
🌐 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:
policies_are():测试命名表上的所有策略是否仅限于该表应有的策略。policy_roles_are():测试策略所适用的角色是否仅限于那些应该在该策略上的角色。policy_cmd_is():测试策略所适用的命令是否与函数参数中给出的命令相同。
你也可以使用 results_eq() 方法来测试一个策略是否返回正确的数据:
🌐 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:
function_returns():测试某个函数是否返回特定的数据类型is_definer():测试一个函数是否为安全定义者(也就是说,一个setuid函数)。
资源 #
🌐 Resources
- 官方
pgTAP文档