Perl日記

日々の知ったことのメモなどです。Perlは最近やってないです。

Testをはじめてみた1

今まで参考書なんかを読んでもTestに関する箇所に関しては飛ばしていたので、今日読んでみて分かったことメモ。
具体的には「続・初めてのPerl」17章 基本的なテスト、18章 高度なテスト。

17.1 テストすればするほどコードはよくなる

ですよねー。
分かってはいるんですけどねー。
では、以下列挙。

  • Test::Moreが超一般的
    • Test::Simpleの後継
  • use Test::More tests => $integer; # Test Count
  • ok() # 第1引数が真ならok, 偽ならnot ok
  • is() # 第1引数と第2引数が文字列として同値ならok, 違うならnot ok
  • isnt() # isの逆
  • like() # 第1引数が第2引数の正規表現にマッチしてるならok, しないならnot ok
#!/usr/bin/perl
# TestMore1.pl
use Test::More tests => 4*2;
ok(1, 'one is true.');
ok(undef, 'undef is false.');
is('Good!!!',  'Good!!!',   q{'Good!!!' is equal.});
is('Good!!!!', 'Good!!!',   q{'Good!!!' is equal.});
isnt('Bad.....', 'Bad....',  q{'Bad....' is not equal.});
isnt('Bad....',  'Bad....',  q{'Bad....' is not equal.});
like('http://google.co.jp/', qr!^http:!, 'like uri.');
like('ttp://google.co.jp/',  qr!^http:!, 'like uri.');
% ./TestMore1.pl
1..8
ok 1 - one is true.
not ok 2 - undef is false.
#   Failed test 'undef is false.'
#   at TestMore1.pl line 5.
ok 3 - 'Good!!!' is equal.
not ok 4 - 'Good!!!' is equal.
#   Failed test ''Good!!!' is equal.'
#   at TestMore1.pl line 7.
#          got: 'Good!!!!'
#     expected: 'Good!!!'
ok 5 - 'Bad....' is not equal.
not ok 6 - 'Bad....' is not equal.
#   Failed test ''Bad....' is not equal.'
#   at TestMore1.pl line 9.
#          got: 'Bad....'
#     expected: anything else
ok 7 - like uri.
not ok 8 - like uri.
#   Failed test 'like uri.'
#   at TestMore1.pl line 11.
#                   'ttp://google.co.jp/'
#     doesn't match '(?-xism:^http:)'
  • use Test::More tests => $integer; # ←何個テストがあるか数えなくちゃなの?
    • そんなときは tests => 'no_plan'でTest::Moreが数えてくれます
      • ただし開発中に限るべき
  • is()で数値比較したいんですけど…
    • →cmp_ok()
cmp_ok(1_000_000, '==', 1_000_000, 'numeral equl 1,000,000');
cmp_ok(1_000_000, '>',  1_000_000, 'smaller than 1,000,000');
ok 9 - numeral equl 1,000,000
not ok 10 - smaller than 1,000,000
#   Failed test 'smaller than 1,000,000'
#   at TestMore1.pl line 13.
#     '1000000'
#         >
#     '1000000'
# Looks like you failed 5 tests of 10.
  • use_ok() # モジュールロードの確認
    • BEGIN{}との併用を推奨
BEGIN { use_ok('MyModule') };

続・初めてのPerl 改訂版

続・初めてのPerl 改訂版