Example #1
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))
Example #2
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)
Example #3
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))
Example #4
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)
Example #5
0
    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
Example #6
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()
Example #7
0
 def __init__(self):
     super().__init__()
     self.candidate_logic = CandidateLogic()
     self.election_candidate_logic = ElectionCandidateLogic()
     self.auth_methods = ["createElectable", "deleteElectable", "getUserElectables",
                          "createCandidate", "createParty"]
Example #8
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)
Example #9
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
Example #10
0
 def __init__(self):
     super().__init__()
     self.candidate_logic = CandidateLogic()
     self.election_candidate_logic = ElectionCandidateLogic()
     self.election_region_logic = ElectionRegionLogic()
Example #11
0
class ElectionLogic(Logic):
    def __init__(self):
        super().__init__()
        self.election_candidate = ElectionCandidateLogic()
        self.election_region_logic = ElectionRegionLogic()

    def get_election(self, _id):
        """Returns the election with given id. Uses the ElectionData instance to utilize it's get method"""
        election1 = self.get(_id)
        if election1:
            return self.jsonify(election1)
        return None

    def get_elections(self):
        """Returns all elections and uses the ElectionData instance to utilize it's get_all method"""
        elections = self.get_all()
        return self.jsonify(elections)

    def get_election_by_name(self, name):
        """Returns an election with given name, if not found returns none"""
        election = next((e for e in self.get_all() if e.name == name), None)
        if election:
            election = self.jsonify(election)
        return election

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

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

        for model in models:
            election_candidates = self.election_candidate.get_candidates_in_election(
                model.id)
            iter_election = {
                'electionID':
                str(model.id),
                'name':
                model.name,
                'candidates':
                self.election_candidate.jsonify(election_candidates),
                'regions':
                self.election_region_logic.jsonify(
                    self.election_region_logic.get_election_regions(model.id))
            }
            json_list.append(iter_election)

        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 json_list

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

        for model in models:
            election_candidates = self.election_candidate.get_candidates_in_election(
                model.id)
            iter_election = {
                'electionID':
                str(model.id),
                'name':
                model.name,
                'candidates':
                self.election_candidate.jsonify_with_candidate_image(
                    election_candidates),
                'regions':
                self.election_region_logic.jsonify(
                    self.election_region_logic.get_election_regions(model.id))
            }
            json_list.append(iter_election)

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

        return json_list