Skip to content

Commit

Permalink
fix: fix user quiz stats "divide by zero" (#1997)
Browse files Browse the repository at this point in the history
  • Loading branch information
raphodn authored Feb 19, 2024
1 parent 876a834 commit c7fa438
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
4 changes: 3 additions & 1 deletion users/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,9 @@ def quiz_answer_success_count_ratio(self) -> float:
quiz.stats.aggregate(Avg("answer_success_count"))["answer_success_count__avg"]
/ quiz.stats.aggregate(Avg("question_count"))["question_count__avg"]
)
return round(answer_success_count_ratio / quiz_played_count * 100, 2)
if quiz_played_count:
return round((answer_success_count_ratio / quiz_played_count) * 100, 2)
return 0

@property
def quiz_like_count(self) -> int:
Expand Down
13 changes: 13 additions & 0 deletions users/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from core import constants
from questions.factories import QuestionFactory
from quizs.factories import QuizFactory
from stats.models import QuizAnswerEvent
from users import constants as user_constants
from users.factories import UserFactory
from users.models import User
Expand Down Expand Up @@ -32,6 +33,18 @@ def test_quiz_count(self):
def test_has_question(self):
self.assertTrue(self.user.has_question)

def test_quiz_answer_success_count_ratio(self):
self.assertEqual(self.user.quiz_answer_success_count_ratio, 0)
# add stats
QuizAnswerEvent.objects.create(quiz=self.quiz, answer_success_count=0, question_count=2)
self.assertEqual(self.user.quiz_answer_success_count_ratio, 0)
QuizAnswerEvent.objects.create(quiz=self.quiz, answer_success_count=1, question_count=2)
self.assertEqual(self.user.quiz_answer_success_count_ratio, 25.0)
QuizAnswerEvent.objects.create(quiz=self.quiz, answer_success_count=2, question_count=2)
self.assertEqual(self.user.quiz_answer_success_count_ratio, 50.0)
QuizAnswerEvent.objects.create(quiz=self.quiz, answer_success_count=2, question_count=2)
self.assertEqual(self.user.quiz_answer_success_count_ratio, 62.5)


class UserModelRoleTest(TestCase):
@classmethod
Expand Down

0 comments on commit c7fa438

Please sign in to comment.