2020年7月9日木曜日

開発環境

Practical Programming: An Introduction to Computer Science Using Python 3.6 (Paul Gries(著)、Jennifer Campbell(著)、Jason Montojo(著)、Pragmatic Bookshelf)のChapter 15(Testing and Debugging)、Exercise 6の解答を求めてみる。

コード

#!/usr/bin/env python3
from unittest import TestCase, main
from typing import List


class TestAverage(TestCase):
    def test_one(self):
        self.assertEqual(average([10]), 10)

    def test_one_none(self):
        self.assertEqual(average([10, None]), 10)

    def test_two(self):
        self.assertEqual(average([10, 20]), 15)

    def test_two_none(self):
        self.assertEqual(average([10, None, 20]), 15)


def average(values: List[float]) -> float:
    count = 0
    total = 0
    for value in values:
        if value is not None:
            total += value
            count += 1
        # count += 1
    return total / count


if __name__ == "__main__":
    main()

入出力結果(Zsh、PowerShell、Terminal、Jupyter(IPython))

% ./sample6.py
.F.F
======================================================================
FAIL: test_one_none (__main__.TestAverage)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "./sample6.py", line 11, in test_one_none
    self.assertEqual(average([10, None]), 10)
AssertionError: 5.0 != 10

======================================================================
FAIL: test_two_none (__main__.TestAverage)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "./sample6.py", line 17, in test_two_none
    self.assertEqual(average([10, None, 20]), 15)
AssertionError: 10.0 != 15

----------------------------------------------------------------------
Ran 4 tests in 0.001s

FAILED (failures=2)
% ./sample6.py
....
----------------------------------------------------------------------
Ran 4 tests in 0.000s

OK
% ./sample6.py -v
test_one (__main__.TestAverage) ... ok
test_one_none (__main__.TestAverage) ... ok
test_two (__main__.TestAverage) ... ok
test_two_none (__main__.TestAverage) ... ok

----------------------------------------------------------------------
Ran 4 tests in 0.000s

OK
% 

0 コメント:

コメントを投稿