2016-04-18 7 views
-3

私は単体テストについて勉強しています。私はPythonを使ってそれについて質問しましたが、言語はよくわかりません。どのように私はこの機能の単体テストを行うことができますか? :ユニットテストの呪文

#following from Python cookbook, #475186 
def has_colours(stream): 

    if not hasattr(stream, "isatty"): 
     return False 

    if not stream.isatty(): 
     return False # auto color only on TTYs 

    try: 
     import curses 
     curses.setupterm() 
     return curses.tigetnum("colors") > 2 
    except: 
     # guess false in case of error 
     return False 

答えて

0

コードの各行が存在しない、または間違っているとします。その行のコードが必要なテストを書く。

>>> has_colours('hello') 
False 

>>> has_colours(StringIO()) 
False 

など

あなたは、おそらく代わりに本物のインポートの偽の呪いに渡す必要があります。

1

各テストケースで適切な入力を送信することによって、関数が処理する可能性のあるすべてのシナリオをカバーするのが最善の方法です。

import unittest 


class TestHasColors(unittest): 
    def test_has_colors_returns_false_when_stream_does_not_have_func_tty(self): 
     # Call `has_colours` with stream that does not have it and verify return result is False 
     stream = object() 
     assert has_colours(stream) is False 

    def test_has_colors_returns_false_when_stream_func_tty_returns_false(self): 
     # TODO: Call `has_colours` with stream that has func tty and verify return result is False 
     pass 

    def test_has_colors_returns_false_when_curses_raises_error(self): 
     # TODO: Call `has_colours` with stream that reaches up to `curses.tigetnum` and patch it to raise an error 
     pass 

    def test_has_colors_returns_false_when_curses_tigetnum_colors_less_than_three(self): 
     # TODO: Call `has_colours` with stream that reaches up to `curses.tigetnum` and patch to return anything lte 2 
     pass 

    def test_has_colors_returns_true_when_curses_tigetnum_colors_greater_than_two(self): 
     # TODO: Call `has_colours` with stream that reaches up to `curses.tigetnum` and patch to return anything gt 2 
     pass 

注:過去3のテストケースがcurses.tigetnumにパッチを当てる必要がここで私が何を意味するかを理解するためのテストクラスのスタブです。理由は、返すものを簡単に制御できるようにするためです。エラーを起こすことさえできます。ドキュメントの例をいくつか示します:

https://docs.python.org/3/library/unittest.mock.html#patch

関連する問題