示例#1
0
 def test_with_separator_identity(self):
     one = Characters()
     other = Characters()
     # a copy of a characters object must be equal, but not the same
     self.assertTrue(one == other,
                     'Objects differ: "{}", "{}"'.format(one, other))
     self.assertFalse(one is other)
示例#2
0
    def get_control_characters(message, characters=None):
        u"""Read the UNA segment from the passed string.

        :param message: a valid EDI message string, or UNA segment string,
                        to extract the control characters from
        :param characters: the control characters to use, if none found in
                           the message
        :rtype: str or None
        :return: the control characters
        """

        if not characters:
            characters = Characters()

        # First, try to read the UNA segment ("Service String Advice",
        # conditional). This segment and the UNB segment (Interchange Header)
        # must always be written in ASCII, even if after the BGM the files
        # continues with cyrillic or UTF-16.

        # If it does not exist, return a default.
        if not message[:3] == u"UNA":
            return characters

        # Get the character definitions
        chars = message[3:9]
        characters.is_extracted_from_message = True

        characters.component_separator = chars[0]
        characters.data_separator = chars[1]
        characters.decimal_point = chars[2]
        characters.escape_character = chars[3]
        characters.reserved_character = chars[4]
        characters.segment_terminator = chars[5]

        return characters
示例#3
0
def setup():
    setup = Setup()
    unb_segment = "UNB+UNOA:4+APIS*ABE+USADHS+070429:0900+000000001++USADHS'"
    cc = Characters()
    setup.cc = cc.with_control_character("decimal_point", ".")
    setup.collection = SegmentCollection.from_str(unb_segment)
    return setup
示例#4
0
    def __init__(self):

        # The segments that make up this message
        self.segments = []
        self.characters = Characters()

        # Flag whether the UNA header is present
        self.has_una_segment = False
示例#5
0
    def create_segment(name: str, *elements: list) -> Segment:
        """Create a new instance of the relevant class type.

        :param name: The name of the segment
        :param elements: The data elements for this segment
        """
        if not SegmentFactory.characters:
            SegmentFactory.characters = Characters()

        # FIXME: characters is not used!
        return Segment(name, *elements)
示例#6
0
    def __init__(self,
                 extra_header_elements: List[Union[str, List[str]]] = []):
        """
        :param extra_header_elements: a list of elements to be appended at the end
          of the header segment (same format as Segment() constructor *elements).
        """

        # The segments that make up this message
        self.segments = []
        self.characters = Characters()

        self.extra_header_elements = extra_header_elements

        # Flag whether the UNA header is present
        self.has_una_segment = False
示例#7
0
 def __init__(self,
              sender: str,
              recipient: str,
              control_reference: str,
              syntax_identifier: Tuple[str, int],
              delimiters: Characters = Characters(),
              timestamp: datetime.datetime = None,
              *args,
              **kwargs):
     super().__init__(*args, **kwargs)
     self.sender = sender
     self.recipient = recipient
     self.control_reference = control_reference
     self.syntax_identifier = syntax_identifier
     self.delimiters = delimiters
     self.timestamp = timestamp or datetime.datetime.now()
示例#8
0
    def create_segment(name: str,
                       *elements: Union[str, List[str]],
                       validate: bool = True) -> Segment:
        """Create a new instance of the relevant class type.

        :param name: The name of the segment
        :param elements: The data elements for this segment
        :param validate: bool if True, the created segment is validated before return
        """
        if not SegmentFactory.characters:
            SegmentFactory.characters = Characters()

        # Basic segment type validation is done here.
        # The more special validation must be done in the corresponding Segment

        if not name:
            raise EDISyntaxError("The tag of a segment must not be empty.")

        if type(name) != str:
            raise EDISyntaxError(
                "The tag name of a segment must be a str, but is a {}: {}".
                format(type(name), name))

        if not name.isalnum():
            raise EDISyntaxError(
                "Tag '{}': A tag name must only contain alphanumeric characters."
                .format(name))

        for Plugin in SegmentProvider.plugins:
            if Plugin().tag == name:
                s = Plugin(name, *elements)
        else:
            # we don't support this kind of EDIFACT segment (yet), so
            # just create a generic Segment()
            s = Segment(name, *elements)

        if validate:
            if not s.validate():
                raise EDISyntaxError(
                    "could not create '{}' Segment. Validation failed.".format(
                        name))

        # FIXME: characters is not used!
        return Segment(name, *elements)
示例#9
0
def test_no_terminator():
    with pytest.raises(RuntimeError):
        Tokenizer().get_tokens("TEST", Characters())
        pytest.fail("Unexpected end of EDI message")
示例#10
0
    def __init__(self, factory: SegmentFactory = None):
        if factory is None:
            factory = SegmentFactory()

        self.factory = factory
        self.characters = Characters()
示例#11
0
 def setUp(self):
     self.cc = Characters()
示例#12
0
 def test_no_terminator(self):
     with self.assertRaises(RuntimeError) as cm:
         self._tokenizer.get_tokens("TEST", Characters())
     self.assertEqual(str(cm.exception), "Unexpected end of EDI message")
示例#13
0
 def _assert_tokens(self, message, expected=None):
     if expected is None:
         expected = []
     tokens = self._tokenizer.get_tokens("{}'".format(message), Characters())
     expected.append(Token(Token.Type.TERMINATOR, "'"))
     self.assertEqual(expected, tokens)
示例#14
0
 def test_cc_assigning(self):
     one = Characters()
     one.component_separator = 'x'
     self.assertEqual(one.component_separator, 'x')
     self.assertEqual(str(one), "x+,? '")
示例#15
0
def test_wrong_cc_assigning():
    with pytest.raises(ValueError):
        Characters().with_control_character("component_separator", "xd")

    with pytest.raises(AttributeError):
        Characters().with_control_character("notexisting", ":")
示例#16
0
def test_cc_assigning():
    one = Characters()
    one.component_separator = "x"
    assert one.component_separator == "x"
    assert one == "x+,? '"
示例#17
0
def test_with_separator_identity():
    one = Characters()
    other = Characters()
    # a copy of a characters object must be equal, but not the same
    assert one == other, 'Objects differ: "{}", "{}"'.format(one, other)
    assert one is not other