Back to index

lightning-sunbird  0.9+nobinonly
test_test_component.py
Go to the documentation of this file.
00001 # ***** BEGIN LICENSE BLOCK *****
00002 # Version: MPL 1.1/GPL 2.0/LGPL 2.1
00003 #
00004 # The contents of this file are subject to the Mozilla Public License Version
00005 # 1.1 (the "License"); you may not use this file except in compliance with
00006 # the License. You may obtain a copy of the License at
00007 # http://www.mozilla.org/MPL/
00008 #
00009 # Software distributed under the License is distributed on an "AS IS" basis,
00010 # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
00011 # for the specific language governing rights and limitations under the
00012 # License.
00013 #
00014 # The Original Code is the Python XPCOM language bindings.
00015 #
00016 # The Initial Developer of the Original Code is
00017 # ActiveState Tool Corp.
00018 # Portions created by the Initial Developer are Copyright (C) 2000, 2001
00019 # the Initial Developer. All Rights Reserved.
00020 #
00021 # Contributor(s):
00022 #        Mark Hammond <MarkH@ActiveState.com> (original author)
00023 #
00024 # Alternatively, the contents of this file may be used under the terms of
00025 # either the GNU General Public License Version 2 or later (the "GPL"), or
00026 # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
00027 # in which case the provisions of the GPL or the LGPL are applicable instead
00028 # of those above. If you wish to allow use of your version of this file only
00029 # under the terms of either the GPL or the LGPL, and not to allow others to
00030 # use your version of this file under the terms of the MPL, indicate your
00031 # decision by deleting the provisions above and replace them with the notice
00032 # and other provisions required by the GPL or the LGPL. If you do not delete
00033 # the provisions above, a recipient may use your version of this file under
00034 # the terms of any one of the MPL, the GPL or the LGPL.
00035 #
00036 # ***** END LICENSE BLOCK *****
00037 
00038 import sys, os, time
00039 import xpcom.components
00040 import xpcom._xpcom
00041 import xpcom.nsError
00042 
00043 try:
00044     import gc
00045 except ImportError:
00046     gc = None
00047 
00048 num_errors = 0
00049 
00050 component_iid = xpcom.components.ID("{7EE4BDC6-CB53-42c1-A9E4-616B8E012ABA}")
00051 new_iid = xpcom.components.ID("{2AF747D3-ECBC-457b-9AF9-5C5D80EDC360}")
00052 
00053 contractid = "Python.TestComponent"
00054 
00055 really_big_string = "This is really repetitive!" * 10000
00056 really_big_wstring = u"This is really repetitive!" * 10000
00057 extended_unicode_string = u"The Euro Symbol is '\u20ac'"
00058 
00059 # Exception raised when a -ve integer is converted to an unsigned C integer
00060 # (via an extension module).  This changed in Python 2.2
00061 if sys.hexversion > 0x02010000:
00062     UnsignedMismatchException = TypeError
00063 else:
00064     UnsignedMismatchException = OverflowError
00065 
00066 def print_error(error):
00067     print error
00068     global num_errors
00069     num_errors = num_errors + 1
00070 
00071 def _test_value(what, got, expecting):
00072     ok = got == expecting
00073     if type(got)==type(expecting)==type(0.0):
00074         ok = abs(got-expecting) < 0.001
00075     if not ok:
00076         print_error("*** Error %s - got '%r', but expecting '%r'" % (what, got, expecting))
00077 
00078 def test_attribute(ob, attr_name, expected_init, new_value, new_value_really = None):
00079     if xpcom.verbose:
00080         print "Testing attribute %s" % (attr_name,)
00081     if new_value_really is None:
00082         new_value_really = new_value # Handy for eg bools - set a BOOL to 2, you still get back 1!
00083         
00084     _test_value( "getting initial attribute value (%s)" % (attr_name,), getattr(ob, attr_name), expected_init)
00085     setattr(ob, attr_name, new_value)
00086     _test_value( "getting new attribute value (%s)" % (attr_name,), getattr(ob, attr_name), new_value_really)
00087     # And set it back to the expected init.
00088     setattr(ob, attr_name, expected_init)
00089     _test_value( "getting back initial attribute value after change (%s)" % (attr_name,), getattr(ob, attr_name), expected_init)
00090 
00091 def test_string_attribute(ob, attr_name, expected_init, is_dumb_sz = False, ascii_only = False):
00092     test_attribute(ob, attr_name, expected_init, "normal value")
00093     val = "a null >\0<"
00094     if is_dumb_sz:
00095         expected = "a null >" # dumb strings are \0 terminated.
00096     else:
00097         expected = val
00098     test_attribute(ob, attr_name, expected_init, val, expected)
00099     test_attribute(ob, attr_name, expected_init, "")
00100     test_attribute(ob, attr_name, expected_init, really_big_string)
00101     test_attribute(ob, attr_name, expected_init, u"normal unicode value")
00102     val = u"a null >\0<"
00103     if is_dumb_sz:
00104         expected = "a null >" # dumb strings are \0 terminated.
00105     else:
00106         expected = val
00107     test_attribute(ob, attr_name, expected_init, val, expected)
00108     test_attribute(ob, attr_name, expected_init, u"")
00109     test_attribute(ob, attr_name, expected_init, really_big_wstring)
00110     if not ascii_only:
00111         test_attribute(ob, attr_name, expected_init, extended_unicode_string)
00112 
00113 def test_attribute_failure(ob, attr_name, new_value, expected_exception):
00114     try:
00115         setattr(ob, attr_name, new_value)
00116         print_error("*** Setting attribute '%s' to '%r' didnt yield an exception!" % (attr_name, new_value) )
00117     except:
00118         exc_typ = sys.exc_info()[0]
00119         exc_val = sys.exc_info()[1]
00120         ok = issubclass(exc_typ, expected_exception)
00121         if not ok:
00122             print_error("*** Wrong exception setting '%s' to '%r'- got '%s: %s', expected '%s'" % (attr_name, new_value, exc_typ, exc_val, expected_exception))
00123 
00124 
00125 def test_method(method, args, expected_results):
00126     if xpcom.verbose:
00127         print "Testing %s%s" % (method.__name__, `args`)
00128     ret = method(*args)
00129     if ret != expected_results:
00130         print_error("calling method %s - expected %r, but got %r" % (method.__name__, expected_results, ret))
00131 
00132 def test_int_method(meth):
00133     test_method(meth, (0,0), (0,0,0))
00134     test_method(meth, (1,1), (2,0,1))
00135     test_method(meth, (5,2), (7,3,10))
00136 #    test_method(meth, (2,5), (7,-3,10))
00137 
00138 def test_constant(ob, cname, val):
00139     v = getattr(ob, cname)
00140     if v != val:
00141         print_error("Bad value for constant '%s' - got '%r'" % (cname, v))
00142     try:
00143         setattr(ob, cname, 0)
00144         print_error("The object allowed us to set the constant '%s'" % (cname,))
00145     except AttributeError:
00146         pass
00147 
00148 def test_base_interface(c):
00149     test_attribute(c, "boolean_value", 1, 0)
00150     test_attribute(c, "boolean_value", 1, -1, 1) # Set a bool to anything, you should always get back 0 or 1
00151     test_attribute(c, "boolean_value", 1, 4, 1) # Set a bool to anything, you should always get back 0 or 1
00152     test_attribute(c, "boolean_value", 1, "1", 1) # This works by virtual of PyNumber_Int - not sure I agree, but...
00153     test_attribute_failure(c, "boolean_value", "boo", ValueError)
00154     test_attribute_failure(c, "boolean_value", test_base_interface, TypeError)
00155 
00156     test_attribute(c, "octet_value", 2, 5)
00157     test_attribute(c, "octet_value", 2, 0)
00158     test_attribute(c, "octet_value", 2, 128) # octet is unsigned 8 bit
00159     test_attribute(c, "octet_value", 2, 255) # octet is unsigned 8 bit
00160     test_attribute(c, "octet_value", 2, -1, 255) # octet is unsigned 8 bit
00161     test_attribute_failure(c, "octet_value", "boo", ValueError)
00162 
00163     test_attribute(c, "short_value", 3, 10)
00164     test_attribute(c, "short_value", 3, -1) # 16 bit signed
00165     test_attribute(c, "short_value", 3, 0xFFFF, -1) # 16 bit signed
00166     test_attribute(c, "short_value", 3, 0L)
00167     test_attribute(c, "short_value", 3, 1L)
00168     test_attribute(c, "short_value", 3, -1L)
00169     test_attribute(c, "short_value", 3, 0xFFFFL, -1)
00170     test_attribute_failure(c, "short_value", "boo", ValueError)
00171 
00172     test_attribute(c, "ushort_value",  4, 5)
00173     test_attribute(c, "ushort_value",  4, 0)
00174     test_attribute(c, "ushort_value",  4, -1, 0xFFFF) # 16 bit signed
00175     test_attribute(c, "ushort_value",  4, 0xFFFF) # 16 bit signed
00176     test_attribute(c, "ushort_value",  4, 0L)
00177     test_attribute(c, "ushort_value",  4, 1L)
00178     test_attribute(c, "ushort_value",  4, -1L, 0xFFFF)
00179     test_attribute_failure(c, "ushort_value", "boo", ValueError)
00180 
00181     test_attribute(c, "long_value",  5, 7)
00182     test_attribute(c, "long_value",  5, 0)
00183     test_attribute(c, "long_value",  5, 0xFFFFFFFF, -1) # 32 bit signed.
00184     test_attribute(c, "long_value",  5, -1) # 32 bit signed.
00185     test_attribute(c, "long_value",  5, 0L)
00186     test_attribute(c, "long_value",  5, 1L)
00187     test_attribute(c, "long_value",  5, -1L)
00188     test_attribute_failure(c, "long_value", 0xFFFFL * 0xFFFF, OverflowError) # long int too long to convert
00189     test_attribute_failure(c, "long_value", "boo", ValueError)
00190 
00191     test_attribute(c, "ulong_value", 6, 7)
00192     test_attribute(c, "ulong_value", 6, 0)
00193     test_attribute(c, "ulong_value", 6, 0xFFFFFFFF) # 32 bit signed.
00194     test_attribute_failure(c, "ulong_value", "boo", ValueError)
00195     
00196     test_attribute(c, "long_long_value", 7, 8)
00197     test_attribute(c, "long_long_value", 7, 0)
00198     test_attribute(c, "long_long_value", 7, -1)
00199     test_attribute(c, "long_long_value", 7, 0xFFFF)
00200     test_attribute(c, "long_long_value", 7, 0xFFFFL * 2)
00201     test_attribute_failure(c, "long_long_value", 0xFFFFL * 0xFFFF * 0xFFFF * 0xFFFF, OverflowError) # long int too long to convert
00202     test_attribute_failure(c, "long_long_value", "boo", ValueError)
00203     
00204     test_attribute(c, "ulong_long_value", 8, 9)
00205     test_attribute(c, "ulong_long_value", 8, 0)
00206     test_attribute_failure(c, "ulong_long_value", "boo", ValueError)
00207     test_attribute_failure(c, "ulong_long_value", -1, UnsignedMismatchException) # can't convert negative value to unsigned long)
00208     
00209     test_attribute(c, "float_value", 9.0, 10.2)
00210     test_attribute(c, "float_value", 9.0, 0)
00211     test_attribute(c, "float_value", 9.0, -1)
00212     test_attribute(c, "float_value", 9.0, 1L)
00213     test_attribute_failure(c, "float_value", "boo", ValueError)
00214 
00215     test_attribute(c, "double_value", 10.0, 9.0)
00216     test_attribute(c, "double_value", 10.0, 0)
00217     test_attribute(c, "double_value", 10.0, -1)
00218     test_attribute(c, "double_value", 10.0, 1L)
00219     test_attribute_failure(c, "double_value", "boo", ValueError)
00220     
00221     test_attribute(c, "char_value", "a", "b")
00222     test_attribute(c, "char_value", "a", "\0")
00223     test_attribute_failure(c, "char_value", "xy", ValueError)
00224     test_attribute(c, "char_value", "a", u"c")
00225     test_attribute(c, "char_value", "a", u"\0")
00226     test_attribute_failure(c, "char_value", u"xy", ValueError)
00227     
00228     test_attribute(c, "wchar_value", "b", "a")
00229     test_attribute(c, "wchar_value", "b", "\0")
00230     test_attribute_failure(c, "wchar_value", "hi", ValueError)
00231     test_attribute(c, "wchar_value", "b", u"a")
00232     test_attribute(c, "wchar_value", "b", u"\0")
00233     test_attribute_failure(c, "wchar_value", u"hi", ValueError)
00234     
00235     test_string_attribute(c, "string_value", "cee", is_dumb_sz = True, ascii_only = True)
00236     test_string_attribute(c, "wstring_value", "dee", is_dumb_sz = True)
00237     test_string_attribute(c, "astring_value", "astring")
00238     test_string_attribute(c, "acstring_value", "acstring", ascii_only = True)
00239 
00240     test_string_attribute(c, "utf8string_value", "utf8string")
00241     # Test a string already encoded gets through correctly.
00242     test_attribute(c, "utf8string_value", "utf8string", extended_unicode_string.encode("utf8"), extended_unicode_string)
00243 
00244     # This will fail internal string representation :(  Test we don't crash
00245     try:
00246         c.wstring_value = "a big char >" + chr(129) + "<"
00247         print_error("strings with chars > 128 appear to have stopped failing?")
00248     except UnicodeError:
00249         pass
00250 
00251     test_attribute(c, "iid_value", component_iid, new_iid)
00252     test_attribute(c, "iid_value", component_iid, str(new_iid), new_iid)
00253     test_attribute(c, "iid_value", component_iid, xpcom._xpcom.IID(new_iid))
00254 
00255     test_attribute_failure(c, "no_attribute", "boo", AttributeError)
00256 
00257     test_attribute(c, "interface_value", None, c)
00258     test_attribute_failure(c, "interface_value", 2, TypeError)
00259 
00260     test_attribute(c, "isupports_value", None, c)
00261 
00262     # The methods
00263     test_method(c.do_boolean, (0,1), (1,0,1))
00264     test_method(c.do_boolean, (1,0), (1,0,1))
00265     test_method(c.do_boolean, (1,1), (0,1,0))
00266 
00267     test_int_method(c.do_octet)
00268     test_int_method(c.do_short)
00269 
00270     test_int_method(c.do_unsigned_short)
00271     test_int_method(c.do_long)
00272     test_int_method(c.do_unsigned_long)
00273     test_int_method(c.do_long_long)
00274     test_int_method(c.do_unsigned_long)
00275     test_int_method(c.do_float)
00276     test_int_method(c.do_double)
00277 
00278     test_method(c.do_char, ("A", " "), (chr(ord("A")+ord(" ")), " ","A") )
00279     test_method(c.do_char, ("A", "\0"), ("A", "\0","A") )
00280     test_method(c.do_wchar, ("A", " "), (chr(ord("A")+ord(" ")), " ","A") )
00281     test_method(c.do_wchar, ("A", "\0"), ("A", "\0","A") )
00282 
00283     test_method(c.do_string, ("Hello from ", "Python"), ("Hello from Python", "Hello from ", "Python") )
00284     test_method(c.do_string, (u"Hello from ", u"Python"), ("Hello from Python", "Hello from ", "Python") )
00285     test_method(c.do_string, (None, u"Python"), ("Python", None, "Python") )
00286     test_method(c.do_string, (None, really_big_string), (really_big_string, None, really_big_string) )
00287     test_method(c.do_string, (None, really_big_wstring), (really_big_string, None, really_big_string) )
00288     test_method(c.do_wstring, ("Hello from ", "Python"), ("Hello from Python", "Hello from ", "Python") )
00289     test_method(c.do_wstring, (u"Hello from ", u"Python"), ("Hello from Python", "Hello from ", "Python") )
00290     test_method(c.do_string, (None, really_big_wstring), (really_big_wstring, None, really_big_wstring) )
00291     test_method(c.do_string, (None, really_big_string), (really_big_wstring, None, really_big_wstring) )
00292     test_method(c.do_nsIIDRef, (component_iid, new_iid), (component_iid, component_iid, new_iid))
00293     test_method(c.do_nsIIDRef, (new_iid, component_iid), (new_iid, component_iid, component_iid))
00294     test_method(c.do_nsIPythonTestInterface, (None, None), (None, None, c))
00295     test_method(c.do_nsIPythonTestInterface, (c, c), (c, c, c))
00296     test_method(c.do_nsISupports, (None, None), (c, None, None))
00297     test_method(c.do_nsISupports, (c,c), (c, c, c))
00298     test_method(c.do_nsISupportsIs, (xpcom._xpcom.IID_nsISupports,), c)
00299     test_method(c.do_nsISupportsIs, (xpcom.components.interfaces.nsIPythonTestInterface,), c)
00300 ##    test_method(c.do_nsISupportsIs2, (xpcom.components.interfaces.nsIPythonTestInterface,c), (xpcom.components.interfaces.nsIPythonTestInterface,c))
00301 ##    test_method(c.do_nsISupportsIs3, (c,), (xpcom.components.interfaces.nsIPythonTestInterface,c))
00302 ##    test_method(c.do_nsISupportsIs4, (), (xpcom.components.interfaces.nsIPythonTestInterface,c))
00303     # Test the constants.
00304     test_constant(c, "One", 1)
00305     test_constant(c, "Two", 2)
00306     test_constant(c, "MinusOne", -1)
00307     test_constant(c, "BigLong", 0x7FFFFFFF)
00308     test_constant(c, "BiggerLong", 0xFFFFFFFF)
00309     test_constant(c, "BigULong", 0xFFFFFFFF)
00310     # Test the components.Interfaces semantics
00311     i = xpcom.components.interfaces.nsIPythonTestInterface
00312     test_constant(i, "One", 1)
00313     test_constant(i, "Two", 2)
00314     test_constant(i, "MinusOne", -1)
00315     test_constant(i, "BigLong", 0x7FFFFFFF)
00316     test_constant(i, "BigULong", 0xFFFFFFFF)
00317 
00318 def test_derived_interface(c, test_flat = 0):
00319     val = "Hello\0there"
00320     expected = val * 2
00321 
00322     test_method(c.DoubleString, (val,), expected)
00323     test_method(c.DoubleString2, (val,), expected)
00324     test_method(c.DoubleString3, (val,), expected)
00325     test_method(c.DoubleString4, (val,), expected)
00326     test_method(c.UpString, (val,), val.upper())
00327     test_method(c.UpString2, (val,), val.upper())
00328     test_method(c.GetFixedString, (20,), "A"*20)
00329     val = u"Hello\0there"
00330     expected = val * 2
00331     test_method(c.DoubleWideString, (val,), expected)
00332     test_method(c.DoubleWideString2, (val,), expected)
00333     test_method(c.DoubleWideString3, (val,), expected)
00334     test_method(c.DoubleWideString4, (val,), expected)
00335     test_method(c.UpWideString, (val,), val.upper())
00336     test_method(c.UpWideString2, (val,), val.upper())
00337     test_method(c.GetFixedWideString, (20,), u"A"*20)
00338     val = extended_unicode_string
00339     test_method(c.CopyUTF8String, ("foo",), "foo")
00340     test_method(c.CopyUTF8String, (u"foo",), "foo")
00341     test_method(c.CopyUTF8String, (val,), val)
00342     test_method(c.CopyUTF8String, (val.encode("utf8"),), val)
00343     test_method(c.CopyUTF8String2, ("foo",), "foo")
00344     test_method(c.CopyUTF8String2, (u"foo",), "foo")
00345     test_method(c.CopyUTF8String2, (val,), val)
00346     test_method(c.CopyUTF8String2, (val.encode("utf8"),), val)
00347     items = [1,2,3,4,5]
00348     test_method(c.MultiplyEachItemInIntegerArray, (3, items,), map(lambda i:i*3, items))
00349 
00350     test_method(c.MultiplyEachItemInIntegerArrayAndAppend, (3, items), items + map(lambda i:i*3, items))
00351     items = "Hello from Python".split()
00352     expected = map( lambda x: x*2, items)
00353     test_method(c.DoubleStringArray, (items,), expected)
00354 
00355     test_method(c.CompareStringArrays, (items, items), cmp(items, items))
00356     # Can we pass lists and tuples correctly?
00357     test_method(c.CompareStringArrays, (items, tuple(items)), cmp(items, items))
00358     items2 = ["Not", "the", "same"]
00359     test_method(c.CompareStringArrays, (items, items2), cmp(items, items2))
00360 
00361     expected = items[:]
00362     expected.reverse()
00363     test_method(c.ReverseStringArray, (items,), expected)
00364 
00365     expected = "Hello from the Python test component".split()
00366     test_method(c.GetStrings, (), expected)
00367 
00368     val = "Hello\0there"
00369     test_method(c.UpOctetArray, (val,), val.upper())
00370     test_method(c.UpOctetArray, (unicode(val),), val.upper())
00371     # Passing Unicode objects here used to cause us grief.
00372     test_method(c.UpOctetArray2, (val,), val.upper())
00373 
00374     test_method(c.CheckInterfaceArray, ((c, c),), 1)
00375     test_method(c.CheckInterfaceArray, ((c, None),), 0)
00376     test_method(c.CheckInterfaceArray, ((),), 1)
00377     test_method(c.CopyInterfaceArray, ((c, c),), [c,c])
00378 
00379     test_method(c.GetInterfaceArray, (), [c,c,c, None])
00380     test_method(c.ExtendInterfaceArray, ((c,c,c, None),), [c,c,c,None,c,c,c,None] )
00381 
00382     expected = [xpcom.components.interfaces.nsIPythonTestInterfaceDOMStrings, xpcom.components.classes[contractid].clsid]
00383     test_method(c.GetIIDArray, (), expected)
00384 
00385     val = [xpcom.components.interfaces.nsIPythonTestInterfaceExtra, xpcom.components.classes[contractid].clsid]
00386     expected = val * 2
00387     test_method(c.ExtendIIDArray, (val,), expected)
00388 
00389     test_method(c.GetArrays, (), ( [1,2,3], [4,5,6] ) )
00390     test_method(c.CopyArray, ([1,2,3],), [1,2,3] )
00391     test_method(c.CopyAndDoubleArray, ([1,2,3],), [1,2,3,1,2,3] )
00392     test_method(c.AppendArray, ([1,2,3],), [1,2,3])
00393     test_method(c.AppendArray, ([1,2,3],[4,5,6]), [1,2,3,4,5,6])
00394 
00395     test_method(c.CopyVariant, (None,), None)
00396     test_method(c.CopyVariant, (1,), 1)
00397     test_method(c.CopyVariant, (1.0,), 1.0)
00398     test_method(c.CopyVariant, (-1,), -1)
00399     test_method(c.CopyVariant, (sys.maxint+1,), sys.maxint+1)
00400     test_method(c.CopyVariant, ("foo",), "foo")
00401     test_method(c.CopyVariant, (u"foo",), u"foo")
00402     test_method(c.CopyVariant, (c,), c)
00403     test_method(c.CopyVariant, (component_iid,), component_iid)
00404     test_method(c.CopyVariant, ((1,2),), [1,2])
00405     test_method(c.CopyVariant, ((1.2,2.1),), [1.2,2.1])
00406     test_method(c.CopyVariant, (("foo","bar"),), ["foo", "bar"])
00407     test_method(c.CopyVariant, ((component_iid,component_iid),), [component_iid,component_iid])
00408     test_method(c.CopyVariant, ((c,c),), [c,c])
00409     test_method(c.AppendVariant, (1,2), 3)
00410     test_method(c.AppendVariant, ((1,2),(3,4)), 10)
00411     test_method(c.AppendVariant, ("bar", "foo"), "foobar")
00412     test_method(c.AppendVariant, (None, None), None)
00413 
00414     if not test_flat:
00415         c = c.queryInterface(xpcom.components.interfaces.nsIPythonTestInterfaceDOMStrings)
00416 # NULL DOM strings don't work yet.
00417 #    test_method(c.GetDOMStringResult, (-1,), None)
00418     test_method(c.GetDOMStringResult, (3,), "PPP")
00419 #    test_method(c.GetDOMStringOut, (-1,), None)
00420     test_method(c.GetDOMStringOut, (4,), "yyyy")
00421     val = "Hello there"
00422     test_method(c.GetDOMStringLength, (val,), len(val))
00423     test_method(c.GetDOMStringRefLength, (val,), len(val))
00424     test_method(c.GetDOMStringPtrLength, (val,), len(val))
00425     test_method(c.ConcatDOMStrings, (val,val), val+val)
00426     test_attribute(c, "domstring_value", "dom", "new dom")
00427     if c.domstring_value_ro != "dom":
00428         print "Read-only DOMString not correct - got", c.domstring_ro
00429     try:
00430         c.dom_string_ro = "new dom"
00431         print "Managed to set a readonly attribute - eek!"
00432     except AttributeError:
00433         pass
00434     except:
00435         print "Unexpected exception when setting readonly attribute: %s: %s" % (sys.exc_info()[0], sys.exc_info()[1])
00436     if c.domstring_value_ro != "dom":
00437         print "Read-only DOMString not correct after failed set attempt - got", c.domstring_ro
00438 
00439 def do_test_failures():
00440     c = xpcom.client.Component(contractid, xpcom.components.interfaces.nsIPythonTestInterfaceExtra)
00441     try:
00442         ret = c.do_nsISupportsIs( xpcom._xpcom.IID_nsIInterfaceInfoManager )
00443         print "*** got", ret, "***"
00444         raise RuntimeError, "We worked when using an IID we dont support!?!"
00445     except xpcom.Exception, details:
00446         if details.errno != xpcom.nsError.NS_ERROR_NO_INTERFACE:
00447             raise RuntimeError, "Wrong COM exception type: %r" % (details,)
00448 
00449 def test_failures():
00450     # This extra stack-frame ensures Python cleans up sys.last_traceback etc
00451     do_test_failures()
00452 
00453 def test_all():
00454     c = xpcom.client.Component(contractid, xpcom.components.interfaces.nsIPythonTestInterface)
00455     test_base_interface(c)
00456     # Now create an instance using the derived IID, and test that.
00457     c = xpcom.client.Component(contractid, xpcom.components.interfaces.nsIPythonTestInterfaceExtra)
00458     test_base_interface(c)
00459     test_derived_interface(c)
00460     # Now create an instance and test interface flattening.
00461     c = xpcom.components.classes[contractid].createInstance()
00462     test_base_interface(c)
00463     test_derived_interface(c, test_flat=1)
00464 
00465     # We had a bug where a "set" of an attribute before a "get" failed.
00466     # Don't let it happen again :)
00467     c = xpcom.components.classes[contractid].createInstance()
00468     c.boolean_value = 0
00469     
00470     # This name is used in exceptions etc - make sure we got it from nsIClassInfo OK.
00471     assert c._object_name_ == "Python.TestComponent"
00472 
00473     test_failures()
00474 
00475 try:
00476     from sys import gettotalrefcount
00477 except ImportError:
00478     # Not a Debug build - assume no references (can't be leaks then :-)
00479     def gettotalrefcount():
00480         return 0
00481 
00482 from pyxpcom_test_tools import getmemusage
00483 
00484 def test_from_js():
00485     # Ensure we can find the js test script - same dir as this!
00486     # Assume the path of sys.argv[0] is where we can find the js test code.
00487     # (Running under the regression test is a little painful)
00488     script_dir = os.path.split(sys.argv[0])[0]
00489     fname = os.path.join( script_dir, "test_test_component.js")
00490     if not os.path.isfile(fname):
00491         raise RuntimeError, "Can not find '%s'" % (fname,)
00492     # Note we _dont_ pump the test output out, as debug "xpcshell" spews
00493     # extra debug info that will cause our output comparison to fail.
00494     try:
00495         data = os.popen('xpcshell "' + fname + '"').readlines()
00496         good = 0
00497         for line in data:
00498             if line.strip() == "javascript successfully tested the Python test component.":
00499                 good = 1
00500         if good:
00501             print "Javascript could successfully use the Python test component."
00502         else:
00503             print "** The javascript test appeared to fail!  Test output follows **"
00504             print "".join(data)
00505             print "** End of javascript test output **"
00506 
00507     except os.error, why:
00508         print "Error executing the javascript test program:", why
00509         
00510 
00511 def doit(num_loops = -1):
00512     if "-v" in sys.argv: # Hack the verbose flag for the server
00513         xpcom.verbose = 1
00514     # Do the test lots of times - can help shake-out ref-count bugs.
00515     print "Testing the Python.TestComponent component"
00516     if num_loops == -1: num_loops = 10
00517     for i in xrange(num_loops):
00518         test_all()
00519 
00520         if i==0:
00521             # First loop is likely to "leak" as we cache things.
00522             # Leaking after that is a problem.
00523             if gc is not None:
00524                 gc.collect()
00525             num_refs = gettotalrefcount()
00526             mem_usage = getmemusage()
00527 
00528         if num_errors:
00529             break
00530 
00531     if gc is not None:
00532         gc.collect()
00533 
00534     lost = gettotalrefcount() - num_refs
00535     # Sometimes we get spurious counts off by 1 or 2.
00536     # This can't indicate a real leak, as we have looped
00537     # more than twice!
00538     if abs(lost)>2:
00539         print "*** Lost %d references" % (lost,)
00540 
00541     # sleep to allow the OS to recover
00542     time.sleep(1)
00543     mem_lost = getmemusage() - mem_usage
00544     # working set size is fickle, and when we were leaking strings, this test
00545     # would report a leak of 100MB.  So we allow a 2MB buffer - but even this
00546     # may still occasionally report spurious warnings.  If you are really
00547     # worried, bump the counter to a huge value, and if there is a leak it will
00548     # show.
00549     if mem_lost > 2000000:
00550         print "*** Lost %.6f MB of memory" % (mem_lost/1000000.0,)
00551 
00552     if num_errors:
00553         print "There were", num_errors, "errors testing the Python component :-("
00554     else:
00555         print "The Python test component worked!"
00556 
00557 # regrtest doesnt like if __name__=='__main__' blocks - it fails when running as a test!
00558 num_iters = -1
00559 if __name__=='__main__' and len(sys.argv) > 1:
00560     num_iters = int(sys.argv[1])
00561 
00562 doit(num_iters)
00563 test_from_js()
00564 
00565 if __name__=='__main__':
00566     # But we can only do this if _not_ testing - otherwise we
00567     # screw up any tests that want to run later.
00568     xpcom._xpcom.NS_ShutdownXPCOM()
00569     ni = xpcom._xpcom._GetInterfaceCount()
00570     ng = xpcom._xpcom._GetGatewayCount()
00571     if ni or ng:
00572         print "********* WARNING - Leaving with %d/%d objects alive" % (ni,ng)