Commit 5608dd56 by Filippo Valsorda Committed by Xavier Antoviaque

Enforce type of the XBlocks Fields when set

This updates the XBlock dependency to edX/XBlock@cba8d788f0c16802b4cc468ccb6dc765b62e55e8
and add the newly introduced enforce_type methods
parent bbac54a7
......@@ -3,6 +3,7 @@ Mixin defining common Studio functionality
"""
import datetime
import time
from xblock.fields import Scope, Field, Integer, XBlockMixin
......@@ -20,6 +21,15 @@ class DateTuple(Field):
return list(value.timetuple())
def enforce_type(self, value):
if isinstance(value, datetime.datetime) or value is None:
return value
if isinstance(value, tuple, time.struct_time):
return self.from_json(DateTuple)
raise TypeError("Value should be datetime, a timetuple or None, not {}".format(type(value)))
class CmsBlockMixin(XBlockMixin):
"""
......
......@@ -68,10 +68,7 @@ class Date(Field):
"""
if value is None:
return None
if isinstance(value, time.struct_time):
# struct_times are always utc
return time.strftime('%Y-%m-%dT%H:%M:%SZ', value)
elif isinstance(value, datetime.datetime):
if isinstance(value, datetime.datetime):
if value.tzinfo is None or value.utcoffset().total_seconds() == 0:
# isoformat adds +00:00 rather than Z
return value.strftime('%Y-%m-%dT%H:%M:%SZ')
......@@ -80,6 +77,8 @@ class Date(Field):
else:
raise TypeError("Cannot convert {!r} to json".format(value))
enforce_type = from_json
TIMEDELTA_REGEX = re.compile(r'^((?P<days>\d+?) day(?:s?))?(\s)?((?P<hours>\d+?) hour(?:s?))?(\s)?((?P<minutes>\d+?) minute(?:s)?)?(\s)?((?P<seconds>\d+?) second(?:s)?)?$')
......@@ -117,6 +116,15 @@ class Timedelta(Field):
values.append("%d %s" % (cur_value, attr))
return ' '.join(values)
def enforce_type(self, value):
"""
Ensure that when set explicitly the Field is set to a timedelta
"""
if isinstance(value, datetime.timedelta) or value is None:
return value
return self.from_json(value)
class RelativeTime(Field):
"""
......@@ -219,3 +227,12 @@ class RelativeTime(Field):
if len(stringified) == 7:
stringified = '0' + stringified
return stringified
def enforce_type(self, value):
"""
Ensure that when set explicitly the Field is set to a timedelta
"""
if isinstance(value, datetime.timedelta) or value is None:
return None
return self.from_json(value)
......@@ -17,7 +17,7 @@
-e git+https://github.com/appliedsec/pygeoip.git@95e69341cebf5a6a9fbf7c4f5439d458898bdc3b#egg=pygeoip
# Our libraries:
-e git+https://github.com/edx/XBlock.git@cfe5c37f98febd9a215d23cb206a25711056a142#egg=XBlock
-e git+https://github.com/edx-solutions/XBlock.git@2821f89f844f644c2091fa50bba06eb209b8f127#egg=XBlock
-e git+https://github.com/edx/codejail.git@e3d98f9455#egg=codejail
-e git+https://github.com/edx/diff-cover.git@v0.2.9#egg=diff_cover
-e git+https://github.com/edx/js-test-tool.git@v0.1.5#egg=js_test_tool
......
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