From: <ps...@us...> - 2008-12-12 08:05:47
|
Revision: 1476 http://pywebsvcs.svn.sourceforge.net/pywebsvcs/?rev=1476&view=rev Author: psha Date: 2008-12-12 08:05:39 +0000 (Fri, 12 Dec 2008) Log Message: ----------- Fix timezone handling in TCtimes Time * When parsing convert all times (dateTime and gTime elements) to local timezone if possible (year must be in range [datetime.MINYEAR, datetime.MAXYEAR]) * dateTime and gTime are serialized to UTC timezone. Argument is treated as local time Date * Date formats (gDate, gYear, ...) ignore timezone portion e.g. values 1968+15:00, 1968Z and 1968 are equal. So this part is not confirming to specs. * Serialize all dates without timezone part. Fixed bugs: #2133723 #2014802 Modified Paths: -------------- trunk/zsi/ZSI/TCtimes.py trunk/zsi/test/test_TCtimes.py Modified: trunk/zsi/ZSI/TCtimes.py =================================================================== --- trunk/zsi/ZSI/TCtimes.py 2008-12-11 04:20:26 UTC (rev 1475) +++ trunk/zsi/ZSI/TCtimes.py 2008-12-12 08:05:39 UTC (rev 1476) @@ -9,14 +9,11 @@ import operator, re, time as _time from time import mktime as _mktime, localtime as _localtime, gmtime as _gmtime from datetime import tzinfo as _tzinfo, timedelta as _timedelta,\ - datetime as _datetime + datetime as _datetime, MINYEAR, MAXYEAR from math import modf as _modf -_niltime = [ - 0, 0, 0, # year month day - 0, 0, 0, # hour minute second - 0, 0, 0 # weekday, julian day, dst flag -] +# Year, month or day may be None +_niltime = [None] * 3 + [0] * 6 #### Code added to check current timezone offset _zero = _timedelta(0) @@ -24,7 +21,6 @@ if _time.daylight: _dstoffset = _timedelta(seconds=-_time.altzone) _dstdiff = _dstoffset - _stdoffset - class _localtimezone(_tzinfo): """ """ def dst(self, dt): @@ -75,6 +71,41 @@ """datetime -> minutes east of UTC (negative for west of UTC).""" return self.__offset +def _tz_to_tzinfo(tz): + if not tz: + return _localtimezone() + if tz == "Z": tz = "+00:00" + h, m = map(int, tz.split(':')) + if h < 0: m = -m + return _fixedoffset(60 * h + m) + +def _fix_timezone(tv, tz_from = "Z", tz_to = None): + if None in tv[3:5]: # Hour or minute is absent + return tv + + # Fix local copy of time tuple + ltv = list(_fix_none_fields(tv)) + + if ltv[0] < MINYEAR or ltv[0] > MAXYEAR: + return tv # Unable to fix timestamp + + _tz_from = _tz_to_tzinfo(tz_from) + _tz_to = _tz_to_tzinfo(tz_to) + + ltv[:6] = _datetime(*(ltv[:6] + [0, _tz_from])).astimezone(_tz_to).timetuple()[:6] + + # Patch local copy with original values + for i in range(0, 6): + if tv[i] is None: ltv[i] = None + + return tuple(ltv) + +def _fix_none_fields(tv): + ltv = list(tv) + if ltv[0] is None: ltv[0] = MINYEAR + 1 # Year is absent + if ltv[1] is None: ltv[1] = 1 # Month is absent + if ltv[2] is None: ltv[2] = 1 # Day is absent + return tuple(ltv) def _dict_to_tuple(d): '''Convert a dictionary to a time tuple. Depends on key values in the @@ -96,42 +127,10 @@ if v: msec,sec = _modf(float(v)) retval[6],retval[5] = int(round(msec*1000)), int(sec) - - v = d.get('tz') - if v and v != 'Z': - h,m = map(int, v.split(':')) - # check for time zone offset, if within the same timezone, - # ignore offset specific calculations - offset=_localtimezone().utcoffset(_datetime.now()) - local_offset_hour = offset.seconds/3600 - local_offset_min = (offset.seconds%3600)%60 - if local_offset_hour > 12: - local_offset_hour -= 24 - - if local_offset_hour != h or local_offset_min != m: - if h<0: - #TODO: why is this set to server - #foff = _fixedoffset(-((abs(h)*60+m)),"server") - foff = _fixedoffset(-((abs(h)*60+m))) - else: - #TODO: why is this set to server - #foff = _fixedoffset((abs(h)*60+m),"server") - foff = _fixedoffset((abs(h)*60+m)) - - dt = _datetime(retval[0],retval[1],retval[2],retval[3],retval[4], - retval[5],0,foff) - - # update dict with calculated timezone - localdt=dt.astimezone(_localtimezone()) - retval[0] = localdt.year - retval[1] = localdt.month - retval[2] = localdt.day - retval[3] = localdt.hour - retval[4] = localdt.minute - retval[5] = localdt.second - + if d.get('neg', 0): - retval[0:5] = map(operator.__neg__, retval[0:5]) + retval[0:5] = map(lambda x: (x is not None or x) and operator.__neg__(x), retval[0:5]) + return tuple(retval) @@ -188,6 +187,7 @@ '''Gregorian times. ''' lex_pattern = tag = format = None + fix_timezone = False def text_to_data(self, text, elt, ps): '''convert text into typecode specific data. @@ -203,7 +203,12 @@ except ValueError, e: #raise EvaluateException(str(e)) raise - + + if self.fix_timezone: + retval = _fix_timezone(retval, tz_from = m.groupdict().get('tz'), tz_to = None) + + retval = _fix_none_fields(retval) + if self.pyclass is not None: return self.pyclass(retval) return retval @@ -212,6 +217,9 @@ if type(pyobj) in _floattypes or type(pyobj) in _inttypes: pyobj = _gmtime(pyobj) + if self.fix_timezone: + pyobj = _fix_timezone(pyobj, tz_from = None, tz_to = "Z") + d = {} pyobj = tuple(pyobj) if 1 in map(lambda x: x < 0, pyobj[0:6]): @@ -220,17 +228,18 @@ else: d['neg'] = '' + d = {} + for k,i in [ ('Y', 0), ('M', 1), ('D', 2), ('h', 3), ('m', 4), ('s', 5) ]: + d[k] = pyobj[i] + ms = pyobj[6] if not ms or not hasattr(self, 'format_ms'): - d = { 'Y': pyobj[0], 'M': pyobj[1], 'D': pyobj[2], - 'h': pyobj[3], 'm': pyobj[4], 's': pyobj[5], } return self.format % d if ms > 999: raise ValueError, 'milliseconds must be a integer between 0 and 999' - d = { 'Y': pyobj[0], 'M': pyobj[1], 'D': pyobj[2], - 'h': pyobj[3], 'm': pyobj[4], 's': pyobj[5], 'ms':ms, } + d['ms'] = ms return self.format_ms % d @@ -245,6 +254,7 @@ tag, format = 'dateTime', '%(Y)04d-%(M)02d-%(D)02dT%(h)02d:%(m)02d:%(s)02dZ' format_ms = format[:-1] + '.%(ms)03dZ' type = (SCHEMA.XSD3, 'dateTime') + fix_timezone = True class gDate(Gregorian): '''A date. @@ -253,7 +263,7 @@ lex_pattern = re.compile('^' r'(?P<neg>-?)' \ '(?P<Y>\d{4,})-' r'(?P<M>\d\d)-' r'(?P<D>\d\d)' \ r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$') - tag, format = 'date', '%(Y)04d-%(M)02d-%(D)02dZ' + tag, format = 'date', '%(Y)04d-%(M)02d-%(D)02d' type = (SCHEMA.XSD3, 'date') class gYearMonth(Gregorian): @@ -263,7 +273,7 @@ lex_pattern = re.compile('^' r'(?P<neg>-?)' \ '(?P<Y>\d{4,})-' r'(?P<M>\d\d)' \ r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$') - tag, format = 'gYearMonth', '%(Y)04d-%(M)02dZ' + tag, format = 'gYearMonth', '%(Y)04d-%(M)02d' type = (SCHEMA.XSD3, 'gYearMonth') class gYear(Gregorian): @@ -273,7 +283,7 @@ lex_pattern = re.compile('^' r'(?P<neg>-?)' \ '(?P<Y>\d{4,})' \ r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$') - tag, format = 'gYear', '%(Y)04dZ' + tag, format = 'gYear', '%(Y)04d' type = (SCHEMA.XSD3, 'gYear') class gMonthDay(Gregorian): @@ -283,7 +293,7 @@ lex_pattern = re.compile('^' r'(?P<neg>-?)' \ r'--(?P<M>\d\d)-' r'(?P<D>\d\d)' \ r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$') - tag, format = 'gMonthDay', '---%(M)02d-%(D)02dZ' + tag, format = 'gMonthDay', '--%(M)02d-%(D)02d' type = (SCHEMA.XSD3, 'gMonthDay') @@ -294,7 +304,7 @@ lex_pattern = re.compile('^' r'(?P<neg>-?)' \ r'---(?P<D>\d\d)' \ r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$') - tag, format = 'gDay', '---%(D)02dZ' + tag, format = 'gDay', '---%(D)02d' type = (SCHEMA.XSD3, 'gDay') class gMonth(Gregorian): @@ -302,9 +312,9 @@ ''' parselist = [ (None,'gMonth') ] lex_pattern = re.compile('^' r'(?P<neg>-?)' \ - r'---(?P<M>\d\d)' \ + r'--(?P<M>\d\d)' \ r'(?P<tz>Z|([-+]\d\d:\d\d))?' '$') - tag, format = 'gMonth', '---%(M)02dZ' + tag, format = 'gMonth', '--%(M)02d' type = (SCHEMA.XSD3, 'gMonth') class gTime(Gregorian): @@ -317,5 +327,6 @@ tag, format = 'time', '%(h)02d:%(m)02d:%(s)02dZ' format_ms = format[:-1] + '.%(ms)03dZ' type = (SCHEMA.XSD3, 'time') + fix_timezone = True if __name__ == '__main__': print _copyright Modified: trunk/zsi/test/test_TCtimes.py =================================================================== --- trunk/zsi/test/test_TCtimes.py 2008-12-11 04:20:26 UTC (rev 1475) +++ trunk/zsi/test/test_TCtimes.py 2008-12-12 08:05:39 UTC (rev 1476) @@ -10,21 +10,32 @@ class TestCase(unittest.TestCase): '''Examples from "Definitive XML Schema, Priscilla Walmsley, p237-246 ''' - def check_dateTime_local_offset(self): - # UTC with local timezone offset - # - typecode = TC.gDateTime() - off_hour = time.altzone/60/60 - off_min = time.altzone%60 - stamp_offset = '1968-04-02T13:20:00+%02d:%02d' %(off_hour,off_min) - data = typecode.text_to_data(stamp_offset, None, None) - stamp = typecode.get_formatted_content(data) + def _check_data2data(self, tc, data, correct, msg): + tmp = tc.text_to_data(data, None, None) + stamp = tc.get_formatted_content(tmp) - correct = "1968-04-01T22:20:00Z" self.failUnless(stamp == correct, - 'dateTime with local offset(%s), expecting "%s" got "%s"' %( - stamp_offset, correct, stamp)) + '%s with local offset(%s): expecting "%s" got "%s"' %( + msg, data, correct, stamp)) + def check_datetime_timezone(self): + # UTC with local timezone offset + # Base example from http://www.w3.org/TR/xmlschema11-2/#dateTime-lexical-mapping + + correct = "2002-10-10T17:00:00Z" + for t in ['2002-10-10T12:00:00-05:00', '2002-10-10T19:00:00+02:00', '2002-10-10T17:00:00+00:00', '2002-10-10T17:00:00Z']: + self._check_data2data(TC.gDateTime(), t, correct, 'dateTime') + + def check_time_timezone(self): + correct = "17:30:00Z" + for t in ['12:30:00-05:00', '19:30:00+02:00', '17:30:00+00:00']: + self._check_data2data(TC.gTime(), t, correct, 'time') + + def check_date_timezone(self): + correct = "2002-10-10" + for t in ['2002-10-10-05:00', '2002-10-10+02:00', '2002-10-10+00:00', '2002-10-10Z']: + self._check_data2data(TC.gDate(), t, correct, 'date') + def check_valid_dateTime(self): typecode = TC.gDateTime() for i in ('1968-04-02T13:20:00', '1968-04-02T13:20:15.5', @@ -42,7 +53,7 @@ def check_serialize_microseconds(self): dateTime = '1968-04-02T13:20:15.511Z' typecode = TC.gDateTime() - text = typecode.get_formatted_content((1968, 4, 2, 13, 20, 15, 511, 0, 0)) + text = typecode.get_formatted_content((1968, 4, 2, 13 - time.timezone / 3600, 20, 15, 511, 0, 0)) self.failUnless(text == dateTime, 'did not serialze correctly %s, not equal %s' %(text, dateTime)) @@ -60,7 +71,7 @@ typecode.get_formatted_content(bad) def check_parse_microseconds2(self): - good = (1968, 4, 2, 13, 20, 15, 500, 0, 0) + good = (1968, 4, 2, 13 - time.timezone / 3600, 20, 15, 500, 0, 0) typecode = TC.gDateTime() data = typecode.text_to_data('1968-04-02T13:20:15.5Z', None,None) self.failUnless(data == good, @@ -109,11 +120,32 @@ for i in ('68-04-02', '1968-4-2', '1968/04/02', '04-02-1968',): self.failUnlessRaises(Exception, typecode.text_to_data, i, None, None), + def check_valid_cast(self): + text = "2002-10-10T17:00:00Z" + tc = TC.gDateTime() + data = tc.text_to_data(text, None, None) + + tct = TC.gTime() + tcd = TC.gDate() + self.assertEquals("2002-10-10", tcd.get_formatted_content(data), "Invalid cast from gDateTime to gDate") + self.assertEquals("17:00:00Z", tct.get_formatted_content(data), "Invalid cast from gDateTime to gTime") + def broke_invalid_date_april31(self): # No checks for valid date April 30 days typecode = TC.gDate() self.failUnlessRaises(Exception, typecode.text_to_data, '1968-04-31', None, None), + def check_gdates(self): + def _assert_tc(tc, val, msg): + self.assertEquals(val, tc.get_formatted_content(tc.text_to_data(val, None, None)), "%s: %s" % (msg, val)) + + _assert_tc(TC.gYear(), '1984', "Invalid gYear") + _assert_tc(TC.gYearMonth(), '1984-10', "Invalid gYearMonth") + _assert_tc(TC.gMonth(), '--10', "Invalid gMonth") + _assert_tc(TC.gMonthDay(), '--10-30', "Invalid gMonthDay") + _assert_tc(TC.gDay(), '---30', "Invalid gDay") + _assert_tc(TC.gDate(), '1984-10-30', "Invalid gDate") + # # Creates permutation of test options: "check", "check_any", etc # This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ps...@us...> - 2008-12-12 14:24:44
|
Revision: 1477 http://pywebsvcs.svn.sourceforge.net/pywebsvcs/?rev=1477&view=rev Author: psha Date: 2008-12-12 14:24:40 +0000 (Fri, 12 Dec 2008) Log Message: ----------- Implement TC.Union.text_to_data method Just like TC.Union.parse - try to parse by every member typecode and raise exception if none succeded. Needed by WS-Addressing for RelationshipType attribute http://www.w3.org/Submission/ws-addressing/#_Toc77464323 Modified Paths: -------------- trunk/zsi/ZSI/TC.py trunk/zsi/test/test_union.py Modified: trunk/zsi/ZSI/TC.py =================================================================== --- trunk/zsi/ZSI/TC.py 2008-12-12 08:05:39 UTC (rev 1476) +++ trunk/zsi/ZSI/TC.py 2008-12-12 14:24:40 UTC (rev 1477) @@ -1575,6 +1575,29 @@ return pyobj + def text_to_data(self, text, elt, ps): + """ Copy of parse method with some cleanups and logging""" + self.setMemberTypeCodes() + + for indx in range(len(self.memberTypeCodes)): + typecode = self.memberTypeCodes[indx] + self.logger.debug("Trying member %s", str(typecode.type)) + try: + pyobj = typecode.text_to_data(text, elt, ps) + except Exception, ex: + self.logger.debug("Fail to parse with %s: %s", typecode, ex) + continue + + if indx > 0: + self.memberTypeCodes.remove(typecode) + self.memberTypeCodes.insert(0, typecode) + break + else: + raise EvaluateException('No member matches data "%s" (while parsing %s)' % (text, str(self.type)), + ps.Backtrace(elt)) + + return pyobj + def get_formatted_content(self, pyobj, **kw): self.setMemberTypeCodes() for indx in range(len(self.memberTypeCodes)): Modified: trunk/zsi/test/test_union.py =================================================================== --- trunk/zsi/test/test_union.py 2008-12-12 08:05:39 UTC (rev 1476) +++ trunk/zsi/test/test_union.py 2008-12-12 14:24:40 UTC (rev 1477) @@ -8,7 +8,6 @@ from ZSI.wstools.Namespaces import WSA200403, SOAP from cStringIO import StringIO - # # Generated code class ns3: @@ -34,8 +33,13 @@ def __init__(self, pname, **kw): ZSI.TC.Union.__init__(self, pname, **kw) +class TestUnionTC(ZSI.TC.Union, TypeDefinition): + memberTypes = [(u'http://www.w3.org/2001/XMLSchema', u'long'), (u'http://www.w3.org/2001/XMLSchema', u'dateTime')] + schema = "urn:test:union" + type = (schema, "TestUnion") + def __init__(self, pname, **kw): + ZSI.TC.Union.__init__(self, pname, **kw) - class UnionTestCase(unittest.TestCase): "test Union TypeCode" @@ -61,8 +65,17 @@ # so string is going to parse the URI when we want anyURI self.failUnless(value == pyobj, 'Expected equivalent') + def check_union_text_to_data(self): + from ZSI.TC import EvaluateException + class _PS: + def Backtrace(self, *a, **kw): return "" + typecode = TestUnionTC("TestUnion") + self.assertEquals(100, typecode.text_to_data('100', None, None), "Fail to parse long") + date = typecode.text_to_data("2002-10-30T12:30:00Z", None, None) + self.assertEquals((2002, 10, 30), date[:3], "Fail to parse dateTime") + self.assertRaises(EvaluateException, typecode.text_to_data, "urn:string", None, _PS()) + - def makeTestSuite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(UnionTestCase, "check")) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lcl...@us...> - 2009-03-31 18:27:11
|
Revision: 1482 http://pywebsvcs.svn.sourceforge.net/pywebsvcs/?rev=1482&view=rev Author: lclement Date: 2009-03-31 18:27:03 +0000 (Tue, 31 Mar 2009) Log Message: ----------- Added binary attachment support (only cliend side). Modified Paths: -------------- trunk/zsi/CHANGES trunk/zsi/ZSI/TCapache.py trunk/zsi/ZSI/client.py trunk/zsi/ZSI/typeinterpreter.py trunk/zsi/ZSI/writer.py trunk/zsi/test/test_t8.py Modified: trunk/zsi/CHANGES =================================================================== --- trunk/zsi/CHANGES 2009-02-10 20:05:51 UTC (rev 1481) +++ trunk/zsi/CHANGES 2009-03-31 18:27:03 UTC (rev 1482) @@ -5,6 +5,8 @@ - In SoapWriter, put nsdecls on body, not envelope - Record facets (restrictions) in XMLSchema.py <vc...@da...> - Remove Send()'s kwargs out of _args list <ef...@bo...> + - Added support for file attachment using AXIS apachesoap:DataHandler to + reference it in the WSDL (only client side) lcl...@sf... Change for 2.1.0_a1 released 31-Oct-2007: - No PyXML Dependency, use minidom by default (much faster) Modified: trunk/zsi/ZSI/TCapache.py =================================================================== --- trunk/zsi/ZSI/TCapache.py 2009-02-10 20:05:51 UTC (rev 1481) +++ trunk/zsi/ZSI/TCapache.py 2009-03-31 18:27:03 UTC (rev 1482) @@ -4,7 +4,9 @@ ''' from ZSI import _copyright, _child_elements, _get_idstr -from ZSI.TC import TypeCode, Struct as _Struct, Any as _Any +from ZSI.TC import SimpleType, TypeCode, Struct as _Struct, Any as _Any +from ZSI.wstools.logging import getLogger as _GetLogger +#import types class Apache: NS = "http://xml.apache.org/xml-soap" @@ -70,6 +72,54 @@ self.tc.serialize(el, sw, {'key': k, 'value': v}, name='item') +class AttachmentRef(SimpleType): + '''Type code for Attachment. This attachment will work only with axis... + ''' + + logger = _GetLogger('ZSI.TC.Attachment') + type = (Apache.NS, "DataHandler") + parselist = [(Apache.NS, "DataHandler")] + #seriallist = [ types.FileType ] + + def __init__(self, pname=None, format='%s', **kw): + TypeCode.__init__(self, pname, **kw) + self.format = format + + + def parse(self, elt, ps): + #never invoked ??? + #print "elt is: " + str(elt) + #print "while ps: " + str(ps) + return + + def get_formatted_content(self, pyobj): + return self.format %pyobj + + def serialize(self, elt, sw, pyobj, name=None, orig=None, **kw): + '''This function is in charge of serializing the attachment + fist it add the <attachment href=""/> tag + then it wraps up everything + + pyobj is the file descriptor pointing to the file we wanna attach + elt is the ElementProxy containing the <inputFile> tag with the attachment tag + sw SoapWriter + ''' + #print "serialize called with pyobj: " + str(pyobj) + #adding the attachment tag + if pyobj is None: + return + if not sw.Known(pyobj): + sw.addAttachment(pyobj) + idhref = id(pyobj) + attachmentElement = elt.createAppendElement(None, "attachment", prefix="") + attachmentElement.setAttributeNS(None, "href", "cid:" + str(idhref)) + else: + #print "the file " + pyobj + " was already attached" + #do nothing + #this should not happen + pass + + Apache.Map = _Map if __name__ == '__main__': print _copyright Modified: trunk/zsi/ZSI/client.py =================================================================== --- trunk/zsi/ZSI/client.py 2009-02-10 20:05:51 UTC (rev 1481) +++ trunk/zsi/ZSI/client.py 2009-03-31 18:27:03 UTC (rev 1482) @@ -289,6 +289,8 @@ soapdata = str(sw) self.h = transport(netloc, None, **self.transdict) self.h.connect() + self.boundary = sw.getMIMEBoundary() + self.startCID = sw.getStartCID() self.SendSOAPData(soapdata, url, soapaction, **kw) def SendSOAPData(self, soapdata, url, soapaction, headers={}, **kw): @@ -301,7 +303,13 @@ request_uri = _get_postvalue_from_absoluteURI(url) self.h.putrequest("POST", request_uri) self.h.putheader("Content-Length", "%d" % len(soapdata)) - self.h.putheader("Content-Type", 'text/xml; charset="%s"' %UNICODE_ENCODING) + if len(self.boundary) == 0: + #no attachment + self.h.putheader("Content-Type", 'text/xml; charset="%s"' %UNICODE_ENCODING) + else: + #we have attachment + contentType = "multipart/related; " + self.h.putheader("Content-Type" , "multipart/related; boundary=\"" + self.boundary + "\"; start=\"" + self.startCID + '\"; type="text/xml"') self.__addcookies() for header,value in headers.items(): Modified: trunk/zsi/ZSI/typeinterpreter.py =================================================================== --- trunk/zsi/ZSI/typeinterpreter.py 2009-02-10 20:05:51 UTC (rev 1481) +++ trunk/zsi/ZSI/typeinterpreter.py 2009-03-31 18:27:03 UTC (rev 1482) @@ -31,7 +31,7 @@ TC.gMonthDay, TC.InonPositiveInteger, \ TC.Ibyte, TC.FPdouble, TC.gTime, TC.gYear, \ TC.Ilong, TC.IunsignedLong, TC.Ishort, \ - TC.Token, TC.QName] + TC.Token, TC.QName, ZSI.TCapache.AttachmentRef] self._tc_to_int = [ ZSI.TCnumbers.IEnumeration, @@ -63,7 +63,8 @@ ZSI.TC.String, ZSI.TC.URI, ZSI.TC.XMLString, - ZSI.TC.Token] + ZSI.TC.Token, + ZSI.TCapache.AttachmentRef] self._tc_to_tuple = [ ZSI.TC.Duration, @@ -86,7 +87,7 @@ if untaged_xsd_types.has_key(msg_type): return untaged_xsd_types[msg_type] for tc in self._type_list: - if tc.type == (SCHEMA.XSD3,msg_type): + if tc.type == (SCHEMA.XSD3,msg_type) or tc.type == (SCHEMA.AXIS,msg_type): break else: tc = TC.AnyType Modified: trunk/zsi/ZSI/writer.py =================================================================== --- trunk/zsi/ZSI/writer.py 2009-02-10 20:05:51 UTC (rev 1481) +++ trunk/zsi/ZSI/writer.py 2009-03-31 18:27:03 UTC (rev 1482) @@ -8,6 +8,8 @@ from ZSI.wstools.Utility import MessageInterface, ElementProxy from ZSI.wstools.Namespaces import XMLNS, SOAP, SCHEMA from ZSI.wstools.c14n import Canonicalize +from ZSI.wstools.MIMEAttachment import MIMEMessage + import types _standard_ns = [ ('xml', XMLNS.XML), ('xmlns', XMLNS.BASE) ] @@ -46,11 +48,36 @@ self.body = None self.callbacks = [] self.closed = False + self._attachments = [] + self._MIMEBoundary = "" + self._startCID = "" def __str__(self): self.close() - return str(self.dom) + if len(self._attachments) == 0: + #we have no attachment let's return the SOAP message + return str(self.dom) + else: + #we have some files to attach let's create the MIME message + #first part the SOAP message + msg = MIMEMessage() + msg.addXMLMessage(str(self.dom)) + for file in self._attachments: + msg.attachFile(file) + msg.makeBoundary() + self._MIMEBoundary = msg.getBoundary() + self._startCID = msg.getStartCID() + return msg.toString() + def getMIMEBoundary(self): + #return the httpHeader if any + return self._MIMEBoundary + + def getStartCID(self): + #return the CID of the xml part + return self._startCID + + def getSOAPHeader(self): if self.header in (True, False): return None @@ -120,7 +147,7 @@ if root not in [ 0, 1 ]: raise ValueError, "SOAP-ENC root attribute not in [0,1]" elt.setAttributeNS(SOAP.ENC, 'root', root) - + return self def writeNSdict(self, nsdict): @@ -175,6 +202,12 @@ ''' return _backtrace(elt._getNode(), self.dom._getNode()) + + def addAttachment(self, fileDesc): + '''This function add an attachment to the SaopMessage + ''' + self._attachments.append(fileDesc) + def close(self): '''Invoke all the callbacks, and close off the SOAP message. ''' Modified: trunk/zsi/test/test_t8.py =================================================================== --- trunk/zsi/test/test_t8.py 2009-02-10 20:05:51 UTC (rev 1481) +++ trunk/zsi/test/test_t8.py 2009-03-31 18:27:03 UTC (rev 1482) @@ -1,6 +1,6 @@ #!/usr/bin/env python import unittest, sys, types, time -from ZSI import TC, SoapWriter, ParsedSoap, EvaluateException +from ZSI import TC, SoapWriter, ParsedSoap, EvaluateException, TCapache from ZSI.wstools.Namespaces import SCHEMA, SOAP NSDICT = {'tns':'xmlns:tns="urn:a"', @@ -31,7 +31,7 @@ def check_parse_empty_all(self): # None - skip = [TC.FPEnumeration, TC.Enumeration, TC.IEnumeration, TC.List, TC.Integer] + skip = [TC.FPEnumeration, TC.Enumeration, TC.IEnumeration, TC.List, TC.Integer, TCapache.AttachmentRef] for typeclass in filter(lambda c: type(c) in [types.ClassType,type] and not issubclass(c, TC.String) and issubclass(c, TC.SimpleType), TC.__dict__.values()): if typeclass in skip: continue tc = typeclass() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bov...@us...> - 2009-04-27 19:14:59
|
Revision: 1490 http://pywebsvcs.svn.sourceforge.net/pywebsvcs/?rev=1490&view=rev Author: boverhof Date: 2009-04-27 19:14:49 +0000 (Mon, 27 Apr 2009) Log Message: ----------- A test/test_AnyType.py M test/test_zsi.py M ZSI/__init__.py M ZSI/TC.py -- FIX BUG [ ZSI.EvaluateException: Any can't parse element - ID: 2762639 ] Modified Paths: -------------- trunk/zsi/ZSI/TC.py trunk/zsi/ZSI/__init__.py trunk/zsi/test/test_zsi.py Added Paths: ----------- trunk/zsi/test/test_AnyType.py Modified: trunk/zsi/ZSI/TC.py =================================================================== --- trunk/zsi/ZSI/TC.py 2009-04-09 18:46:59 UTC (rev 1489) +++ trunk/zsi/ZSI/TC.py 2009-04-27 19:14:49 UTC (rev 1490) @@ -1465,7 +1465,7 @@ # element declarations prefix, typeName = SplitQName(_find_type(elt)) if not skip and typeName: - namespaceURI = _resolve_prefix(elt, prefix or 'xmlns') + namespaceURI = _resolve_prefix(elt, prefix) # First look thru user defined namespaces, if don't find # look for 'primitives'. pyclass = GTD(namespaceURI, typeName) or Any Modified: trunk/zsi/ZSI/__init__.py =================================================================== --- trunk/zsi/ZSI/__init__.py 2009-04-09 18:46:59 UTC (rev 1489) +++ trunk/zsi/ZSI/__init__.py 2009-04-27 19:14:49 UTC (rev 1490) @@ -224,9 +224,9 @@ _find_type = lambda E: _find_xsi_attr(E, "type") _find_xmlns_prefix = lambda E, attr: E.getAttributeNS(_XMLNS.BASE, attr) -_find_default_namespace = lambda E: E.getAttributeNS(_XMLNS.BASE, None) +_find_default_namespace = lambda E: E.getAttributeNS(_XMLNS.BASE, 'xmlns') -#_textprotect = lambda s: s.replace('&', '&').replace('<', '<') +_textprotect = lambda s: s.replace('&', '&').replace('<', '<') _get_element_nsuri_name = lambda E: (E.namespaceURI, E.localName) Added: trunk/zsi/test/test_AnyType.py =================================================================== --- trunk/zsi/test/test_AnyType.py (rev 0) +++ trunk/zsi/test/test_AnyType.py 2009-04-27 19:14:49 UTC (rev 1490) @@ -0,0 +1,74 @@ +#!/usr/bin/env python +import unittest, sys, tests_good, tests_bad, time +from ZSI import * +try: + import cStringIO as StringIO +except ImportError: + import StringIO + +"""Bug [ 1520092 ] URI Bug: urllib.quote escaping reserved chars + Bug [ 2748314 ] Malformed type attribute (bad NS) with 2.1a1 but not with 2. +""" + +class MyInt_Def(TC.Integer, schema.TypeDefinition): + # ComplexType/SimpleContent derivation of built-in type + schema = "urn:vim25" + type = (schema, "myInt") + def __init__(self, pname, **kw): + self.attribute_typecode_dict = {} + TC.Integer.__init__(self, pname, **kw) + #class Holder(int): + # __metaclass__ = pyclass_type + # typecode = self + #self.pyclass = Holder + self.pyclass = int + +class TestCase(unittest.TestCase): + + def check_type_attribute_qname_in_default_ns(self): + msg = """ +<ns1:test xsi:type="ns1:myInt" xmlns:ns1="urn:vim25" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="http://www.w3.org/2001/XMLSchema"> +100 +</ns1:test>""" + ps = ParsedSoap(msg, envelope=False) + pyobj = ps.Parse(TC.AnyType(pname=("urn:vim25","test"))) + self.failUnless(pyobj == 100, 'failed to parse type in default ns') + + def check_element_in_default_ns(self): + msg = """ +<test xsi:type="myInt" xmlns="urn:vim25" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:xsd="http://www.w3.org/2001/XMLSchema"> +100 +</test>""" + ps = ParsedSoap(msg, envelope=False) + pyobj = ps.Parse(TC.AnyType(pname=("urn:vim25","test"))) + self.failUnless(pyobj == 100, 'failed to parse element in default ns') + + +# +# Creates permutation of test options: "check", "check_any", etc +# +_SEP = '_' +for t in [i[0].split(_SEP) for i in filter(lambda i: callable(i[1]), TestCase.__dict__.items())]: + test = '' + for f in t: + test += f + if globals().has_key(test): test += _SEP; continue + def _closure(): + name = test + def _makeTestSuite(): + suite = unittest.TestSuite() + suite.addTest(unittest.makeSuite(TestCase, name)) + return suite + return _makeTestSuite + + globals()[test] = _closure() + test += _SEP + + +makeTestSuite = check +def main(): + unittest.main(defaultTest="makeTestSuite") +if __name__ == "__main__" : main() + Modified: trunk/zsi/test/test_zsi.py =================================================================== --- trunk/zsi/test/test_zsi.py 2009-04-09 18:46:59 UTC (rev 1489) +++ trunk/zsi/test/test_zsi.py 2009-04-27 19:14:49 UTC (rev 1490) @@ -14,6 +14,7 @@ import test_URI import test_rfc2617 import test_QName +import test_AnyType def makeTestSuite(): return unittest.TestSuite( This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bov...@us...> - 2009-05-18 19:48:39
|
Revision: 1491 http://pywebsvcs.svn.sourceforge.net/pywebsvcs/?rev=1491&view=rev Author: boverhof Date: 2009-05-18 19:48:29 +0000 (Mon, 18 May 2009) Log Message: ----------- M test/wsdl2py/wsdl/test_SubstitutionGroup.xsd M ZSI/TCcompound.py Changes: -- formerly: parse all items, set into a dict, then loop on that dict and set all items on pyobj -- now: parse all items, set in pyobj directly, if no pyclass return "pyobj.__dict__" Wildcards (any): -- formerly: parse, then set them last -- now: parse & set them inorder Unittest change: -- was actually wrong since it was an extension of a type that had a wildcard -- remove wildcard declaration in base so "child" can be parsed by the "extension" element Modified Paths: -------------- trunk/zsi/ZSI/TCcompound.py trunk/zsi/test/wsdl2py/wsdl/test_SubstitutionGroup.xsd Modified: trunk/zsi/ZSI/TCcompound.py =================================================================== --- trunk/zsi/ZSI/TCcompound.py 2009-04-27 19:14:49 UTC (rev 1490) +++ trunk/zsi/ZSI/TCcompound.py 2009-05-18 19:48:29 UTC (rev 1491) @@ -92,6 +92,7 @@ elements. ''' logger = _GetLogger('ZSI.TCcompound.ComplexType') + class _DictHolder: pass def __init__(self, pyclass, ofwhat, pname=None, inorder=False, inline=False, mutable=True, mixed=False, mixed_aname='_text', **kw): @@ -156,17 +157,26 @@ if self.nilled(elt, ps): return Nilled # Create the object. - v = {} + if self.pyclass: + # type definition must be informed of element tag (nspname,pname), + # element declaration is initialized with a tag. + try: + pyobj = self.pyclass() + except Exception, e: + raise TypeError("Constructing element (%s,%s) with pyclass(%s), %s" \ + %(self.nspname, self.pname, self.pyclass.__name__, str(e))) + else: + pyobj = ComplexType._DictHolder() # parse all attributes contained in attribute_typecode_dict (user-defined attributes), # the values (if not None) will be keyed in self.attributes dictionary. attributes = self.parse_attributes(elt, ps) if attributes: - v[self.attrs_aname] = attributes + setattr(pyobj, self.attrs_aname, attributes) #MIXED if self.mixed is True: - v[self.mixed_aname] = self.simple_value(elt,ps, mixed=True) + setattr(pyobj, self.mixed_aname, self.simple_value(elt,ps, mixed=True)) # Clone list of kids (we null it out as we process) c, crange = c[:], range(len(c)) @@ -194,6 +204,9 @@ if what.name_match(c_elt): match = True value = what.parse(c_elt, ps) + elif isinstance(what,AnyElement): + match = True + value = what.parse(c_elt, ps) else: # substitutionGroup head must be a global element declaration # if successful delegate to matching GED @@ -207,14 +220,15 @@ if match: if what.maxOccurs > 1: - if v.has_key(what.aname): - v[what.aname].append(value) + attr = getattr(pyobj, what.aname, None) + if attr is not None: + attr.append(value) else: - v[what.aname] = [value] + setattr(pyobj, what.aname, [value]) c[j] = None continue else: - v[what.aname] = value + setattr(pyobj, what.aname, value) c[j] = None break @@ -226,48 +240,15 @@ raise EvaluateException('Out of order complexType', ps.Backtrace(c_elt)) else: - # only supporting 1 <any> declaration in content. - if isinstance(what,AnyElement): - any = what - elif hasattr(what, 'default'): - v[what.aname] = what.default - elif what.minOccurs > 0 and not v.has_key(what.aname): + if hasattr(what, 'default'): + setattr(pyobj, what.aname, what.default) + elif what.minOccurs > 0 and not hasattr(pyobj, what.aname): raise EvaluateException('Element "' + what.aname + \ '" missing from complexType', ps.Backtrace(elt)) - # Look for wildcards and unprocessed children - # XXX Stick all this stuff in "any", hope for no collisions - if any is not None: - occurs = 0 - v[any.aname] = [] - for j,c_elt in [ (j, c[j]) for j in crange if c[j] ]: - value = any.parse(c_elt, ps) - if any.maxOccurs == UNBOUNDED or any.maxOccurs > 1: - v[any.aname].append(value) - else: - v[any.aname] = value + if isinstance(pyobj, ComplexType._DictHolder): + return pyobj.__dict__ - occurs += 1 - - # No such thing as nillable <any> - if any.maxOccurs == 1 and occurs == 0: - v[any.aname] = None - elif occurs < any.minOccurs or (any.maxOccurs!=UNBOUNDED and any.maxOccurs<occurs): - raise EvaluateException('occurances of <any> elements(#%d) bound by (%d,%s)' %( - occurs, any.minOccurs,str(any.maxOccurs)), ps.Backtrace(elt)) - - if not self.pyclass: - return v - - # type definition must be informed of element tag (nspname,pname), - # element declaration is initialized with a tag. - try: - pyobj = self.pyclass() - except Exception, e: - raise TypeError("Constructing element (%s,%s) with pyclass(%s), %s" \ - %(self.nspname, self.pname, self.pyclass.__name__, str(e))) - for key in v.keys(): - setattr(pyobj, key, v[key]) return pyobj def serialize(self, elt, sw, pyobj, inline=False, name=None, **kw): Modified: trunk/zsi/test/wsdl2py/wsdl/test_SubstitutionGroup.xsd =================================================================== --- trunk/zsi/test/wsdl2py/wsdl/test_SubstitutionGroup.xsd 2009-04-27 19:14:49 UTC (rev 1490) +++ trunk/zsi/test/wsdl2py/wsdl/test_SubstitutionGroup.xsd 2009-05-18 19:48:29 UTC (rev 1491) @@ -9,7 +9,6 @@ <xsd:complexType name='baseType'> <xsd:sequence> <xsd:element name="base" type='xsd:string'/> - <xsd:any namespace="##other" minOccurs="0" maxOccurs="unbounded" processContents="lax"/> </xsd:sequence> </xsd:complexType> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <bov...@us...> - 2009-08-24 23:40:34
|
Revision: 1495 http://pywebsvcs.svn.sourceforge.net/pywebsvcs/?rev=1495&view=rev Author: boverhof Date: 2009-08-24 23:40:21 +0000 (Mon, 24 Aug 2009) Log Message: ----------- M test/wsdl2py/config.txt M test/wsdl2py/test_AWSECommerceService.py -- updated namespace, but RPC returns an error "missing Signature" so I'm catching it then punting for later M ZSI/__init__.py -- _get_default_namespace calls change to key "xmlns" M ZSI/TC.py -- ParsedSoap.GetElementNSDict actually changes key "xmlns" to '', so must use '' to grab default ns Modified Paths: -------------- trunk/zsi/ZSI/TC.py trunk/zsi/ZSI/__init__.py trunk/zsi/test/wsdl2py/config.txt trunk/zsi/test/wsdl2py/test_AWSECommerceService.py Modified: trunk/zsi/ZSI/TC.py =================================================================== --- trunk/zsi/ZSI/TC.py 2009-08-24 21:55:45 UTC (rev 1494) +++ trunk/zsi/ZSI/TC.py 2009-08-24 23:40:21 UTC (rev 1495) @@ -213,15 +213,8 @@ # Parse the QNAME. prefix,typeName = SplitQName(typeName) - nsdict = ps.GetElementNSdict(elt) - prefix = prefix or '' - - try: - uri = nsdict[prefix] - except KeyError, ex: - raise EvaluateException('cannot resolve prefix(%s)'%prefix, - ps.Backtrace(elt)) - + # Use '' for default namespace with ParsedSoap + uri = ps.GetElementNSdict(elt).get(prefix or '') if uri is None: raise EvaluateException('Malformed type attribute (bad NS)', ps.Backtrace(elt)) Modified: trunk/zsi/ZSI/__init__.py =================================================================== --- trunk/zsi/ZSI/__init__.py 2009-08-24 21:55:45 UTC (rev 1494) +++ trunk/zsi/ZSI/__init__.py 2009-08-24 23:40:21 UTC (rev 1495) @@ -251,6 +251,9 @@ else: if prefix: raise EvaluateException, 'cant resolve xmlns:%s' %prefix + else: + raise EvaluateException, 'cant resolve default namespace' + return namespaceURI def _valid_encoding(elt): Modified: trunk/zsi/test/wsdl2py/config.txt =================================================================== --- trunk/zsi/test/wsdl2py/config.txt 2009-08-24 21:55:45 UTC (rev 1494) +++ trunk/zsi/test/wsdl2py/config.txt 2009-08-24 23:40:21 UTC (rev 1495) @@ -186,6 +186,7 @@ test_NVOAdmin = wsdl/nvo-admin.wsdl test_Clearspace = http://eval.jivesoftware.com/clearspace/rpc/soap/BlogService?wsdl test_VIM = wsdl/vim.wsdl +test_VIM25 = wsdl/vim25/vimService.wsdl test_NoMessagePart = wsdl/NoMessagePart.wsdl Modified: trunk/zsi/test/wsdl2py/test_AWSECommerceService.py =================================================================== --- trunk/zsi/test/wsdl2py/test_AWSECommerceService.py 2009-08-24 21:55:45 UTC (rev 1494) +++ trunk/zsi/test/wsdl2py/test_AWSECommerceService.py 2009-08-24 23:40:21 UTC (rev 1495) @@ -43,8 +43,7 @@ -#TargetNamespace = 'http://webservices.amazon.com/AWSECommerceService/2007-10-29' -TargetNamespace = 'http://webservices.amazon.com/AWSECommerceService/2009-02-01' +TargetNamespace = 'http://webservices.amazon.com/AWSECommerceService/2009-07-01' class AmazonTestCase(ServiceTestCase): """Test case for Amazon ECommerce Web service @@ -112,7 +111,11 @@ request.Keywords = 'Tamerlane' request.ResponseGroup = ['Medium',] - response = port.ItemSearch(msg) + try: + response = port.ItemSearch(msg) + except: + # NOTE: Requires a Signature now.. skip rest, returns a soap fault + return response.OperationRequest self.failUnless(response.OperationRequest.Errors is None, 'ecommerce site reported errors') This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <em...@us...> - 2011-12-01 08:17:13
|
Revision: 1501 http://pywebsvcs.svn.sourceforge.net/pywebsvcs/?rev=1501&view=rev Author: emmebi Date: 2011-12-01 08:17:02 +0000 (Thu, 01 Dec 2011) Log Message: ----------- Just a quick fix: the zsi.xsd was not available anymore at the old location, so I moved it into the ZSI website, which should provide a more stable URL. Modified Paths: -------------- trunk/zsi/setup.cfg trunk/zsi/test/test_t4.py Modified: trunk/zsi/setup.cfg =================================================================== --- trunk/zsi/setup.cfg 2011-11-21 17:58:29 UTC (rev 1500) +++ trunk/zsi/setup.cfg 2011-12-01 08:17:02 UTC (rev 1501) @@ -8,7 +8,7 @@ minor = 1 patchlevel = 0 candidate = 0 -alpha = 1 +alpha = 2 beta = 0 [egg_info] Modified: trunk/zsi/test/test_t4.py =================================================================== --- trunk/zsi/test/test_t4.py 2011-11-21 17:58:29 UTC (rev 1500) +++ trunk/zsi/test/test_t4.py 2011-12-01 08:17:02 UTC (rev 1501) @@ -11,7 +11,7 @@ xmlns:ZSI="http://www.zolera.com/schemas/ZSI/"> <SOAP-ENV:Body> <hreftest> - <xmltest href="http://www-itg.lbl.gov/~kjackson/zsi.xsd"/> + <xmltest href="http://pywebsvcs.sourceforge.net/zsi.xsd"/> <stringtest href="http://www.microsoft.com"/> </hreftest> </SOAP-ENV:Body> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <em...@us...> - 2012-03-29 10:46:33
|
Revision: 1502 http://pywebsvcs.svn.sourceforge.net/pywebsvcs/?rev=1502&view=rev Author: emmebi Date: 2012-03-29 10:46:23 +0000 (Thu, 29 Mar 2012) Log Message: ----------- Just a little clean-up of the existing tests, plus the removal of a few warnings. Modified Paths: -------------- trunk/zsi/ZSI/digest_auth.py trunk/zsi/ZSI/resolvers.py trunk/zsi/test/test_AnyType.py trunk/zsi/test/test_QName.py trunk/zsi/test/test_TCtimes.py trunk/zsi/test/test_URI.py trunk/zsi/test/test_callhome.py trunk/zsi/test/test_list.py trunk/zsi/test/test_rfc2617.py trunk/zsi/test/test_t1.py trunk/zsi/test/test_t2.py trunk/zsi/test/test_t3.py trunk/zsi/test/test_t4.py trunk/zsi/test/test_t5.py trunk/zsi/test/test_t6.py trunk/zsi/test/test_t7.py trunk/zsi/test/test_t9.py trunk/zsi/test/test_union.py trunk/zsi/test/test_zsi.py trunk/zsi/test/test_zsi_net.py Modified: trunk/zsi/ZSI/digest_auth.py =================================================================== --- trunk/zsi/ZSI/digest_auth.py 2011-12-01 08:17:02 UTC (rev 1501) +++ trunk/zsi/ZSI/digest_auth.py 2012-03-29 10:46:23 UTC (rev 1502) @@ -2,11 +2,14 @@ # $Header$ '''Utilities for HTTP Digest Authentication ''' +import httplib +import random import re -from md5 import md5 -import random import time -import httplib +try: + from hashlib import md5 +except ImportError: + from md5 import md5 random.seed(int(time.time()*10)) Modified: trunk/zsi/ZSI/resolvers.py =================================================================== --- trunk/zsi/ZSI/resolvers.py 2011-12-01 08:17:02 UTC (rev 1501) +++ trunk/zsi/ZSI/resolvers.py 2012-03-29 10:46:23 UTC (rev 1502) @@ -3,12 +3,18 @@ '''SOAP messaging parsing. ''' -from ZSI import _copyright, _child_elements, EvaluateException, TC -import multifile, mimetools, urllib +try: + import cStringIO as StringIO +except ImportError: + import StringIO +import multifile +import mimetools +import urllib from base64 import decodestring as b64decode -import cStringIO as StringIO +from ZSI import _copyright, _child_elements, EvaluateException, TC + def Opaque(uri, tc, ps, **keywords): '''Resolve a URI and return its content as a string. ''' Modified: trunk/zsi/test/test_AnyType.py =================================================================== --- trunk/zsi/test/test_AnyType.py 2011-12-01 08:17:02 UTC (rev 1501) +++ trunk/zsi/test/test_AnyType.py 2012-03-29 10:46:23 UTC (rev 1502) @@ -1,11 +1,9 @@ #!/usr/bin/env python -import unittest, sys, tests_good, tests_bad, time -from ZSI import * -try: - import cStringIO as StringIO -except ImportError: - import StringIO +import unittest + +from ZSI import schema, ParsedSoap, TC + """Bug [ 1520092 ] URI Bug: urllib.quote escaping reserved chars Bug [ 2748314 ] Malformed type attribute (bad NS) with 2.1a1 but not with 2. """ Modified: trunk/zsi/test/test_QName.py =================================================================== --- trunk/zsi/test/test_QName.py 2011-12-01 08:17:02 UTC (rev 1501) +++ trunk/zsi/test/test_QName.py 2012-03-29 10:46:23 UTC (rev 1502) @@ -1,12 +1,9 @@ #!/usr/bin/env python -import unittest, sys, tests_good, tests_bad, time -from ZSI import * -try: - import cStringIO as StringIO -except ImportError: - import StringIO +import unittest +from ZSI import ParsedSoap, TC, FaultFromFaultMessage + """Bug [ 1520092 ] URI Bug: urllib.quote escaping reserved chars Bug [ 2748314 ] Malformed type attribute (bad NS) with 2.1a1 but not with 2. """ @@ -33,7 +30,6 @@ </soapenv:Body> </soapenv:Envelope>""" - from ZSI import ParsedSoap, FaultFromFaultMessage ps = ParsedSoap(msg) fault = FaultFromFaultMessage(ps) self.failUnless(fault.code == ('','ServerFaultCode'), 'faultcode should be (namespace,name) tuple') Modified: trunk/zsi/test/test_TCtimes.py =================================================================== --- trunk/zsi/test/test_TCtimes.py 2011-12-01 08:17:02 UTC (rev 1501) +++ trunk/zsi/test/test_TCtimes.py 2012-03-29 10:46:23 UTC (rev 1502) @@ -1,8 +1,11 @@ #!/usr/bin/env python # vim: sts=4 sw=4 et -import unittest, sys, tests_good, tests_bad, time, os -from ZSI import * +import os +import time +import unittest + +from ZSI import TC try: import cStringIO as StringIO except ImportError: Modified: trunk/zsi/test/test_URI.py =================================================================== --- trunk/zsi/test/test_URI.py 2011-12-01 08:17:02 UTC (rev 1501) +++ trunk/zsi/test/test_URI.py 2012-03-29 10:46:23 UTC (rev 1502) @@ -1,12 +1,9 @@ #!/usr/bin/env python -import unittest, sys, tests_good, tests_bad, time -from ZSI import * -try: - import cStringIO as StringIO -except ImportError: - import StringIO +import unittest +from ZSI import ParsedSoap, SoapWriter, TC + """Bug [ 1520092 ] URI Bug: urllib.quote escaping reserved chars From rfc2396: @@ -45,8 +42,8 @@ sw2.serialize(orig, typecode=tc2, typed=False) s2 = str(sw2) - print s1 - print s2 +# print s1 +# print s2 self.failUnless(s1 == s2, 'reserved characters used for reserved purpose should not be escaped.') Modified: trunk/zsi/test/test_callhome.py =================================================================== --- trunk/zsi/test/test_callhome.py 2011-12-01 08:17:02 UTC (rev 1501) +++ trunk/zsi/test/test_callhome.py 2012-03-29 10:46:23 UTC (rev 1502) @@ -1,5 +1,8 @@ #!/usr/bin/env python -import os,unittest + +import os +import unittest + from ZSI import version from ZSI.wstools.logging import gridLog @@ -9,7 +12,8 @@ class TestCase(unittest.TestCase): def ping(self): - gridLog(event="zsi.test.test_callhome.ping", zsi="v%d.%d.%d" % version.Version, prog="test_callhome.py") + gridLog(event="zsi.test.test_callhome.ping", zsi="v%d.%d.%d" % version.Version, + prog="test_callhome.py") def makeTestSuite(): suite = unittest.TestSuite() Modified: trunk/zsi/test/test_list.py =================================================================== --- trunk/zsi/test/test_list.py 2011-12-01 08:17:02 UTC (rev 1501) +++ trunk/zsi/test/test_list.py 2012-03-29 10:46:23 UTC (rev 1502) @@ -1,13 +1,15 @@ #!/usr/bin/env python -import unittest, time, datetime + +import time +import unittest +from cStringIO import StringIO + import ZSI from ZSI.writer import SoapWriter from ZSI import _get_element_nsuri_name from ZSI.schema import GED, TypeDefinition, ElementDeclaration from ZSI.parse import ParsedSoap -from cStringIO import StringIO - class TestList1_Def(ZSI.TC.List, TypeDefinition): itemType = (u'http://www.w3.org/2001/XMLSchema', u'dateTime') schema = "urn:test" @@ -15,7 +17,6 @@ def __init__(self, pname, **kw): ZSI.TC.List.__init__(self, pname, **kw) - class TestList2_Def(ZSI.TC.List, TypeDefinition): itemType = ZSI.TC.gDateTime() schema = "urn:test" @@ -23,7 +24,6 @@ def __init__(self, pname, **kw): ZSI.TC.List.__init__(self, pname, **kw) - class ListTestCase(unittest.TestCase): "test List TypeCode" @@ -44,7 +44,7 @@ sw = SoapWriter() sw.serialize(data, typecode) s = str(sw) - print s + #print s ps = ParsedSoap(s); pyobj = ps.Parse(typecode) assert pyobj == data, 'Data corruption expected "%s", got "%s"' %(str(data),str(pyobj)) if data is None: @@ -57,7 +57,6 @@ utc = list(time.gmtime(i)[:-3]) + [999,0,0] data.append(tuple(utc)) - def makeTestSuite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(ListTestCase, "check")) Modified: trunk/zsi/test/test_rfc2617.py =================================================================== --- trunk/zsi/test/test_rfc2617.py 2011-12-01 08:17:02 UTC (rev 1501) +++ trunk/zsi/test/test_rfc2617.py 2012-03-29 10:46:23 UTC (rev 1502) @@ -4,19 +4,19 @@ HTTP Authentication: Basic and Digest Access Authentication """ + import unittest + from ZSI import digest_auth -from ZSI.wstools.logging import setBasicLoggerDEBUG -setBasicLoggerDEBUG() class DATestCase(unittest.TestCase): "test Union TypeCode" def check_challenge_single_www_authenticate_header(self): challenge='Basic realm="WallyWorld"' - print "=="*30 - print challenge - print "=="*30 + #print "=="*30 + #print challenge + #print "=="*30 cd = digest_auth.fetch_challenge(challenge) expect = {'challenge': 'Basic', 'realm': 'WallyWorld'} self.failUnless(cd == expect, 'Expected equivalent') Modified: trunk/zsi/test/test_t1.py =================================================================== --- trunk/zsi/test/test_t1.py 2011-12-01 08:17:02 UTC (rev 1501) +++ trunk/zsi/test/test_t1.py 2012-03-29 10:46:23 UTC (rev 1502) @@ -1,11 +1,18 @@ #!/usr/bin/env python -import unittest, sys, tests_good, tests_bad, time -from ZSI import * try: import cStringIO as StringIO except ImportError: import StringIO +import unittest +import sys +import time +from ZSI import * + +import tests_good +import tests_bad + + class t1TestCase(unittest.TestCase): "Test case wrapper for old ZSI t1 test case" @@ -35,10 +42,10 @@ def checkt1(self): for key,val in self.badTests: - print "\n", "." * 60, key + #print "\n", "." * 60, key self.failUnlessRaises(ParseException, ParsedSoap, val) for key,val in self.goodTests: - print "\n", "." * 60, key + #print "\n", "." * 60, key ps = ParsedSoap(val) ps = ParsedSoap(datatest) @@ -141,13 +148,13 @@ a = bar() except Exception, e: f = FaultFromException(e, 0, sys.exc_info()[2]) - print f.AsSOAP() - print - print - print FaultFromNotUnderstood('myuri', 'dalocalname', actor='cher').AsSOAP() - print - print - print FaultFromActor('actor:i:dont:understand').AsSOAP() + #print f.AsSOAP() + #print + #print + #print FaultFromNotUnderstood('myuri', 'dalocalname', actor='cher').AsSOAP() + #print + #print + #print FaultFromActor('actor:i:dont:understand').AsSOAP() def makeTestSuite(): @@ -163,12 +170,15 @@ def bar(): return foo() + 2 -class zParseException: pass +class zParseException: + pass class myclass: + def __init__(self, name=None): self.name = name or id(self) self.z = 'z value' + def __str__(self): return 'myclass-%s-(%d,"%s")' % (self.name, self.i, self.t) + \ str(self.z) @@ -229,7 +239,7 @@ def main(): unittest.main(defaultTest="makeTestSuite") +if __name__ == "__main__" : + main() -if __name__ == "__main__" : main() - Modified: trunk/zsi/test/test_t2.py =================================================================== --- trunk/zsi/test/test_t2.py 2011-12-01 08:17:02 UTC (rev 1501) +++ trunk/zsi/test/test_t2.py 2012-03-29 10:46:23 UTC (rev 1502) @@ -1,8 +1,11 @@ #!/usr/bin/env python -import unittest, sys -from ZSI import * +import sys +import unittest +from ZSI import TC, ParsedSoap, ParseException, FaultFromZSIException, FaultFromException, SoapWriter + + class t2TestCase(unittest.TestCase): "Test case wrapper for old ZSI t2 test case" @@ -40,8 +43,9 @@ import operator total = reduce(operator.add, player.Scores, 0) result = Average(foo(total, len(player.Scores))) - sw = SoapWriter().serialize(result) - print >>OUT, str(sw) + sw = SoapWriter().serialize(result) + str(sw) + #print >>OUT, str(sw) except Exception, e: print >>OUT, FaultFromException(e, 0, sys.exc_info()[2]).AsSOAP() self.fail() Modified: trunk/zsi/test/test_t3.py =================================================================== --- trunk/zsi/test/test_t3.py 2011-12-01 08:17:02 UTC (rev 1501) +++ trunk/zsi/test/test_t3.py 2012-03-29 10:46:23 UTC (rev 1502) @@ -1,8 +1,8 @@ #!/usr/bin/env python import unittest from ZSI import * -from ZSI.wstools.logging import setBasicLoggerDEBUG -setBasicLoggerDEBUG() +#from ZSI.wstools.logging import setBasicLoggerDEBUG +#setBasicLoggerDEBUG() class t3TestCase(unittest.TestCase): "Test case wrapper for old ZSI t3 test case" @@ -17,14 +17,14 @@ text = f.AsSOAP() i = 0 for l in text.split('\n'): - print i, l + #print i, l i += 1 ps = ParsedSoap(text) if ps.IsAFault(): f = FaultFromFaultMessage(ps) - print f.AsSOAP() + #print f.AsSOAP() self.failUnless(f.AsSOAP().find(str(a)) > 0) - print '--'*20 + #print '--'*20 def makeTestSuite(): Modified: trunk/zsi/test/test_t4.py =================================================================== --- trunk/zsi/test/test_t4.py 2011-12-01 08:17:02 UTC (rev 1501) +++ trunk/zsi/test/test_t4.py 2012-03-29 10:46:23 UTC (rev 1502) @@ -32,7 +32,7 @@ # Faulted while processing; assume it's in the header. print >>OUT, FaultFromException(e, 1, sys.exc_info()[2]).AsSOAP() self.fail() - print 'resolving' + #print 'resolving' typecode = TC.Struct(None, [ TC.XML('xmltest'), TC.String('stringtest', resolver=r.Opaque), ]) try: @@ -45,7 +45,7 @@ print >>OUT, FaultFromException(e, 0, sys.exc_info()[2]).AsSOAP() self.fail() ##PrettyPrint(dict['xmltest']) - print '**', dict['stringtest'], '**' + #print '**', dict['stringtest'], '**' def makeTestSuite(): suite = unittest.TestSuite() Modified: trunk/zsi/test/test_t5.py =================================================================== --- trunk/zsi/test/test_t5.py 2011-12-01 08:17:02 UTC (rev 1501) +++ trunk/zsi/test/test_t5.py 2012-03-29 10:46:23 UTC (rev 1502) @@ -1,17 +1,16 @@ #!/usr/bin/env python -import unittest, multifile, mimetools -from ZSI import * -from ZSI import resolvers -from xml.dom import Node -#from xml.dom.ext.reader import PyExpat -from ZSI.parse import DefaultReader as Reader - +import mimetools +import unittest try: import cStringIO as StringIO except ImportError: import StringIO +from ZSI import resolvers +from ZSI.parse import DefaultReader as Reader + + class t5TestCase(unittest.TestCase): "Test case wrapper for old ZSI t5 test case" @@ -21,11 +20,11 @@ if m.gettype()[0:10] == "multipart/": cid = resolvers.MIMEResolver(m['content-type'], istr) xml = cid.GetSOAPPart() - print 'xml=', xml.getvalue() - for h,b in cid.parts: - print h, b.read() + #print 'xml=', xml.getvalue() +# for h,b in cid.parts: +# print h, b.read() dom = Reader.fromStream(xml) - print dom + #print dom def makeTestSuite(): suite = unittest.TestSuite() Modified: trunk/zsi/test/test_t6.py =================================================================== --- trunk/zsi/test/test_t6.py 2011-12-01 08:17:02 UTC (rev 1501) +++ trunk/zsi/test/test_t6.py 2012-03-29 10:46:23 UTC (rev 1502) @@ -1,6 +1,11 @@ #!/usr/bin/env python -import unittest, sys, multifile, mimetools, base64 -from ZSI import * +import unittest +import sys +import multifile +import mimetools +import base64 + +from ZSI import TC, ParseException, FaultFromException, ParsedSoap from ZSI import resolvers try: import cStringIO as StringIO @@ -34,16 +39,16 @@ self.failUnlessEqual(dict['stringtest'], strExtTest, "Failed to extract stringtest correctly") - print base64.encodestring(cid['pa...@zo...'].read()) + #print base64.encodestring(cid['pa...@zo...'].read()) v = dict['b64'] - print type(v), 'is type(v)' + #print type(v), 'is type(v)' self.failUnlessEqual(cid['pa...@zo...'].getvalue(), v, "mismatch") - print base64.encodestring(v) - from ZSI.wstools.c14n import Canonicalize - z = dict['xmltest'] - print type(z), z - print Canonicalize(z) + #print base64.encodestring(v) + #from ZSI.wstools.c14n import Canonicalize + #z = dict['xmltest'] + #print type(z), z + #print Canonicalize(z) def makeTestSuite(): suite = unittest.TestSuite() Modified: trunk/zsi/test/test_t7.py =================================================================== --- trunk/zsi/test/test_t7.py 2011-12-01 08:17:02 UTC (rev 1501) +++ trunk/zsi/test/test_t7.py 2012-03-29 10:46:23 UTC (rev 1502) @@ -1,8 +1,10 @@ #!/usr/bin/env python -import unittest, sys -from ZSI import * +import unittest +import sys +from ZSI import ParsedSoap, SoapWriter, TC + class t7TestCase(unittest.TestCase): "Test case wrapper for old ZSI t7 test case" @@ -14,22 +16,22 @@ d = tcdict.parse(ps.body_root, ps) self.assertEqual(d, { u'a':123, '\x00\x01':456 }) - print 'as dictionary\n', d + #print 'as dictionary\n', d l = tclist.parse(ps.body_root, ps) self.assertEqual(l, [('\x00\x01', 456), (u'a', 123)]) - print '\n', '=' * 30 - print 'as list\n', l + #print '\n', '=' * 30 + #print 'as list\n', l - print '\n', '=' * 30 + #print '\n', '=' * 30 sw = SoapWriter() sw.serialize(d, tcdict) - print >>sys.stdout, sw + #print >>sys.stdout, sw - print '\n', '=' * 30 + #print '\n', '=' * 30 sw = SoapWriter() sw.serialize(l, tclist) - print >>sys.stdout, sw + #print >>sys.stdout, sw def makeTestSuite(): suite = unittest.TestSuite() Modified: trunk/zsi/test/test_t9.py =================================================================== --- trunk/zsi/test/test_t9.py 2011-12-01 08:17:02 UTC (rev 1501) +++ trunk/zsi/test/test_t9.py 2012-03-29 10:46:23 UTC (rev 1502) @@ -1,5 +1,13 @@ #!/usr/bin/env python -import unittest, sys, sha, base64 + +import base64 +import unittest +try: + from hashlib import sha1 as local_sha +except ImportError: + import sha1 as local_sha +import sys + from ZSI import _get_element_nsuri_name from ZSI.parse import ParsedSoap from ZSI.wstools.c14n import Canonicalize @@ -25,8 +33,8 @@ s = StringIO() Canonicalize(self.el, s, unsuppressedPrefixes=None) cxml = s.getvalue() - d1 = base64.encodestring(sha.sha(C14N_INC1).digest()).strip() - d2 = base64.encodestring(sha.sha(cxml).digest()).strip() + d1 = base64.encodestring(local_sha(C14N_INC1).digest()).strip() + d2 = base64.encodestring(local_sha(cxml).digest()).strip() self.assertEqual(d1, d2) self.assertEqual(d1, C14N_INC1_DIGEST) @@ -36,8 +44,8 @@ s = StringIO() Canonicalize(self.el, s, unsuppressedPrefixes=[]) cxml = s.getvalue() - d1 = base64.encodestring(sha.sha(C14N_EXCL1).digest()).strip() - d2 = base64.encodestring(sha.sha(cxml).digest()).strip() + d1 = base64.encodestring(local_sha(C14N_EXCL1).digest()).strip() + d2 = base64.encodestring(local_sha(cxml).digest()).strip() self.assertEqual(d1, C14N_EXCL1_DIGEST) self.assertEqual(d1, d2) @@ -50,8 +58,8 @@ s = StringIO() Canonicalize(self.el, s, unsuppressedPrefixes=['xsi', 'xsd']) cxml = s.getvalue() - d1 = base64.encodestring(sha.sha(C14N_EXCL2).digest()).strip() - d2 = base64.encodestring(sha.sha(cxml).digest()).strip() + d1 = base64.encodestring(local_sha(C14N_EXCL2).digest()).strip() + d2 = base64.encodestring(local_sha(cxml).digest()).strip() self.assertEqual(d1, C14N_EXCL2_DIGEST) self.assertEqual(d1, d2) @@ -67,9 +75,9 @@ s = StringIO() Canonicalize(self.el, s, unsuppressedPrefixes=[]) cxml = s.getvalue() - print cxml - d1 = base64.encodestring(sha.sha(C14N_EXCL3).digest()).strip() - d2 = base64.encodestring(sha.sha(cxml).digest()).strip() + #print cxml + d1 = base64.encodestring(local_sha(C14N_EXCL3).digest()).strip() + d2 = base64.encodestring(local_sha(cxml).digest()).strip() self.assertEqual(d1, C14N_EXCL3_DIGEST) self.assertEqual(d1, d2) @@ -77,8 +85,8 @@ RCVDIGEST = "jhTbi7gWlY9oLqsRr+EZ0bokRFA=" CALDIGEST = "IkMyI4zCDlK41qE7sZxvkFHJioU=" - d1 = base64.encodestring(sha.sha(WRONG).digest()).strip() - d2 = base64.encodestring(sha.sha(CORRECT).digest()).strip() + d1 = base64.encodestring(local_sha(WRONG).digest()).strip() + d2 = base64.encodestring(local_sha(CORRECT).digest()).strip() ps = ParsedSoap(XML_INST4) el = filter(lambda el: _get_element_nsuri_name(el) == (WSA200403.ADDRESS, "MessageID"), @@ -87,10 +95,10 @@ s = StringIO() Canonicalize(el, s, unsuppressedPrefixes=[]) cxml = s.getvalue() - print "-- "*20 - print cxml - print "-- "*20 - d3 = base64.encodestring(sha.sha(cxml).digest()).strip() +# print "-- "*20 +# print cxml +# print "-- "*20 + d3 = base64.encodestring(local_sha(cxml).digest()).strip() self.assertEqual(d1, RCVDIGEST) self.assertEqual(d2, CALDIGEST) Modified: trunk/zsi/test/test_union.py =================================================================== --- trunk/zsi/test/test_union.py 2011-12-01 08:17:02 UTC (rev 1501) +++ trunk/zsi/test/test_union.py 2012-03-29 10:46:23 UTC (rev 1502) @@ -1,12 +1,15 @@ #!/usr/bin/env python -import unittest, sys, sha, base64 +import base64 +import unittest +import sys +from cStringIO import StringIO + import ZSI from ZSI import _get_element_nsuri_name from ZSI.schema import GED, TypeDefinition, ElementDeclaration from ZSI.parse import ParsedSoap from ZSI.wstools.c14n import Canonicalize from ZSI.wstools.Namespaces import WSA200403, SOAP -from cStringIO import StringIO # # Generated code Modified: trunk/zsi/test/test_zsi.py =================================================================== --- trunk/zsi/test/test_zsi.py 2011-12-01 08:17:02 UTC (rev 1501) +++ trunk/zsi/test/test_zsi.py 2012-03-29 10:46:23 UTC (rev 1502) @@ -26,4 +26,5 @@ unittest.main(defaultTest="makeTestSuite") suite = unittest.TestSuite() -if __name__ == "__main__" : main() +if __name__ == "__main__": + main() Modified: trunk/zsi/test/test_zsi_net.py =================================================================== --- trunk/zsi/test/test_zsi_net.py 2011-12-01 08:17:02 UTC (rev 1501) +++ trunk/zsi/test/test_zsi_net.py 2012-03-29 10:46:23 UTC (rev 1502) @@ -13,4 +13,5 @@ unittest.main(defaultTest="makeTestSuite") suite = unittest.TestSuite() -if __name__ == "__main__" : main() +if __name__ == "__main__" : + main() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |