浏览代码

moved Period class from ioex to ioex.datetimeex module

Fabian Peter Hammerle 9 年之前
父节点
当前提交
c7dae8b119
共有 4 个文件被更改,包括 115 次插入123 次删除
  1. 1 96
      ioex/__init__.py
  2. 87 0
      ioex/datetimeex.py
  3. 18 18
      tests/datetimeex/test_period.py
  4. 9 9
      tests/datetimeex/test_period_yaml.py

+ 1 - 96
ioex/__init__.py

@@ -1,15 +1,7 @@
 import contextlib
-import datetime
-import dateutil.parser
 import locale
-import os
-import re
-import sys
+import readline
 import threading
-try:
-    import yaml
-except ImportError:
-    yaml = None
 
 class UnsupportedLocaleSettingError(locale.Error):
     pass
@@ -32,7 +24,6 @@ def setlocale(temporary_locale):
             locale.setlocale(locale.LC_ALL, primary_locale)
 
 def raw_input_with_default(prompt, default):
-    import readline
     def pre_input_hook():
         readline.insert_text(default)
         readline.redisplay()
@@ -52,89 +43,3 @@ def int_input_with_default(prompt, default):
         return int(s)
     else:
         return None
-
-class Period(object):
-
-    yaml_tag = u'!period'
-
-    _timestamp_iso_format = r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(.\d+)?(Z|[-\+]\d{2}:\d{2})?'
-    _timeperiod_iso_format = r'(?P<start>%(t)s)\/(?P<end>%(t)s)' % {'t': _timestamp_iso_format}
-
-    def __init__(self, start = None, end = None, isoformat = None):
-        self._start = None
-        self._end = None
-        if (start or end) and isoformat:
-            raise AttributeError('when providing isoformat no other parameters may be specified')
-        elif isoformat:
-            self.isoformat = isoformat
-        else:
-            self.start = start
-            self.end = end
-
-    @property
-    def start(self):
-        return self._start
-
-    @start.setter
-    def start(self, start):
-        if not (start is None or type(start) is datetime.datetime):
-            raise TypeError()
-        self._start = start
-
-    @property
-    def end(self):
-        return self._end
-
-    @end.setter
-    def end(self, end):
-        if not (end is None or type(end) is datetime.datetime):
-            raise TypeError()
-        self._end = end
-
-    @property
-    def isoformat(self):
-        if self.start is None or self.end is None:
-            raise ValueError('both start and end must be set')
-        return '%s/%s' % (
-                self.start.isoformat().replace('+00:00', 'Z'),
-                self.end.isoformat().replace('+00:00', 'Z'),
-                )
-
-    @isoformat.setter
-    def isoformat(self, text):
-        match = re.search('^%s$' % self.__class__._timeperiod_iso_format, text)
-        if not match:
-            raise ValueError(
-                    "given string '%s' does not match the supported pattern '%s'"
-                     % (text, self.__class__._timeperiod_iso_format)
-                     )
-        attr = match.groupdict()
-        self.start = dateutil.parser.parse(attr['start'])
-        self.end = dateutil.parser.parse(attr['end'])
-
-    def __eq__(self, other):
-        return (type(self) == type(other)
-            and self.start == other.start
-            and self.end == other.end)
-
-    @classmethod
-    def from_yaml(cls, loader, node):
-        return cls(**loader.construct_mapping(node))
-
-    @classmethod
-    def to_yaml(cls, dumper, period):
-        return dumper.represent_mapping(
-            tag = cls.yaml_tag,
-            mapping = {
-                'start': period.start,
-                'end': period.end,
-                },
-            # represent datetime objects with !timestamp tag
-            flow_style = False,
-            )
-
-if yaml:
-    yaml.add_representer(Period, Period.to_yaml)
-    yaml.SafeDumper.add_representer(Period, Period.to_yaml)
-    yaml.add_constructor(u'!period', Period.from_yaml)
-    yaml.SafeLoader.add_constructor(u'!period', Period.from_yaml)

+ 87 - 0
ioex/datetimeex.py

@@ -1,4 +1,5 @@
 import datetime
+import dateutil.parser
 import dateutil.tz.tz
 import re
 try:
@@ -28,3 +29,89 @@ def construct_yaml_timestamp(loader, node):
 
 def add_yaml_timestamp_constructor(loader, tag = u'tag:yaml.org,2002:timestamp'):
     loader.add_constructor(tag, construct_yaml_timestamp)
+
+class Period(object):
+
+    yaml_tag = u'!period'
+
+    _timestamp_iso_format = r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(.\d+)?(Z|[-\+]\d{2}:\d{2})?'
+    _timeperiod_iso_format = r'(?P<start>%(t)s)\/(?P<end>%(t)s)' % {'t': _timestamp_iso_format}
+
+    def __init__(self, start = None, end = None, isoformat = None):
+        self._start = None
+        self._end = None
+        if (start or end) and isoformat:
+            raise AttributeError('when providing isoformat no other parameters may be specified')
+        elif isoformat:
+            self.isoformat = isoformat
+        else:
+            self.start = start
+            self.end = end
+
+    @property
+    def start(self):
+        return self._start
+
+    @start.setter
+    def start(self, start):
+        if not (start is None or type(start) is datetime.datetime):
+            raise TypeError()
+        self._start = start
+
+    @property
+    def end(self):
+        return self._end
+
+    @end.setter
+    def end(self, end):
+        if not (end is None or type(end) is datetime.datetime):
+            raise TypeError()
+        self._end = end
+
+    @property
+    def isoformat(self):
+        if self.start is None or self.end is None:
+            raise ValueError('both start and end must be set')
+        return '%s/%s' % (
+                self.start.isoformat().replace('+00:00', 'Z'),
+                self.end.isoformat().replace('+00:00', 'Z'),
+                )
+
+    @isoformat.setter
+    def isoformat(self, text):
+        match = re.search('^%s$' % self.__class__._timeperiod_iso_format, text)
+        if not match:
+            raise ValueError(
+                    "given string '%s' does not match the supported pattern '%s'"
+                     % (text, self.__class__._timeperiod_iso_format)
+                     )
+        attr = match.groupdict()
+        self.start = dateutil.parser.parse(attr['start'])
+        self.end = dateutil.parser.parse(attr['end'])
+
+    def __eq__(self, other):
+        return (type(self) == type(other)
+            and self.start == other.start
+            and self.end == other.end)
+
+    @classmethod
+    def from_yaml(cls, loader, node):
+        return cls(**loader.construct_mapping(node))
+
+    @classmethod
+    def to_yaml(cls, dumper, period):
+        return dumper.represent_mapping(
+            tag = cls.yaml_tag,
+            mapping = {
+                'start': period.start,
+                'end': period.end,
+                },
+            # represent datetime objects with !timestamp tag
+            flow_style = False,
+            )
+
+if yaml:
+    yaml.add_representer(Period, Period.to_yaml)
+    yaml.SafeDumper.add_representer(Period, Period.to_yaml)
+    yaml.add_constructor(u'!period', Period.from_yaml)
+    yaml.SafeLoader.add_constructor(u'!period', Period.from_yaml)

+ 18 - 18
tests/test_period.py → tests/datetimeex/test_period.py

@@ -2,7 +2,7 @@
 import pytest
 
 import pytz
-import ioex
+import ioex.datetimeex
 import datetime
 
 @pytest.mark.parametrize(('start', 'end'), [
@@ -12,7 +12,7 @@ import datetime
     [None, None],
     ])
 def test_init_start_end(start, end):
-    p = ioex.Period(start = start, end = end)
+    p = ioex.datetimeex.Period(start = start, end = end)
     assert p.start == start
     assert p.end == end
 
@@ -22,7 +22,7 @@ def test_init_start_end(start, end):
     ])
 def test_init_start_end_fail(start, end):
     with pytest.raises(TypeError):
-        ioex.Period(start = start, end = end)
+        ioex.datetimeex.Period(start = start, end = end)
 
 @pytest.mark.parametrize(('start', 'end', 'iso'), [
     [
@@ -32,7 +32,7 @@ def test_init_start_end_fail(start, end):
         ],
     ])
 def test_init_isoformat(start, end, iso):
-    p = ioex.Period(isoformat = iso)
+    p = ioex.datetimeex.Period(isoformat = iso)
     assert p.start == start
     assert p.end == end
 
@@ -53,14 +53,14 @@ def test_init_isoformat(start, end, iso):
     ])
 def test_init_param_fail(params):
     with pytest.raises(StandardError):
-        ioex.Period(**params)
+        ioex.datetimeex.Period(**params)
 
 @pytest.mark.parametrize(('start'), [
     datetime.datetime(2016, 7, 24, 12, 21),
     None,
     ])
 def test_set_start(start):
-    p = ioex.Period()
+    p = ioex.datetimeex.Period()
     assert p.start is None
     p.start = start
     assert p.start == start
@@ -69,7 +69,7 @@ def test_set_start(start):
     ':-/',
     ])
 def test_set_start_fail(start):
-    p = ioex.Period()
+    p = ioex.datetimeex.Period()
     with pytest.raises(TypeError):
         p.start = start
 
@@ -78,7 +78,7 @@ def test_set_start_fail(start):
     None,
     ])
 def test_set_end(end):
-    p = ioex.Period()
+    p = ioex.datetimeex.Period()
     assert p.end is None
     p.end = end
     assert p.end == end
@@ -87,7 +87,7 @@ def test_set_end(end):
     ':-/',
     ])
 def test_set_end_fail(end):
-    p = ioex.Period()
+    p = ioex.datetimeex.Period()
     with pytest.raises(TypeError):
         p.end = end
 
@@ -119,7 +119,7 @@ def test_set_end_fail(end):
         ],
     ])
 def test_get_isoformat(start, end, iso):
-    p = ioex.Period(start = start, end = end)
+    p = ioex.datetimeex.Period(start = start, end = end)
     assert p.isoformat == iso
 
 @pytest.mark.parametrize(('start', 'end', 'iso'), [
@@ -155,7 +155,7 @@ def test_get_isoformat(start, end, iso):
         ],
     ])
 def test_set_isoformat(start, end, iso):
-    p = ioex.Period()
+    p = ioex.datetimeex.Period()
     p.isoformat = iso
     assert p.start == start
     assert p.end == end
@@ -164,37 +164,37 @@ def test_set_isoformat(start, end, iso):
     '2016-07-24T12:20:0<INVALID>0.0255/2016-07-24T12:21:00.13Z',
     ])
 def test_set_isoformat_fail(iso):
-    p = ioex.Period()
+    p = ioex.datetimeex.Period()
     with pytest.raises(ValueError):
         p.isoformat = iso
 
 @pytest.mark.parametrize(('a', 'b'), [
     [
-        ioex.Period(
+        ioex.datetimeex.Period(
             start = datetime.datetime(2016, 7, 24, 12, 21, 0),
             end = datetime.datetime(2016, 7, 24, 12, 22, 13),
             ),
-        ioex.Period(
+        ioex.datetimeex.Period(
             start = datetime.datetime(2016, 7, 24, 12, 21, 0, 0),
             end = datetime.datetime(2016, 7, 24, 12, 22, 13, 0),
             ),
         ],
     [
-        ioex.Period(
+        ioex.datetimeex.Period(
             start = pytz.timezone('Europe/Vienna').localize(datetime.datetime(2016, 7, 24, 12, 21, 0)),
             end = datetime.datetime(2016, 7, 24, 12, 22, 13),
             ),
-        ioex.Period(
+        ioex.datetimeex.Period(
             start = pytz.timezone('Europe/Vienna').localize(datetime.datetime(2016, 7, 24, 12, 21, 0)),
             end = datetime.datetime(2016, 7, 24, 12, 22, 13),
             ),
         ],
     [
-        ioex.Period(
+        ioex.datetimeex.Period(
             start = pytz.timezone('Europe/Vienna').localize(datetime.datetime(2016, 7, 24, 12, 21, 0)),
             end = pytz.timezone('Europe/London').localize(datetime.datetime(2016, 7, 24, 12, 22, 13)),
             ),
-        ioex.Period(
+        ioex.datetimeex.Period(
             start = pytz.timezone('Europe/London').localize(datetime.datetime(2016, 7, 24, 11, 21, 0)),
             end = pytz.timezone('Europe/Vienna').localize(datetime.datetime(2016, 7, 24, 13, 22, 13)),
             ),

+ 9 - 9
tests/test_period_yaml.py → tests/datetimeex/test_period_yaml.py

@@ -2,34 +2,34 @@
 import pytest
 
 import pytz
-import ioex
+import ioex.datetimeex
 import datetime
 yaml = pytest.importorskip('yaml')
 
 @pytest.mark.parametrize(('period', 'yaml_string'), [
     [
-        ioex.Period(
+        ioex.datetimeex.Period(
             start = datetime.datetime(2016, 7, 24, 12, 21, 0),
             end = datetime.datetime(2016, 7, 24, 12, 22, 13),
             ),
         '!period\nstart: 2016-07-24T12:21:00\nend: 2016-07-24T12:22:13',
         ],
     [
-        ioex.Period(
+        ioex.datetimeex.Period(
             start = datetime.datetime(2016, 7, 24, 12, 21, 0),
             end = datetime.datetime(2016, 7, 24, 12, 22, 13),
             ),
         '!period\nstart: 2016-07-24 12:21:00\nend: 2016-07-24 12:22:13',
         ],
     [
-        ioex.Period(
+        ioex.datetimeex.Period(
             start = datetime.datetime(2016, 7, 24, 12, 20, 0, microsecond = 25500),
             end = datetime.datetime(2016, 7, 24, 12, 21, 0, microsecond = 13),
             ),
         '!period\nstart: 2016-07-24T12:20:00.025500\nend: 2016-07-24T12:21:00.000013',
         ],
     [
-        ioex.Period(
+        ioex.datetimeex.Period(
             start = datetime.datetime(2016, 7, 24, 12, 20, 0, microsecond = 25500),
             end = datetime.datetime(2016, 7, 24, 12, 21, 0, microsecond = 13, tzinfo = pytz.utc),
             ),
@@ -37,28 +37,28 @@ yaml = pytest.importorskip('yaml')
         ],
     ])
 def test_from_yaml(period, yaml_string):
-    if period.start.tzinfo or period.end.tzinfo: 
+    if period.start.tzinfo or period.end.tzinfo:
         pytest.xfail('pyyaml ignores timezones when loading timestamps')
     assert period == yaml.load(yaml_string)
     assert period == yaml.safe_load(yaml_string)
 
 @pytest.mark.parametrize(('period', 'yaml_string'), [
     [
-        ioex.Period(
+        ioex.datetimeex.Period(
             start = datetime.datetime(2016, 7, 24, 12, 21, 0),
             end = datetime.datetime(2016, 7, 24, 12, 22, 13),
             ),
         '!period\nend: 2016-07-24 12:22:13\nstart: 2016-07-24 12:21:00\n',
         ],
     [
-        ioex.Period(
+        ioex.datetimeex.Period(
             start = datetime.datetime(2016, 7, 24, 12, 20, 0, microsecond = 25500),
             end = datetime.datetime(2016, 7, 24, 12, 21, 0, microsecond = 13),
             ),
         '!period\nend: 2016-07-24 12:21:00.000013\nstart: 2016-07-24 12:20:00.025500\n',
         ],
     [
-        ioex.Period(
+        ioex.datetimeex.Period(
             start = pytz.timezone('Europe/London').localize(datetime.datetime(2016, 7, 24, 12, 20, 0)),
             end = pytz.utc.localize(datetime.datetime(2016, 7, 24, 12, 21, 0, microsecond = 13)),
             ),