[Test][ShellScript]シェル(Bash)で shunit2 shcov を使ってテストを書いてC0カバレッジを測る

Contents

概要

シェルスクリプトでもTDDするためにテストコードを書いてカバレッジ測定をする。
テストにはshunit2を使用し、カバレッジ測定にはshcovを利用する。
shunit2 shcov は利用が簡単のためおすすめだが、メンテナンスが十分されるかどうかが心配。

テスト

インストール

wget https://shunit2.googlecode.com/files/shunit2-2.1.6.tgz
tar zxvf shunit2-2.1.6.tgz

テストを書いてみる

vim firstTest.sh
---
#!/bin/bash

### firstTest.sh ###

function testWeCanWriteTests () {
    assertEquals "it works" "it works"
}

## Call and Run all Tests
. "./shunit2-2.1.6/src/shunit2"
---
chmod +x firstTest.sh
./firstTest.sh
---
testWeCanWriteTests

Ran 1 test.

OK

カバレッジ

インストール

wget https://shcov.googlecode.com/files/shcov-5.tar.gz
tar zxvf shcov-5.tar.gz

カバレッジを測定してみる

first.sh

#!/bin/bash

function Hello () {
  echo "Hello World!"
}

firstTest.sh

#!/bin/bash

## Load target shell
. first.sh

### firstTest.sh ###
function testWeCanWriteTests () {
    Hello
    assertEquals $? 0
}

## Call and Run all Tests
. "./shunit2-2.1.6/src/shunit2"

カバレッジ測定

shcov-5/scripts/shcov firstTest.sh
---
testWeCanWriteTests
Hello World!

Ran 1 test.

OK
---

ls /tmp/shcov
shcov-5/scripts/shlcov /tmp/shcov output
ls output

結果

zuqqhi2

某Web系の会社でエンジニアをやっています。 学術的なことに非常に興味があります。 趣味は楽器演奏、ジョギング、読書、料理などなど手広くやっています。