def test_set_recipe_popularity(self): recipe = TestRecipe() for i in range(3): TestRating(recipe=recipe, vote=True) expected_rating = Decimal(wilson_score_interval(3, 0)).quantize(Decimal(".0001")) recipe = Recipe.objects.get(id=recipe.id) self.assertEqual(expected_rating, recipe.popularity) # only sets popularity for ratings stored in the db rating = Rating(recipe=recipe, rated_by=TestUser(), vote=False) rating.set_recipe_popularity() recipe = Recipe.objects.get(id=recipe.id) self.assertEqual(expected_rating, recipe.popularity) # default case, and no error/change when calling twice on same # unchanged rating rating.save() rating.set_recipe_popularity() new_rating = Decimal(wilson_score_interval(3, 1)).quantize(Decimal(".0001")) recipe = Recipe.objects.get(id=recipe.id) self.assertNotEqual(expected_rating, new_rating) self.assertEqual(new_rating, recipe.popularity) rating.set_recipe_popularity() recipe = Recipe.objects.get(id=recipe.id) self.assertEqual(new_rating, recipe.popularity)
def test_save(self): recipe = TestRecipe() self.assertEqual(0, recipe.popularity) for i in range(1, 5): TestRating(recipe=recipe, vote=True) recipe = Recipe.objects.get(id=recipe.id) wsi = wilson_score_interval(i, 0) self.assertEqual(Decimal(wsi).quantize(Decimal(".0001")), recipe.popularity) for i in range(1, 5): TestRating(recipe=recipe, vote=False) recipe = Recipe.objects.get(id=recipe.id) wsi = wilson_score_interval(4, i) self.assertEqual(Decimal(wsi).quantize(Decimal(".0001")), recipe.popularity)
def set_recipe_popularity(self): """ Updates the popularity on self.recipe based on the newest vote """ ratings = Rating.objects.filter(recipe=self.recipe) ups = ratings.filter(vote=True).count() downs = ratings.filter(vote=False).count() self.recipe.popularity = str(wilson_score_interval(ups, downs)) self.recipe.likes = ups self.recipe.dislikes = downs self.recipe.save()