Esempio n. 1
0
class TestElectionCandidateLogic(unittest.TestCase):
    def setUp(self):
        self.election = ElectionLogic()
        self.candidate = CandidateLogic()
        self.election_can = ElectionCandidateLogic()
        self.model_candidate1 = self.candidate.add(CandidateModel(None, 'Peter', 'URL', 'Vote for me'))
        self.model_candidate2 = self.candidate.add(CandidateModel(None, 'Gigi', 'URL', 'I rock'))
        self.model_election = self.election.add(ElectionModel(None, 'Election test'))
        self.model_election_can = self.election_can.add(
            ElectionCandidateModel(None, self.model_candidate1.id, self.model_election.id))
        self.model_election_can2 = self.election_can.add(ElectionCandidateModel(
            None, self.model_candidate2.id, self.model_election.id))

    def test_get_candidates_in_poll(self):
        candidates_in_poll = self.election_can.get_candidates_in_election(self.model_election.id)
        self.assertEqual(type(candidates_in_poll), list)
        id_lst = []
        for candidate in candidates_in_poll:
            id_lst.append(candidate.id)

        if self.model_candidate1.id not in id_lst:
            self.assertEqual(True, False)
        if self.model_candidate2.id not in id_lst:
            self.assertEqual(True, False)

    def test_get_error_candidates_in_poll(self):
        candidates_in_poll = self.election_can.get_candidates_in_election(0)
        self.assertEqual(candidates_in_poll, [])

    def tearDown(self):
        self.candidate.delete(self.model_candidate1.id)
        self.candidate.delete(self.model_candidate2.id)
        self.election.delete(self.model_election.id)
        self.election_can.delete(self.model_election_can.id)
        self.election_can.delete(self.model_election_can2.id)
Esempio n. 2
0
class TestElectionLogic(unittest.TestCase):
    def setUp(self):
        self.election_logic = ElectionLogic()
        self.candidate = CandidateLogic()
        self.election_can = ElectionCandidateLogic()
        self.election_data = ElectionData()
        self.model_candidate1 = CandidateModel(None, 'Peter', 'URL', 'Vote for me')
        self.model_candidate2 = CandidateModel(None, 'Gigi', 'URL', 'I rock')
        self.model_election = ElectionModel(None, 'Election test')
        self.election_logic.add(self.model_election)
        self.candidate.add(self.model_candidate1)
        self.candidate.add(self.model_candidate2)
        self.model_election_can = ElectionCandidateModel(None, self.model_candidate1.id, self.model_election.id)
        self.model_election_can2 = ElectionCandidateModel(None, self.model_candidate2.id, self.model_election.id)
        self.election_can.add(self.model_election_can)
        self.election_can.add(self.model_election_can2)
        self.model_candidate1_jsonify = self.candidate.jsonify(self.model_candidate1)
        self.model_candidate2_jsonify = self.candidate.jsonify(self.model_candidate2)

    def tearDown(self):
        self.candidate.delete(self.model_candidate1.id)
        self.candidate.delete(self.model_candidate2.id)
        self.election_logic.delete(self.model_election.id)
        self.election_can.delete(self.model_election_can.id)
        self.election_can.delete(self.model_candidate2.id)

    def test_get_election_by_id(self):
        election = self.election_logic.get_election(self.model_election.id)
        self.assertEqual(election, self.election_logic.jsonify(self.model_election))
        self.assertEqual(type(election), dict)

    def test_get_error_election(self):
        election = self.election_logic.get_election(999)
        self.assertEqual(election, None)
        election = self.election_logic.get_election('string')
        self.assertEqual(election, None)

    def test_get_all_elections(self):
        elections = self.election_logic.get_elections()
        self.assertEqual(type(elections), list)
        self.assertGreaterEqual(len(elections), 1)
        for x in elections:
            self.assertEqual(type(x), dict)

    def test_get_election_by_name(self):
        election = self.election_logic.get_election_by_name("Election test")
        self.assertEqual(type(election), dict)
        self.assertEqual(election, self.election_logic.jsonify(self.model_election))
        self.assertNotEqual(election, None)

    def test_get_error_election_by_name(self):
        election = self.election_logic.get_election_by_name("")
        self.assertEqual(election, None)
        self.assertNotEqual(type(election), dict)
        self.assertNotEqual(election, self.election_logic.jsonify(self.model_election))
        election = self.election_logic.get_election_by_name(1)
        self.assertEqual(election, None)
        self.assertNotEqual(type(election), dict)
        self.assertNotEqual(election, self.election_logic.jsonify(self.model_election))
Esempio n. 3
0
 def __init__(self):
     super().__init__()
     self.poll_vote_logic = PollVoteLogic()
     self.candidate_logic = CandidateLogic()
     self.election_candidate_logic = ElectionCandidateLogic()
     self.election_region_logic = ElectionRegionLogic()
     self.election_logic = ElectionLogic()
     self.source_logic = SourceLogic()
     self.region_logic = RegionLogic()
Esempio n. 4
0
 def setUp(self):
     self.election = ElectionLogic()
     self.candidate = CandidateLogic()
     self.election_can = ElectionCandidateLogic()
     self.model_candidate1 = self.candidate.add(CandidateModel(None, 'Peter', 'URL', 'Vote for me'))
     self.model_candidate2 = self.candidate.add(CandidateModel(None, 'Gigi', 'URL', 'I rock'))
     self.model_election = self.election.add(ElectionModel(None, 'Election test'))
     self.model_election_can = self.election_can.add(
         ElectionCandidateModel(None, self.model_candidate1.id, self.model_election.id))
     self.model_election_can2 = self.election_can.add(ElectionCandidateModel(
         None, self.model_candidate2.id, self.model_election.id))
Esempio n. 5
0
class ElectionCandidateLogic(Logic):
    def __init__(self):
        super().__init__()
        self.candidates = CandidateLogic()

    def safe_delete_candidate(self, candidate_id: int) -> None:
        data = self.get_all()
        new_data = []
        for el_candidate in data:
            if el_candidate.candidate_id != candidate_id:
                new_data.append(el_candidate)
        self.save(new_data)
        self.candidates.delete(candidate_id)

    def delete_election_candidates(self, election_id):
        """Delete candidates in election"""
        data = self.get_all()
        new_data = []
        for i in range(len(data)):
            if data[i].election_id != election_id:
                new_data.append(data[i])

        self.save(new_data)

    def get_candidates_in_election(self, election_id):
        """Returns all candidates in a specific election"""
        candidate_ids = []
        all_candidates = []
        # Fetch all candidate id's for given election_id
        for x in self.get_all():
            if x.election_id == election_id:
                candidate_ids.append(x.candidate_id)

        # Fetch all candidate models for candidate id's
        # Það væri betra að fetcha all einu sinni hér ertu að ýtra yfir alla kandídata aftur og aftur
        for _id in candidate_ids:
            all_candidates.append(self.candidates.get(_id))
        return all_candidates

    def jsonify(self, models):
        if models:
            return self.candidates.jsonify(models)
        return []

    def jsonify_with_candidate_image(self, models):
        if models:
            return self.candidates.jsonify_with_image(models)
        return []
Esempio n. 6
0
 def setUp(self):
     self.election_logic = ElectionLogic()
     self.candidate = CandidateLogic()
     self.election_can = ElectionCandidateLogic()
     self.election_data = ElectionData()
     self.model_candidate1 = CandidateModel(None, 'Peter', 'URL', 'Vote for me')
     self.model_candidate2 = CandidateModel(None, 'Gigi', 'URL', 'I rock')
     self.model_election = ElectionModel(None, 'Election test')
     self.election_logic.add(self.model_election)
     self.candidate.add(self.model_candidate1)
     self.candidate.add(self.model_candidate2)
     self.model_election_can = ElectionCandidateModel(None, self.model_candidate1.id, self.model_election.id)
     self.model_election_can2 = ElectionCandidateModel(None, self.model_candidate2.id, self.model_election.id)
     self.election_can.add(self.model_election_can)
     self.election_can.add(self.model_election_can2)
     self.model_candidate1_jsonify = self.candidate.jsonify(self.model_candidate1)
     self.model_candidate2_jsonify = self.candidate.jsonify(self.model_candidate2)
Esempio n. 7
0
 def __init__(self):
     super().__init__()
     self.candidates = CandidateLogic()
Esempio n. 8
0
 def __init__(self):
     super().__init__()
     self.candidate_logic = CandidateLogic()
     self.election_candidate_logic = ElectionCandidateLogic()
     self.auth_methods = ["createElectable", "deleteElectable", "getUserElectables",
                          "createCandidate", "createParty"]
Esempio n. 9
0
class CandidateInterface(Interface):
    def __init__(self):
        super().__init__()
        self.candidate_logic = CandidateLogic()
        self.election_candidate_logic = ElectionCandidateLogic()
        self.auth_methods = ["createElectable", "deleteElectable", "getUserElectables",
                             "createCandidate", "createParty"]

    def createElectable(self, args: dict, auth) -> dict:
        desired_args = ["name", "description"]
        optional_args = ["imageUrl"]
        try:
            req_args = self.get_args_or_key_error(desired_args, args)
        except KeyError as error:
            return self.set_msg_or_error(str(error), 400)

        optional_args = self.get_possible_args(optional_args, args)
        image_url = ""
        if optional_args["imageUrl"] is not None:
            image_url = optional_args["imageUrl"]

        new_electable = CandidateModel(id=None, name=req_args["name"], image_url=image_url, info=req_args["bio"])
        electable = self.candidate_logic.add(new_electable)
        ret_str = self.create_relation(auth, electable.id)
        if ret_str == "":
            return self.set_msg_or_error(self.candidate_logic.jsonify(electable), 0)
        self.candidate_logic.delete(electable)
        return self.set_msg_or_error(ret_str, 401)

    def createCandidate(self, args: dict, auth) -> dict:
        return self.createElectable(args, auth)

    def createParty(self, args: dict, auth) -> dict:
        return self.createElectable(args, auth)

    def deleteElectable(self, args: dict, auth) -> dict:
        desired_args = ["electableID"]
        try:
            req_args = self.get_args_or_key_error(desired_args, args)
        except KeyError as error:
            return self.set_msg_or_error(str(error), 400)

        electable_id = self.convert_id(req_args["electableID"])
        if electable_id is None:
            return self.set_msg_or_error("electableID invalid.", 400)

        ret_str = self.delete_relation(auth, electable_id)
        if ret_str != "":
            return self.set_msg_or_error(ret_str, 401)

        self.election_candidate_logic.safe_delete_candidate(electable_id)
        return self.set_msg_or_error("Successfully removed electable.", 0)

    def getUserElectables(self, args: dict, auth) -> dict:
        if not auth.logged_in:
            return self.set_msg_or_error("Must be logged in.", 401)
        id_list = self.get_user_creations(auth)
        electables = self.candidate_logic.get_all()
        ret_models = []
        for electable in electables:
            if electable.id in id_list:
                ret_models.append(electable)

        return self.set_msg_or_error(self.candidate_logic.jsonify(ret_models), 0)

    def getElectables(self, args: dict) -> dict:
        """Returns all candidates for a given election. Returns an empty array if no election with this ID exists,
        or the election has no candidate."""
        # Return empty array if no election with this id exists
        # return [Candidate]
        desired_args = ['electionID']
        try:
            req_args = self.get_args_or_key_error(desired_args, args)
        except KeyError as error:
            return self.set_msg_or_error(str(error), 400)

        election_id = self.convert_id(req_args['electionID'])
        if not election_id:
            return self.set_msg_or_error('electionID must be a number.', 400)

        election_candidates = self.election_candidate_logic.get_candidates_in_election(election_id)
        if not election_candidates:
            return self.set_msg_or_error([], 0)
        return self.set_msg_or_error(self.election_candidate_logic.jsonify(election_candidates), 0)

    def getElectableDetails(self, args: dict) -> dict:
        """Returns a single candidate with the given ID. Returns an empty string if no candidate with this ID exists."""
        # return Candidate
        # return empty string if no candidate
        desired_args = ['electableID']
        try:
            req_args = self.get_args_or_key_error(desired_args, args)
        except KeyError as error:
            return self.set_msg_or_error(str(error), 400)

        candidate_id = self.convert_id(req_args['electableID'])
        if not candidate_id:
            return self.set_msg_or_error('electableID must be a number.', 400)

        candidate = self.candidate_logic.get(_id=candidate_id)
        if not candidate:
            return self.set_msg_or_error("Electable does not exist.", 404)
        return self.set_msg_or_error(self.candidate_logic.jsonify(candidate), 0)

    def getAllCandidates(self, args: dict):
        candidates = self.candidate_logic.get_all()
        if not candidates:
            return self.set_msg_or_error([], 0)
        return self.set_msg_or_error(self.candidate_logic.jsonify(candidates), 0)

    def getAllParties(self, args: dict):
        # not available in our system
        return self.set_msg_or_error([], 0)
Esempio n. 10
0
class PollLogic(Logic):
    def __init__(self):
        super().__init__()
        self.poll_vote_logic = PollVoteLogic()
        self.candidate_logic = CandidateLogic()
        self.election_candidate_logic = ElectionCandidateLogic()
        self.election_region_logic = ElectionRegionLogic()
        self.election_logic = ElectionLogic()
        self.source_logic = SourceLogic()
        self.region_logic = RegionLogic()

    def safe_delete_election(self, election_id):
        """Safely remove election. Removes all objects that depend on the election being deleted.
        Had to put it in logic layer because of circular import if placed in election... This would not be a
        problem if jsonify didn't need election logic...
        We should consider making jsonify a separate entity e.g Adapter"""

        election_candidate_logic = ElectionCandidateLogic()
        election_region_logic = ElectionRegionLogic()
        # Delete related election_candidate relations
        election_candidate_logic.delete_election_candidates(election_id=election_id)
        # Delete related election_region relations
        election_region_logic.delete_election_regions(election_id=election_id)
        # Delete related polls (Polls deletes votes)
        self.delete_election_polls(election_id=election_id)

        # Delete election
        removed = self.election_logic.delete(election_id)
        return removed

    @staticmethod
    def validate_date(x_date: str):
        try:
            iso_date = date.fromisoformat(x_date)
            return True
        except ValueError:
            return False

    def delete_election_polls(self, election_id):
        data = self.get_polls_in_election(election_id=election_id)
        poll_ids_in_election = []
        if not data:
            return

        for e_poll in data:
            poll_ids_in_election.append(e_poll.id)
            if e_poll.election_id == election_id:
                self.poll_vote_logic.delete_poll_votes(e_poll.id)

        polls = self.get_all()
        new_polls = []
        for e_poll in polls:
            if e_poll.id not in poll_ids_in_election:
                new_polls.append(e_poll)

        self.save(new_polls)

    def safe_delete(self, _id):
        """Safely remove object. Removes all objects that depend on the object being deleted"""
        data = self.get_all()
        removed = None
        for i in range(len(data)):
            if data[i].id == _id:
                # Deleting related poll votes
                self.poll_vote_logic.delete_poll_votes(data[i].id)
                removed = data.pop(i)
                break

        self.save(data)
        return removed

    def get_poll(self, _id):
        """Returns specific poll jsonified"""
        this_poll = self.get(_id)
        if this_poll:
            return self.jsonify(this_poll)
        return None

    def get_polls_in_election(self, election_id):
        """ Returns all the polls in the given election as models"""
        election_poll_list = []
        data = self.get_all()
        for poll in data:
            if poll.election_id == election_id:
                election_poll_list.append(poll)
        if len(election_poll_list) == 0:
            return None
        return election_poll_list

    def get_poll_end_date(self, _id):
        """Returns the end date of a specific poll as a dictionary
        {'end_date': poll_with_id.end_date} or None"""
        poll = self.get(_id)
        if poll:
            return {'end_date': poll.end_date}
        return None

    def get_poll_per_region(self, election, region):
        """ Returns all polls in the region from the given election. Gets all the polls and
         excludes the one that are not from the election and don't have any votes from the region.
         RETURNS IN JSONIFIED FORMAT"""
        all_polls = self.get_polls_in_election(election.id)
        poll_list = []
        for poll in all_polls:
            votes_in_poll = self.poll_vote_logic.get_all_by_poll(poll.id)
            for vote in votes_in_poll:
                if vote.region_id == region.id and poll not in poll_list:
                    poll_list.append(poll)
        return self.jsonify(poll_list)

    def get_polls(self):
        """Returns all polls in jsonified format"""
        return self.jsonify(self.get_all())

    def get_overall_election_poll(self, election_id):
        """Returns the overall poll result of a specific election in the form {'candidate': number of votes from all
        the polls} """
        polls_in_election = self.get_polls_in_election(election_id)
        votes_in_election = []
        if polls_in_election:
            for poll in polls_in_election:
                votes_in_poll = self.poll_vote_logic.get_all_by_poll(poll.id)
                if votes_in_poll:
                    votes_in_election.append(votes_in_poll)
            if len(polls_in_election) == 0:
                return {}

            votes_in_election = [item for elem in votes_in_election for item in elem]
            election_result = {}
            for vote in votes_in_election:
                candidate_id = self.poll_vote_logic.get_vote_option(vote.id)
                candidate = self.candidate_logic.get(candidate_id)
                if candidate:
                    if candidate.name not in election_result.keys():
                        election_result[candidate.name] = 1
                    else:
                        election_result[candidate.name] += 1
            return election_result
        return None

    def get_overall_election_poll2(self, election_id):
        """Returns the overall poll result of a specific election in the form of a poll"""
        polls_in_election = self.get_polls_in_election(election_id)
        if not polls_in_election:
            return None

        if type(polls_in_election) is not list:
            polls_in_election = [polls_in_election]

        polls_json = self.jsonify_with_candidate_image(polls_in_election)

        first_poll = polls_json[0]
        first_poll["pollID"] = 0
        for i in range(1, len(polls_json)):
            fp_data_array = first_poll["dataArray"]
            data_array = polls_json[i]['dataArray']
            for y in range(len(data_array)):
                fp_region_data = fp_data_array[y]
                region_data = data_array[y]
                data = region_data['data']
                fp_data = fp_region_data['data']
                for z in range(len(data)):
                    votes = data[z]['votes']
                    fp_data[z]['votes'] += votes

        return first_poll

    def _get_region_in_election(self, election_id):
        """Returns a list of the regions that have votes in the election"""
        regions = []
        data = self.get_all()
        for poll in data:
            if poll.election_id == election_id:
                votes = self.poll_vote_logic.get_all_by_poll(poll.id)
                for vote in votes:
                    if vote.region_id not in regions:
                        regions.append(vote.region_id)
        return regions

    def get_average_poll(self, election):
        """Returns a single poll object with the average votes on electable for the election.
         Method jsonify the poll from the election.
          gets all the votes from from each region that participated in the any poll in the election.
           divides the votes with number of polls """
        polls = self.get_polls_in_election(election.id)
        regions_in_election = self._get_region_in_election(election.id)
        votes_per_region = self.poll_vote_logic.get_votes_in_election_per_region(regions_in_election, election.id)
        polls_jsons = self.jsonify(polls)
        if type(polls_jsons) != list:
            polls_jsons = [polls_jsons]
        for model in polls_jsons:
            if model.get('dataArray'):
                for obj in model['dataArray']:
                    try:
                        region_id = obj.get('region')['regionID']
                        candidate = int(obj.get('data')[0]['candidate']['electableID'])
                        average_vote = round(votes_per_region.get(int(region_id))[candidate]/len(polls_jsons), 2)
                        obj.get('data')[0]['votes'] = average_vote
                    except:
                        pass # object is not vote related, then pass

        if type(polls_jsons) == list:
            return polls_jsons[0]
        return polls_jsons

    def get_election_statistics(self, election_id):
        """Returns how many votes, in percentage each candidate holds for a given election"""
        results = self.get_overall_election_poll(election_id)
        total_votes = 0
        election_statistics = {}
        for value in results.values():
            total_votes += value
        for key, value in results.items():
            election_statistics[key] = str(value/total_votes * 100) + '%'
        return election_statistics

    def get_polls_from_source_name(self, source_name):
        """Returns a list of polls with a given source name. Returns None if nothing found.
        Accounts for lower case name search and partial name search (using if str in target function)
        Returns jsonified polls"""
        source = self.source_logic.get_source_by_name(source_name)
        polls = []

        if not source:
            return None

        for _poll in self.get_all():
            if _poll.source_id == source.id:
                polls.append(_poll)

        if polls:
            return self.jsonify(polls)
        return None

    def get_polls_from_specific_time_frame(self, start_date, end_date):
        """"Returns polls that were performed in the time between begin_date and end_date.
        Uses the 'fromisoformat' method, requiring input to be in the format: 2020-10-25.
        Returns list of jsonified poll objects.
        Returns None if nothing found."""
        return_polls = []
        _start_date = date.fromisoformat(start_date)
        _end_date = date.fromisoformat(end_date)
        for x in self.get_all():
            if _start_date <= date.fromisoformat(x.start_date) and _end_date >= date.fromisoformat(
                    x.end_date):
                return_polls.append(x)

        if not return_polls:
            return None
        return self.jsonify(return_polls)

    def get_historical_polls_for_election(self, election_id, start_date, end_date):
        """Returns polls from a specific election in a specific time frame.
        Uses the 'fromisoformat' method, requiring input to be in the format: 2020-10-25.
        Returns list of jsonified poll objects or None if nothing found."""

        return_polls = []
        election = self.election_logic.get_election(election_id)
        designated_begin_date = date.fromisoformat(start_date)
        designated_end_date = date.fromisoformat(end_date)

        for x in self.get_all():
            if designated_begin_date <= date.fromisoformat(x.start_date) and designated_end_date >= date.fromisoformat(
                    x.end_date):
                if str(x.election_id) == str(election_id):
                    return_polls.append(x)

        if not return_polls:
            return None
        return self.jsonify(return_polls)


    def jsonify(self, models):
        json_list = []
        if not models:
            return []

        if type(models) != list:
            models = [models]

        for model in models:
            election = self.election_logic.get(model.election_id)
            source = self.source_logic.get(model.source_id)
            poll_data = {
                'pollID': str(model.id),
                'election': self.election_logic.jsonify(election),
                'organization': self.source_logic.jsonify(source),
                'startDate': model.start_date,
                'endDate': model.end_date,
                "dataArray": self.poll_vote_logic.jsonify(model)
            }
            json_list.append(poll_data)

        if len(json_list) == 1:
            return json_list[0]

        return json_list

    def jsonify_with_candidate_image(self, models):
        json_list = []
        if not models:
            return []

        if type(models) != list:
            models = [models]

        for model in models:
            election = self.election_logic.get(model.election_id)
            source = self.source_logic.get(model.source_id)
            poll_data = {
                'pollID': str(model.id),
                'election': self.election_logic.jsonify_with_candidate_image(election),
                'organization': self.source_logic.jsonify(source),
                'startDate': model.start_date,
                'endDate': model.end_date,
                "dataArray": self.poll_vote_logic.jsonify(model)
            }
            json_list.append(poll_data)

        if len(json_list) == 1:
            return json_list[0]

        return json_list
Esempio n. 11
0
class PollVoteLogic(Logic):
    def __init__(self):
        super().__init__()
        self.candidate_logic = CandidateLogic()
        self.election_candidate_logic = ElectionCandidateLogic()
        self.election_region_logic = ElectionRegionLogic()

    def vote(self, region_id, poll_id, electable_id) -> None:
        new_model = PollVoteModel(id=None, region_id=region_id, poll_id=poll_id, candidate_id=electable_id)
        self.add(new_model)

    def delete_poll_votes(self, poll_id) -> None:
        data = self.get_all()
        new_data = []
        for i in range(len(data)):
            if data[i].poll_id != poll_id:
                new_data.append(data[i])

        self.save(new_data)
        return

    def get_vote_option(self, vote_id):
        """Return the choice of the voter"""
        data = self.get_all()
        for vote in data:
            if vote.id == vote_id:
                return vote.candidate_id
        return None

    def get_poll_from_vote(self, vote_id):
        data = self.get_all()
        for vote in data:
            if vote.id == vote_id:
                return vote.region_id
        return None

    def get_all_by_poll(self, poll_id, _count=False):
        """Returns all vote objects on specific poll"""
        poll_votes = []
        data = self.get_all()
        for vote in data:
            if vote.poll_id == poll_id:
                poll_votes.append(vote)
        if _count:
            return len(poll_votes)
        return poll_votes

    def get_all_by_election_and_region(self, region_id, election_id):
        """Returns the votes in a election for candidates in the given region"""
        vote_list = {}
        data = self.get_all()
        candidate_data = self.election_candidate_logic.get_candidates_in_election(election_id)
        for vote in data:
            if vote.region_id == region_id and self.candidate_logic.get(vote.candidate_id) in candidate_data:
                if vote.candidate_id not in vote_list:
                    vote_list[vote.candidate_id] = 1
                else:
                    vote_list[vote.candidate_id] += 1
        return vote_list

    def get_all_votes_on_poll_candidate(self, poll_id, candidate_id, _count=False):
        """Returns all votes on a poll on a specific Candidate"""
        poll_votes_on_candidate = []
        data = self.get_all()
        for vote in data:
            if vote.poll_id == poll_id and vote.candidate_id == candidate_id:
                poll_votes_on_candidate.append(vote)

        if _count:
            return len(poll_votes_on_candidate)
        return poll_votes_on_candidate

    def get_votes_in_election_per_region(self, regions, election_id):
        """Returns a dictionary with votes for each candidate in the region """
        region_votes = {}
        for i in regions:
            if i not in region_votes:
                region_votes[i] = self.get_all_by_election_and_region(i, election_id)
        return region_votes

    def get_all_poll_votes_in_region(self, poll_id, region_id, _count=False):
        """Returns all votes on a poll for a specific region"""
        poll_votes_on_region = []
        data = self.get_all()
        for vote in data:
            if vote.poll_id == poll_id and vote.region_id == region_id:
                poll_votes_on_region.append(vote)
        if _count:
            return len(poll_votes_on_region)
        return poll_votes_on_region

    def get_all_poll_votes_on_candidate_in_region(self, poll_id, candidate_id, region_id, _count=False):
        """Returns all votes in a poll that were on a specific candidate in a specific region"""
        poll_votes_on_region_candidate = []
        data = self.get_all()
        for vote in data:
            if vote.poll_id == poll_id and vote.region_id == region_id and vote.candidate_id == candidate_id:
                poll_votes_on_region_candidate.append(vote)
        if _count:
            return len(poll_votes_on_region_candidate)
        return poll_votes_on_region_candidate

    def jsonify(self, poll_model):
        """Enter a poll model. This returns the equivalent of regionPoll in the interface"""
        models = self.get_all_by_poll(poll_model.id)
        json_list = []
        if not models:
            return []

        if type(models) != list:
            models = [models]

        poll_candidates = self.election_candidate_logic.get_candidates_in_election(election_id=poll_model.election_id)
        poll_regions = self.election_region_logic.get_election_regions(_id=poll_model.election_id)

        hash_bucket_counter = {}
        candidate_dicts = {}
        # building a candidate dictionary to put into hack bucket
        for candidate in poll_candidates:
            candidate_dicts[candidate.id] = {"candidate": self.election_candidate_logic.jsonify(candidate), "votes": 0}

        # Building a has bucket
        for region in poll_regions:
            hash_bucket_counter[region.id] = copy.deepcopy(candidate_dicts)

        # Iterating only once over all votes to distribute them into the correct region / candidate
        for model in models:
            # If not all poll id's are the same
            if model.poll_id != poll_model.id:
                raise KeyError("ALL VOTES ENTERED IN THE VOTE JSONIFY MUST HAVE SAME POLL ID")

            try:
                # Count vote for desired region and candidate
                hash_bucket_counter[model.region_id][model.candidate_id]["votes"] += 1
            except KeyError:
                # If vote data is flawed raise error
                for region in poll_regions:
                    if model.region_id == region.id:
                        raise KeyError("The election for which vote " + str(model.id) + " is, does not contain candidate "
                                       + str(model.candidate_id))

                raise KeyError("The election for which vote " + str(model.id) + " is, does not contain region "
                               + str(model.region_id))

        # Set it up into the requested format
        for region in poll_regions:
            poll_vote_data_array = {
                'region': self.election_region_logic.jsonify(region),
                'data': self.create_data_array(hash_bucket_counter[region.id])
            }
            json_list.append(poll_vote_data_array)
        if len(json_list) == 1:
            return json_list[0]

        return json_list

    @staticmethod
    def create_data_array(hash_bucket_region):
        data = []
        for key in hash_bucket_region:
            data.append(hash_bucket_region[key])
        return data
Esempio n. 12
0
 def __init__(self):
     super().__init__()
     self.candidate_logic = CandidateLogic()
     self.election_candidate_logic = ElectionCandidateLogic()
     self.election_region_logic = ElectionRegionLogic()
Esempio n. 13
0
 def setUp(self):
     self.candidate = CandidateLogic()
     self.model1 = CandidateModel(None, 'Peter', 'URL', 'Vote for me')
     self.model2 = CandidateModel(None, 'John', 'URL', 'I am the greatest')
     self.candidate.add(self.model1)
     self.candidate.add(self.model2)
Esempio n. 14
0
class TestCandidateLogic(unittest.TestCase):
    def setUp(self):
        self.candidate = CandidateLogic()
        self.model1 = CandidateModel(None, 'Peter', 'URL', 'Vote for me')
        self.model2 = CandidateModel(None, 'John', 'URL', 'I am the greatest')
        self.candidate.add(self.model1)
        self.candidate.add(self.model2)

    def test_get_candidates(self):
        candidates = self.candidate.get_candidates()
        self.assertEqual(type(candidates), list)
        self.assertGreaterEqual(len(candidates), 2)

    def test_get_candidate_by_id(self):
        candidate = self.candidate.get_candidate_by_id(self.model1.id)
        self.assertEqual(candidate, self.candidate.jsonify(self.model1))
        self.assertNotEqual(candidate, self.candidate.jsonify(self.model2))

    def test_get_error_candidate_by_id_(self):
        candidate = self.candidate.get_candidate_by_id(850000)
        self.assertEqual(candidate, None)

    def test_get_candidate_by_name(self):
        candidate = self.candidate.get_candidate_by_name("John")
        self.assertEqual(candidate, self.candidate.jsonify(self.model2))
        self.assertNotEqual(candidate, self.candidate.jsonify(self.model1))

    def test_get_error_candidate_by_name(self):
        candidate = self.candidate.get_candidate_by_name("")
        self.assertEqual(candidate, None)

    def tearDown(self):
        self.candidate.delete(self.model1.id)
        self.candidate.delete(self.model2.id)