moritetuのIT関連技術メモ

cram

pythonで書かれた、コマンドラインベースのプログラムのテストに有用なテストツール。
特徴的なのは、実行コマンドと結果をターミナル画面のような形式で記述するところである。
これの何が良いのかというと、テストファイルを見れば、どのようなコマンドを実行して、どのような結果となるのか、直感的に判断することができる、という点である。

例1 sample.t

$ cat tests.t
test echo:

  $ echo foo
  foo

test expr:

  $ expr 1 + 1
  10

実行すると以下のようになる。

$ cram tests.t
!
--- tests.t
+++ tests.t.err
@@ -6,4 +6,4 @@
 test expr:

   $ expr 1 + 1
-  10
+  2

# Ran 1 tests, 0 skipped, 1 failed.

と、上記のとおり、
echo fooの結果がfoo、
expr 1 + 1の結果が10(誤りで正しくは2)
であることが、テストファイルを見ればすぐに分かる。

インストール

インストールは簡単であり、pipまたはmakeで可能。

pip install cram

or

git clone https://github.com/brodie/cram.git
cd cram
make install

テスト

テストプログラム

その他の記述はコメントとして解釈されるので、テストに関する説明を自由に記述できる。
インデントでfocusされた箇所が、ターミナルの画面をそのまま投影したような感じであることが分かるだろう。

メモ >が結果に含まれるテスト結果の記述

curlの-vオプション付きの結果を比較しようとするとやや面倒である。
>の記号がリクエストヘッダーの入力と一致するためである。
この場合は、sedコマンドなどで置換して結果を作成する必要がある。

curl test:

  $ curl -s -vLo- "http://localhost/" |& sed -e 's/>/!/g'
  !
  * About to connect() to localhost port 80 (#0)
  *   Trying ::1...
  * Connected to localhost (::1) port 80 (#0)
  ! GET / HTTP/1.1\r (esc)
  ! User-Agent: curl/7.29.0\r (esc)
  ! Host: localhost\r (esc)
  ! Accept: */*\r (esc)
  ! \r (esc)
  < HTTP/1.1 403 Forbidden\r (esc)
  < Date: Sun, 16 Feb 2020 13:51:34 GMT\r (esc)
  < Server: Apache/2.4.6 (CentOS) PHP/7.3.14\r (esc)
  < Last-Modified: Thu, 16 Oct 2014 13:20:58 GMT\r (esc)
  < ETag: "1321-5058a1e728280"\r (esc)
  < Accept-Ranges: bytes\r (esc)
  < Content-Length: 4897\r (esc)
  < Content-Type: text/html; charset=UTF-8\r (esc)
  < \r (esc)
  { [data not shown]
  (省略)

テストの実行結果

テストの実行結果について、柔軟なAssertが可能なように、cram独自のシンタックスが用意されている。

(re)

正規表現でマッチすることを示す。

$ cat re.t
Re test:

  $ echo "hello world"
  hello .* (re)
$ cram re.t
.
# Ran 1 tests, 0 skipped, 0 failed.

(glob)

glob形式でマッチすることを示す。

$ cat glob.t
glob test:

  $ touch hoge.txt
  $ ls hoge.txt
  *.txt (glob)

$ cram glob.t
.
# Ran 1 tests, 0 skipped, 0 failed.

(esc)

改行などの制御系の文字を含む行のマッチ。

$ cat esc.t
esc test:

  $ printf "%s\r\n" "hello world"
  hello world\r (esc)
$ cram esc.t
.
# Ran 1 tests, 0 skipped, 0 failed.

(no-eol)

改行区切りでない文字列のマッチ。

$ cat no-eol.t
no-eol test:

  $ printf "%s" "hello world"
  hello world (no-eol)
$ cram no-eol.t
.
# Ran 1 tests, 0 skipped, 0 failed.

参考リンク


トップ   差分 バックアップ リロード   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
目次
ダブルクリックで閉じるTOP | 閉じる
GO TO TOP