Skip to content
Database

测试你的数据库

为了确保查询返回预期的数据、RLS 策略正确应用等等,我们鼓励你编写自动化测试。测试基本上有两种方法:

🌐 To ensure that queries return the expected data, RLS policies are correctly applied and etc., we encourage you to write automated tests. There are essentially two approaches to testing:

  • 首先,你可以编写测试,来与 Supabase 客户端实例进行交互(就像在应用代码中使用 Supabase 客户端一样),使用你在应用中使用的编程语言和你喜欢的测试框架。
  • 其次,你可以通过 Supabase CLI 进行测试,这是一种更底层的方法,你需要用 SQL 来编写测试。

使用 Supabase CLI 进行测试 #

🌐 Testing using the Supabase CLI

你可以使用 Supabase CLI 来测试你的数据库。CLI 的最低版本要求是 v1.11.4。开始使用方法如下:

🌐 You can use the Supabase CLI to test your database. The minimum required version of the CLI is v1.11.4. To get started:

创建一个测试 #

🌐 Creating a test

supabase 文件夹里创建一个 tests 文件夹:

🌐 Create a tests folder inside the supabase folder:

1
mkdir -p ./supabase/tests/database

创建一个带有 .sql 扩展名的新文件,用来存放测试内容。

🌐 Create a new file with the .sql extension which will contain the test.

1
touch ./supabase/tests/database/hello_world.test.sql

写测试 #

🌐 Writing tests

所有 sql 文件都使用 pgTAP 作为测试运行器。

🌐 All sql files use pgTAP as the test runner.

写一个测试来检查我们的 auth.users 表是否有 ID 列。打开 hello_world.test.sql 并添加以下代码:

🌐 Write a test to check that our auth.users table has an ID column. Open hello_world.test.sql and add the following code:

1
begin;
2
select plan(1); -- only one statement to run
3
4
SELECT has_column(
5
'auth',
6
'users',
7
'id',
8
'id should exist'
9
);
10
11
select * from finish();
12
rollback;

运行测试 #

🌐 Running tests

要运行测试,你可以用:

🌐 To run the test, you can use:

1
supabase test db

这将产生以下输出:

🌐 This will produce the following output:

1
$ supabase test db
2
supabase/tests/database/hello_world.test.sql .. ok
3
All tests successful.
4
Files=1, Tests=1, 1 wallclock secs ( 0.01 usr 0.00 sys + 0.04 cusr 0.02 csys = 0.07 CPU)
5
Result: PASS

更多资源 #

🌐 More resources