我使用这个的目的是为了测试和跑一下 fluent python 2nd edition 的代码。
发现,这就是一个模块,其实还是很简单的,相当于测试模块,但是又有不同,总是,这个也是可以模拟交互式的 Python 的,
# ex01.py
'''
>>> beer_card = Card('7', 'diamonds')
>>> beer_card
Card(rank='7', suit='diamonds')
'''
import collections
Card = collections.namedtuple('Card', ['rank', 'suit'])
class FrenchDeck:
ranks = [str(n) for n in range(2, 11)] + list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
def __init__(self) -> None:
self._cards = [Card(rank, suit) for suit in self.suits
for rank in self.ranks]
def __len__(self):
return len(self._cards)
def __getitem__(self, position):
return self._cards[position]
if __name__ == "__main__":
import doctest
doctest.testmod()
上面的代码,我们直接 python [ex01.py](<http://ex01.py>)
就行了,如果没有问题,那么,什么都不会输出,而如果我们想看到详细的信息,那么,可以加一个 -v
参数,python ex01.py -v
,输出的结果如下,
PyCodes/fluentpy2ed/ch01 via 🐍 v3.12.4
❯ python ex01.py -v
Trying:
beer_card = Card('7', 'diamonds')
Expecting nothing
ok
Trying:
beer_card
Expecting:
Card(rank='7', suit='diamonds')
ok
5 items had no tests:
__main__.Card
__main__.FrenchDeck
__main__.FrenchDeck.__getitem__
__main__.FrenchDeck.__init__
__main__.FrenchDeck.__len__
1 items passed all tests:
2 tests in __main__
2 tests in 6 items.
2 passed and 0 failed.
Test passed.
当然,我们也可以给 testmod 方法里面传递 verbose = True
,这样,就不用我们在执行 python 的时候加 -v
参数了,
# ex01.py
'''
>>> beer_card = Card('7', 'diamonds')
>>> beer_card
Card(rank='7', suit='diamonds')
'''
import collections
Card = collections.namedtuple('Card', ['rank', 'suit'])
class FrenchDeck:
ranks = [str(n) for n in range(2, 11)] + list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
def __init__(self) -> None:
self._cards = [Card(rank, suit) for suit in self.suits
for rank in self.ranks]
def __len__(self):
return len(self._cards)
def __getitem__(self, position):
return self._cards[position]
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)