はじめに
こんにちわ、すえけん(sueken5)です。
この記事ではgithub actionsを使ってDB接続部分のテストをしようと思います。
前提条件
今回のケースでは以下のような状況です。
- golangを使っている
- gcp datastoreへのテストがある
datastoreへのテストがあるのでテスト環境にdatastoreのエミュレータを立てる必要があります。
github actions
github actionsでは自作のアクションを作ることができ、今回はそれを使います。
- .github
- actions
- mytest
- action.yaml
- Dockerfile
- entrypoint.sh
ディレクトリはこのような感じです。
name: mytest
author: sueken
description: my test
runs:
using: 'docker'
image: 'Dockerfile'
action.yamlにはDockerfileを使うこと設定します。色々argsとか設定できますので適宜設定してみましょう。
#!/bin/sh
set -e
cd "${GITHUB_WORKSPACE}"/myapp
export CLOUDSDK_CORE_PROJECT=myapp
gcloud beta emulators datastore start --host-port 0.0.0.0:3000 --store-on-disk --data-dir /datastore --consistency 1.0 &
export DATASTORE_EMULATOR_HOST=localhost:3000
go test -v ./...
entrypoint.shです。 chmod +x entrypoint.sh
で実行可能にすることを忘れないでください。
ここでdatastoreの起動やテストのスタートをさせています。
FROM google/cloud-sdk:277.0.0
ENV GO111MODULE=on
ENV GOROOT=/usr/local/go
ENV GOPATH=/go
ENV PATH=$GOPATH/bin:$GOROOT/bin:$PATH
RUN apt update
RUN apt install -y wget
RUN wget -q https://dl.google.com/go/go1.13.6.linux-amd64.tar.gz
RUN tar -xf go1.13.6.linux-amd64.tar.gz
RUN mv go /usr/local
COPY entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
dockerfileにはcloudsdkをベースにgolangをインストールしています。
ここまでで自作のアクションを作成できました。次にこのアクションを呼び出すworkflowを見てます。
name: myapp
on:
push:
paths:
- 'myapp/**'
- '.github/workflows/myapp.yaml'
- '.github/actions/mytest/**'
jobs:
test:
name: GoTest
runs-on: ubuntu-18.04
steps:
- uses: actions/checkout@master
- name: test
uses: "./.github/actions/mytest" # <- ここで呼び出し
これで自作のアクションを呼び出すことができます。
まとめ
簡単にデータベースを用意しテストする環境が作れるのはいいなと思いました。
今回はDockerを使いましたが、nodejsを使いcloudsdkをインストールし、host上でテストするやり方があります。
参考になれば幸いです。