From b2039944913a25b68fe876c3320beb92ccde59d1 Mon Sep 17 00:00:00 2001 From: Ben Bals Date: Mon, 1 Apr 2024 13:41:37 +0200 Subject: [PATCH] deal with empty ballots (and test correct behaviour) --- myhpi/polls/models.py | 3 ++- myhpi/tests/polls/test_ranked_choice_algorithm.py | 7 +++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/myhpi/polls/models.py b/myhpi/polls/models.py index 9017020f..d1ee293b 100644 --- a/myhpi/polls/models.py +++ b/myhpi/polls/models.py @@ -234,7 +234,8 @@ def calculate_ranking(self): names[option.pk] = option.name for ballot in ballots: - current_votes[heapq.heappop(ballot)[1].option.pk].append(ballot) + if ballot: + current_votes[heapq.heappop(ballot)[1].option.pk].append(ballot) def find_loosers(): threshold = min(map(lambda key: len(current_votes[key]), current_votes.keys())) diff --git a/myhpi/tests/polls/test_ranked_choice_algorithm.py b/myhpi/tests/polls/test_ranked_choice_algorithm.py index 4811e218..9aad7bd2 100644 --- a/myhpi/tests/polls/test_ranked_choice_algorithm.py +++ b/myhpi/tests/polls/test_ranked_choice_algorithm.py @@ -111,6 +111,13 @@ def test_no_ballots(self): [(1, "Alice", 0), (1, "Bob", 0), (1, "Charlie", 0), (1, "Dora", 0)], ) + def test_empty_ballots(self): + self.cast_ballots([[]]) + self.assertEqual( + self.poll.calculate_ranking(), + [(1, "Alice", 0), (1, "Bob", 0), (1, "Charlie", 0), (1, "Dora", 0)], + ) + def test_fast(self): self.cast_ballots(([["alice", "bob"]] * 1000) + ([["bob", "alice", "charlie"]] * 900))