Adding unit testing for the poker app

git-svn-id: file:///srv/svn/euler@2 e5f4c3ec-3c0c-11df-b522-21efaa4426b5
This commit is contained in:
Correl Roush 2010-03-30 16:03:41 +00:00
parent 27734df4c4
commit b4e349239b
2 changed files with 65 additions and 26 deletions

View file

@ -1,5 +1,10 @@
import operator import operator
class InvalidCard(Exception):
pass
class InvalidHand(Exception):
pass
class PokerCard: class PokerCard:
values = {'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14} values = {'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14}
def __init__(self, string): def __init__(self, string):
@ -7,8 +12,13 @@ class PokerCard:
if self.value in '23456789': if self.value in '23456789':
self.value = int(self.value) self.value = int(self.value)
else: else:
try:
self.value = PokerCard.values[self.value] self.value = PokerCard.values[self.value]
except KeyError as e:
raise InvalidCard
self.suit = string[1] self.suit = string[1]
if not self.suit in ['H', 'C', 'S', 'D']:
raise InvalidCard
@staticmethod @staticmethod
def compare(a, b): def compare(a, b):
if a.value > b.value: if a.value > b.value:
@ -118,9 +128,10 @@ class PokerHand:
return result return result
return result return result
wins = 0 if __name__ == '__main__':
counter = 0 wins = 0
with open('poker.txt', 'r') as f: counter = 0
with open('poker.txt', 'r') as f:
while True: while True:
line = f.readline() line = f.readline()
if not line: if not line:
@ -142,4 +153,4 @@ with open('poker.txt', 'r') as f:
outcome, outcome,
one, one,
two) two)
print "Player one won {0} hands".format(wins) print "Player one won {0} hands".format(wins)

28
054/test.py Normal file
View file

@ -0,0 +1,28 @@
from e054 import *
import unittest
class TestCards(unittest.TestCase):
def setUp(self):
pass
def test_valid_number_card(self):
card = PokerCard('9D')
self.assertEqual(card.value, 9)
def test_valid_face_card(self):
card = PokerCard('QH')
self.assertEqual(card.value, 12)
def test_invalid_card_value(self):
self.assertRaises(InvalidCard, PokerCard, 'ZH')
def test_invalid_card_suit(self):
self.assertRaises(InvalidCard, PokerCard, '9Z')
def test_compare(self):
cards = ['QH', '9D', 'JS']
cards_sorted = sorted([PokerCard(c) for c in cards], cmp=PokerCard.compare, reverse=True)
self.assertEqual([c.value for c in cards_sorted], [12, 11, 9])
class TestHands(unittest.TestCase):
def setUp(self):
pass
if __name__ == '__main__':
unittest.main()