Back to index

lightning-sunbird  0.9+nobinonly
test_misc.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
00019 # the Initial Developer. All Rights Reserved.
00020 #
00021 # Contributor(s):
00022 #    Mark Hammond <MarkH@ActiveState.com>
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 xpcom
00039 import xpcom.client
00040 import xpcom.server
00041 import xpcom._xpcom
00042 import xpcom.components
00043 import string
00044 
00045 import unittest
00046 
00047 import traceback, getopt, sys
00048 
00049 verbose_level = 0
00050 
00051 reportedSampleMissing = 0
00052 
00053 def get_sample_component_cpp():
00054     global reportedSampleMissing
00055     contractid = "@mozilla.org/sample;1" # The C++ version.
00056     try:
00057         return xpcom.components.classes[contractid].createInstance()
00058     except xpcom.COMException:
00059         if not reportedSampleMissing:
00060             print "***"
00061             print "*** This test requires an XPCOM sample component,"
00062             print "*** which does not exist.  To build this test, you"
00063             print "*** should change to the 'mozilla/xpcom/sample' directory,"
00064             print "*** and run 'make', then run this test again."
00065             print "***"
00066             reportedSampleMissing = 1
00067         else:
00068             print "(skipping - no C++ sample...) ",
00069         return None
00070 
00071 def get_sample_component_js():
00072     # This should *always* exist - no special make process.
00073     contractid = "@mozilla.org/jssample;1" # the JS version
00074     return xpcom.components.classes[contractid].createInstance()
00075     
00076 class TestDumpInterfaces(unittest.TestCase):
00077     def testAllInterfaces(self):
00078         "Dump every interface under the sun!"
00079         import xpcom, xpcom.xpt, xpcom._xpcom
00080         iim = xpcom._xpcom.XPTI_GetInterfaceInfoManager()
00081     
00082         if verbose_level:
00083             print "Dumping every interface I can find"
00084         enum = iim.EnumerateInterfaces()
00085         rc = enum.First()
00086         num = 0
00087         while rc==0:
00088             item = enum.CurrentItem(xpcom._xpcom.IID_nsIInterfaceInfo)
00089             try:
00090                 iid = item.GetIID()
00091             except xpcom.COMException:
00092                 if verbose_level:
00093                     print "Can't dump", item
00094                 continue # Dont bother dumping this.
00095             interface = xpcom.xpt.Interface(iid)
00096             num = num + 1
00097             text = interface.Describe()
00098             if verbose_level:
00099                 print text
00100     
00101             rc = enum.Next()
00102         if num < 200:
00103             print "Only found", num, "interfaces - this seems unusually low!"
00104 
00105 class TestEnumContractIDs(unittest.TestCase):
00106     def testContractIDs(self):
00107         """Enumerate all the ContractIDs registered"""
00108         enum = xpcom.components.registrar.enumerateContractIDs()
00109         n = 0
00110         while enum.hasMoreElements():
00111             item = enum.getNext(xpcom.components.interfaces.nsISupportsCString)
00112             n = n + 1
00113             if verbose_level:
00114                 print "ContractID:", item.data
00115         if n < 200:
00116             print "Only found", n, "ContractIDs - this seems unusually low!"
00117 
00118 class TestSampleComponent(unittest.TestCase):
00119     def _doTestSampleComponent(self, test_flat = 0):
00120         """Test the standard Netscape 'sample' sample"""
00121         c = get_sample_component_cpp()
00122         if c is None:
00123             return
00124         if not test_flat:
00125             c = c.queryInterface(xpcom.components.interfaces.nsISample)
00126         self.failUnlessEqual(c.value, "initial value")
00127         c.value = "new value"
00128         self.failUnlessEqual(c.value, "new value")
00129         c.poke("poked value")
00130         self.failUnlessEqual(c.value, "poked value")
00131         c.writeValue("Python just poked:")
00132 
00133     def testSampleComponentFlat(self):
00134         """Test the standard Netscape 'sample' sample using interface flattening"""
00135         self._doTestSampleComponent(1)
00136 
00137     def testSampleComponentOld(self):
00138         """Test the standard Netscape 'sample' sample using explicit QI"""
00139         self._doTestSampleComponent(0)
00140     
00141     def _doTestHash(self, c):
00142         "Test that hashing COM objects works"
00143         d = {}
00144         d[c] = None
00145         if not d.has_key(c):
00146             raise RuntimeError, "Can't get the exact same object back!"
00147         if not d.has_key(c.queryInterface(xpcom.components.interfaces.nsISupports)):
00148             raise RuntimeError, "Can't get back as nsISupports"
00149 
00150         # And the same in reverse - stick an nsISupports in, and make sure an explicit interface comes back.
00151         d = {}
00152 #        contractid = "@mozilla.org/sample;1" # The C++ version.
00153 #        c = xpcom.components.classes[contractid].createInstance() \
00154 #            .queryInterface(xpcom.components.interfaces.nsISupports)
00155         d[c] = None
00156         if not d.has_key(c):
00157             raise RuntimeError, "Can't get the exact same object back!"
00158         if not d.has_key(c.queryInterface(xpcom.components.interfaces.nsISample)):
00159             raise RuntimeError, "Can't get back as nsISupports"
00160 
00161     def testHashJS(self):
00162         c = get_sample_component_js()
00163         self._doTestHash(c)
00164 
00165     def testHashCPP(self):
00166         c = get_sample_component_cpp()
00167         if c is not None:
00168             self._doTestHash(c)
00169 
00170 
00171 class TestIIDs(unittest.TestCase):
00172     def TestIIDs(self):
00173         "Do some basic IID semantic tests."
00174         iid_str = "{7ee4bdc6-cb53-42c1-a9e4-616b8e012aba}"
00175         IID = xpcom._xpcom.IID
00176         self.failUnlessEqual(IID(iid_str), IID(iid_str))
00177         self.failUnlessEqual(hash(IID(iid_str)), hash(IID(iid_str)))
00178         self.failUnlessEqual(IID(iid_str), IID(iid_str.upper()))
00179         self.failUnlessEqual(hash(IID(iid_str)), hash(IID(iid_str.upper())))
00180         # If the above work, this shoud too, but WTF
00181         dict = {}
00182         dict[IID(iid_str)] = None
00183         self.failUnless(dict.has_key(IID(iid_str)), "hashes failed in dictionary")
00184         self.failUnless(dict.has_key(IID(iid_str.upper())), "uppercase hash failed in dictionary")
00185 
00186 class TestRepr(unittest.TestCase):
00187     def _doTestRepr(self, progid, interfaces):
00188         if isinstance(progid, str):
00189             ob = xpcom.components.classes[progid].createInstance()
00190         else:
00191             ob = progid
00192         self.failUnless(repr(ob).find(str(progid)) >= 0, repr(ob))
00193         for interface_name in interfaces.split():
00194             self.failUnless(repr(ob).find(interface_name) >= 0, repr(ob))
00195 
00196     def testReprPython(self):
00197         "Test repr() of Python objects"
00198         self._doTestRepr("Python.TestComponent", "nsIPythonTestInterfaceDOMStrings nsIPythonTestInterfaceExtra nsIPythonTestInterface")
00199 
00200     # JS does not provide class-info :(
00201     #def testReprJS(self):
00202     #    self._doTestRepr("@mozilla.org/jssample;1", "nsISample")
00203 
00204     def testReprSample(self):
00205         "Test repr() of non-Python objects"
00206         ob = get_sample_component_cpp()
00207         if ob is None:
00208             return
00209         self._doTestRepr(ob, "nsISample")
00210 
00211 class TestUnwrap(unittest.TestCase):
00212     "Test the unwrap facilities"
00213     def testUnwrap(self):
00214         # First test that a Python object can be unwrapped.
00215         ob = xpcom.components.classes["Python.TestComponent"].createInstance()
00216         pyob = xpcom.server.UnwrapObject(ob)
00217         # This depends on our __repr__ implementation, but that's OK - it
00218         # can be updated should our __repr__ change :)
00219         self.failUnless(str(pyob).startswith("<component:py_test_component.PythonTestComponent"))
00220         # Test that a non-Python implemented object can NOT be unwrapped.
00221         ob = get_sample_component_cpp()
00222         if ob is None:
00223             return
00224         self.failUnlessRaises(ValueError, xpcom.server.UnwrapObject, ob)
00225 
00226 if __name__=='__main__':
00227     unittest.main()
00228     xpcom._xpcom.NS_ShutdownXPCOM()
00229     ni = xpcom._xpcom._GetInterfaceCount()
00230     ng = xpcom._xpcom._GetGatewayCount()
00231     if ni or ng:
00232         print "********* WARNING - Leaving with %d/%d objects alive" % (ni,ng)