シェルスクリプトのユニットテスト

ちょっとシェルスクリプトを書く機会があったので、ユニットテストできるかなーと思って調べてみたのでメモ。

こんなんがあった。
Google Code Archive - Long-term storage for Google Code Project Hosting.

ダウンロードして解凍

$ wget http://shunit2.googlecode.com/files/shunit2-2.1.5.tgz 
$ tar zxvf shunit2-2.1.5.tgz 

サンプル実行

$ cd shunit2-2.1.5
$ ls
Makefile	doc		lib		src
bin		examples	share
$ cd examples/
$ ls
equality_test.sh	math.inc		mkdir_test.sh
lineno_test.sh		math_test.sh		party_test.sh
$ cat equality_test.sh 
#! /bin/sh
# file: examples/equality_test.sh

testEquality()
{
  assertEquals 1 1
}

# load shunit2
. ../src/shell/shunit2

$ ./equality_test.sh 
testEquality

Ran 1 test.

OK

ふむふむ。

試しにhelloスクリプトでやってみる

$ cat hello.sh 
#!/bin/sh

echo "hello"
$ cat hello_test.sh 
#! /bin/sh

testHello()
{
  result=`./hello.sh`
  assertEquals "hello" "${result}"
}

# load shunit2
. ../shunit2-2.1.5/src/shell/shunit2

$ ./hello_test.sh 
testHello

Ran 1 test.

OK

なるほど。

assertEquals [message] expected actual

という感じで書きます。

Mercurialのprecommitとも絡めてみる

$ cat precommit-test 
#!/bin/bash
for script in *_test.sh
do
"./${script}" || exit 1
done
$ cat .hg/hgrc 
[ui]
username=wyukawa

[hooks]
precommit=./precommit-test

フォルダ構成はこんな感じ

shunit2-2.1.5/
work/
- .hg/
- hello.sh
- hello_test.sh
- precommit-test

適当にhello.shを編集してコミット

$ hg ci -m "success"
testHello

Ran 1 test.

OK

おー。

わざと失敗させてみる。

$ cat hello.sh 
#!/bin/sh

echo "hllo"
$ hg ci -m "fail"
testHello
ASSERT:expected:<hello> but was:<hllo>

Ran 1 test.

FAILED (failures=1)
中止: precommit フック 終了コード 1 で終了しました

ほむほむ

ま、だからなんだというわけじゃないけどw いじょ