pgTAP:单元测试
pgTAP
是 Postgres 的单元测试扩展。
概述
让我们了解一些基本概念:
- 单元测试:允许您测试系统中的小部分(比如数据库表!)。
- TAP:代表测试任意协议。这是一个旨在简化测试期间错误报告的框架。
启用扩展
- 进入控制面板的数据库页面。
- 点击侧边栏中的扩展。
- 搜索
pgtap
并启用该扩展。
测试表
1234567begin;select plan( 1 );select has_table( 'profiles' );select * from finish();rollback;
API:
has_table()
:测试数据库中是否存在指定的表has_index()
:检查指定表是否存在命名的索引。has_relation()
:测试数据库中是否存在指定的关系。
测试列
12345678begin;select plan( 2 );select has_column( 'profiles', 'id' ); -- 测试"profiles"表中是否存在"id"列select col_is_pk( 'profiles', 'id' ); -- 测试"id"列是否是主键select * from finish();rollback;
API:
has_column()
: 测试给定表、视图、物化视图或复合类型中是否存在某列。col_is_pk()
: 测试表中指定的一列或多列是否是该表的主键。
测试RLS策略
1234567891011121314begin;select plan( 1 );select policies_are( 'public', 'profiles', ARRAY [ 'Profiles are public', -- 测试 profiles 表上存在名为 "Profiles are public" 的策略 'Profiles can only be updated by the owner' -- 测试 profiles 表上存在名为 "Profiles can only be updated by the owner" 的策略 ]);select * from finish();rollback;
API方法:
policies_are()
: 测试指定表上的所有策略是否仅包含应有的策略policy_roles_are()
: 测试策略适用的角色是否仅包含应有的角色policy_cmd_is()
: 测试策略适用的命令是否与函数参数中给定的命令相同
您也可以使用 results_eq()
方法来测试策略是否返回正确的数据:
123456789101112begin;select plan( 1 );select results_eq( 'select * from profiles()', $$VALUES ( 1, 'Anna'), (2, 'Bruce'), (3, 'Caryn')$$, 'profiles() 应该返回所有用户');select * from finish();rollback;
API方法:
测试函数
1234567891011prepare hello_expr as select 'hello'begin;select plan(3);-- 您需要创建一个hello_world和is_even函数select function_returns( 'hello_world', 'text' ); -- 测试函数"hello_world"是否返回text类型select function_returns( 'is_even', ARRAY['integer'], 'boolean' ); -- 测试函数"is_even"是否返回boolean类型select results_eq('select * from hello_world()', 'hello_expr'); -- 测试函数"hello_world"是否返回"hello"select * from finish();rollback;
API接口:
function_returns()
: 测试特定函数是否返回特定数据类型is_definer()
: 测试函数是否为安全定义器(即setuid
函数)
相关资源
- 官方
pgTAP
文档