def test_add_candidate(self): """Test the public ``add_candidate'' function provided by the Constituency() class. """ con = Constituency("test") con2 = Constituency("test2") party1 = Party("party1") party2 = Party("party2") party3 = Party("party3") candidate1 = Candidate("candidate1", party1, con) candidate2 = Candidate("candidate2", party2, con) candidate3 = Candidate("candidate3", party3, con2) candidate4 = Candidate("candidate4", party2, con) con.add_candidate(candidate1) self.assertTrue(candidate1 in con.candidates) self.assertEqual(len(con.candidates), 1) # attempt to add a candidate twice with self.assertRaises(AssertionError): con.add_candidate(candidate1) self.assertEqual(len(con.candidates), 1) self.assertEqual(len(con.parties), 1) con.add_candidate(candidate2) self.assertTrue(candidate1 in con.candidates) self.assertTrue(candidate2 in con.candidates) self.assertEqual(len(con.candidates), 2) self.assertEqual(len(con.parties), 2) # attempt to add a candidate with the wrong constituency with self.assertRaises(AssertionError): con.add_candidate(candidate3) self.assertEqual(len(con.candidates), 2) # attempt to add a candidate with the same party with self.assertRaises(AssertionError): con.add_candidate(candidate4) self.assertEqual(len(con.candidates), 2)
def election_from_csv(filename): """ Create an Election object from a csv file of election data. """ election = None with open(filename, 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=',', quotechar='"') # create an Election object election = Election() constituencies = {} parties = {} candidates = {} for row in reader: # extract the fields from the CSV data constituencyName = row[0] candidateName = row[1] partyName = row[2] voteCount = int(row[3]) # reconcile the constituency if constituencyName not in constituencies: con = Constituency(constituencyName) constituencies[constituencyName] = con else: con = constituencies[constituencyName] # reconcile the party if partyName not in parties: par = Party(partyName) parties[partyName] = par else: par = parties[partyName] # reconcile the candidate if (candidateName, partyName, constituencyName) \ not in candidates: can = Candidate(candidateName, par, con, voteCount) candidates[(candidateName, partyName, constituencyName)] = can else: raise ValueError( """A candidate with the same details already exists""") # add the candidate to the constituency con.add_candidate(can) # add the candidate to the party par.add_candidate(can) # add the candidate to the election election.add_candidate(can) return election