diff --git a/gradefetcher/gradefetcher.py b/gradefetcher/gradefetcher.py index e31ab68..e4aeb39 100644 --- a/gradefetcher/gradefetcher.py +++ b/gradefetcher/gradefetcher.py @@ -1,6 +1,7 @@ import logging import os import urllib.parse +from operator import truediv import pkg_resources import requests @@ -20,6 +21,16 @@ loader = ResourceLoader(__name__) +def grade_from_list(grades): + """take a list of integers and calculate grade from them""" + if len(grades) > 1: + total_grade = sum(grades) + grade = int(truediv(total_grade * 100, len(grades))) + else: + grade = grades[0] * 100 + return grade + + @XBlock.needs("i18n", "user") @XBlock.wants("settings") class GradeFetcherXBlock(XBlock, StudioEditableXBlockMixin): @@ -399,15 +410,7 @@ def grade_user(self, data, suffix=""): for result in grader_response.json()["results"]: if "grade" in result: grades.append(result["grade"]) - if len(grades) > 1: - from operator import truediv - - total_grade = 0 - for g in grades: - total_grade += g - grade = int(truediv(total_grade * 100, len(grades))) - else: - grade = grades[0] * 100 + grade = grade_from_list(grades) reasons = [] for result in grader_response.json()["results"]: if "grade" in result: diff --git a/gradefetcher/tests/test_gradefetcher.py b/gradefetcher/tests/test_gradefetcher.py new file mode 100644 index 0000000..3534dac --- /dev/null +++ b/gradefetcher/tests/test_gradefetcher.py @@ -0,0 +1,13 @@ +import unittest + +from gradefetcher.gradefetcher import grade_from_list + + +class GradeFetcherHelperTests(unittest.TestCase): + def test_grade_from_list(self): + assert grade_from_list([0]) == 0 + assert grade_from_list([1]) == 100 + assert grade_from_list([2]) == 200 + assert grade_from_list([0, 0]) == 0 + assert grade_from_list([1, 1]) == 100 + assert grade_from_list([1, 0]) == 50