1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Docker上のPostgreSQLに単体テストプラグイン pgtapを導入する

Last updated at Posted at 2025-02-13

概要

postgresqlの単体テストをする機会がありましたので、テストフレームワークの
導入方法を共有します。

対象読者

Docker上のPostgreSQLにpgtapを導入したい方

pgtapとは

PostgreSQLのプラグインの一種。
単体テストツール。

手順

linuxの設定

dockerfile

FROM postgres:14.0-bullseye

ENV UNAME=user
ENV GID=1000
ENV UID=1000

RUN groupadd -g $GID -o $UNAME
RUN useradd -m -u $UID -g $GID -G sudo -o -s /bin/bash $UNAME
RUN echo "$UNAME ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers


# pgtap
RUN apt-get update \
    && apt-get install -y build-essential git-core libv8-dev curl postgresql-server-dev-$PG_MAJOR \
    && rm -rf /var/lib/apt/lists/*

# install pg_prove
RUN curl -LO http://xrl.us/cpanm \
    && chmod +x cpanm \
    && ./cpanm TAP::Parser::SourceHandler::pgTAP

# install pgtap
RUN git clone https://github.com/theory/pgtap.git \
    && cd /pgtap \
    && make \
    && make install



postgreSQLの設定

pgtapを有効化する

00_test_pgtap.sql
CREATE EXTENSION IF NOT EXISTS pgtap;

結果

psql:0_setup_pgtap.sql:1: NOTICE:  extension "pgtap" already exists, skipping
CREATE EXTENSION

テストコードを書く

テスト内容はテーブルが存在するかという内容です。

ddl

1_productcode.sql

create table public.t1(
no int
)

テストコード

1_testcode.sql
BEGIN;
SELECT plan(2);

SELECT tables_are (
        'public',
        ARRAY[
        't1'
        ]
);

SELECT * FROM finish();
ROLLBACK;

A5:SQLで実行したときの画面

image.png

image.png

image.png

docker-コンテナ内のpsqlで実行したときの結果

実行コマンド

su postgres
psql -U postgres -f src/00_test/1_testcode.sql

結果


postgres@474d21ef2c49:$ psql -U postgres -f 1_testcode.sql
BEGIN
 plan
------
 1..1
(1 row)

                     tables_are
-----------------------------------------------------
 ok 1 - Schema public should have the correct tables 
(1 row)

 finish
--------
(0 rows)

ROLLBACK
postgres@474d21ef2c49:



感想

・CREATE EXTENSION IF NOT EXISTS pgtap;
 の実行が成功するまでの設定が手間どりましたね。l
 PostgreSQLは拡張性が高いから良いんですけど、設定に慣れないといけないですね。

・CI,CDを使ってテストの自動化もできたら良いですね。
 Github Actionで実現できるか試してみます。

・もうちょっと掘り下げたいですね。
 とりあえずはレコードのアセーションあたりを確認したいですね。

・書き方がxUnit系統なので、学習コストは低いと思われます。

参考

issue部分

参考にしたdockerfile

result_eq

日本語の記事

github 差分
https://github.com/RYA234/SQL_Puzzle_Learning/commit/f547b18d6da442311519cee2a0dda618042049da

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?