Skip to content

Commit 5923969

Browse files
committed
Add test for default Race votes and add_result method that updates unique candidate instance
1 parent 958a03d commit 5923969

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

elex4/lib/models.py

+16
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,24 @@ class Race(object):
44
def __init__(self, date, raw_office):
55
self.date = date
66
self.office, self.district = self.__clean_office(raw_office)
7+
self.total_votes = 0
8+
self.candidates = {}
9+
10+
def add_result(self, result):
11+
self.total_votes += result['votes']
12+
candidate = self.__get_or_create_candidate(result)
13+
candidate.add_votes(result['county'], result['votes'])
714

815
# Private methods
16+
def __get_or_create_candidate(self, result):
17+
key = (result['party'], result['candidate'])
18+
try:
19+
candidate = self.candidates[key]
20+
except KeyError:
21+
candidate = Candidate(result['candidate'], result['party'])
22+
self.candidates[key] = candidate
23+
return candidate
24+
925
def __clean_office(self, office):
1026
if 'Rep' in office:
1127
office_clean = 'U.S. House of Representatives'

elex4/tests/test_models.py

+10
Original file line numberDiff line numberDiff line change
@@ -77,3 +77,13 @@ def test_total_votes_update(self):
7777
race = Race("2012-11-06", "President")
7878
race.add_result(self.smith_result)
7979
self.assertEquals(race.total_votes, 2000)
80+
81+
def test_add_result_to_candidate(self):
82+
"Race.add_result update unique candidate instance"
83+
race = Race("2012-11-06", "President")
84+
# Add a vote twice. If it's the same candidate, vote total should be sum of results
85+
race.add_result(self.smith_result)
86+
race.add_result(self.smith_result)
87+
cand_key = (self.smith_result['party'], self.smith_result['candidate'])
88+
candidate = race.candidates[cand_key]
89+
self.assertEquals(candidate.votes, 4000)

0 commit comments

Comments
 (0)