我想测试我对 postgres-schema 所做的以下约束:
-- status 'online' is just allowed with a suffix, e.g. 'online:sometimes'
CONSTRAINT status_format CHECK(((status)::text~*'^(online:.*|online:.*/.*)$'::text))
因此,我计划编写一个在插入错误的
status
失败时通过的测试。例如,这会失败:
INSERT INTO cmdb (name, beschreibung, status) VALUES ('new device', 'descriptive details', 'online')
因为
online
字符串缺少后缀(例如 :sometimes
)。我决定使用 pgTAP 来实现此目的,但我在语法上遇到了困难。这是我已经想出的:
BEGIN; -- Test to check if the INSERT statement fails as expected
SELECT plan(1);
-- Check if the insertion operation fails
SELECT ok(
$$NOT EXISTS (
INSERT INTO mytable (name, beschreibung, status) VALUES ('new device', 'descriptive details', 'online')
RETURNING id
)$$,
'Constraint check failed for inserting "online" status without valid time period'
);
SELECT * FROM finish();
ROLLBACK;
但是使用
pg_prove
执行时出现以下错误:
ERROR: invalid input syntax for type boolean: "NOT EXISTS (
也许这是我的一个小语法错误,或者我误解了
ok()
函数的用法。或者也许有不同的方法来测试插入。
感谢您的时间!
我没有使用
ok()
并将我的 INSERT
查询嵌套到 和 NOT EXIST
中,而是使用 throws_ok()
函数找到了一种不同的方法,检查抛出的错误。
BEGIN; -- Test to check if the INSERT statement fails as expected
SELECT plan(1);
PREPARE status_insert AS INSERT INTO mytable (name, beschreibung, status) VALUES ('foobar', 'barfoo', 'online');
-- testing for thrown error
SELECT throws_ok(
'status_insert',
'23514', -- wanted error code https://www.postgresql.org/docs/current/errcodes-appendix.html
'new row for relation "cmdb" violates check constraint "status_format"'); -- wanted message
SELECT * FROM finish();
ROLLBACK;
您可以在文档中找到有关
throws_ok()
的进一步说明: