Implement xUnit-style testing with runtests()
mainInstead of writing procedural SQL scripts, you can collect tests into database functions and run them all at once using runtests(). This approach supports setup and teardown functions and runs each test in its own transaction.
Pattern:
- Create a setup function that returns
SETOF TEXT(using assertions). - Create test functions that return
SETOF TEXT. - Call
runtests()to execute them.
Example:
CREATE OR REPLACE FUNCTION setup_insert() RETURNS SETOF TEXT AS $$
BEGIN
RETURN NEXT is( MAX(nick), NULL, 'Should have no users') FROM users;
INSERT INTO users (nick) VALUES ('theory');
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION test_user() RETURNS SETOF TEXT AS $$
SELECT is( nick, 'theory', 'Should have nick') FROM users;
$$ LANGUAGE sql;
-- To run:
SELECT * FROM runtests();SELECT * FROM runtests();