diff --git a/hl7apy/base_datatypes.py b/hl7apy/base_datatypes.py index 7bf4629..fbe6204 100644 --- a/hl7apy/base_datatypes.py +++ b/hl7apy/base_datatypes.py @@ -35,6 +35,7 @@ from __future__ import absolute_import import re import numbers +import sys from datetime import datetime from decimal import Decimal from functools import cmp_to_key @@ -44,6 +45,10 @@ InvalidDateOffset, InvalidMicrosecondsPrecision from hl7apy.validation import Validator +if sys.version_info.major == 2: + bytes, unicode = str, unicode +else: + bytes, unicode = bytes, str class BaseDataType(object): """ @@ -71,8 +76,13 @@ def __init__(self, value, max_length=None, validation_level=None): self.validation_level = validation_level self.max_length = max_length if Validator.is_strict(self.validation_level): - if self.max_length is not None and len('{0}'.format(value)) > self.max_length: - raise MaxLengthReached(value, self.max_length) + if self.max_length is not None: + if isinstance(value, (bytes, unicode)): + if len(value) > self.max_length: + raise MaxLengthReached(value, self.max_length) + elif len("{0}".format(value)) > self.max_length: + raise MaxLengthReached(value, self.max_length) + self.value = value def to_er7(self, encoding_chars=None): diff --git a/tests/test_to_string.py b/tests/test_to_string.py index b936757..fc3fe22 100644 --- a/tests/test_to_string.py +++ b/tests/test_to_string.py @@ -266,6 +266,11 @@ def test_to_string_wd_field(self): parsed_s = parse_segment(s, version='2.7') self.assertEqual(parsed_s.to_er7(), 'EVN||20080115153000||AAA|AAA|20080114003000') + def test_to_string_unicode_field(self): + pid = Segment('PID', validation_level=VALIDATION_LEVEL.STRICT) + pid.pid_5.pid_5_1 = u'€' + self.assertEqual(pid.to_er7(), u'PID|||||€') + if __name__ == '__main__': unittest.main()