Commit b2e7be92 by Will Daly

Migrate submissions app from the edx-ora2 repository

parent 7d98d907
from django.contrib import admin
from django.core.urlresolvers import reverse
from django.utils import html
from submissions.models import Score, ScoreSummary, StudentItem, Submission
class StudentItemAdminMixin(object):
"""Mix this class into anything that has a student_item fkey."""
search_fields = (
'student_item__course_id',
'student_item__student_id',
'student_item__item_id',
'student_item__id'
)
def course_id(self, obj):
return obj.student_item.course_id
course_id.admin_order_field = 'student_item__course_id'
def item_id(self, obj):
return obj.student_item.item_id
item_id.admin_order_field = 'student_item__item_id'
def student_id(self, obj):
return obj.student_item.student_id
student_id.admin_order_field = 'student_item__student_id'
def student_item_id(self, obj):
url = reverse(
'admin:submissions_studentitem_change',
args=[obj.student_item.id]
)
return u'<a href="{}">{}</a>'.format(url, obj.student_item.id)
student_item_id.allow_tags = True
student_item_id.admin_order_field = 'student_item__id'
student_item_id.short_description = 'S.I. ID'
class StudentItemAdmin(admin.ModelAdmin):
list_display = ('id', 'course_id', 'item_type', 'item_id', 'student_id')
list_filter = ('item_type',)
search_fields = ('id', 'course_id', 'item_type', 'item_id', 'student_id')
readonly_fields = ('course_id', 'item_type', 'item_id', 'student_id')
class SubmissionAdmin(admin.ModelAdmin, StudentItemAdminMixin):
list_display = (
'id', 'uuid',
'course_id', 'item_id', 'student_id', 'student_item_id',
'attempt_number', 'submitted_at',
)
list_display_links = ('id', 'uuid')
list_filter = ('student_item__item_type',)
readonly_fields = (
'student_item_id',
'course_id', 'item_id', 'student_id',
'attempt_number', 'submitted_at', 'created_at',
'raw_answer', 'all_scores',
)
search_fields = ('id', 'uuid') + StudentItemAdminMixin.search_fields
# We're creating our own explicit link and displaying parts of the
# student_item in separate fields -- no need to display this as well.
exclude = ('student_item',)
def all_scores(self, submission):
return "\n".join(
"{}/{} - {}".format(
score.points_earned, score.points_possible, score.created_at
)
for score in Score.objects.filter(submission=submission)
)
class ScoreAdmin(admin.ModelAdmin, StudentItemAdminMixin):
list_display = (
'id',
'course_id', 'item_id', 'student_id', 'student_item_id',
'points', 'created_at'
)
list_filter = ('student_item__item_type',)
readonly_fields = (
'student_item_id',
'student_item',
'submission',
'points_earned',
'points_possible',
'reset',
)
search_fields = ('id', ) + StudentItemAdminMixin.search_fields
def points(self, score):
return u"{}/{}".format(score.points_earned, score.points_possible)
class ScoreSummaryAdmin(admin.ModelAdmin, StudentItemAdminMixin):
list_display = (
'id',
'course_id', 'item_id', 'student_id', 'student_item_id',
'latest', 'highest',
)
search_fields = ('id', ) + StudentItemAdminMixin.search_fields
readonly_fields = (
'student_item_id', 'student_item', 'highest_link', 'latest_link'
)
exclude = ('highest', 'latest')
def highest_link(self, score_summary):
url = reverse(
'admin:submissions_score_change', args=[score_summary.highest.id]
)
return u'<a href="{}">{}</a>'.format(url, score_summary.highest)
highest_link.allow_tags = True
highest_link.short_description = 'Highest'
def latest_link(self, score_summary):
url = reverse(
'admin:submissions_score_change', args=[score_summary.latest.id]
)
return u'<a href="{}">{}</a>'.format(url, score_summary.latest)
latest_link.allow_tags = True
latest_link.short_description = 'Latest'
admin.site.register(Score, ScoreAdmin)
admin.site.register(StudentItem, StudentItemAdmin)
admin.site.register(Submission, SubmissionAdmin)
admin.site.register(ScoreSummary, ScoreSummaryAdmin)
\ No newline at end of file
"""
Public interface for the submissions app.
"""
import copy
import logging
import json
from django.core.cache import cache
from django.db import IntegrityError, DatabaseError
from dogapi import dog_stats_api
from submissions.serializers import (
SubmissionSerializer, StudentItemSerializer, ScoreSerializer, JsonFieldError
)
from submissions.models import Submission, StudentItem, Score, ScoreSummary
logger = logging.getLogger("submissions.api")
class SubmissionError(Exception):
"""An error that occurs during submission actions.
This error is raised when the submission API cannot perform a requested
action.
"""
pass
class SubmissionInternalError(SubmissionError):
"""An error internal to the Submission API has occurred.
This error is raised when an error occurs that is not caused by incorrect
use of the API, but rather internal implementation of the underlying
services.
"""
pass
class SubmissionNotFoundError(SubmissionError):
"""This error is raised when no submission is found for the request.
If a state is specified in a call to the API that results in no matching
Submissions, this error may be raised.
"""
pass
class SubmissionRequestError(SubmissionError):
"""This error is raised when there was a request-specific error
This error is reserved for problems specific to the use of the API.
"""
def __init__(self, field_errors):
Exception.__init__(self, repr(field_errors))
self.field_errors = copy.deepcopy(field_errors)
def create_submission(student_item_dict, answer, submitted_at=None,
attempt_number=None):
"""Creates a submission for assessment.
Generic means by which to submit an answer for assessment.
Args:
student_item_dict (dict): The student_item this
submission is associated with. This is used to determine which
course, student, and location this submission belongs to.
answer (JSON-serializable): The answer given by the student to be assessed.
submitted_at (datetime): The date in which this submission was submitted.
If not specified, defaults to the current date.
attempt_number (int): A student may be able to submit multiple attempts
per question. This allows the designated attempt to be overridden.
If the attempt is not specified, it will take the most recent
submission, as specified by the submitted_at time, and use its
attempt_number plus one.
Returns:
dict: A representation of the created Submission. The submission
contains five attributes: student_item, attempt_number, submitted_at,
created_at, and answer. 'student_item' is the ID of the related student
item for the submission. 'attempt_number' is the attempt this submission
represents for this question. 'submitted_at' represents the time this
submission was submitted, which can be configured, versus the
'created_at' date, which is when the submission is first created.
Raises:
SubmissionRequestError: Raised when there are validation errors for the
student item or submission. This can be caused by the student item
missing required values, the submission being too long, the
attempt_number is negative, or the given submitted_at time is invalid.
SubmissionInternalError: Raised when submission access causes an
internal error.
Examples:
>>> student_item_dict = dict(
>>> student_id="Tim",
>>> item_id="item_1",
>>> course_id="course_1",
>>> item_type="type_one"
>>> )
>>> create_submission(student_item_dict, "The answer is 42.", datetime.utcnow, 1)
{
'student_item': 2,
'attempt_number': 1,
'submitted_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 649284 tzinfo=<UTC>),
'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>),
'answer': u'The answer is 42.'
}
"""
student_item_model = _get_or_create_student_item(student_item_dict)
if attempt_number is None:
try:
submissions = Submission.objects.filter(
student_item=student_item_model)[:1]
except DatabaseError:
error_message = u"An error occurred while filtering submissions for student item: {}".format(
student_item_dict)
logger.exception(error_message)
raise SubmissionInternalError(error_message)
attempt_number = submissions[0].attempt_number + 1 if submissions else 1
model_kwargs = {
"student_item": student_item_model.pk,
"answer": answer,
"attempt_number": attempt_number,
}
if submitted_at:
model_kwargs["submitted_at"] = submitted_at
try:
submission_serializer = SubmissionSerializer(data=model_kwargs)
if not submission_serializer.is_valid():
raise SubmissionRequestError(submission_serializer.errors)
submission_serializer.save()
sub_data = submission_serializer.data
_log_submission(sub_data, student_item_dict)
return sub_data
except JsonFieldError:
error_message = u"Could not serialize JSON field in submission {} for student item {}".format(
model_kwargs, student_item_dict
)
raise SubmissionRequestError(error_message)
except DatabaseError:
error_message = u"An error occurred while creating submission {} for student item: {}".format(
model_kwargs,
student_item_dict
)
logger.exception(error_message)
raise SubmissionInternalError(error_message)
def get_submission(submission_uuid):
"""Retrieves a single submission by uuid.
Args:
submission_uuid (str): Identifier for the submission.
Raises:
SubmissionNotFoundError: Raised if the submission does not exist.
SubmissionRequestError: Raised if the search parameter is not a string.
SubmissionInternalError: Raised for unknown errors.
Examples:
>>> get_submission("20b78e0f32df805d21064fc912f40e9ae5ab260d")
{
'student_item': 2,
'attempt_number': 1,
'submitted_at': datetime.datetime(2014, 1, 29, 23, 14, 52, 649284, tzinfo=<UTC>),
'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>),
'answer': u'The answer is 42.'
}
"""
if not isinstance(submission_uuid, basestring):
raise SubmissionRequestError(
"submission_uuid ({!r}) must be a string type".format(submission_uuid)
)
cache_key = "submissions.submission.{}".format(submission_uuid)
try:
cached_submission_data = cache.get(cache_key)
except Exception as ex:
# The cache backend could raise an exception
# (for example, memcache keys that contain spaces)
logger.exception("Error occurred while retrieving submission from the cache")
cached_submission_data = None
if cached_submission_data:
logger.info("Get submission {} (cached)".format(submission_uuid))
return cached_submission_data
try:
submission = Submission.objects.get(uuid=submission_uuid)
submission_data = SubmissionSerializer(submission).data
cache.set(cache_key, submission_data)
except Submission.DoesNotExist:
logger.error("Submission {} not found.".format(submission_uuid))
raise SubmissionNotFoundError(
u"No submission matching uuid {}".format(submission_uuid)
)
except Exception as exc:
# Something very unexpected has just happened (like DB misconfig)
err_msg = "Could not get submission due to error: {}".format(exc)
logger.exception(err_msg)
raise SubmissionInternalError(err_msg)
logger.info("Get submission {}".format(submission_uuid))
return submission_data
def get_submission_and_student(uuid):
"""
Retrieve a submission by its unique identifier, including the associated student item.
Args:
uuid (str): the unique identifier of the submission.
Returns:
Serialized Submission model (dict) containing a serialized StudentItem model
Raises:
SubmissionNotFoundError: Raised if the submission does not exist.
SubmissionRequestError: Raised if the search parameter is not a string.
SubmissionInternalError: Raised for unknown errors.
"""
# This may raise API exceptions
submission = get_submission(uuid)
# Retrieve the student item from the cache
cache_key = "submissions.student_item.{}".format(submission['student_item'])
try:
cached_student_item = cache.get(cache_key)
except:
# The cache backend could raise an exception
# (for example, memcache keys that contain spaces)
logger.exception("Error occurred while retrieving student item from the cache")
cached_student_item = None
if cached_student_item is not None:
submission['student_item'] = cached_student_item
else:
# There is probably a more idiomatic way to do this using the Django REST framework
try:
student_item = StudentItem.objects.get(id=submission['student_item'])
submission['student_item'] = StudentItemSerializer(student_item).data
cache.set(cache_key, submission['student_item'])
except Exception as ex:
err_msg = "Could not get submission due to error: {}".format(ex)
logger.exception(err_msg)
raise SubmissionInternalError(err_msg)
return submission
def get_submissions(student_item_dict, limit=None):
"""Retrieves the submissions for the specified student item,
ordered by most recent submitted date.
Returns the submissions relative to the specified student item. Exception
thrown if no submission is found relative to this location.
Args:
student_item_dict (dict): The location of the problem this submission is
associated with, as defined by a course, student, and item.
limit (int): Optional parameter for limiting the returned number of
submissions associated with this student item. If not specified, all
associated submissions are returned.
Returns:
List dict: A list of dicts for the associated student item. The submission
contains five attributes: student_item, attempt_number, submitted_at,
created_at, and answer. 'student_item' is the ID of the related student
item for the submission. 'attempt_number' is the attempt this submission
represents for this question. 'submitted_at' represents the time this
submission was submitted, which can be configured, versus the
'created_at' date, which is when the submission is first created.
Raises:
SubmissionRequestError: Raised when the associated student item fails
validation.
SubmissionNotFoundError: Raised when a submission cannot be found for
the associated student item.
Examples:
>>> student_item_dict = dict(
>>> student_id="Tim",
>>> item_id="item_1",
>>> course_id="course_1",
>>> item_type="type_one"
>>> )
>>> get_submissions(student_item_dict, 3)
[{
'student_item': 2,
'attempt_number': 1,
'submitted_at': datetime.datetime(2014, 1, 29, 23, 14, 52, 649284, tzinfo=<UTC>),
'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>),
'answer': u'The answer is 42.'
}]
"""
student_item_model = _get_or_create_student_item(student_item_dict)
try:
submission_models = Submission.objects.filter(
student_item=student_item_model)
except DatabaseError:
error_message = (
u"Error getting submission request for student item {}"
.format(student_item_dict)
)
logger.exception(error_message)
raise SubmissionNotFoundError(error_message)
if limit:
submission_models = submission_models[:limit]
return SubmissionSerializer(submission_models, many=True).data
def get_score(student_item):
"""Get the score for a particular student item
Each student item should have a unique score. This function will return the
score if it is available. A score is only calculated for a student item if
it has completed the workflow for a particular assessment module.
Args:
student_item (dict): The dictionary representation of a student item.
Function returns the score related to this student item.
Returns:
score (dict): The score associated with this student item. None if there
is no score found.
Raises:
SubmissionInternalError: Raised if a score cannot be retrieved because
of an internal server error.
Examples:
>>> student_item = {
>>> "student_id":"Tim",
>>> "course_id":"TestCourse",
>>> "item_id":"u_67",
>>> "item_type":"openassessment"
>>> }
>>>
>>> get_score(student_item)
[{
'student_item': 2,
'submission': 2,
'points_earned': 8,
'points_possible': 20,
'created_at': datetime.datetime(2014, 2, 7, 18, 30, 1, 807911, tzinfo=<UTC>)
}]
"""
try:
student_item_model = StudentItem.objects.get(**student_item)
score = ScoreSummary.objects.get(student_item=student_item_model).latest
except (ScoreSummary.DoesNotExist, StudentItem.DoesNotExist):
return None
# By convention, scores are hidden if "points possible" is set to 0.
# This can occur when an instructor has reset scores for a student.
if score.is_hidden():
return None
else:
return ScoreSerializer(score).data
def get_scores(course_id, student_id):
"""Return a dict mapping item_ids -> (points_earned, points_possible).
This method would be used by an LMS to find all the scores for a given
student in a given course.
Scores that are "hidden" (because they have points earned set to zero)
are excluded from the results.
Args:
course_id (str): Course ID, used to do a lookup on the `StudentItem`.
student_id (str): Student ID, used to do a lookup on the `StudentItem`.
Returns:
dict: The keys are `item_id`s (`str`) and the values are tuples of
`(points_earned, points_possible)`. All points are integer values and
represent the raw, unweighted scores. Submissions does not have any
concept of weights. If there are no entries matching the `course_id` or
`student_id`, we simply return an empty dictionary. This is not
considered an error because there might be many queries for the progress
page of a person who has never submitted anything.
Raises:
SubmissionInternalError: An unexpected error occurred while resetting scores.
"""
try:
score_summaries = ScoreSummary.objects.filter(
student_item__course_id=course_id,
student_item__student_id=student_id,
).select_related('latest', 'student_item')
except DatabaseError:
msg = u"Could not fetch scores for course {}, student {}".format(
course_id, student_id
)
logger.exception(msg)
raise SubmissionInternalError(msg)
scores = {
summary.student_item.item_id:
(summary.latest.points_earned, summary.latest.points_possible)
for summary in score_summaries
if not summary.latest.is_hidden()
}
return scores
def get_latest_score_for_submission(submission_uuid):
"""
Retrieve the latest score for a particular submission.
Args:
submission_uuid (str): The UUID of the submission to retrieve.
Returns:
dict: The serialized score model, or None if no score is available.
"""
try:
score = Score.objects.filter(
submission__uuid=submission_uuid
).order_by("-id").select_related("submission")[0]
if score.is_hidden():
return None
except IndexError:
return None
return ScoreSerializer(score).data
def reset_score(student_id, course_id, item_id):
"""
Reset scores for a specific student on a specific problem.
Note: this does *not* delete `Score` models from the database,
since these are immutable. It simply creates a new score with
the "reset" flag set to True.
Args:
student_id (unicode): The ID of the student for whom to reset scores.
course_id (unicode): The ID of the course containing the item to reset.
item_id (unicode): The ID of the item for which to reset scores.
Returns:
None
Raises:
SubmissionInternalError: An unexpected error occurred while resetting scores.
"""
# Retrieve the student item
try:
student_item = StudentItem.objects.get(
student_id=student_id, course_id=course_id, item_id=item_id
)
except StudentItem.DoesNotExist:
# If there is no student item, then there is no score to reset,
# so we can return immediately.
return
# Create a "reset" score
try:
Score.create_reset_score(student_item)
except DatabaseError:
msg = (
u"Error occurred while reseting scores for"
u" item {item_id} in course {course_id} for student {student_id}"
).format(item_id=item_id, course_id=course_id, student_id=student_id)
logger.exception(msg)
raise SubmissionInternalError(msg)
else:
msg = u"Score reset for item {item_id} in course {course_id} for student {student_id}".format(
item_id=item_id, course_id=course_id, student_id=student_id
)
logger.info(msg)
def set_score(submission_uuid, points_earned, points_possible):
"""Set a score for a particular submission.
Sets the score for a particular submission. This score is calculated
externally to the API.
Args:
submission_uuid (str): UUID for the submission (must exist).
points_earned (int): The earned points for this submission.
points_possible (int): The total points possible for this particular
student item.
Returns:
None
Raises:
SubmissionInternalError: Thrown if there was an internal error while
attempting to save the score.
SubmissionRequestError: Thrown if the given student item or submission
are not found.
Examples:
>>> set_score("a778b933-9fb3-11e3-9c0f-040ccee02800", 11, 12)
{
'student_item': 2,
'submission': 1,
'points_earned': 11,
'points_possible': 12,
'created_at': datetime.datetime(2014, 2, 7, 20, 6, 42, 331156, tzinfo=<UTC>)
}
"""
try:
submission_model = Submission.objects.get(uuid=submission_uuid)
except Submission.DoesNotExist:
raise SubmissionNotFoundError(
u"No submission matching uuid {}".format(submission_uuid)
)
except DatabaseError:
error_msg = u"Could not retrieve student item: {} or submission {}.".format(
submission_uuid
)
logger.exception(error_msg)
raise SubmissionRequestError(error_msg)
score = ScoreSerializer(
data={
"student_item": submission_model.student_item.pk,
"submission": submission_model.pk,
"points_earned": points_earned,
"points_possible": points_possible,
}
)
if not score.is_valid():
logger.exception(score.errors)
raise SubmissionInternalError(score.errors)
# When we save the score, a score summary will be created if
# it does not already exist.
# When the database's isolation level is set to repeatable-read,
# it's possible for a score summary to exist for this student item,
# even though we cannot retrieve it.
# In this case, we assume that someone else has already created
# a score summary and ignore the error.
try:
score_model = score.save()
_log_score(score_model)
except IntegrityError:
pass
def _log_submission(submission, student_item):
"""
Log the creation of a submission.
Args:
submission (dict): The serialized submission model.
student_item (dict): The serialized student item model.
Returns:
None
"""
logger.info(
u"Created submission uuid={submission_uuid} for "
u"(course_id={course_id}, item_id={item_id}, "
u"anonymous_student_id={anonymous_student_id})"
.format(
submission_uuid=submission["uuid"],
course_id=student_item["course_id"],
item_id=student_item["item_id"],
anonymous_student_id=student_item["student_id"]
)
)
tags = [
u"course_id:{course_id}".format(course_id=student_item['course_id']),
u"item_id:{item_id}".format(item_id=student_item['item_id']),
u"item_type:{item_type}".format(item_type=student_item['item_type']),
]
dog_stats_api.increment('submissions.submission.count', tags=tags)
# Submission answer is a JSON serializable, so we need to serialize it to measure its size in bytes
try:
answer_size = len(json.dumps(submission['answer']))
except (ValueError, TypeError):
msg = u"Could not serialize submission answer to calculate its length: {}".format(submission['answer'])
logger.exception(msg)
else:
dog_stats_api.histogram('submissions.submission.size', answer_size, tags=tags)
def _log_score(score):
"""
Log the creation of a score.
Args:
score (Score): The score model.
Returns:
None
"""
logger.info(
"Score of ({}/{}) set for submission {}"
.format(score.points_earned, score.points_possible, score.submission.uuid)
)
tags = [
u"course_id:{course_id}".format(course_id=score.student_item.course_id),
u"item_id:{item_id}".format(item_id=score.student_item.item_id),
u"item_type:{item_type}".format(item_type=score.student_item.item_type),
]
time_delta = score.created_at - score.submission.created_at
dog_stats_api.histogram(
'submissions.score.seconds_since_submission',
time_delta.total_seconds(),
tags=tags
)
score_percentage = score.to_float()
if score_percentage is not None:
dog_stats_api.histogram(
'submissions.score.score_percentage',
score_percentage,
tags=tags
)
dog_stats_api.increment('submissions.score.count', tags=tags)
def _get_or_create_student_item(student_item_dict):
"""Gets or creates a Student Item that matches the values specified.
Attempts to get the specified Student Item. If it does not exist, the
specified parameters are validated, and a new Student Item is created.
Args:
student_item_dict (dict): The dict containing the student_id, item_id,
course_id, and item_type that uniquely defines a student item.
Returns:
StudentItem: The student item that was retrieved or created.
Raises:
SubmissionInternalError: Thrown if there was an internal error while
attempting to create or retrieve the specified student item.
SubmissionRequestError: Thrown if the given student item parameters fail
validation.
Examples:
>>> student_item_dict = dict(
>>> student_id="Tim",
>>> item_id="item_1",
>>> course_id="course_1",
>>> item_type="type_one"
>>> )
>>> _get_or_create_student_item(student_item_dict)
{'item_id': 'item_1', 'item_type': 'type_one', 'course_id': 'course_1', 'student_id': 'Tim'}
"""
try:
try:
return StudentItem.objects.get(**student_item_dict)
except StudentItem.DoesNotExist:
student_item_serializer = StudentItemSerializer(
data=student_item_dict)
if not student_item_serializer.is_valid():
raise SubmissionRequestError(student_item_serializer.errors)
return student_item_serializer.save()
except DatabaseError:
error_message = u"An error occurred creating student item: {}".format(
student_item_dict)
logger.exception(error_message)
raise SubmissionInternalError(error_message)
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'StudentItem'
db.create_table('submissions_studentitem', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('student_id', self.gf('django.db.models.fields.CharField')(max_length=255, db_index=True)),
('course_id', self.gf('django.db.models.fields.CharField')(max_length=255, db_index=True)),
('item_id', self.gf('django.db.models.fields.CharField')(max_length=255, db_index=True)),
('item_type', self.gf('django.db.models.fields.CharField')(max_length=100)),
))
db.send_create_signal('submissions', ['StudentItem'])
# Adding unique constraint on 'StudentItem', fields ['course_id', 'student_id', 'item_id']
db.create_unique('submissions_studentitem', ['course_id', 'student_id', 'item_id'])
# Adding model 'Submission'
db.create_table('submissions_submission', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('uuid', self.gf('django.db.models.fields.CharField')(db_index=True, max_length=36, blank=True)),
('student_item', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['submissions.StudentItem'])),
('attempt_number', self.gf('django.db.models.fields.PositiveIntegerField')()),
('submitted_at', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now, db_index=True)),
('created_at', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now, db_index=True)),
('answer', self.gf('django.db.models.fields.TextField')(blank=True)),
))
db.send_create_signal('submissions', ['Submission'])
# Adding model 'Score'
db.create_table('submissions_score', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('student_item', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['submissions.StudentItem'])),
('submission', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['submissions.Submission'], null=True)),
('points_earned', self.gf('django.db.models.fields.PositiveIntegerField')(default=0)),
('points_possible', self.gf('django.db.models.fields.PositiveIntegerField')(default=0)),
('created_at', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now, db_index=True)),
))
db.send_create_signal('submissions', ['Score'])
def backwards(self, orm):
# Removing unique constraint on 'StudentItem', fields ['course_id', 'student_id', 'item_id']
db.delete_unique('submissions_studentitem', ['course_id', 'student_id', 'item_id'])
# Deleting model 'StudentItem'
db.delete_table('submissions_studentitem')
# Deleting model 'Submission'
db.delete_table('submissions_submission')
# Deleting model 'Score'
db.delete_table('submissions_score')
models = {
'submissions.score': {
'Meta': {'object_name': 'Score'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'points_earned': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'points_possible': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'student_item': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.StudentItem']"}),
'submission': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.Submission']", 'null': 'True'})
},
'submissions.studentitem': {
'Meta': {'unique_together': "(('course_id', 'student_id', 'item_id'),)", 'object_name': 'StudentItem'},
'course_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'item_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'item_type': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'student_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'})
},
'submissions.submission': {
'Meta': {'ordering': "['-submitted_at', '-id']", 'object_name': 'Submission'},
'answer': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'attempt_number': ('django.db.models.fields.PositiveIntegerField', [], {}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'student_item': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.StudentItem']"}),
'submitted_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'uuid': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '36', 'blank': 'True'})
}
}
complete_apps = ['submissions']
\ No newline at end of file
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'ScoreSummary'
db.create_table('submissions_scoresummary', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('student_item', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['submissions.StudentItem'], unique=True)),
('highest', self.gf('django.db.models.fields.related.ForeignKey')(related_name='+', to=orm['submissions.Score'])),
('latest', self.gf('django.db.models.fields.related.ForeignKey')(related_name='+', to=orm['submissions.Score'])),
))
db.send_create_signal('submissions', ['ScoreSummary'])
def backwards(self, orm):
# Deleting model 'ScoreSummary'
db.delete_table('submissions_scoresummary')
models = {
'submissions.score': {
'Meta': {'object_name': 'Score'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'points_earned': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'points_possible': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'student_item': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.StudentItem']"}),
'submission': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.Submission']", 'null': 'True'})
},
'submissions.scoresummary': {
'Meta': {'object_name': 'ScoreSummary'},
'highest': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'+'", 'to': "orm['submissions.Score']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'latest': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'+'", 'to': "orm['submissions.Score']"}),
'student_item': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.StudentItem']", 'unique': 'True'})
},
'submissions.studentitem': {
'Meta': {'unique_together': "(('course_id', 'student_id', 'item_id'),)", 'object_name': 'StudentItem'},
'course_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'item_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'item_type': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'student_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'})
},
'submissions.submission': {
'Meta': {'ordering': "['-submitted_at', '-id']", 'object_name': 'Submission'},
'answer': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'attempt_number': ('django.db.models.fields.PositiveIntegerField', [], {}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'student_item': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.StudentItem']"}),
'submitted_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'uuid': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '36', 'blank': 'True'})
}
}
complete_apps = ['submissions']
\ No newline at end of file
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Submission.answer'
db.delete_column('submissions_submission', 'answer')
# Adding field 'Submission.raw_answer'
db.add_column('submissions_submission', 'raw_answer',
self.gf('django.db.models.fields.TextField')(default='', blank=True),
keep_default=False)
def backwards(self, orm):
# Adding field 'Submission.answer'
db.add_column('submissions_submission', 'answer',
self.gf('django.db.models.fields.TextField')(default='', blank=True),
keep_default=False)
# Deleting field 'Submission.raw_answer'
db.delete_column('submissions_submission', 'raw_answer')
models = {
'submissions.score': {
'Meta': {'object_name': 'Score'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'points_earned': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'points_possible': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'student_item': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.StudentItem']"}),
'submission': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.Submission']", 'null': 'True'})
},
'submissions.scoresummary': {
'Meta': {'object_name': 'ScoreSummary'},
'highest': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'+'", 'to': "orm['submissions.Score']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'latest': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'+'", 'to': "orm['submissions.Score']"}),
'student_item': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.StudentItem']", 'unique': 'True'})
},
'submissions.studentitem': {
'Meta': {'unique_together': "(('course_id', 'student_id', 'item_id'),)", 'object_name': 'StudentItem'},
'course_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'item_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'item_type': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'student_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'})
},
'submissions.submission': {
'Meta': {'ordering': "['-submitted_at', '-id']", 'object_name': 'Submission'},
'attempt_number': ('django.db.models.fields.PositiveIntegerField', [], {}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'raw_answer': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'student_item': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.StudentItem']"}),
'submitted_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'uuid': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '36', 'blank': 'True'})
}
}
complete_apps = ['submissions']
\ No newline at end of file
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Score.reset'
db.add_column('submissions_score', 'reset',
self.gf('django.db.models.fields.BooleanField')(default=False),
keep_default=False)
def backwards(self, orm):
# Deleting field 'Score.reset'
db.delete_column('submissions_score', 'reset')
models = {
'submissions.score': {
'Meta': {'object_name': 'Score'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'points_earned': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'points_possible': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'reset': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'student_item': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.StudentItem']"}),
'submission': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.Submission']", 'null': 'True'})
},
'submissions.scoresummary': {
'Meta': {'object_name': 'ScoreSummary'},
'highest': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'+'", 'to': "orm['submissions.Score']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'latest': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'+'", 'to': "orm['submissions.Score']"}),
'student_item': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.StudentItem']", 'unique': 'True'})
},
'submissions.studentitem': {
'Meta': {'unique_together': "(('course_id', 'student_id', 'item_id'),)", 'object_name': 'StudentItem'},
'course_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'item_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'item_type': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'student_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'})
},
'submissions.submission': {
'Meta': {'ordering': "['-submitted_at', '-id']", 'object_name': 'Submission'},
'attempt_number': ('django.db.models.fields.PositiveIntegerField', [], {}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'raw_answer': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'student_item': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.StudentItem']"}),
'submitted_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'uuid': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '36', 'blank': 'True'})
}
}
complete_apps = ['submissions']
\ No newline at end of file
"""
Submission models hold student responses to problems, scores, and a history of
those scores. It is intended to be a general purpose store that is usable by
different problem types, and is therefore ignorant of ORA workflow.
NOTE: We've switched to migrations, so if you make any edits to this file, you
need to then generate a matching migration for it using:
./manage.py schemamigration submissions --auto
"""
import json
import logging
from django.db import models, DatabaseError
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils.timezone import now
from django_extensions.db.fields import UUIDField
logger = logging.getLogger(__name__)
class StudentItem(models.Model):
"""Represents a single item for a single course for a single user.
This is typically an XBlock problem, but could be something more generic
like class participation.
"""
# The anonymized Student ID that the XBlock sees, not their real ID.
student_id = models.CharField(max_length=255, blank=False, db_index=True)
# Not sure yet whether these are legacy course_ids or new course_ids
course_id = models.CharField(max_length=255, blank=False, db_index=True)
# Version independent, course-local content identifier, i.e. the problem
# This is the block_id for XBlock items.
item_id = models.CharField(max_length=255, blank=False, db_index=True)
# What kind of problem is this? The XBlock tag if it's an XBlock
item_type = models.CharField(max_length=100)
def __repr__(self):
return repr(dict(
student_id=self.student_id,
course_id=self.course_id,
item_id=self.item_id,
item_type=self.item_type,
))
def __unicode__(self):
return u"({0.student_id}, {0.course_id}, {0.item_type}, {0.item_id})".format(self)
class Meta:
unique_together = (
# For integrity reasons, and looking up all of a student's items
("course_id", "student_id", "item_id"),
)
class Submission(models.Model):
"""A single response by a student for a given problem in a given course.
A student may have multiple submissions for the same problem. Submissions
should never be mutated. If the student makes another Submission, or if we
have to make corrective Submissions to fix bugs, those should be new
objects. We want to keep Submissions immutable both for audit purposes, and
because it makes caching trivial.
"""
MAXSIZE = 1024*100 # 100KB
uuid = UUIDField(version=1, db_index=True)
student_item = models.ForeignKey(StudentItem)
# Which attempt is this? Consecutive Submissions do not necessarily have
# increasing attempt_number entries -- e.g. re-scoring a buggy problem.
attempt_number = models.PositiveIntegerField()
# submitted_at is separate from created_at to support re-scoring and other
# processes that might create Submission objects for past user actions.
submitted_at = models.DateTimeField(default=now, db_index=True)
# When this row was created.
created_at = models.DateTimeField(editable=False, default=now, db_index=True)
# The answer (JSON-serialized)
raw_answer = models.TextField(blank=True)
def __repr__(self):
return repr(dict(
uuid=self.uuid,
student_item=self.student_item,
attempt_number=self.attempt_number,
submitted_at=self.submitted_at,
created_at=self.created_at,
raw_answer=self.raw_answer,
))
def __unicode__(self):
return u"Submission {}".format(self.uuid)
class Meta:
ordering = ["-submitted_at", "-id"]
class Score(models.Model):
"""What the user scored for a given StudentItem at a given time.
Note that while a Score *can* be tied to a Submission, it doesn't *have* to.
Specifically, if we want to have scores for things that are not a part of
the courseware (like "class participation"), there would be no corresponding
Submission.
"""
student_item = models.ForeignKey(StudentItem)
submission = models.ForeignKey(Submission, null=True)
points_earned = models.PositiveIntegerField(default=0)
points_possible = models.PositiveIntegerField(default=0)
created_at = models.DateTimeField(editable=False, default=now, db_index=True)
# Flag to indicate that this score should reset the current "highest" score
reset = models.BooleanField(default=False)
@property
def submission_uuid(self):
"""
Retrieve the submission UUID associated with this score.
If the score isn't associated with a submission (for example, if this is
a "reset" score or a a non-courseware item like "class participation"),
then this will return None.
Returns:
str or None
"""
if self.submission is not None:
return self.submission.uuid
else:
return None
def to_float(self):
"""
Calculate (points earned) / (points possible).
If points possible is None (e.g. this is a "hidden" score)
then return None.
Returns:
float or None
"""
if self.points_possible == 0:
return None
return float(self.points_earned) / self.points_possible
def __repr__(self):
return repr(dict(
student_item=self.student_item,
submission=self.submission,
created_at=self.created_at,
points_earned=self.points_earned,
points_possible=self.points_possible,
))
def is_hidden(self):
"""
By convention, a score of 0/0 is not displayed to users.
Hidden scores are filtered by the submissions API.
Returns:
bool: Whether the score should be hidden.
"""
return self.points_possible == 0
@classmethod
def create_reset_score(cls, student_item):
"""
Create a "reset" score (a score with a null submission).
Only scores created after the most recent "reset" score
should be used to determine a student's effective score.
Args:
student_item (StudentItem): The student item model.
Returns:
Score: The newly created "reset" score.
Raises:
DatabaseError: An error occurred while creating the score
"""
# By setting the "reset" flag, we ensure that the "highest"
# score in the score summary will point to this score.
# By setting points earned and points possible to 0,
# we ensure that this score will be hidden from the user.
return cls.objects.create(
student_item=student_item,
submission=None,
points_earned=0,
points_possible=0,
reset=True,
)
def __unicode__(self):
return u"{0.points_earned}/{0.points_possible}".format(self)
class ScoreSummary(models.Model):
"""Running store of the highest and most recent Scores for a StudentItem."""
student_item = models.ForeignKey(StudentItem, unique=True)
highest = models.ForeignKey(Score, related_name="+")
latest = models.ForeignKey(Score, related_name="+")
class Meta:
verbose_name_plural = "Score Summaries"
@receiver(post_save, sender=Score)
def update_score_summary(sender, **kwargs):
"""
Listen for new Scores and update the relevant ScoreSummary.
Args:
sender: not used
Kwargs:
instance (Score): The score model whose save triggered this receiver.
"""
score = kwargs['instance']
try:
score_summary = ScoreSummary.objects.get(
student_item=score.student_item
)
score_summary.latest = score
# A score with the "reset" flag set will always replace the current highest score
if score.reset:
score_summary.highest = score
# The conversion to a float may return None if points possible is zero
# In Python, None is always less than an integer, so any score
# with non-null points possible will take precedence.
elif score.to_float() > score_summary.highest.to_float():
score_summary.highest = score
score_summary.save()
except ScoreSummary.DoesNotExist:
ScoreSummary.objects.create(
student_item=score.student_item,
highest=score,
latest=score,
)
except DatabaseError as err:
logger.exception(
u"Error while updating score summary for student item {}"
.format(score.student_item)
)
"""
Serializers are created to ensure models do not have to be accessed outside the
scope of the Tim APIs.
"""
import json
from rest_framework import serializers
from submissions.models import StudentItem, Submission, Score
class JsonFieldError(Exception):
"""
An error occurred while serializing/deserializing JSON.
"""
pass
class JsonField(serializers.WritableField):
"""
JSON-serializable field.
"""
def to_native(self, obj):
"""
Deserialize the JSON string.
Args:
obj (str): The JSON string stored in the database.
Returns:
JSON-serializable
Raises:
JsonFieldError: The field could not be deserialized.
"""
try:
return json.loads(obj)
except (TypeError, ValueError):
raise JsonFieldError(u"Could not deserialize as JSON: {}".format(obj))
def from_native(self, data):
"""
Serialize an object to JSON.
Args:
data (JSON-serializable): The data to serialize.
Returns:
str
Raises:
ValueError: The data could not be serialized as JSON.
"""
try:
return json.dumps(data)
except (TypeError, ValueError):
raise JsonFieldError(u"Could not serialize as JSON: {}".format(data))
class StudentItemSerializer(serializers.ModelSerializer):
class Meta:
model = StudentItem
fields = ('student_id', 'course_id', 'item_id', 'item_type')
class SubmissionSerializer(serializers.ModelSerializer):
answer = JsonField(source='raw_answer')
def validate_answer(self, attrs, source):
"""Check that the answer is within an acceptable size range."""
value = attrs[source]
if len(value) > Submission.MAXSIZE:
raise serializers.ValidationError("Maximum answer size exceeded.")
return attrs
class Meta:
model = Submission
fields = (
'uuid',
'student_item',
'attempt_number',
'submitted_at',
'created_at',
# Computed
'answer',
)
class ScoreSerializer(serializers.ModelSerializer):
submission_uuid = serializers.Field(source='submission_uuid')
class Meta:
model = Score
fields = (
'student_item',
'submission',
'points_earned',
'points_possible',
'created_at',
# Computed
'submission_uuid',
)
<h3>Submissions for {{ student_id }} > {{ course_id }} > {{ item_id }}:</h3>
{{ error }} <br/>
{{ submissions|length }} total submissions. <br/>
<br/>
<table border=1>
<th>Submission UUID</th>
<th>Student Item</th>
<th>Attempt Number</th>
<th>Answer</th>
<th>Submitted At</th>
<th>Created At</th>
{% for submission in submissions%}
<tr>
<td>{{ submission.uuid }}</td>
<td>{{ submission.student_item }}</td>
<td>{{ submission.attempt_number }}</td>
<td>{{ submission.answer }}</td>
<td>{{ submission.submitted_at }}</td>
<td>{{ submission.created_at }}</td>
</tr>
{% endfor %}
</table>
{
"no_item_type": {
"student_id": "Bad Tim",
"course_id": "451",
"item_id": "2"
},
"no_student_id": {
"course_id": "Course_One",
"item_id": "5",
"item_type": "Peer"
},
"just_student_and_course": {
"student_id": "Tim",
"course_id": "Course_One"
},
"just_student_id": {
"student_id": "Tim"
},
"just_item_id_and_type": {
"item_id": "5",
"item_type": "Peer"
},
"just_course_id": {
"course_id": "Course_One"
},
"just_item_id": {
"item_id": "5"
},
"bad_item_id_empty": {
"student_id": "Tim",
"course_id": "Course_One",
"item_id": "",
"item_type": "Peer"
}
}
\ No newline at end of file
{
"unicode_characters": {
"student_id": "学生",
"course_id": "漢字",
"item_id": "这是中国",
"item_type": "窥视"
},
"basic_student_item": {
"student_id": "Tom",
"course_id": "Demo_Course",
"item_id": "1",
"item_type": "Peer"
}
}
\ No newline at end of file
import datetime
import copy
from ddt import ddt, file_data
from django.db import DatabaseError
from django.core.cache import cache
from django.test import TestCase
from nose.tools import raises
from mock import patch
import pytz
from submissions import api as api
from submissions.models import ScoreSummary, Submission, StudentItem
from submissions.serializers import StudentItemSerializer
STUDENT_ITEM = dict(
student_id="Tim",
course_id="Demo_Course",
item_id="item_one",
item_type="Peer_Submission",
)
SECOND_STUDENT_ITEM = dict(
student_id="Alice",
course_id="Demo_Course",
item_id="item_one",
item_type="Peer_Submission",
)
ANSWER_ONE = u"this is my answer!"
ANSWER_TWO = u"this is my other answer!"
ANSWER_THREE = u'' + 'c' * (Submission.MAXSIZE + 1)
@ddt
class TestSubmissionsApi(TestCase):
"""
Testing Submissions
"""
def setUp(self):
"""
Clear the cache.
"""
cache.clear()
def test_create_submission(self):
submission = api.create_submission(STUDENT_ITEM, ANSWER_ONE)
student_item = self._get_student_item(STUDENT_ITEM)
self._assert_submission(submission, ANSWER_ONE, student_item.pk, 1)
def test_create_huge_submission_fails(self):
with self.assertRaises(api.SubmissionRequestError):
api.create_submission(STUDENT_ITEM, ANSWER_THREE)
def test_get_submission_and_student(self):
submission = api.create_submission(STUDENT_ITEM, ANSWER_ONE)
# Retrieve the submission by its uuid
retrieved = api.get_submission_and_student(submission['uuid'])
self.assertItemsEqual(submission, retrieved)
# Should raise an exception if the student item does not exist
with self.assertRaises(api.SubmissionNotFoundError):
api.get_submission_and_student(u'no such uuid')
def test_get_submissions(self):
api.create_submission(STUDENT_ITEM, ANSWER_ONE)
api.create_submission(STUDENT_ITEM, ANSWER_TWO)
submissions = api.get_submissions(STUDENT_ITEM)
student_item = self._get_student_item(STUDENT_ITEM)
self._assert_submission(submissions[1], ANSWER_ONE, student_item.pk, 1)
self._assert_submission(submissions[0], ANSWER_TWO, student_item.pk, 2)
def test_get_submission(self):
# Test base case that we can create a submission and get it back
sub_dict1 = api.create_submission(STUDENT_ITEM, ANSWER_ONE)
sub_dict2 = api.get_submission(sub_dict1["uuid"])
self.assertEqual(sub_dict1, sub_dict2)
# Test invalid inputs
with self.assertRaises(api.SubmissionRequestError):
api.get_submission(20)
with self.assertRaises(api.SubmissionRequestError):
api.get_submission({})
# Test not found
with self.assertRaises(api.SubmissionNotFoundError):
api.get_submission("notarealuuid")
with self.assertRaises(api.SubmissionNotFoundError):
api.get_submission("0" * 50) # This is bigger than our field size
@patch.object(Submission.objects, 'get')
@raises(api.SubmissionInternalError)
def test_get_submission_deep_error(self, mock_get):
# Test deep explosions are wrapped
mock_get.side_effect = DatabaseError("Kaboom!")
api.get_submission("000000000000000")
def test_two_students(self):
api.create_submission(STUDENT_ITEM, ANSWER_ONE)
api.create_submission(SECOND_STUDENT_ITEM, ANSWER_TWO)
submissions = api.get_submissions(STUDENT_ITEM)
self.assertEqual(1, len(submissions))
student_item = self._get_student_item(STUDENT_ITEM)
self._assert_submission(submissions[0], ANSWER_ONE, student_item.pk, 1)
submissions = api.get_submissions(SECOND_STUDENT_ITEM)
self.assertEqual(1, len(submissions))
student_item = self._get_student_item(SECOND_STUDENT_ITEM)
self._assert_submission(submissions[0], ANSWER_TWO, student_item.pk, 1)
@file_data('data/valid_student_items.json')
def test_various_student_items(self, valid_student_item):
api.create_submission(valid_student_item, ANSWER_ONE)
student_item = self._get_student_item(valid_student_item)
submission = api.get_submissions(valid_student_item)[0]
self._assert_submission(submission, ANSWER_ONE, student_item.pk, 1)
def test_get_latest_submission(self):
past_date = datetime.datetime(2007, 9, 12, 0, 0, 0, 0, pytz.UTC)
more_recent_date = datetime.datetime(2007, 9, 13, 0, 0, 0, 0, pytz.UTC)
api.create_submission(STUDENT_ITEM, ANSWER_ONE, more_recent_date)
api.create_submission(STUDENT_ITEM, ANSWER_TWO, past_date)
# Test a limit on the submissions
submissions = api.get_submissions(STUDENT_ITEM, 1)
self.assertEqual(1, len(submissions))
self.assertEqual(ANSWER_ONE, submissions[0]["answer"])
self.assertEqual(more_recent_date.year,
submissions[0]["submitted_at"].year)
def test_set_attempt_number(self):
api.create_submission(STUDENT_ITEM, ANSWER_ONE, None, 2)
submissions = api.get_submissions(STUDENT_ITEM)
student_item = self._get_student_item(STUDENT_ITEM)
self._assert_submission(submissions[0], ANSWER_ONE, student_item.pk, 2)
@raises(api.SubmissionRequestError)
@file_data('data/bad_student_items.json')
def test_error_checking(self, bad_student_item):
api.create_submission(bad_student_item, -100)
@raises(api.SubmissionRequestError)
def test_error_checking_submissions(self):
api.create_submission(STUDENT_ITEM, ANSWER_ONE, None, -1)
@patch.object(Submission.objects, 'filter')
@raises(api.SubmissionInternalError)
def test_error_on_submission_creation(self, mock_filter):
mock_filter.side_effect = DatabaseError("Bad things happened")
api.create_submission(STUDENT_ITEM, ANSWER_ONE)
def test_create_non_json_answer(self):
with self.assertRaises(api.SubmissionRequestError):
api.create_submission(STUDENT_ITEM, datetime.datetime.now())
def test_load_non_json_answer(self):
# This should never happen, if folks are using the public API.
# Create a submission with a raw answer that is NOT valid JSON
submission = api.create_submission(STUDENT_ITEM, ANSWER_ONE)
sub_model = Submission.objects.get(uuid=submission['uuid'])
sub_model.raw_answer = ''
sub_model.save()
with self.assertRaises(api.SubmissionInternalError):
api.get_submission(sub_model.uuid)
with self.assertRaises(api.SubmissionInternalError):
api.get_submission_and_student(sub_model.uuid)
@patch.object(StudentItemSerializer, 'save')
@raises(api.SubmissionInternalError)
def test_create_student_item_validation(self, mock_save):
mock_save.side_effect = DatabaseError("Bad things happened")
api.create_submission(STUDENT_ITEM, ANSWER_ONE)
def test_unicode_enforcement(self):
api.create_submission(STUDENT_ITEM, "Testing unicode answers.")
submissions = api.get_submissions(STUDENT_ITEM, 1)
self.assertEqual(u"Testing unicode answers.", submissions[0]["answer"])
def _assert_submission(self, submission, expected_answer, expected_item,
expected_attempt):
self.assertIsNotNone(submission)
self.assertEqual(submission["answer"], expected_answer)
self.assertEqual(submission["student_item"], expected_item)
self.assertEqual(submission["attempt_number"], expected_attempt)
def _get_student_item(self, student_item):
return StudentItem.objects.get(
student_id=student_item["student_id"],
course_id=student_item["course_id"],
item_id=student_item["item_id"]
)
def test_caching(self):
sub = api.create_submission(STUDENT_ITEM, "Hello World!")
# The first request to get the submission hits the database...
with self.assertNumQueries(1):
db_sub = api.get_submission(sub["uuid"])
# The next one hits the cache only...
with self.assertNumQueries(0):
cached_sub = api.get_submission(sub["uuid"])
# The data that gets passed back matches the original in both cases
self.assertEqual(sub, db_sub)
self.assertEqual(sub, cached_sub)
"""
Testing Scores
"""
def test_create_score(self):
submission = api.create_submission(STUDENT_ITEM, ANSWER_ONE)
student_item = self._get_student_item(STUDENT_ITEM)
self._assert_submission(submission, ANSWER_ONE, student_item.pk, 1)
api.set_score(submission["uuid"], 11, 12)
score = api.get_latest_score_for_submission(submission["uuid"])
self._assert_score(score, 11, 12)
def test_get_score(self):
submission = api.create_submission(STUDENT_ITEM, ANSWER_ONE)
api.set_score(submission["uuid"], 11, 12)
score = api.get_score(STUDENT_ITEM)
self._assert_score(score, 11, 12)
self.assertEqual(score['submission_uuid'], submission['uuid'])
def test_get_score_for_submission_hidden_score(self):
# Create a "hidden" score for the submission
# (by convention, a score with points possible set to 0)
submission = api.create_submission(STUDENT_ITEM, ANSWER_ONE)
api.set_score(submission["uuid"], 0, 0)
# Expect that the retrieved score is None
score = api.get_latest_score_for_submission(submission['uuid'])
self.assertIs(score, None)
def test_get_score_no_student_id(self):
student_item = copy.deepcopy(STUDENT_ITEM)
student_item['student_id'] = None
self.assertIs(api.get_score(student_item), None)
def test_get_scores(self):
student_item = copy.deepcopy(STUDENT_ITEM)
student_item["course_id"] = "get_scores_course"
student_item["item_id"] = "i4x://a/b/c/s1"
s1 = api.create_submission(student_item, "Hello World")
student_item["item_id"] = "i4x://a/b/c/s2"
s2 = api.create_submission(student_item, "Hello World")
student_item["item_id"] = "i4x://a/b/c/s3"
s3 = api.create_submission(student_item, "Hello World")
api.set_score(s1['uuid'], 3, 5)
api.set_score(s1['uuid'], 4, 5)
api.set_score(s1['uuid'], 2, 5) # Should overwrite previous lines
api.set_score(s2['uuid'], 0, 10)
api.set_score(s3['uuid'], 4, 4)
# Getting the scores for a user should never take more than one query
with self.assertNumQueries(1):
scores = api.get_scores(
student_item["course_id"], student_item["student_id"]
)
self.assertEqual(
scores,
{
u"i4x://a/b/c/s1": (2, 5),
u"i4x://a/b/c/s2": (0, 10),
u"i4x://a/b/c/s3": (4, 4),
}
)
@patch.object(ScoreSummary.objects, 'filter')
@raises(api.SubmissionInternalError)
def test_error_on_get_scores(self, mock_filter):
mock_filter.side_effect = DatabaseError("Bad things happened")
api.get_scores("some_course", "some_student")
def _assert_score(
self,
score,
expected_points_earned,
expected_points_possible):
self.assertIsNotNone(score)
self.assertEqual(score["points_earned"], expected_points_earned)
self.assertEqual(score["points_possible"], expected_points_possible)
"""
Tests for submission models.
"""
from django.test import TestCase
from submissions.models import Submission, Score, ScoreSummary, StudentItem
class TestScoreSummary(TestCase):
"""
Test selection of options from a rubric.
"""
def test_latest(self):
item = StudentItem.objects.create(
student_id="score_test_student",
course_id="score_test_course",
item_id="i4x://mycourse/class_participation.section_attendance"
)
first_score = Score.objects.create(
student_item=item,
submission=None,
points_earned=8,
points_possible=10,
)
second_score = Score.objects.create(
student_item=item,
submission=None,
points_earned=5,
points_possible=10,
)
latest_score = ScoreSummary.objects.get(student_item=item).latest
self.assertEqual(second_score, latest_score)
def test_highest(self):
item = StudentItem.objects.create(
student_id="score_test_student",
course_id="score_test_course",
item_id="i4x://mycourse/special_presentation"
)
# Low score is higher than no score...
low_score = Score.objects.create(
student_item=item,
points_earned=0,
points_possible=0,
)
self.assertEqual(
low_score,
ScoreSummary.objects.get(student_item=item).highest
)
# Medium score should supplant low score
med_score = Score.objects.create(
student_item=item,
points_earned=8,
points_possible=10,
)
self.assertEqual(
med_score,
ScoreSummary.objects.get(student_item=item).highest
)
# Even though the points_earned is higher in the med_score, high_score
# should win because it's 4/4 as opposed to 8/10.
high_score = Score.objects.create(
student_item=item,
points_earned=4,
points_possible=4,
)
self.assertEqual(
high_score,
ScoreSummary.objects.get(student_item=item).highest
)
# Put another medium score to make sure it doesn't get set back down
med_score2 = Score.objects.create(
student_item=item,
points_earned=5,
points_possible=10,
)
self.assertEqual(
high_score,
ScoreSummary.objects.get(student_item=item).highest
)
self.assertEqual(
med_score2,
ScoreSummary.objects.get(student_item=item).latest
)
def test_reset_score_highest(self):
item = StudentItem.objects.create(
student_id="score_test_student",
course_id="score_test_course",
item_id="i4x://mycourse/special_presentation"
)
# Reset score with no score
Score.create_reset_score(item)
highest = ScoreSummary.objects.get(student_item=item).highest
self.assertEqual(highest.points_earned, 0)
self.assertEqual(highest.points_possible, 0)
# Non-reset score after a reset score
submission = Submission.objects.create(student_item=item, attempt_number=1)
Score.objects.create(
student_item=item,
submission=submission,
points_earned=2,
points_possible=3,
)
highest = ScoreSummary.objects.get(student_item=item).highest
self.assertEqual(highest.points_earned, 2)
self.assertEqual(highest.points_possible, 3)
# Reset score after a non-reset score
Score.create_reset_score(item)
highest = ScoreSummary.objects.get(student_item=item).highest
self.assertEqual(highest.points_earned, 0)
self.assertEqual(highest.points_possible, 0)
def test_highest_score_hidden(self):
item = StudentItem.objects.create(
student_id="score_test_student",
course_id="score_test_course",
item_id="i4x://mycourse/special_presentation"
)
# Score with points possible set to 0
# (by convention a "hidden" score)
submission = Submission.objects.create(student_item=item, attempt_number=1)
Score.objects.create(
student_item=item,
submission=submission,
points_earned=0,
points_possible=0,
)
highest = ScoreSummary.objects.get(student_item=item).highest
self.assertEqual(highest.points_earned, 0)
self.assertEqual(highest.points_possible, 0)
# Score with points
submission = Submission.objects.create(student_item=item, attempt_number=1)
Score.objects.create(
student_item=item,
submission=submission,
points_earned=1,
points_possible=2,
)
highest = ScoreSummary.objects.get(student_item=item).highest
self.assertEqual(highest.points_earned, 1)
self.assertEqual(highest.points_possible, 2)
# Another score with points possible set to 0
# The previous score should remain the highest score.
submission = Submission.objects.create(student_item=item, attempt_number=1)
Score.objects.create(
student_item=item,
submission=submission,
points_earned=0,
points_possible=0,
)
highest = ScoreSummary.objects.get(student_item=item).highest
self.assertEqual(highest.points_earned, 1)
self.assertEqual(highest.points_possible, 2)
"""
Test reset scores.
"""
import copy
from mock import patch
from django.test import TestCase
import ddt
from django.core.cache import cache
from django.db import DatabaseError
from submissions import api as sub_api
from submissions.models import Score
@ddt.ddt
class TestResetScore(TestCase):
"""
Test resetting scores for a specific student on a specific problem.
"""
STUDENT_ITEM = {
'student_id': 'Test student',
'course_id': 'Test course',
'item_id': 'Test item',
'item_type': 'Test item type',
}
def setUp(self):
"""
Clear the cache.
"""
cache.clear()
def test_reset_with_no_scores(self):
sub_api.reset_score(
self.STUDENT_ITEM['student_id'],
self.STUDENT_ITEM['course_id'],
self.STUDENT_ITEM['item_id'],
)
self.assertIs(sub_api.get_score(self.STUDENT_ITEM), None)
scores = sub_api.get_scores(self.STUDENT_ITEM['course_id'], self.STUDENT_ITEM['student_id'])
self.assertEqual(len(scores), 0)
def test_reset_with_one_score(self):
# Create a submission for the student and score it
submission = sub_api.create_submission(self.STUDENT_ITEM, 'test answer')
sub_api.set_score(submission['uuid'], 1, 2)
# Reset scores
sub_api.reset_score(
self.STUDENT_ITEM['student_id'],
self.STUDENT_ITEM['course_id'],
self.STUDENT_ITEM['item_id'],
)
# Expect that no scores are available for the student
self.assertIs(sub_api.get_score(self.STUDENT_ITEM), None)
scores = sub_api.get_scores(self.STUDENT_ITEM['course_id'], self.STUDENT_ITEM['student_id'])
self.assertEqual(len(scores), 0)
def test_reset_with_multiple_scores(self):
# Create a submission for the student and score it
submission = sub_api.create_submission(self.STUDENT_ITEM, 'test answer')
sub_api.set_score(submission['uuid'], 1, 2)
sub_api.set_score(submission['uuid'], 2, 2)
# Reset scores
sub_api.reset_score(
self.STUDENT_ITEM['student_id'],
self.STUDENT_ITEM['course_id'],
self.STUDENT_ITEM['item_id'],
)
# Expect that no scores are available for the student
self.assertIs(sub_api.get_score(self.STUDENT_ITEM), None)
scores = sub_api.get_scores(self.STUDENT_ITEM['course_id'], self.STUDENT_ITEM['student_id'])
self.assertEqual(len(scores), 0)
@ddt.data(
{'student_id': 'other student'},
{'course_id': 'other course'},
{'item_id': 'other item'},
)
def test_reset_different_student_item(self, changed):
# Create a submissions for two students
submission = sub_api.create_submission(self.STUDENT_ITEM, 'test answer')
sub_api.set_score(submission['uuid'], 1, 2)
other_student = copy.copy(self.STUDENT_ITEM)
other_student.update(changed)
submission = sub_api.create_submission(other_student, 'other test answer')
sub_api.set_score(submission['uuid'], 3, 4)
# Reset the score for the first student
sub_api.reset_score(
self.STUDENT_ITEM['student_id'],
self.STUDENT_ITEM['course_id'],
self.STUDENT_ITEM['item_id'],
)
# The first student's scores should be reset
self.assertIs(sub_api.get_score(self.STUDENT_ITEM), None)
scores = sub_api.get_scores(self.STUDENT_ITEM['course_id'], self.STUDENT_ITEM['student_id'])
self.assertNotIn(self.STUDENT_ITEM['item_id'], scores)
# But the second student should still have a score
score = sub_api.get_score(other_student)
self.assertEqual(score['points_earned'], 3)
self.assertEqual(score['points_possible'], 4)
scores = sub_api.get_scores(other_student['course_id'], other_student['student_id'])
self.assertIn(other_student['item_id'], scores)
def test_reset_then_add_score(self):
# Create a submission for the student and score it
submission = sub_api.create_submission(self.STUDENT_ITEM, 'test answer')
sub_api.set_score(submission['uuid'], 1, 2)
# Reset scores
sub_api.reset_score(
self.STUDENT_ITEM['student_id'],
self.STUDENT_ITEM['course_id'],
self.STUDENT_ITEM['item_id'],
)
# Score the student again
sub_api.set_score(submission['uuid'], 3, 4)
# Expect that the new score is available
score = sub_api.get_score(self.STUDENT_ITEM)
self.assertEqual(score['points_earned'], 3)
self.assertEqual(score['points_possible'], 4)
scores = sub_api.get_scores(self.STUDENT_ITEM['course_id'], self.STUDENT_ITEM['student_id'])
self.assertIn(self.STUDENT_ITEM['item_id'], scores)
self.assertEqual(scores[self.STUDENT_ITEM['item_id']], (3, 4))
def test_reset_then_get_score_for_submission(self):
# Create a submission for the student and score it
submission = sub_api.create_submission(self.STUDENT_ITEM, 'test answer')
sub_api.set_score(submission['uuid'], 1, 2)
# Reset scores
sub_api.reset_score(
self.STUDENT_ITEM['student_id'],
self.STUDENT_ITEM['course_id'],
self.STUDENT_ITEM['item_id'],
)
# If we're retrieving the score for a particular submission,
# instead of a student item, then we should STILL get a score.
self.assertIsNot(sub_api.get_latest_score_for_submission(submission['uuid']), None)
@patch.object(Score.objects, 'create')
def test_database_error(self, create_mock):
# Create a submission for the student and score it
submission = sub_api.create_submission(self.STUDENT_ITEM, 'test answer')
sub_api.set_score(submission['uuid'], 1, 2)
# Simulate a database error when creating the reset score
create_mock.side_effect = DatabaseError("Test error")
with self.assertRaises(sub_api.SubmissionInternalError):
sub_api.reset_score(
self.STUDENT_ITEM['student_id'],
self.STUDENT_ITEM['course_id'],
self.STUDENT_ITEM['item_id'],
)
"""
Tests for submissions serializers.
"""
from django.test import TestCase
from submissions.models import Score, StudentItem
from submissions.serializers import ScoreSerializer
class ScoreSerializerTest(TestCase):
"""
Tests for the score serializer.
"""
def test_score_with_null_submission(self):
item = StudentItem.objects.create(
student_id="score_test_student",
course_id="score_test_course",
item_id="i4x://mycourse/special_presentation"
)
# Create a score with a null submission
score = Score.objects.create(
student_item=item,
submission=None,
points_earned=2,
points_possible=6
)
score_dict = ScoreSerializer(score).data
self.assertIs(score_dict['submission_uuid'], None)
self.assertEqual(score_dict['points_earned'], 2)
self.assertEqual(score_dict['points_possible'], 6)
from django.conf.urls import patterns, url
urlpatterns = patterns(
'submissions.views',
url(
r'^(?P<student_id>[^/]+)/(?P<course_id>[^/]+)/(?P<item_id>[^/]+)$',
'get_submissions_for_student_item'
),
)
import logging
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from submissions.api import SubmissionRequestError, get_submissions
log = logging.getLogger(__name__)
@login_required()
def get_submissions_for_student_item(request, course_id, student_id, item_id):
"""Retrieve all submissions associated with the given student item.
Developer utility for accessing all the submissions associated with a
student item. The student item is specified by the unique combination of
course, student, and item.
Args:
request (dict): The request.
course_id (str): The course id for this student item.
student_id (str): The student id for this student item.
item_id (str): The item id for this student item.
Returns:
HttpResponse: The response object for this request. Renders a simple
development page with all the submissions related to the specified
student item.
"""
student_item_dict = dict(
course_id=course_id,
student_id=student_id,
item_id=item_id,
)
context = dict(**student_item_dict)
try:
submissions = get_submissions(student_item_dict)
context["submissions"] = submissions
except SubmissionRequestError:
context["error"] = "The specified student item was not found."
return render_to_response('submissions.html', context)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment