首页 > 解决方案 > 测试 PSQL DB 的最佳方法

问题描述

假设我有下表、函数和数据

create table people (
     id bigserial primary key,                       
     age int,
     height int,
     weight int
 );

create or replace function add_person (p_age int, p_height int, p_weight int);
create or replace function get_person_by_age (p_age int);
create or replace function get_person_by_height (p_height int);
create or replace function get_person_by_weight (p_weight int);
add_person (20,180,100);
add_person (20,181,101);
add_person (20,182,102);
add_person (20,183,103);

我目前正在纯粹用 bash 测试我的数据库,所以我会有这些非常长的文件(仅限伪代码)

#!/bin/bash

# Insert data
sudo -u postgres psql -d $db_name -c "add_person(20,180,100)"
sudo -u postgres psql -d $db_name -c "add_person(20,181,101)"
sudo -u postgres psql -d $db_name -c "add_person(20,182,102)"
sudo -u postgres psql -d $db_name -c "add_person(20,183,103)"

# Retrieve data
persons=$(sudo -u postgres psql -d $db_name -c "get_person_by_age (20)")

# Count number of rows and make sure it matches the expected outcome
# (You have to manually strip header and footer lines but ignore for now)
if [ $(echo $persons | wc -l) -ne 4]
then
    echo "Fail"
    exit 1
fi

我的测试脚本变得太大了,我试图捕捉很多东西(应该抛出错误但不会的操作,即误报,不应该抛出错误但确实会出错的操作,即误报,抛出错误的操作除了他们应该做的,等等)。更重要的是,由于 bash 不断尝试建立与 Postgre 的连接,因此测试速度非常慢。

我不在 PGSQL 中这样做的原因是因为我的数据库查询有很多过滤器,所以查询的逻辑会变得非常复杂。

是否有更好的现有解决方案来解决我的问题?我查看了 pgTAP,但其文档太可怕了

标签: postgresqltesting

解决方案


首先,我认为您可以通过在一个客户端初始化中运行多个命令来提高速度。如您所说,“-c”标志仅运行一个命令,并且在启动连接时会产生一些小的开销,如果您正在运行许多命令,这些开销确实会增加。

例如,您可以对插入命令执行以下操作:

sudo -u postgres psql -d $db_name << EOF
add_person(20,180,100);
add_person(20,181,101);
add_person(20,182,102);
add_person(20,183,103);

或者,您可以列出要在文件中运行的所有命令,并使用“--file”/“-f”运行它们:

sudo -u postgres psql -d $db_name -f "my_add_commands.psql"

我无法解释为什么会出现错误错误,但通常我发现在 bash 中编写复杂的测试脚本很痛苦。如果可能的话,我会考虑使用您熟悉的任何具有正确 try/catch 逻辑和带有断言的健壮测试库的语言。这就是我个人为 SQL 函数编写测试的方式。但是,您可能还需要使用可让您以相应语言进行和处理 psql 查询的库。

python有一个轻量级的 psql 测试库,但我自己没有使用过。也许值得一看。


推荐阅读