LoginSignup
18
6

GitHub ActionsのElixir自動テスト環境構築最短手順

Last updated at Posted at 2023-11-06

本記事では表題通り,GitHub Actionsを用いてElixir自動テスト環境を構築する最短手順をご紹介します.Dependabotの設定もつけています.

GitHub Actions による自動テスト環境を導入する意義

GitHubを用いて開発しているときに,ソースコード改変のたびにLinux/Windows/macOS等の様々な環境でテストして動作を確認するのは大変な労力がかかります.

自動テスト環境がすでに構築されている場合(Elixirの場合では,mix testによる自動テストを実施できている場合)に,本記事に沿って環境を設定するだけで,ソースコードをGitHubのmainブランチにpushもしくはPull Requestを送るたびに,GitHubのクラウド上のUbuntu環境で自動テストを実行して結果を得ることができます.

手順

本手法の手順は次のとおりです.

  1. mix newで新しいプロジェクトを作る
  2. GitHubでプロジェクトを新規作成し,登録する
  3. ActionsでElixirのテスト環境を設定する
  4. テストが成功することを確認する
  5. (オプション)Matrixを用いて複数バージョンでテストする環境を構築する
  6. (オプション)Dependabotを設定する

1. mix newで新しいプロジェクトを作る

たとえば sample_project というプロジェクトを作ってみます.この名称は他の名称に変更しても良いですが,以降のsample_projectをその名称に変更します.

mix new sample_project

その後,プロジェクトのディレクトリへ移動します.

cd sample_project

自動テストを実行する方法は下記のとおりです.

mix test

緑色で1 doctest, 1 test, 0 failuresと表示され,テストが成功することを確認します.

2. GitHubでプロジェクトを新規作成し,登録する

次にGitHubでsample_projectというプロジェクトを新規作成します.GitHubにログインすると右上部分が下図のようになっていると思います.

GitHubの右上

なお,私のGitHubアカウントでの画像なので,一番右の画像アイコンは私,山崎進の画像アイコンになっていますが,実際には読者各自のアカウントになります.

このアイコンの+記号のボタンを押します.

GitHub右上で+ボタンを押した時

この New repository を押します.すると次のような画面になります.

New repository

なお,私のアカウントなので,Ownerには私のアカウントであるzacky1972が表示されていますが,これは実際には読者各自のアカウントになります.

Repository nameに,手順1で作成したレポジトリ名であるsample_projectを入れます.

create sample_project and choose public

上図のように,緑文字でsample_project is available.と出るならば,レポジトリを作成することができます.もしそうではなく,エラーが出るようならば,すでに存在するレポジトリ名である場合が多いので,手順1に戻って別の名前でプロジェクトを作るか,GitHub上のsample_projectレポジトリを削除してください.

また,このレポジトリを公開したくない時には,その下の Private の左にある丸を選択してください.

他はそのままにして,一番下の Create repository ボタンを押します.

Create repository

すると画面が切り替わります.

下図の手順に着目します.

steps

おそらく git remote ... の手順のところは,私とみなさんとで異なるはずです.

次のように打ち込んでいきます.

  1. git init
  2. git add -A

続けて,git commit -m "first commit"からgit push -u origin mainまでをマウスで選択して,コピーし,手順1で操作したターミナル画面にペーストします.ペーストできない場合には,キーボードで順番に打ってください.パスワード等が求められる場合には,状況により,GitHubアカウントのパスワード,SSH鍵のパスフレーズ,指紋認証などで対応します.

うまくいけば,GitHubの画面をリロードすると次のような画面になると思います.

Created GitHub repository

3. ActionsでElixirのテスト環境を設定する

作成したGitHubプロジェクトの下図部分のActionsをクリックします.

tool bar

すると下図のような画面になると思います.おすすめされるままにElixirの下のConfigureを押します.

Get Started with GitHub Actions

すると下図のような画面になります.

elixir.yml

コードは次のとおりです.

.github/workflows/elixir.yaml
# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
# documentation.

name: Elixir CI

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

permissions:
  contents: read

jobs:
  build:

    name: Build and test
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v3
    - name: Set up Elixir
      uses: erlef/setup-beam@61e01a43a562a89bfc54c7f9a378ff67b03e4a21 # v1.16.0
      with:
        elixir-version: '1.15.2' # [Required] Define the Elixir version
        otp-version: '26.0'      # [Required] Define the Erlang/OTP version
    - name: Restore dependencies cache
      uses: actions/cache@v3
      with:
        path: deps
        key: ${{ runner.os }}-mix-${{ hashFiles('**/mix.lock') }}
        restore-keys: ${{ runner.os }}-mix-
    - name: Install dependencies
      run: mix deps.get
    - name: Run tests
      run: mix test

右上の緑色のCommit changes...を押します.すると次のポップアップが出ますので,右下のCommit changesを押します.

Popup

4. テストが成功することを確認する

その後,プロジェクト画面に戻るので,Actionsを押します.

tool bar

順調にいけば,下記のワークフローが緑✅で完了するのですが,私の場合,次のようにエラーになりました.

Create elixir.yml

Create elixir.ymlをクリックして,Build and testをクリックすると,下図のようなログを出して,原因を探ることができます.この場合,mix.exsに定義しているElixirバージョンが新しすぎたみたいです.

Log

ローカル環境を最新にするために,ターミナルで git pull をしてください.

さて,mix.exsは次のようでした.

defmodule SampleProject.MixProject do
  use Mix.Project

  def project do
    [
      app: :sample_project,
      version: "0.1.0",
      elixir: "~> 1.16-rc",
      start_permanent: Mix.env() == :prod,
      deps: deps()
    ]
  end

  # Run "mix help compile.app" to learn about applications.
  def application do
    [
      extra_applications: [:logger]
    ]
  end

  # Run "mix help deps" to learn about dependencies.
  defp deps do
    [
      # {:dep_from_hexpm, "~> 0.3.0"},
      # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
    ]
  end
end

この project 関数の中の elixir: の後の,1.16-rc1.15に変更して,commitし,pushします.

プロジェクト画面のActionsを再確認すると,次のように成功しました.

Success

ここまでで,一旦,手順は完成です.

5. (オプション)Matrixを用いて複数バージョンでテストする環境を構築する

Elixirの複数バージョンでテストする方法をご紹介します.

まずブランチを切ります.名前はなんでも良いのですが,仮にmatrixとします.

git checkout -b matrix

次にエディタで.github/workflows/elixir.ymlを開いて,次のように修正します.
この例では,Elixirのバージョン1.15.71.16.0-rc.0でテストします.

.github/workflows/elixir.yml
# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
# documentation.

name: Elixir CI

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

permissions:
  contents: read

jobs:
  build:

    name: Build and test
    runs-on: ubuntu-latest

    strategy:
      matrix:
        elixir-version: ['1.15.7', '1.16.0-rc.0']

    steps:
    - uses: actions/checkout@v3
    - name: Set up Elixir
      uses: erlef/setup-beam@61e01a43a562a89bfc54c7f9a378ff67b03e4a21 # v1.16.0
      with:
        elixir-version: ${{ matrix.elixir-version }} # [Required] Define the Elixir version
        otp-version: '26.0'      # [Required] Define the Erlang/OTP version
    - name: Restore dependencies cache
      uses: actions/cache@v3
      with:
        path: deps
        key: ${{ runner.os }}-mix-${{ hashFiles('**/mix.lock') }}
        restore-keys: ${{ runner.os }}-mix-
    - name: Install dependencies
      run: mix deps.get
    - name: Run tests
      run: mix test

差分は次のとおりです.

diff --git a/.github/workflows/elixir.yml b/.github/workflows/elixir.yml
index 132226f..3d2ce78 100644
--- a/.github/workflows/elixir.yml
+++ b/.github/workflows/elixir.yml
@@ -20,12 +20,16 @@ jobs:
     name: Build and test
     runs-on: ubuntu-latest
 
+    strategy:
+      matrix:
+        elixir-version: ['1.15.7', '1.16.0-rc.0']
+
     steps:
     - uses: actions/checkout@v3
     - name: Set up Elixir
       uses: erlef/setup-beam@61e01a43a562a89bfc54c7f9a378ff67b03e4a21 # v1.16.0
       with:
-        elixir-version: '1.15.2' # [Required] Define the Elixir version
+        elixir-version: ${{ matrix.elixir-version }} # [Required] Define the Elixir version
         otp-version: '26.0'      # [Required] Define the Erlang/OTP version
     - name: Restore dependencies cache
       uses: actions/cache@v3

たとえば次のようにcommitします.

git commit -am "ci: add matrix strategy"

その後,次のようにブランチごとpushします.matrixの部分は,作成したブランチ名が入ります.

git push --set-upstream origin matrix 

すると次のようにメッセージが出ると思いますので,中に表示されているURLを開きます.

% git push --set-upstream origin matrix
Enumerating objects: 9, done.
Counting objects: 100% (9/9), done.
Delta compression using up to 12 threads
Compressing objects: 100% (3/3), done.
Writing objects: 100% (5/5), 478 bytes | 478.00 KiB/s, done.
Total 5 (delta 2), reused 0 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (2/2), completed with 2 local objects.
remote: 
remote: Create a pull request for 'matrix' on GitHub by visiting:
remote:      https://github.com/zacky1972/sample_project/pull/new/matrix
remote: 
To github.com:zacky1972/sample_project.git
 * [new branch]      matrix -> matrix
branch 'matrix' set up to track 'origin/matrix'.

あるいは,GitHubプロジェクト画面に下図のようなCompare & pull requestボタンが表示されますので,それを押下します.

Compare & pull request

あるいは,下図のPull requestsを押します.

tool bar

その後,右のNew pull requestボタンを押し,compare: mainを押下して,matrixを選択します.

compare: matrix

次のようになるはずです.右の緑のCreate pull requestボタンを押します.

Create pull request

以上の3つの方法のどれかを用いると,次の画面になります.下の緑のCreate pull requestボタンを押します.

Create pull request

次の画面で下図のように2つテストが走れば大成功です.

CI

テストが完了すれば下図のようになりますので,緑のMerge pull requestボタンを押します.

Merge pull request

次の緑のConfirm mergeボタンも押します.すると次の画面になります.もうブランチは用済みですので,Delete branchを押します.

Delete branch

ターミナルに戻って,次のコマンドを打ちます.matrixには作成したブランチ名を入れます.

git checkout main
git pull
git branch -D matrix

6. (オプション)Dependabotを設定する

最後にDependabotを設定する方法を紹介します.Dependabotを設定することで,GitHub Actionsやhexライブラリが更新された時に,GitHubがPRを自動で作ってくれます.

まず下図のSettingsを押します.

tool bar overview

次のように...が出ている場合には,...を押してからSettingsを押します.

tool bar dotted

左側のCode security and analysisを押します.

Code security and analysis

下図のDependabot部分のEnablesボタンを全て押します.

Dependabot

一番下のDependabot version updatesEnableを押すと下図の画面になります.

dependabot.yml

下図のようにして,右上の緑のCommit changes...を押します.

dependabot.yml

次のようなコードです.

.github/dependabot.yml
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates

version: 2
updates:
  - package-ecosystem: "github-actions" 
    directory: "/" # Location of package manifests
    schedule:
      interval: "daily"
  - package-ecosystem: "mix" 
    directory: "/" # Location of package manifests
    schedule:
      interval: "daily"

次のポップアップも下の緑のCommit changesを押します.下記コマンドで,ターミナルでmainブランチに移動した後,git pullとします.

git checkout main
git pull

このようにすることで,GitHub Actions,もしくは,使用するHexパッケージが更新されると,自動的にPRが発行されます.便利ですね.

しばらくすると,GitHubの右上部分に,下図のように通知が来ることがあります.

notification

クリックして開いてみると,次のような感じで更新のPRが来ています.

notifications

これを開いて良さそうならばマージしていきましょう.

18
6
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
18
6