Skip to content
Database

pgTAP:单元测试

pgTAP 是用于 Postgres 的单元测试扩展。

概览 #

🌐 Overview

本节涵盖基本概念:

🌐 This section covers basic concepts:

  • 单元测试:让你可以测试系统的小部分(比如一个数据库表!)。
  • TAP:代表测试任意协议。它是一个框架,旨在简化测试过程中的错误报告。

启用扩展 #

🌐 Enable the extension

  1. 在仪表板中转到数据库页面。
  2. 点击侧边栏的 扩展
  3. 搜索 pgtap 并启用这个扩展。

测试表格 #

🌐 Testing tables

1
begin;
2
select plan( 1 );
3
4
select has_table( 'profiles' );
5
6
select * from finish();
7
rollback;

API:

  • has_table():测试数据库中是否存在某个表
  • has_index():检查与指定表关联的命名索引是否存在。
  • has_relation():测试数据库中是否存在某个关系。

测试列 #

🌐 Testing columns

1
begin;
2
select plan( 2 );
3
4
select has_column( 'profiles', 'id' ); -- test that the "id" column exists in the "profiles" table
5
select col_is_pk( 'profiles', 'id' ); -- test that the "id" column is a primary key
6
7
select * from finish();
8
rollback;

API:

  • has_column():测试给定表、视图、物化视图或复合类型中是否存在某列。
  • [col_is_pk()](https://pgtap.org/documentation.html#col_is_pk):测试表中指定的列是否为该表的主键。

测试 RLS 策略 #

🌐 Testing RLS policies

1
begin;
2
select plan( 1 );
3
4
select 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
);
12
13
select * from finish();
14
rollback;

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:

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

API:

测试功能 #

🌐 Testing functions

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

API:

  • function_returns():测试某个函数是否返回特定的数据类型
  • is_definer():测试一个函数是否为安全定义者(也就是说,一个 setuid 函数)。

资源 #

🌐 Resources