10
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Step CIでpluginを独自実装する

Posted at

はじめに

Step CIのpluginを実装した際の覚書です。

Step CIでリグレッションテストを実装した際に、テストケース内で直接DBを操作する必要がありました。
しかし、Step CIではDB操作がサポートされていなかったためDB操作用のpluginを自作することにしました。

フォルダ構成(抜粋)

.
├── db-handler/
│   ├── index.js
│   └── package.json
├── stepci.js         ・・・Step CIの実行ファイル
├── package.json
└── workflow.yaml

実装例

処理内容は公式ドキュメントにあるボイラープレートをベースに、要件に応じて必要なロジックを実装します。

db-handler/index.js
import * as mysql from 'mysql2/promise';
const { checkResult } = require('@stepci/runner/dist/matcher');

module.exports.default = async (input) => {
  const connection = await mysql.createConnection({
    host: HOST,
    database: DATABASE,
    user: USER,
    password: PASSWORD,
  });

  let stepResult = {};  // Step CIが当該stepの実行結果として受け取るオブジェクト
  stepResult.request = input.query;
  try {
    const [result] = await connection.execute(input.query);
    stepResult.response = result;

    // 実行結果のアサーション
    if (input.check) {
      stepResult.checks = {};
      if (input.check.status) {
        const is_success = result[input.action == 'update' ? 'changedRows' : 'affectedRows'] >= 1;
        const given = is_success ? 'success' : 'failure';
        stepResult.checks.status = checkResult(given, input.check.status);
      }
    }

    return stepResult;
  } catch (error) {
    stepResult.response = error;
    stepResult.checks = {
      status: {
        expected: input?.check?.status ?? null,
        given: 'ERROR',
        passed: false,
      },
    };
    return stepResult;
  }
};

テストケース内での使用

workflow.yaml
- name: テストデータ作成
  plugin:
    id: db-hundler
    action: insert
    query: 
      INSERT INTO users (name, email) VALUES ('test_user', 'test@example.com')
    check:
      status: inserted

ハマったポイント

実装時にハマった点としては以下の箇所です。

CommonJSで実装する

Step CI側の実装がCommonJSであり、自作したpluginをrequireで読み込んでいるのでそれに合わせてCommonJSで実装しmodule.exportsする必要があります。

db-handler/package.json
{
  "name": "db-hundler",
  "type": "commonjs",
  "version": "1.0.0",
  "main": "index.js"
}

dependencyへの追加

実装したpluginをyaml内で使用するには、ローカルパッケージとしてdb-handlerディレクトリをプロジェクトの package.json に依存として追加しnpm installを実行してnode_modulesに取り込む必要があります。

package.json
{
  "dependencies": {
    "db-hundler": "file:./db-hundler"
  }
}

yamlのplugin.idにはdependenciesに記載したキーを指定します。

おわりに

Step CIでDB操作を可能にする自作プラグインの実装方法のメモでした。
公式でサポートされていない機能でも、プラグインを活用すれば柔軟に拡張ができるので便利です。

自動テストでは、システム固有の前処理や検証が必要になる場面も少なくありません。
プラグインを積極的に活用し、より良いCI/CDの実現を目指していきたいです。

10
1
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
10
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?