uokadaの見逃し三振は嫌いです

ここで述べられていることは私の個人的な意見に基づくものであり、私が所属する組織には一切の関係はありません。

nosetestsが出すカバレッジ率の罠

  • leap.py
#!/usr/bin/env python2.7
# -*- coding:utf-8 -*-

def is_leap(year):
    """ judgement is leap
    """
    #assert( isinstance(year, int) == True )
    if year % 400 == 0 or (year % 100 != 0 and year % 4 == 0):
        result = True
    else:
        result = False
    return result
  • test_leap.py
#!/usr/bin/env python2.7
# -*- coding:utf-8 -*-

from nose.tools import *

import leap

class TestLeapYear(object):
    """TestLeapYear
        leap モジュールのテストクラス
    """
    def test_is_leap_01(self):
        """leap.is_leap の正常系テスト 01
        """
        result = leap.is_leap(2000)
        ok_(result)

    def test_is_leap_02(self):
        """leap.is_leap の正常系テスト 02
        """
        result = leap.is_leap(1900)
        ok_(result == False)

このままテストしてみます。

% nosetests -v --with-cover --cover-package=leap --rednose test_leap.py
leap.is_leap の正常系テスト 01 ... passed
leap.is_leap の正常系テスト 02 ... passed
Name    Stmts   Miss  Cover   Missing
-------------------------------------
leap        5      0   100%   

-----------------------------------------------------------------------------
2 tests run in 0.0 seconds (2 tests passed)

カバレッジ率が100%になってますね。

(year % 100 != 0 and year % 4 == 0)

上のパスを通ってないのに100%になっているのはまずいですね。
Perlのproveならブランチまでちゃんとカバーしてないことを教えてくれるのですが、
nosetestsでもプラグインが誰か用意してくれると思うので探してみます。






ありました。
nosexcover 1.0.7 : Python Package Index
Always look on the funny side of life: noseがbranch coverage(C1)に対応したようなので、jenkinsでレポートを作成した

% pip install nosexcover
Downloading/unpacking nosexcover
  Downloading nosexcover-1.0.7.tar.gz
  Running setup.py egg_info for package nosexcover
    
Requirement already satisfied (use --upgrade to upgrade): nose in /Users/callistoiv/works/msgpackrpc/smigrate/lib/python2.7/site-packages (from nosexcover)
Requirement already satisfied (use --upgrade to upgrade): coverage>=3.4 in /Users/callistoiv/works/msgpackrpc/smigrate/lib/python2.7/site-packages (from nosexcover)
Installing collected packages: nosexcover
  Running setup.py install for nosexcover
    
Successfully installed nosexcover
Cleaning up...
    • with-xcover --cover-branches をオプションに入れてテストを実行します。
% nosetests -v --with-xcover --cover-branches  --cover-package=leap --rednose test_leap.py            
leap.is_leap の正常系テスト 01 ... passed
leap.is_leap の正常系テスト 02 ... passed
Name    Stmts   Miss Branch BrPart  Cover   Missing
---------------------------------------------------
leap        5      0      2      0   100%   

-----------------------------------------------------------------------------
2 tests run in 0.1 seconds (2 tests passed)

Branch、 BrPart ってカラムが追加されてますね〜
ただ、通過してないパスがあるのにカバレッジ率100%になっているのは気になる・・・・(´・ω・`)