def test_can_specify_additional_custom_message(self):
     try:
         assert_not_raises(Exception, self._fail_with(ValueError), message='Foo')
     except AssertionError as e:
         assert_equals('unexpected exception ValueError(): Foo', exception_message(e))
     else:
         self.fail('test did not catch exception!')
Example #2
0
 def test_append_restriction(self):
     l = xsd.ListElement(xsd.String, maxOccurs=1,
                         tagname='toto').empty_value()
     l.append('a')
     e = assert_raises(ValueError, lambda: l.append('a'))
     assert_equals('You must not add more than 1 items to this list.',
                   str(e))
    def test_supports_very_distant_dates(self):
        raise SkipTest('XSDDate can currently only represent the value range of datetime.date')
        future = XSDDate(12345, 4, 21)
        assert_equals(12345, future.year)

        past = XSDDate(-12345, 4, 21)
        assert_equals(-12345, past.year)
 def test_fails_with_sensible_default_error_message(self):
     try:
         assert_not_raises(Exception, self._fail_with(ValueError))
     except AssertionError as e:
         assert_equals('unexpected exception ValueError()', exception_message(e))
     else:
         self.fail('test did not catch exception!')
Example #5
0
 def test_parsing(self):
     self.assert_parse(None, None)
     self.assert_parse(None, 'nil')
     parsed_time = self._parse('23:59:59+01:00')
     assert_equals(time(23, 59, 59, tzinfo=FixedOffset(1, 0, '+01:00')), parsed_time)
     parsed_time = self._parse('23:59:59-02:30')
     assert_equals(time(23, 59, 59, tzinfo=FixedOffset(-2, -30, '-02:30')), parsed_time)
Example #6
0
    def test_can_generate_code_with_xsd_refs_to_elements_with_anoynmous_complex_types(self):
        # The final test should have an object graph representation of the
        # schema below. Currently I don't know how to represent multiple
        # xs:elements in a schema without using ComplexTypes.
        # Maybe we should have a special type like AnonymousComplexType and
        # put that directly into schema.elements?
        xml = utils.open_document('tests/assets/generation/reference_complex.xsd')
        schema = xsdspec.Schema.parse_xmlelement(etree.fromstring(xml))
        code = xsd2py.schema_to_py(schema, ['xs'])

        schemas, symbols = generated_symbols(code)
        assert_is_not_empty(schemas)
        assert_length(3, symbols)
        assert_contains('Person', symbols.keys())
        assert_contains('Job', symbols.keys())

        assert_equals(set(['person', 'job']), list(schemas[0].elements))

        Job = symbols['Job']
        Person = symbols['Person']
        person_ref = Job.person
        assert_isinstance(person_ref, xsd.Ref)
        assert_equals(person_ref._type, Person)

        job = Job()
        person = Person()
        person.name = 'Foo'
        job.person = person
Example #7
0
    def test_can_generate_code_with_xsd_refs_to_simple_elements(self):
        xml = utils.open_document(
            'tests/assets/generation/reference_simple.xsd')
        code = xsd2py.generate_code_from_xsd(xml)

        schemas, symbols = generated_symbols(code)
        assert_is_not_empty(schemas)
        # somehow we need to be able to have schemas with multiple possible
        # root elements
        assert_length(3, symbols)
        assert_contains('Name', symbols.keys())
        assert_contains('Job', symbols.keys())

        assert_equals(set(['name', 'job']), list(schemas[0].elements))

        Job = symbols['Job']
        Name = symbols['Name']
        name_ref = Job.name
        # not sure if these assertions are correct but they should give you
        # the idea
        assert_isinstance(name_ref, xsd.Ref)
        assert_equals(name_ref._type, Name)

        job = Job()
        # Should not raise
        job.name = u'Foo'
Example #8
0
    def test_can_generate_code_with_xsd_refs_to_elements_with_anoynmous_complex_types(
            self):
        # The final test should have an object graph representation of the
        # schema below. Currently I don't know how to represent multiple
        # xs:elements in a schema without using ComplexTypes.
        # Maybe we should have a special type like AnonymousComplexType and
        # put that directly into schema.elements?
        xml = utils.open_document(
            'tests/assets/generation/reference_complex.xsd')
        schema = xsdspec.Schema.parse_xmlelement(etree.fromstring(xml))
        code = xsd2py.schema_to_py(schema, ['xs'])

        schemas, symbols = generated_symbols(code)
        assert_is_not_empty(schemas)
        assert_length(3, symbols)
        assert_contains('Person', symbols.keys())
        assert_contains('Job', symbols.keys())

        assert_equals(set(['person', 'job']), list(schemas[0].elements))

        Job = symbols['Job']
        Person = symbols['Person']
        person_ref = Job.person
        assert_isinstance(person_ref, xsd.Ref)
        assert_equals(person_ref._type, Person)

        job = Job()
        person = Person()
        person.name = 'Foo'
        job.person = person
Example #9
0
    def test_can_generate_code_with_xsd_refs_to_simple_elements(self):
        xml = utils.open_document('tests/assets/generation/reference_simple.xsd')
        code = xsd2py.generate_code_from_xsd(xml)

        schemas, symbols = generated_symbols(code)
        assert_is_not_empty(schemas)
        # somehow we need to be able to have schemas with multiple possible
        # root elements
        assert_length(3, symbols)
        assert_contains('Name', symbols.keys())
        assert_contains('Job', symbols.keys())

        assert_equals(set(['name', 'job']), list(schemas[0].elements))

        Job = symbols['Job']
        Name = symbols['Name']
        name_ref = Job.name
        # not sure if these assertions are correct but they should give you
        # the idea
        assert_isinstance(name_ref, xsd.Ref)
        assert_equals(name_ref._type, Name)

        job = Job()
        # Should not raise
        job.name = u'Foo'
Example #10
0
    def test_can_dispatch_good_soap_message(self):
        handler, handler_state = echo_handler()
        dispatcher = SOAPDispatcher(echo_service(handler))
        soap_message = (
            '<ns1:echoRequest xmlns:ns1="http://soap.example/echo/types">'
            '<value>foobar</value>'
            '</ns1:echoRequest>')
        request_message = self._wrap_with_soap_envelope(soap_message)
        request = SOAPRequest(dict(SOAPACTION='echo', REQUEST_METHOD='POST'),
                              request_message)

        response = dispatcher.dispatch(request)
        self.assert_is_successful_response(response, handler_state)
        assert_equals('foobar', handler_state.input_.value)

        response_document = etree.fromstring(response.http_content)
        response_xml = etree.tostring(response_document, pretty_print=True)
        expected_xml = (
            b'<ns0:Envelope xmlns:ns0="http://schemas.xmlsoap.org/soap/envelope/">\n'
            b'  <ns0:Body>\n'
            b'    <ns0:echoResponse xmlns:ns0="http://soap.example/echo/types">\n'
            b'      <value>foobar</value>\n'
            b'    </ns0:echoResponse>\n'
            b'  </ns0:Body>\n'
            b'</ns0:Envelope>\n')
        assert_equals(expected_xml, response_xml)
Example #11
0
    def test_can_include_imported_schemas_during_validation(self):
        # In case the SOAPDispatcher would not use imported schemas for
        # validation it would fail because the 'code' tag is only defined in
        # the imported schema
        handler, handler_state = echo_handler()
        service = echo_service(handler)

        class CodeType(xsd.String):
            pattern = r'[0-9]{5}'

        class Container(xsd.ComplexType):
            value = xsd.Element(CodeType)

        code_schema = xsd.Schema(
            'http://soap.example/included',
            location='http://soap.example/included',
            elementFormDefault=xsd.ElementFormDefault.UNQUALIFIED,
            simpleTypes=[CodeType],
            complexTypes=[Container],
            elements={'foo': xsd.Element(Container)},
        )
        service.methods[0].input = 'foo'
        service.schemas[0].imports = [code_schema]
        # The setup is a bit simplistic because the <code> tag is not parsed
        # into a soapfish model element for the handler but this was enough
        # to trigger the bug
        dispatcher = SOAPDispatcher(service)
        wsgi_environ = dict(SOAPACTION='echo', REQUEST_METHOD='POST')
        soap_message = '<ns0:foo xmlns:ns0="http://soap.example/included"><value>12345</value></ns0:foo>'
        request = SOAPRequest(wsgi_environ,
                              self._wrap_with_soap_envelope(soap_message))
        response = dispatcher.dispatch(request)
        self.assert_is_successful_response(response, handler_state)
        assert_equals('12345', handler_state.input_.value)
Example #12
0
    def test_can_render_simple_element(self):
        element = xsdspec.Element()
        element.name = 'Name'
        element.type = 'xs:string'

        expected_xml = b'<element name="Name" type="xs:string"/>\n'
        assert_equals(expected_xml, element.xml('element'))
Example #13
0
    def test_can_specify_additional_custom_message(self):
        e = self.assert_fail({'foo': '42'}, {}, message='Bar')
        assert_equals("%r not in {}: Bar" % 'foo', exception_message(e))

        e = self.assert_fail({'foo': 21}, {'foo': 42}, message='Bar')
        expected_error = "%r=21 != %r=42: Bar" % ('foo', 'foo')
        assert_equals(expected_error, exception_message(e))
Example #14
0
    def test_fails_with_sensible_default_error_message(self):
        e = self.assert_fail({'foo': '42'}, {})
        assert_equals("%r not in {}" % 'foo', exception_message(e))

        e = self.assert_fail({'foo': 21}, {'foo': 42})
        expected_error = "%r=21 != %r=42" % ('foo', 'foo')
        assert_equals(expected_error, exception_message(e))
    def test_can_render_simple_element(self):
        element = xsdspec.Element()
        element.name = 'Name'
        element.type = 'xs:string'

        expected_xml = b'<element name="Name" type="xs:string"/>\n'
        assert_equals(expected_xml, element.xml('element'))
Example #16
0
 def test_parsing(self):
     self.assert_parse(None, None)
     self.assert_parse(None, 'nil')
     parsed_time = self._parse('23:59:59+01:00')
     assert_equals(time(23, 59, 59, tzinfo=iso8601.FixedOffset(1, 0, '+01:00')), parsed_time)
     parsed_time = self._parse('23:59:59-02:30')
     assert_equals(time(23, 59, 59, tzinfo=iso8601.FixedOffset(-2, -30, '-02:30')), parsed_time)
Example #17
0
    def test_can_dispatch_good_soap_message(self):
        handler, handler_state = echo_handler()
        dispatcher = SOAPDispatcher(echo_service(handler))
        soap_message = (
            '<ns1:echoRequest xmlns:ns1="http://soap.example/echo/types">'
            '<value>foobar</value>'
            '</ns1:echoRequest>'
        )
        request_message = self._wrap_with_soap_envelope(soap_message)
        request = SOAPRequest(dict(SOAPACTION='echo', REQUEST_METHOD='POST'), request_message)

        response = dispatcher.dispatch(request)
        self.assert_is_successful_response(response, handler_state)
        assert_equals('foobar', handler_state.input_.value)

        response_document = etree.fromstring(response.http_content)
        response_xml = etree.tostring(response_document, pretty_print=True)
        expected_xml = (
            b'<ns0:Envelope xmlns:ns0="http://schemas.xmlsoap.org/soap/envelope/">\n'
            b'  <ns0:Body>\n'
            b'    <ns0:echoResponse xmlns:ns0="http://soap.example/echo/types">\n'
            b'      <value>foobar</value>\n'
            b'    </ns0:echoResponse>\n'
            b'  </ns0:Body>\n'
            b'</ns0:Envelope>\n'
        )
        assert_equals(expected_xml, response_xml)
Example #18
0
 def test_can_reject_malformed_xml_soap_message(self):
     request = SOAPRequest(dict(SOAPACTION='echo', REQUEST_METHOD='POST'), 'garbage')
     dispatcher = SOAPDispatcher(echo_service())
     response = dispatcher.dispatch(request)
     assert_equals(500, response.http_status_code)
     assert_equals('text/xml', response.http_headers['Content-Type'])
     self.assert_is_soap_fault(response, partial_fault_string=u"Start tag expected, '<' not found")
Example #19
0
    def test_can_include_imported_schemas_during_validation(self):
        # In case the SOAPDispatcher would not use imported schemas for
        # validation it would fail because the 'code' tag is only defined in
        # the imported schema
        handler, handler_state = echo_handler()
        service = echo_service(handler)

        class CodeType(xsd.String):
            pattern = r'[0-9]{5}'

        class Container(xsd.ComplexType):
            value = xsd.Element(CodeType)
        code_schema = xsd.Schema('http://soap.example/included',
                                 location='http://soap.example/included',
                                 elementFormDefault=xsd.ElementFormDefault.UNQUALIFIED,
                                 simpleTypes=[CodeType],
                                 complexTypes=[Container],
                                 elements={'foo': xsd.Element(Container)},
                                 )
        service.methods[0].input = 'foo'
        service.schemas[0].imports = [code_schema]
        # The setup is a bit simplistic because the <code> tag is not parsed
        # into a soapfish model element for the handler but this was enough
        # to trigger the bug
        dispatcher = SOAPDispatcher(service)
        wsgi_environ = dict(SOAPACTION='echo', REQUEST_METHOD='POST')
        soap_message = '<ns0:foo xmlns:ns0="http://soap.example/included"><value>12345</value></ns0:foo>'
        request = SOAPRequest(wsgi_environ, self._wrap_with_soap_envelope(soap_message))
        response = dispatcher.dispatch(request)
        self.assert_is_successful_response(response, handler_state)
        assert_equals('12345', handler_state.input_.value)
Example #20
0
 def test_rendering_timezones(self):
     time_ = time(10,
                  15,
                  20,
                  tzinfo=iso8601.FixedOffset(1, 15, 'dummy zone'))
     rendered_xml = self.xsd_type().xmlvalue(time_)
     assert_equals('10:15:20+01:15', rendered_xml)
Example #21
0
 def test_can_generate_extension_of_type_with_special_chars(self):
     xml = utils.open_document(
         'tests/assets/generation/extension_with_special_chars.xsd')
     code = xsd2py.generate_code_from_xsd(xml)
     schemas, symbols = generated_symbols(code)
     assert_true('BaseType_with_special_chars_123' in symbols)
     assert_equals('BaseType_with_special_chars_123',
                   symbols['ComplexType'].__base__.__name__)
 def test_accepts_plain_strings_even_if_subclassed(self):
     class StringWithPattern(xsd.String):
         pattern = r'[0-9]{3}'
     self.xsd_type = StringWithPattern
     stored = self.assert_can_set('123')
     assert_equals('123', stored)
     self.assert_can_not_set('abc')
     self.assert_can_not_set('1234')
 def test_can_generate_code_for_two_schemas(self):
     xml = utils.open_document("tests/assets/generation/multi_schema.wsdl")
     code = wsdl2py.generate_code_from_wsdl(xml, "client")
     schemas, symbols = generated_symbols(code)
     assert_is_not_empty(schemas)
     assert_length(4, symbols)
     assert_equals(["A"], list(schemas[0].elements))
     assert_equals(["B"], list(schemas[1].elements))
Example #24
0
 def test_fails_with_sensible_default_error_message(self):
     try:
         assert_not_raises(Exception, self._fail_with(ValueError))
     except AssertionError as e:
         assert_equals('unexpected exception ValueError()',
                       exception_message(e))
     else:
         self.fail('test did not catch exception!')
Example #25
0
 def test_can_generate_code_for_two_schemas(self):
     xml = utils.open_document('tests/assets/generation/multi_schema.wsdl')
     code = wsdl2py.generate_code_from_wsdl(xml, 'client')
     schemas, symbols = generated_symbols(code)
     assert_is_not_empty(schemas)
     assert_length(2, [s for s in symbols if s.startswith('Schema_')])
     assert_equals(['A'], list(schemas[0].elements))
     assert_equals(['B'], list(schemas[1].elements))
Example #26
0
    def test_parsing_timezone(self):
        class Test(xsd.ComplexType):
            time_ = xsd.Element(self.xsd_type, tagname='time')

        parsed = Test.parsexml('<root><time>20:19:00+01:00</time></root>')
        assert_equals(
            time(20, 19, 0, tzinfo=iso8601.FixedOffset(1, 0, '+01:00')),
            parsed.time_)
    def test_can_omit_optional_attributes(self):
        instance = self.SampleType(name='someName')
        element = etree.Element('sample')
        instance.render(element, instance)

        assert_equals('someName', element.get('name'))
        assert_none(element.get('value'))
        assert_none(element.get('type'))
 def test_can_generate_code_for_two_schemas(self):
     xml = utils.open_document('tests/assets/generation/multi_schema.wsdl')
     code = wsdl2py.generate_code_from_wsdl(xml, 'client')
     schemas, symbols = generated_symbols(code)
     assert_is_not_empty(schemas)
     assert_length(2, [s for s in symbols if s.startswith('Schema_')])
     assert_equals(['A'], list(schemas[0].elements))
     assert_equals(['B'], list(schemas[1].elements))
Example #29
0
 def test_relative_paths(self):
     path = 'tests/assets/relative/relative.wsdl'
     xml = utils.open_document(path)
     code = wsdl2py.generate_code_from_wsdl(xml, 'server', cwd=os.path.dirname(path))
     if six.PY3:
         code = code.decode()
     assert_contains('Schema2_Element', code)
     assert_contains('Schema3_Element', code)
     assert_equals(1, code.count('Schema3_Element'))
 def test_can_generate_code_for_inheritance(self):
     xml = utils.open_document('tests/assets/generation/inheritance.wsdl')
     code = wsdl2py.generate_code_from_wsdl(xml, 'client')
     schemas, symbols = generated_symbols(code)
     assert_is_not_empty(schemas)
     assert_length(4, symbols)
     assert_equals(['B', 'A'], list(schemas[0].elements))
     assert_isinstance(schemas[0].elements['B']._type, xsd.String)
     assert_isinstance(schemas[0].elements['A']._type, schemas[0].elements['B']._type.__class__)
Example #31
0
    def test_supports_very_distant_dates(self):
        raise SkipTest(
            'XSDDate can currently only represent the value range of datetime.date'
        )
        future = XSDDate(12345, 4, 21)
        assert_equals(12345, future.year)

        past = XSDDate(-12345, 4, 21)
        assert_equals(-12345, past.year)
Example #32
0
 def test_can_generate_code_for_inheritance(self):
     xml = utils.open_document('tests/assets/generation/inheritance.wsdl')
     code = wsdl2py.generate_code_from_wsdl(xml, 'client')
     schemas, symbols = generated_symbols(code)
     assert_is_not_empty(schemas)
     assert_length(4, symbols)
     assert_equals(['B', 'A'], list(schemas[0].elements))
     assert_isinstance(schemas[0].elements['B']._type, xsd.String)
     assert_isinstance(schemas[0].elements['A']._type, schemas[0].elements['B']._type.__class__)
Example #33
0
    def test_accepts_plain_strings_even_if_subclassed(self):
        class StringWithPattern(xsd.String):
            pattern = r'[0-9]{3}'

        self.xsd_type = StringWithPattern
        stored = self.assert_can_set('123')
        assert_equals('123', stored)
        self.assert_can_not_set('abc')
        self.assert_can_not_set('1234')
Example #34
0
    def test_can_reject_non_soap_xml_body(self):
        request = SOAPRequest(dict(SOAPACTION='echo', REQUEST_METHOD='POST'), '<some>xml</some>')
        dispatcher = SOAPDispatcher(echo_service())

        # previously this raised an AttributeError due to an unhandled exception
        response = dispatcher.dispatch(request)
        assert_equals(500, response.http_status_code)
        assert_equals('text/xml', response.http_headers['Content-Type'])
        self.assert_is_soap_fault(response, partial_fault_string=u'Missing SOAP body')
    def test_can_omit_optional_attributes(self):
        with testutil.import_code(self.code) as generated:
            instance = generated.SampleType(sampleAttrs=generated.SampleAttrs(name='someName'))
            element = etree.Element('sample')
            instance.render(element, instance)

            assert_equals('someName', element.get('name'))
            assert_none(element.get('value'))
            assert_none(element.get('type'))
Example #36
0
 def test_can_reject_malformed_xml_soap_message(self):
     request = SOAPRequest(dict(SOAPACTION='echo', REQUEST_METHOD='POST'),
                           'garbage')
     dispatcher = SOAPDispatcher(echo_service())
     response = dispatcher.dispatch(request)
     assert_equals(500, response.http_status_code)
     assert_equals('text/xml', response.http_headers['Content-Type'])
     self.assert_is_soap_fault(
         response,
         partial_fault_string=u"Start tag expected, '<' not found")
Example #37
0
 def test_can_specify_additional_custom_message(self):
     try:
         assert_not_raises(Exception,
                           self._fail_with(ValueError),
                           message='Foo')
     except AssertionError as e:
         assert_equals('unexpected exception ValueError(): Foo',
                       exception_message(e))
     else:
         self.fail('test did not catch exception!')
Example #38
0
    def test_can_reject_non_soap_xml_body(self):
        request = SOAPRequest(dict(SOAPACTION='echo', REQUEST_METHOD='POST'),
                              '<some>xml</some>')
        dispatcher = SOAPDispatcher(echo_service())

        # previously this raised an AttributeError due to an unhandled exception
        response = dispatcher.dispatch(request)
        assert_equals(500, response.http_status_code)
        assert_equals('text/xml', response.http_headers['Content-Type'])
        self.assert_is_soap_fault(response,
                                  partial_fault_string=u'Missing SOAP body')
Example #39
0
    def test_can_generate_code_for_simple_element(self):
        xml = utils.open_document('tests/assets/generation/simple_element.xsd')
        code = xsd2py.generate_code_from_xsd(xml)

        schemas, symbols = generated_symbols(code)
        assert_is_not_empty(schemas)
        assert_length(1, symbols)

        assert_equals(['simpleElement'], list(schemas[0].elements))
        simple_element = schemas[0].elements['simpleElement']
        assert_isinstance(simple_element._type, xsd.String)
Example #40
0
    def test_can_generate_code_for_simple_element(self):
        xml = utils.open_document('tests/assets/generation/simple_element.xsd')
        code = xsd2py.generate_code_from_xsd(xml)

        schemas, symbols = generated_symbols(code)
        assert_is_not_empty(schemas)
        assert_length(1, symbols)

        assert_equals(['simpleElement'], list(schemas[0].elements))
        simple_element = schemas[0].elements['simpleElement']
        assert_isinstance(simple_element._type, xsd.String)
Example #41
0
    def test_can_generate_list_enumeration(self):
        xml = utils.open_document('tests/assets/generation/enumeration.xsd')
        code = xsd2py.generate_code_from_xsd(xml)
        schemas, symbols = generated_symbols(code)
        assert_is_not_empty(schemas)
        assert_length(2, symbols)

        assert_true(issubclass(symbols['MyList'], xsd.List))

        my_list = symbols['MyList']()
        assert_equals(my_list.accept(['B']), True)
Example #42
0
 def _check_reparse_wsdl(self, base, target):
     tree = py2wsdl.generate_wsdl(base['PutOpsPort_SERVICE'])
     xml = etree.tostring(tree, pretty_print=True)
     code = wsdl2py.generate_code_from_wsdl(xml, target)
     m = {}
     self._exec(code, m)
     # XXX too much autonaming magic
     m['PutOpsPort_SERVICE'] = m.pop('PutOpsPortPort_SERVICE')
     if target == 'client':
         m['PutOpsPortServiceStub'] = m.pop('PutOpsPortPortServiceStub')
     assert_equals(sorted(m), sorted(base))
Example #43
0
    def test_can_generate_list_enumeration(self):
        xml = utils.open_document('tests/assets/generation/enumeration.xsd')
        code = xsd2py.generate_code_from_xsd(xml)
        schemas, symbols = generated_symbols(code)
        assert_is_not_empty(schemas)
        assert_length(2, symbols)

        assert_true(issubclass(symbols['MyList'], xsd.List))

        my_list = symbols['MyList']()
        assert_equals(my_list.accept(['B']), True)
Example #44
0
 def _check_reparse_wsdl(self, base, target):
     tree = py2wsdl.generate_wsdl(base['PutOpsPort_SERVICE'])
     xml = etree.tostring(tree, pretty_print=True)
     code = wsdl2py.generate_code_from_wsdl(xml, target)
     m = {}
     self._exec(code, m)
     # XXX too much autonaming magic
     m['PutOpsPort_SERVICE'] = m.pop('PutOpsPortPort_SERVICE')
     if target == 'client':
         m['PutOpsPortServiceStub'] = m.pop('PutOpsPortPortServiceStub')
     assert_equals(sorted(m), sorted(base))
Example #45
0
    def test_parsing(self):
        self.assert_parse(None, None)
        self.assert_parse(None, 'nil')
        self.assert_parse(XSDDate(2012, 10, 26), '2012-10-26')
        self.assert_parse(XSDDate(2016, 2, 29, tzinfo=UTC), '2016-02-29Z')
        parsed_date = self._parse('2012-02-29+01:00')
        assert_equals(date(2012, 2, 29), parsed_date.as_datetime_date())
        self.assert_same_tz(FixedOffset(1, 0, '+01:00'), parsed_date.tzinfo)

        parsed_date = self._parse('2012-02-29-02:30')
        assert_equals(date(2012, 2, 29), parsed_date.as_datetime_date())
        self.assert_same_tz(FixedOffset(-2, -30, '-02:30'), parsed_date.tzinfo)
Example #46
0
 def test_can_render_elements_with_anonymous_simple_types(self):
     element = xsdspec.Element()
     element.name = 'versionNumber'
     element.simpleType = xsdspec.SimpleType(
         restriction=xsdspec.Restriction(base='string',
                                         pattern=xsdspec.Pattern(
                                             value='\d{2}\.\d{1,2}')))
     expected_xml = (b'<element name="versionNumber">\n'
                     b'  <simpleType>\n'
                     b'    <restriction base="string">\n'
                     b'      <pattern value="\d{2}\.\d{1,2}"/>\n'
                     b'    </restriction>\n'
                     b'  </simpleType>\n'
                     b'</element>\n')
     assert_equals(expected_xml, element.xml('element'))
Example #47
0
    def test_soap11_fault_handling(self):
        service = soap.Service(
            location='mock_location',
            methods=[],
            name=None,
            schemas=[],
            targetNamespace=None,
            version=soap.SOAPVersion.SOAP11,
        )
        stub = soap.Stub(location='empty', service=service)

        e = assert_raises(core.SOAPError, lambda: stub._handle_response(None, None, SOAP11_ERROR_MESSAGE))
        assert_equals('Result', e.code)
        assert_none(e.message)
        assert_equals('Resultset empty2.', e.actor)
Example #48
0
    def test_can_parse_choice_groups(self):
        schema = self._choice_schema()
        Result = schema.elements['result']._type

        xml = '<message>foo bar</message>'
        self.assert_is_valid(self._result_wrap(xml), schema)
        result = Result.parse_xmlelement(etree.fromstring(xml))
        assert_equals('foo bar', result.message)
        assert_none(result.code)

        xml = '<code>123</code>'
        self.assert_is_valid(self._result_wrap(xml), schema)
        result = Result.parse_xmlelement(etree.fromstring(xml))
        assert_none(result.message)
        assert_equals('123', result.code)
Example #49
0
 def test_can_propagate_custom_input_header(self):
     handler, handler_state = echo_handler()
     dispatcher = SOAPDispatcher(echo_service(handler, input_header=EchoInputHeader))
     soap_header = ('<tns:InputVersion>42</tns:InputVersion>')
     soap_message = (
         '<tns:echoRequest>'
         '<value>foobar</value>'
         '</tns:echoRequest>'
     )
     request_message = self._wrap_with_soap_envelope(soap_message, header=soap_header)
     request = SOAPRequest(dict(SOAPACTION='echo', REQUEST_METHOD='POST'), request_message)
     response = dispatcher.dispatch(request)
     self.assert_is_successful_response(response, handler_state)
     assert_not_none(handler_state.input_header)
     assert_equals('42', handler_state.input_header.InputVersion)
Example #50
0
    def test_can_correctly_determine_utc_offset(self):
        # Ensure that the DateTime type really uses the correct UTC offset
        # depending on the passed datetime value.
        class SummerWinterTZ(tzinfo):
            def utcoffset(self, dt):
                if dt.month in (10, 11, 12, 1, 2, 3):
                    return timedelta(0)
                return timedelta(hours=1)

            def dst(self, dt):
                return timedelta(hours=1)
        tz = SummerWinterTZ()
        xsd_dt = xsd.DateTime()
        assert_equals('2013-11-26T00:00:00+00:00', xsd_dt.xmlvalue(datetime(2013, 11, 26, tzinfo=tz)))
        assert_equals('2013-07-26T00:00:00+01:00', xsd_dt.xmlvalue(datetime(2013, 7, 26, tzinfo=tz)))
Example #51
0
    def test_can_parse_choice_groups(self):
        schema = self._choice_schema()
        Result = schema.elements['result']._type

        xml = '<message>foo bar</message>'
        self.assert_is_valid(self._result_wrap(xml), schema)
        result = Result.parse_xmlelement(etree.fromstring(xml))
        assert_equals('foo bar', result.message)
        assert_none(result.code)

        xml = '<code>123</code>'
        self.assert_is_valid(self._result_wrap(xml), schema)
        result = Result.parse_xmlelement(etree.fromstring(xml))
        assert_none(result.message)
        assert_equals('123', result.code)
    def test_can_lookup_element_by_name(self):
        ns = 'http://soap.example/schema.xsd'

        class CodeType(xsd.String):
            pattern = r'[0-9]{5}'
        schema = xsd.Schema(ns,
                            location=ns,
                            elementFormDefault=xsd.ElementFormDefault.QUALIFIED,
                            simpleTypes=[CodeType],
                            elements={'code': xsd.Element(CodeType)}
                            )
        schema_element = schema.get_element_by_name('code')
        assert_equals(CodeType, schema_element._passed_type)

        assert_none(schema.get_element_by_name('invalid'))
Example #53
0
    def test_can_lookup_element_by_name(self):
        ns = 'http://soap.example/schema.xsd'

        class CodeType(xsd.String):
            pattern = r'[0-9]{5}'

        schema = xsd.Schema(
            ns,
            location=ns,
            elementFormDefault=xsd.ElementFormDefault.QUALIFIED,
            simpleTypes=[CodeType],
            elements={'code': xsd.Element(CodeType)})
        schema_element = schema.get_element_by_name('code')
        assert_equals(CodeType, schema_element._passed_type)

        assert_none(schema.get_element_by_name('invalid'))
Example #54
0
 def test_can_propagate_custom_input_header(self):
     handler, handler_state = echo_handler()
     dispatcher = SOAPDispatcher(
         echo_service(handler, input_header=EchoInputHeader))
     soap_header = ('<tns:InputVersion>42</tns:InputVersion>')
     soap_message = ('<tns:echoRequest>'
                     '<value>foobar</value>'
                     '</tns:echoRequest>')
     request_message = self._wrap_with_soap_envelope(soap_message,
                                                     header=soap_header)
     request = SOAPRequest(dict(SOAPACTION='echo', REQUEST_METHOD='POST'),
                           request_message)
     response = dispatcher.dispatch(request)
     self.assert_is_successful_response(response, handler_state)
     assert_not_none(handler_state.input_header)
     assert_equals('42', handler_state.input_header.InputVersion)
Example #55
0
 def test_return_soap_fault_on_exception(self):
     def handler(request, _input):
         raise Exception('unexpected exception')
     service = echo_service(handler)
     dispatcher = SOAPDispatcher(service, [ExceptionToSoapFault()])
     soap_message = (
         '<tns:echoRequest xmlns:tns="http://soap.example/echo/types">'
         '<value>foobar</value>'
         '</tns:echoRequest>'
     )
     request_message = self._wrap_with_soap_envelope(soap_message)
     request = SOAPRequest(dict(SOAPACTION='echo', REQUEST_METHOD='POST'), request_message)
     response = dispatcher.dispatch(request)
     self.assert_is_soap_fault(response, fault_code=service.version.Code.SERVER,
                               partial_fault_string=u'Internal Error')
     assert_equals('text/xml', response.http_headers['Content-Type'])
     assert_equals(500, response.http_status_code)
    def test_can_render_references_to_groups(self):
        class Person(xsd.Group):
            name = xsd.Element(xsd.String)

        class Job(xsd.ComplexType):
            title = xsd.Element(xsd.String)
            person = xsd.Ref(Person)

        job = Job()
        job.person = Person(name=u'Foo Bar')
        assert_equals(u'Foo Bar', job.person.name)
        # TODO: actually I think the current state is invalid as title is missing?
        expected_xml = (
            b'<job>\n'
            b'  <name>Foo Bar</name>\n'
            b'</job>\n'
        )
        assert_equals(expected_xml, job.xml('job'))
Example #57
0
    def test_can_use_soap_error_from_handler(self):
        soap_error = SOAPError('code', 'internal data error', 'actor')

        def faulty_handler(request, input_):
            return SOAPResponse(soap_error)
        dispatcher = SOAPDispatcher(echo_service(handler=faulty_handler))
        soap_message = (
            '<ns1:echoRequest xmlns:ns1="http://soap.example/echo/types">'
            '<value>foobar</value>'
            '</ns1:echoRequest>'
        )
        request_message = self._wrap_with_soap_envelope(soap_message)
        request = SOAPRequest(dict(REQUEST_METHOD='POST'), request_message)

        response = dispatcher.dispatch(request)
        assert_equals('text/xml', response.http_headers['Content-Type'])
        assert_equals(500, response.http_status_code)
        self.assert_is_soap_fault(response, fault_code='code', partial_fault_string=u'internal data error')
    def test_can_render_references_to_complex_types(self):
        class Person(xsd.ComplexType):
            name = xsd.Element(xsd.String)

        class Job(xsd.ComplexType):
            title = xsd.Element(xsd.String)
            person = xsd.Ref(Person)

        job = Job()
        job.person = Person(name=u'Foo Bar')
        assert_equals(u'Foo Bar', job.person.name)
        expected_xml = (
            b'<job>\n'
            b'  <person>\n'
            b'    <name>Foo Bar</name>\n'
            b'  </person>\n'
            b'</job>\n'
        )
        assert_equals(expected_xml, job.xml('job'))
 def test_can_render_elements_with_anonymous_simple_types(self):
     element = xsdspec.Element()
     element.name = 'versionNumber'
     element.simpleType = xsdspec.SimpleType(
         restriction=xsdspec.Restriction(
             base='string',
             pattern=xsdspec.Pattern(value='\d{2}\.\d{1,2}')
         )
     )
     expected_xml = (
         b'<element name="versionNumber">\n'
         b'  <simpleType>\n'
         b'    <restriction base="string">\n'
         b'      <pattern value="\d{2}\.\d{1,2}"/>\n'
         b'    </restriction>\n'
         b'  </simpleType>\n'
         b'</element>\n'
     )
     assert_equals(expected_xml, element.xml('element'))