Пример #1
0
    def _generate(self):
        """call the wsdl2py and wsdl2dispatch scripts and
        automatically add the "-f" or "-u" argument.  Other args
        can be appended via the "wsdl2py_args" and "wsdl2dispatch_args"
        instance attributes.
        """
        url = self.url
        if os.path.isfile(url):
            url = os.path.abspath(url)

        if SKIP:
            ServiceTestCase._wsdl[url] = True
            return

        ServiceTestCase._wsdl[url] = False
        try:
            os.mkdir(MODULEDIR)
        except OSError as ex:
            pass

        os.chdir(MODULEDIR)
        if MODULEDIR not in sys.path:
            sys.path.append(MODULEDIR)

        try:
            commands.wsdl2py([url] + self.wsdl2py_args)
            ServiceTestCase._wsdl[url] = True
        finally:
            os.chdir(TOPDIR)
Пример #2
0
def cacore2py():

    # Find settings.py
    try:
        sys.path.insert(0,'.')
        import settings # Assumed to be in the current working directory.
    except ImportError:
        sys.stderr.write("Error: Can't find settings.py\n")
        sys.exit(1)
    
    print "Cleaning output directory",settings.OUTPUT_DIR
    
    # Clean output dir
    try:
        dir_util.remove_tree(settings.OUTPUT_DIR)
    except OSError:
        pass
    
    r = [settings.OUTPUT_DIR,]+settings.ROOT_PACKAGE.split('.')
    outputDir = os.path.join(*r)
    dir_util.mkpath(settings.OUTPUT_DIR)
    
    print "Generating Python API from",settings.WSDL_FILE
    
    # Recreate output tree with __init__.py files at each level
    for p in [settings.ROOT_PACKAGE+"."+v for v in settings.PACKAGE_MAPPING.values()]:
        prefix = settings.OUTPUT_DIR
        # p is something like "cabig.cabio.common.domain"
        # Now iterate thru each prefix of p, "cabig/", "cabig/cabio/", etc
        # But don't create a directory for the leaf, since it will be a module.
        for d in p.split('.')[:-1]: 
            prefix = os.path.join(prefix,d)
            dir_util.mkpath(prefix)
            # The "cabig" package is a namespace package.
            contents = ''
            if d == 'cabig': contents = NS_INIT
            # Yes, this might write the same file several times, not a big deal.
            file_util.write_file(os.path.join(prefix,'__init__.py'),contents)
    
    # Generate ZSI API (*services.py and *_services_types.py)
    # Note that we must use the "-l" option here to do lazy evaluation of type 
    # codes, necessary to support 1-to-1 associations in caCORE-like systems.
    args = ['-lbo', outputDir, settings.WSDL_FILE]
    wsdl2py(args)
    
    # A really ugly way of dynamically loading the module we just generated.
    # The __import__ function doesn't seem to like packages though...
    sys.path.insert(0,outputDir)
    fileName = [f for f in os.listdir(outputDir) if f.endswith('_client.py')][0]
    moduleName = fileName.replace('.py','')
    module = __import__(moduleName)
    
    # Generate a nicer caCORE-like API on top of the ZSI one
    cacore2python.generate(module, settings, outputDir)

    print "API generation completed"
Пример #3
0
    def _load(self, location):
        """
        location -- URL or file location
        isxsd -- is this a xsd file?
        """
        cachedir = self._cachedir
        # wsdl2py: deal with XML Schema
        if not os.path.isdir(cachedir): os.mkdir(cachedir)

        _file = os.path.join(cachedir, '.cache')
        section = 'TYPES'
        cp = ConfigParser()
        try:
            cp.readfp(open(_file, 'r'))
        except IOError:
            del cp
            cp = None

        option = location.replace(':', '-')  # colons seem to screw up option
        if (not self._force and cp is not None and cp.has_section(section)
                and cp.has_option(section, option)):
            types = cp.get(section, option)
        else:
            # dont do anything to anames
            if not self._pyclass:
                containers.ContainerBase.func_aname = lambda instnc, n: str(n)

            args = ['-o', cachedir, location]
            if self._lazy: args.insert(0, '-l')
            if self._pyclass: args.insert(0, '-b')
            files = commands.wsdl2py(args)

            if cp is None: cp = ConfigParser()
            if not cp.has_section(section): cp.add_section(section)
            types = [f for f in files if f.endswith('_types.py')][0]
            cp.set(section, option, types)
            cp.write(open(_file, 'w'))

        if os.path.abspath(cachedir) not in sys.path:
            sys.path.append(os.path.abspath(cachedir))

        mod = os.path.split(types)[-1].rstrip('.py')
        return __import__(mod)
Пример #4
0
    def _load(self, location):
        """
        location -- URL or file location
        isxsd -- is this a xsd file?
        """
        cachedir = self._cachedir
        # wsdl2py: deal with XML Schema
        if not os.path.isdir(cachedir): os.mkdir(cachedir)
    
        file = os.path.join(cachedir, '.cache')
        section = 'TYPES'
        cp = ConfigParser()
        try:
            cp.readfp(open(file, 'r'))
        except IOError:
            del cp;  cp = None
            
        option = location.replace(':', '-') # colons seem to screw up option
        if (not self._force and cp is not None and cp.has_section(section) and 
            cp.has_option(section, option)):
            types = cp.get(section, option)
        else:
            # dont do anything to anames
            if not self._pyclass:
                containers.ContainerBase.func_aname = lambda instnc,n: str(n)
                
            args = ['-o', cachedir, location]
            if self._lazy: args.insert(0, '-l')
            if self._pyclass: args.insert(0, '-b')
            files = commands.wsdl2py(args)

            if cp is None: cp = ConfigParser()
            if not cp.has_section(section): cp.add_section(section)
            types = filter(lambda f: f.endswith('_types.py'), files)[0]
            cp.set(section, option, types)
            cp.write(open(file, 'w'))
            
        if os.path.abspath(cachedir) not in sys.path:
            sys.path.append(os.path.abspath(cachedir))
            
        mod = os.path.split(types)[-1].rstrip('.py')
        return __import__(mod)
Пример #5
0
class ServiceTestCase(unittest.TestCase):
    """Conventions for method names:
    test_net*
    -- network tests
    
    test_local*
    -- local tests
    
    test_dispatch*
    -- tests that use the a spawned local container
    
    class attributes: Edit/Override these in the inheriting class as needed
        out -- file descriptor to write output to
        name -- configuration item, must be set in class.
        url_section -- configuration section, maps a test module 
           name to an URL.
        client_file_name --
        types_file_name --
        server_file_name --
    """
    out = OUTPUT
    name = None
    url_section = 'WSDL'
    client_file_name = None
    types_file_name = None
    server_file_name = None

    def __init__(self, methodName):
        """
        parameters:
           methodName -- 
        instance variables:
            client_module
            types_module
            server_module
            processID
            done

        """
        self.methodName = methodName
        self.url = None
        self.wsdl2py_args = []
        self.wsdl2dispatch_args = []
        self.portkwargs = {}
        self.client_module = self.types_module = self.server_module = None
        self.done = False

        if TWISTED:
            self.wsdl2py_args.append('--twisted')

        if LAZY:
            self.wsdl2py_args.append('--lazy')

        unittest.TestCase.__init__(self, methodName)

    write = lambda self, arg: self.out.write(arg)

    if sys.version_info[:2] >= (2, 5):
        _exc_info = unittest.TestCase._exc_info
    else:
        _exc_info = unittest.TestCase._TestCase__exc_info

    def __call__(self, *args, **kwds):
        self.run(*args, **kwds)

    def run(self, result=None):
        if result is None: result = self.defaultTestResult()
        result.startTest(self)
        testMethod = getattr(self, self.methodName)
        try:
            try:
                self.setUp()
            except KeyboardInterrupt:
                raise
            except:
                result.addError(self, self._exc_info())
                return

            ok = False
            try:
                t1 = time.time()
                pyobj = testMethod()
                t2 = time.time()
                ok = True
            except self.failureException:
                result.addFailure(self, self._exc_info())
            except KeyboardInterrupt:
                raise
            except:
                result.addError(self, self._exc_info())

            try:
                self.tearDown()
            except KeyboardInterrupt:
                raise
            except:
                result.addError(self, self._exc_info())
                ok = False
            if ok:
                result.addSuccess(self)
                print >> self
                print >> self, "|" + "-" * 60
                print >> self, "|  TestCase: %s" % self.methodName
                print >> self, "|" + "-" * 20
                print >> self, "|  run time:   %s ms" % ((t2 - t1) * 1000)
                print >> self, "|  return  :   %s" % pyobj
                print >> self, "|" + "-" * 60

        finally:
            result.stopTest(self)

    def getPortKWArgs(self):
        kw = {}
        if CONFIG_PARSER.getboolean(SECTION_CONFIGURATION, 'tracefile'):
            kw['tracefile'] = TRACEFILE

        kw.update(self.portkwargs)
        return kw

    def _setUpDispatch(self):
        """Set this test up as a dispatch test.
        url -- 
        """
        host = CONFIG_PARSER.get(SECTION_DISPATCH, 'host')
        port = CONFIG_PARSER.get(SECTION_DISPATCH, 'port')
        path = CONFIG_PARSER.get(SECTION_DISPATCH, 'path')

        scheme = 'http'
        netloc = '%s:%s' % (host, port)
        params = query = fragment = None

        self.portkwargs['url'] = \
            urlparse.urlunparse((scheme,netloc,path,params,query,fragment))

    _wsdl = {}

    def _generate(self):
        """call the wsdl2py and wsdl2dispatch scripts and
        automatically add the "-f" or "-u" argument.  Other args
        can be appended via the "wsdl2py_args" and "wsdl2dispatch_args"
        instance attributes.
        """
        url = self.url
        if os.path.isfile(url):
            url = os.path.abspath(url)

        if SKIP:
            ServiceTestCase._wsdl[url] = True
            return

        ServiceTestCase._wsdl[url] = False
        try:
            os.mkdir(MODULEDIR)
        except OSError, ex:
            pass

        os.chdir(MODULEDIR)
        if MODULEDIR not in sys.path:
            sys.path.append(MODULEDIR)

        try:
            commands.wsdl2py([url] + self.wsdl2py_args)
            ServiceTestCase._wsdl[url] = True
        finally:
            os.chdir(TOPDIR)
Пример #6
0
    """Run all network tests"""
    suite = ServiceTestSuite()
    suite.addTest(unittest.makeSuite(ServiceTest, 'test_net'))
    return suite
    
def all():
    """Run all tests"""
    suite = ServiceTestSuite()
    suite.addTest(unittest.makeSuite(ServiceTest, 'test_'))
    return suite


# NEED TO CREATE WSSE typecodes
from ZSI.generate.commands import wsdl2py
if not os.path.isdir('stubs'): os.makedirs('stubs')
wsdl2py(['--complexType', '--schema','--output-dir=stubs', 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'])


class BlogServiceTest(ServiceTestCase):
    """Test case for Clearspace sandbox, example how to use client WSSE:Security UsernameToken Profile
    
<wsdl:Envelope xmlns:soap="..." xmlns:wsse="..." >
   <wsdl:Header>
      <wsse:Security>
         <wsse:UsernameToken>
            <wsse:Username>admin</wsse:Username>
            <wsse:Password>password</wsse:Password>
         </wsse:UsernameToken>
      </wsse:Security>
   </wsdl:Header>
</wsdl:Envelope>
Пример #7
0
    suite.addTest(unittest.makeSuite(ServiceTest, 'test_net'))
    return suite


def all():
    """Run all tests"""
    suite = ServiceTestSuite()
    suite.addTest(unittest.makeSuite(ServiceTest, 'test_'))
    return suite


# NEED TO CREATE WSSE typecodes
from ZSI.generate.commands import wsdl2py
if not os.path.isdir('stubs'): os.makedirs('stubs')
wsdl2py([
    '--complexType', '--schema', '--output-dir=stubs',
    'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'
])


class BlogServiceTest(ServiceTestCase):
    """Test case for Clearspace sandbox, example how to use client WSSE:Security UsernameToken Profile
    
<wsdl:Envelope xmlns:soap="..." xmlns:wsse="..." >
   <wsdl:Header>
      <wsse:Security>
         <wsse:UsernameToken>
            <wsse:Username>admin</wsse:Username>
            <wsse:Password>password</wsse:Password>
         </wsse:UsernameToken>
      </wsse:Security>
   </wsdl:Header>
Пример #8
0
    def __init__(self, wsdl, url=None, service=None, port=None, tracefile=None,
                 nsdict=None, transport=None, transdict=None, 
                 cachedir='.service_proxy_dir', asdict=True):
        """
        Parameters:
           wsdl -- URL of WSDL.
           url -- override WSDL SOAP address location
           service -- service name or index
           port -- port name or index
           tracefile -- 
           nsdict -- key prefix to namespace mappings for serialization
              in SOAP Envelope.
           transport -- override default transports.
           transdict -- arguments to pass into HTTPConnection constructor.
           cachedir -- where to store generated files
           asdict -- use dicts, else use generated pyclass
        """
        self._asdict = asdict
        
        # client._Binding
        self._tracefile = tracefile
        self._nsdict = nsdict or {}
        self._transdict = transdict 
        self._transport = transport
        self._url = url
        
        # WSDL
        self._wsdl = wstools.WSDLTools.WSDLReader().loadFromURL(wsdl)
        self._service = self._wsdl.services[service or 0]
        self.__doc__ = self._service.documentation
        self._port = self._service.ports[port or 0]
        self._name = self._service.name
        self._methods = {}
        
        # Set up rpc methods for service/port
        port = self._port
        binding = port.getBinding()
        portType = binding.getPortType()
        for port in self._service.ports:
            for item in port.getPortType().operations:
                callinfo = wstools.WSDLTools.callInfoFromWSDL(port, item.name)
                method = MethodProxy(self, callinfo)
                setattr(self, item.name, method)
                self._methods.setdefault(item.name, []).append(method)
       
        # wsdl2py: deal with XML Schema
        if not os.path.isdir(cachedir): os.mkdir(cachedir)
    
        file = os.path.join(cachedir, '.cache')
        section = 'TYPES'
        cp = ConfigParser()
        try:
            cp.readfp(open(file, 'r'))
        except IOError:
            del cp;  cp = None
            
        option = wsdl.replace(':', '-') # colons seem to screw up option
        if (cp is not None and cp.has_section(section) and 
            cp.has_option(section, option)):
            types = cp.get(section, option)
        else:
            # dont do anything to anames
            containers.ContainerBase.func_aname = lambda instnc,n: str(n)
            #client,types = commands.wsdl2py(['-u', wsdl,'-o', cachedir, '-t', "%s_types.py" %])
            types = _urn_to_module(wsdl)
            commands.wsdl2py(['-u', wsdl,'-o', cachedir, '-t', types])
            if cp is None: cp = ConfigParser()
            if not cp.has_section(section): cp.add_section(section)
            cp.set(section, option, types)
            cp.write(open(file, 'w'))
            
        if os.path.abspath(cachedir) not in sys.path:
            sys.path.append(os.path.abspath(cachedir))

        self._mod = __import__(types)