LoginSignup
0
0

More than 1 year has passed since last update.

GitHubActionsクイックスタート

Last updated at Posted at 2022-07-29

概要

GitHubActionsはCI/CDツールとして後発にも関わらず、デファクトスタンダードと言っていいほど定着しており気になっていた。
関連記事は山ほどあるが、クイックスタートするという観点では情報不足であったり、初心者(ワイ含む)には難しくてちょうどいい記事がないなと

「それじゃ、とりあえず触ってみて初心者の速習用にワイが記事を投稿してやるぜ!」ということで、まとめてみました。

☆当記事で使用するコードは、私のGithubで公開しています☆彡

準備

GithubActionsでテスト実行するコードを準備する。
今回は、Pythonで作成した簡単なソースコードをテストすることにしよう。

Pythonで作成した関数をテスト対象にする。
「名字、名前、ミドルネームの3つを引数に渡すとそれぞれの頭文字を大文字にして返却する」単純なソースコード。
「ミドルネーム??」、欧米の方にも対応していますよ~!

テスト対象コード
def get_formatted_name(first,last,middle=''):
    """フォーマットされたフルネームを返す。"""
    if middle:
        full_name = f"{first} {middle} {last}"
    else:
        full_name = f"{first} {last}"
    return full_name.title()

加えて、この関数をテストするテストコードも用意しましょう!
このテストコードをGithubActionsで実行するわけですよ!

テストコード
import unittest
from name_function import get_formatted_name

class NamesTestCase(unittest.TestCase):
    """name_function.pyをテストする"""

    def test_first_last_name(self):
        formatted_name = get_formatted_name('test', 'taro')
        self.assertEqual(formatted_name,'Test Taro')

    def test_first_last_middle_name(self):
        formatted_name = get_formatted_name('test' , 'taro', 'hanako')
        self.assertEqual(formatted_name, 'Test Hanako Taro')

if __name__ == '__main__':
    unittest.main()

これで、GithubActionsを体験する準備は整った!

GithubActionsを試そう!

  1. GitHubで「Actions」を押す!
    GitHubActions1.JPG
  2. Pythonで作成したテストコードを実行したいので、「set up a workflow yourself」をクリック
    GitHubActions2.JPG
    サンプルコードが表示!
    GitHubActions3.JPG
    3.「Start commit」でサンプルコードをコミット!

これでひとまずworkflowができたよ!

サンプルworkflow
# This is a basic workflow to help you get started with Actions

name: CI

# Controls when the workflow will run
on:
  # Triggers the workflow on push or pull request events but only for the "main" branch
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
  # This workflow contains a single job called "build"
  build:
    # The type of runner that the job will run on
    runs-on: ubuntu-latest

    # Steps represent a sequence of tasks that will be executed as part of the job
    steps:
      # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
      - uses: actions/checkout@v3

      # Runs a single command using the runners shell
      - name: Run a one-line script
        run: echo Hello, world!

      # Runs a set of commands using the runners shell
      - name: Run a multi-line script
        run: |
          echo Add other actions to build,
          echo test, and deploy your project.

ちょっと解説

  • workflowを実行するタイミングを指定しているのは?
    「on」で、実行タイミングを指定する。
    サンプルコードの場合は「main」ブランチに『Push』もしくは『Pull Request』されたらworkflowを実行💨
  • 実行環境は?
    buildの内の「runs-on」に指定する。
    サンプルコードの場合は、Ubuntuの最新版で実行!
    それ以外には、「Mac」もしくは「windows」の環境を指定できるよ。
  • 実行する内容は?
    steps以下に記述
    処理名を「name」で指定し、実行内容を「run」に指定する。
    サンプルコードの場合は、echoコマンドを実行するだけのシンプルな感じ。
  • 開発したソースコードは、実行環境に自動的に配置されるの?
    明示的に「git checkout」する必要がある。
    でもどうやってやるの?「run」でコマンド実行??
    「uses」でできあいの優れものがあるんですよ!
    「気づいていますよ!」 という方も多いかと思います。そういうワイもすぐ気づきました!
    「uses」でできあいの優れものを使用できる!
    そうです。この部分👇
Checkoutのできあいの優れものを使用する
- uses: actions/checkout@v3

「オイオイ!、Pythonのテストコードを実行するんじゃないのかよ?」 と思った方、

お待たせしました!Pythonのテストコード実行に着手しますよ!

Pythonのテストコードを実行する

まずは環境ですな。
初心者はこれも優れものを使いましょう!

Usageを参考にサンプルコードに追記すれば、実行できちゃうんです。
書いてみるとこんな感じ(^o^)!
折角だから複数のPythonバージョン(環境)で走らせるテスト(workflow)を作成してみたよ!
こういうworkflowを見るとで『できるイケてるエンジニア』感出るよね(^^)

Python環境の整備とテストコードの実行
jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version: ['3.7','3.8','3.9','3.10']

    # Steps represent a sequence of tasks that will be executed as part of the job
    steps:
      # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
      - uses: actions/checkout@v3
      - uses: actions/setup-python@v4
        with:
          # python-version: '3.8'
          python-version: ${{ matrix.python-version }}
          architecture: 'x64'

      # Runs a single command using the runners shell
      - name: Run a one-line script
        run: echo Hello, world!

      # Runs a set of commands using the runners shell
      - name: Run a multi-line script
        run: |
          echo Add other actions to build,
          echo test, and deploy your project.
      
      - name: Try Python UnitTest
        run: |
          python3 --version
          python3 ./src/test_name_function.py

ちょっと解説

  • Python環境をセットアップ
    優れものを使うよ!
    その前に、テストで使用するPythonのバージョンを設定
    今回は、「3.7」~「3.10」を設定してみたよ!
Pythonのバージョンを設定
strategy:
      matrix:
        python-version: ['3.7','3.8','3.9','3.10']

設定したPythonバージョンをインストールした環境をビルド🔧
「uses acitons/setup-python@v4」で優れものを使用して環境をビルドする。
その際に、「with」にビルドするPythonのバージョンと環境のビット数を指定
今回は、「matrix」で使用した設定を使ってPythonのバージョンを指定して、64bits版ね!

Python環境整備
steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-python@v4
        with:
          # python-version: '3.8'
          python-version: ${{ matrix.python-version }}
          architecture: 'x64'
  • テストコードを実行
    もうわかってますよ!、stepsに「run」にテストコードのPythonを実行するスクリプトを記述でしょ!
    今回は、マルチPython環境で実行しているのを確認するために、テストコード実行前にPythonのバージョンを表示するようにしたよ!
テストコード実行
 - name: Try Python UnitTest
        run: |
          python3 --version
          python3 ./src/test_name_function.py

実行結果

このworkflowのymlファイルをコミットすると、CI(Actions)が実行される!
実行結果.JPG
👇マルチのPython環境で実行できているでしょ(^^)!
実行結果2.JPG
「build(3.10)」を押して見ると、実行結果が見れるよ!
実行結果3.JPG
👇Pythonのテストコードもちゃんと実行できているよ😆!
実行結果4.JPG

まとめ

実際やってみると、簡単なCIはGitHubActionsで簡単に作れる!
なぜなら、MarketPlaceに優れたworkflowがあるから、それを「uses」で活用することでワークフローは簡単に作成できる。
それゆえ、我々Developerはテストコードを書くことに集中できる。
凝ったCI/CDのワークフローを作成するとなると、恐らく難しいんだろうけど。

参考文献

  • Eric Mattes著、鈴木たかのり、安田善一郎訳、「最短距離でゼロからしっかり学ぶ Python入門 必修編」、技術評論社、2021年6月11日 初版 第3刷、P244~251
0
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
0
0