当前位置: 首页>>代码示例>>Python>>正文


Python GangaList.append方法代码示例

本文整理汇总了Python中Ganga.GPIDev.Lib.GangaList.GangaList.GangaList.append方法的典型用法代码示例。如果您正苦于以下问题:Python GangaList.append方法的具体用法?Python GangaList.append怎么用?Python GangaList.append使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Ganga.GPIDev.Lib.GangaList.GangaList.GangaList的用法示例。


在下文中一共展示了GangaList.append方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: testPrintingGPIObjectList

# 需要导入模块: from Ganga.GPIDev.Lib.GangaList.GangaList import GangaList [as 别名]
# 或者: from Ganga.GPIDev.Lib.GangaList.GangaList.GangaList import append [as 别名]
    def testPrintingGPIObjectList(self):

        g = GangaList()
        for _ in range(10):
            g.append(self._makeRandomTFile())

        g_string = str(g)
        assert eval(g_string) == g, 'String should correctly eval'
开发者ID:VladimirRomanovsky,项目名称:ganga,代码行数:10,代码来源:TestMutableMethods.py

示例2: cloneVal

# 需要导入模块: from Ganga.GPIDev.Lib.GangaList.GangaList import GangaList [as 别名]
# 或者: from Ganga.GPIDev.Lib.GangaList.GangaList.GangaList import append [as 别名]
 def cloneVal(v):
     GangaList = _getGangaList()
     if isinstance(v, (list, tuple, GangaList)):
         new_v = GangaList()
         for elem in v:
             new_v.append(self.__cloneVal(elem, obj))
         return new_v
     else:
         return self.__cloneVal(v, obj)
开发者ID:rmatev,项目名称:ganga,代码行数:11,代码来源:Objects.py

示例3: testFullPrintingGPIObjectList

# 需要导入模块: from Ganga.GPIDev.Lib.GangaList.GangaList import GangaList [as 别名]
# 或者: from Ganga.GPIDev.Lib.GangaList.GangaList.GangaList import append [as 别名]
    def testFullPrintingGPIObjectList(self):

        g = GangaList()
        for _ in range(10):
            g.append(self._makeRandomTFile())
        g_string = str(g)

        import StringIO
        sio = StringIO.StringIO()
        full_print(g, sio)
        assert g_string == str(sio.getvalue()).rstrip(), 'Orphaned lists should full_print'
开发者ID:VladimirRomanovsky,项目名称:ganga,代码行数:13,代码来源:TestMutableMethods.py

示例4: testPrintingPlainList

# 需要导入模块: from Ganga.GPIDev.Lib.GangaList.GangaList import GangaList [as 别名]
# 或者: from Ganga.GPIDev.Lib.GangaList.GangaList.GangaList import append [as 别名]
    def testPrintingPlainList(self):

        g = GangaList()
        l = []
        print('"'+str(g)+'"')
        print('"'+str(l)+'"')
        print(l == g)
        assert str(l) == str(g), 'Empty lists should print the same'

        for i in xrange(100):
            g.append(i)
            l.append(i)
        assert str(l) == str(g), 'Normal Python objects should print the same'
开发者ID:VladimirRomanovsky,项目名称:ganga,代码行数:15,代码来源:TestMutableMethods.py

示例5: _stripAttribute

# 需要导入模块: from Ganga.GPIDev.Lib.GangaList.GangaList import GangaList [as 别名]
# 或者: from Ganga.GPIDev.Lib.GangaList.GangaList.GangaList import append [as 别名]
 def _stripAttribute(obj, v, name):
     # just warn
     # print '**** checking',v,v.__class__,
     # isinstance(val,GPIProxyObject)
     if isinstance(v, list):
         from Ganga.GPIDev.Lib.GangaList.GangaList import GangaList
         v_new = GangaList()
         for elem in v:
             v_new.append(elem)
         v = v_new
     if isinstance(v, GPIProxyObject) or hasattr(v, implRef):
         v = stripProxy(v)
         logger.debug('%s property: assigned a component object (%s used)' % (name, implRef))
     return stripProxy(obj)._attribute_filter__set__(name, v)
开发者ID:alexpearce,项目名称:ganga,代码行数:16,代码来源:Proxy.py

示例6: testCopy

# 需要导入模块: from Ganga.GPIDev.Lib.GangaList.GangaList import GangaList [as 别名]
# 或者: from Ganga.GPIDev.Lib.GangaList.GangaList.GangaList import append [as 别名]
    def testCopy(self):

        gl = GangaList()

        numberOfFiles = 100

        for _ in range(numberOfFiles):
            # add something which is generally not allowed by GangaList
            gl.append([self._makeRandomTFile()])

        assert len(gl) == numberOfFiles, 'Right number of files must be made'

        gl2 = copy.copy(gl)
        assert gl2 == gl, 'lists must be equal'
        assert gl2 is not gl, 'list must be copies'
开发者ID:mjmottram,项目名称:ganga,代码行数:17,代码来源:TestCopy.py

示例7: testDeepCopy

# 需要导入模块: from Ganga.GPIDev.Lib.GangaList.GangaList import GangaList [as 别名]
# 或者: from Ganga.GPIDev.Lib.GangaList.GangaList.GangaList import append [as 别名]
    def testDeepCopy(self):

        gl = GangaList()

        numberOfFiles = 100

        for _ in range(numberOfFiles):
            # add something which is generally not allowed by GangaList
            gl.append([self._makeRandomTFile()])

        assert len(gl) == numberOfFiles, "Right number of files must be made"

        gl2 = copy.deepcopy(gl)
        assert gl2 == gl, "lists must be equal"
        assert gl2 is not gl, "list must be copies"
        assert gl[0] is not gl2[0], "the references must be copied"
开发者ID:chrisburr,项目名称:ganga,代码行数:18,代码来源:TestCopy.py

示例8: __cloneVal

# 需要导入模块: from Ganga.GPIDev.Lib.GangaList.GangaList import GangaList [as 别名]
# 或者: from Ganga.GPIDev.Lib.GangaList.GangaList.GangaList import append [as 别名]
    def __cloneVal(self, v, obj):

        item = obj._schema[getName(self)]

        if v is None:
            if item.hasProperty('category'):
                assertion = item['optional'] and (item['category'] != 'internal')
            else:
                assertion = item['optional']
            #assert(assertion)
            if assertion is False:
                logger.warning("Item: '%s'. of class type: '%s'. Has a Default value of 'None' but is NOT optional!!!" % (getName(self), type(obj)))
                logger.warning("Please contact the developers and make sure this is updated!")
            return None
        elif isinstance(v, str):
            return str(v)
        elif isinstance(v, int):
            return int(v)
        elif isinstance(v, dict):
            new_dict = {}
            for key, item in new_dict.iteritems():
                new_dict[key] = self.__cloneVal(v, obj)
            return new_dict
        else:
            if not isinstance(v, Node) and isinstance(v, (list, tuple)):
                try:
                    GangaList = _getGangaList()
                    new_v = GangaList()
                except ImportError:
                    new_v = []
                for elem in v:
                    new_v.append(self.__cloneVal(elem, obj))
                #return new_v
            elif not isinstance(v, Node):
                if inspect.isclass(v):
                    new_v = v()
                else:
                    new_v = v
                if not isinstance(new_v, Node):
                    logger.error("v: %s" % str(v))
                    raise GangaException("Error: found Object: %s of type: %s expected an object inheriting from Node!" % (str(v), str(type(v))))
                else:
                    new_v = self.__copyNodeObject(new_v, obj)
            else:
                new_v = self.__copyNodeObject(v, obj)

            return new_v
开发者ID:rmatev,项目名称:ganga,代码行数:49,代码来源:Objects.py

示例9: testDeepCopy

# 需要导入模块: from Ganga.GPIDev.Lib.GangaList.GangaList import GangaList [as 别名]
# 或者: from Ganga.GPIDev.Lib.GangaList.GangaList.GangaList import append [as 别名]
    def testDeepCopy(self):

        from Ganga.GPIDev.Lib.GangaList.GangaList import GangaList
        gl = GangaList()

        numberOfFiles = 100

        for _ in range(numberOfFiles):
            # add something which is generally not allowed by GangaList
            gl.append([self._makeRandomTFile()])

        assert len(gl) == numberOfFiles, 'Right number of files must be made'

        gl2 = copy.deepcopy(gl)
        assert len(gl2) == len(gl), 'lists must be equal'
        assert gl2 is not gl, 'list must be copies'
        assert gl[0] is not gl2[0], 'the references must not be copied'
开发者ID:Erni1619,项目名称:ganga,代码行数:19,代码来源:TestCopy.py

示例10: __init__

# 需要导入模块: from Ganga.GPIDev.Lib.GangaList.GangaList import GangaList [as 别名]
# 或者: from Ganga.GPIDev.Lib.GangaList.GangaList.GangaList import append [as 别名]
    def __init__(self, files=None, persistency=None, depth=0):
        super(LHCbDataset, self).__init__()
        if files is None:
            files = []
        new_files = GangaList()
        if isType(files, LHCbDataset):
            for this_file in files:
                new_files.append(deepcopy(this_file))
        elif isType(files, IGangaFile):
            new_files.append(deepcopy(this_file))
        elif isType(files, (list, tuple, GangaList)):
            new_list = []
            for this_file in files:
                if type(this_file) is str:
                    new_file = string_datafile_shortcut_lhcb(this_file, None)
                elif isType(this_file, IGangaFile):
                    new_file = this_file
                else:
                    new_file = strToDataFile(this_file)
                new_list.append(stripProxy(new_file))
            stripProxy(new_files)._list = new_list
        elif type(files) is str:
            new_files.append(string_datafile_shortcut_lhcb(this_file, None), False)
        else:
            raise GangaException("Unknown object passed to LHCbDataset constructor!")
        new_files._setParent(self)

        logger.debug("Processed inputs, assigning files")

        # Feel free to turn this on again for debugging but it's potentially quite expensive
        #logger.debug( "Creating dataset with:\n%s" % files )
        self.files = new_files
        
        logger.debug("Assigned files")

        self.persistency = persistency
        self.depth = depth
        logger.debug("Dataset Created")
开发者ID:VladimirRomanovsky,项目名称:ganga,代码行数:40,代码来源:LHCbDataset.py

示例11: put

# 需要导入模块: from Ganga.GPIDev.Lib.GangaList.GangaList import GangaList [as 别名]
# 或者: from Ganga.GPIDev.Lib.GangaList.GangaList.GangaList import append [as 别名]

#.........这里部分代码省略.........
            import datetime
            t = datetime.datetime.now()
            this_date = t.strftime("%H.%M_%A_%d_%B_%Y")
            self.lfn = os.path.join(configDirac['DiracLFNBase'], 'GangaFiles_%s' % this_date)
            selfConstructedLFN = True
        #if self.remoteDir == '' and self.lfn != '':
        #    self.remoteDir = configDirac['DiracLFNBase']

        if self.remoteDir[:4] == 'LFN:':
            lfn_base = self.remoteDir[4:]
        else:
            lfn_base = self.remoteDir

        if uploadSE != "":
            storage_elements = all_SE_list(uploadSE)
        else:
            storage_elements = all_SE_list(self.defaultSE)

        outputFiles = GangaList()
        for this_file in glob.glob(os.path.join(sourceDir, self.namePattern)):
            name = this_file

            if not os.path.exists(name):
                if not self.compressed:
                    raise GangaException('Cannot upload file. File "%s" must exist!' % name)
                name += '.gz'
                if not os.path.exists(name):
                    raise GangaException('File "%s" must exist!' % name)
            else:
                if self.compressed:
                    os.system('gzip -c %s > %s.gz' % (name, name))
                    name += '.gz'
                    if not os.path.exists(name):
                        raise GangaException('File "%s" must exist!' % name)

            if lfn == "":
                lfn = os.path.join(lfn_base, os.path.basename(name))

            if selfConstructedLFN is True:
                self.lfn = os.path.join(self.lfn, os.path.basename(name))

            lfn = self.lfn

            d = DiracFile()
            d.namePattern = os.path.basename(name)
            d.compressed = self.compressed
            d.localDir = sourceDir
            stderr = ''
            stdout = ''
            logger.info('Uploading file %s to %s as %s' % (name, storage_elements[0], lfn))
            stdout = execute('uploadFile("%s", "%s", %s)' % (lfn, name, str([storage_elements[0]])))
            if type(stdout) == str:
                logger.warning("Couldn't upload file '%s': %s" % (os.path.basename(name), stdout))
                continue
            if stdout.get('OK', False) and lfn in stdout.get('Value', {'Successful': {}})['Successful']:
                # when doing the two step upload delete the temp file
                if self.compressed or self._parent != None:
                    os.remove(name)
                # need another eval as datetime needs to be included.
                guid = stdout['Value']['Successful'][lfn].get('GUID', '')
                if regex.search(self.namePattern) is not None:
                    d.lfn = lfn
                    d.remoteDir = os.path.dirname(lfn)
                    d.locations = stdout['Value']['Successful'][lfn].get('allDiracSE', '')
                    d.guid = guid
                    outputFiles.append(GPIProxyObjectFactory(d))
                    continue
                else:
                    self.lfn = lfn
                    self.remoteDir = os.path.dirname(lfn)
                    self.locations = stdout['Value']['Successful'][lfn].get('allDiracSE', '')
                    self.guid = guid
                # return ## WHY?
            else:
                failureReason = "Error in uploading file %s : %s" % (os.path.basename(name), str(stdout))
                logger.error(failureReason)
                if regex.search(self.namePattern) is not None:
                    d.failureReason = failureReason
                    outputFiles.append(GPIProxyObjectFactory(d))
                    continue
                self.failureReason = failureReason
                return str(stdout)

        if replicate == True:

            if len(outputFiles) == 1 or len(outputFiles) == 0:
                storage_elements.pop(0)
                for se in storage_elements:
                    self.replicate(se)
            else:
                storage_elements.pop(0)
                for this_file in outputFiles:
                    for se in storage_elements:
                        this_file.replicate(se)

        if len(outputFiles) > 0:
            return GPIProxyObjectFactory(outputFiles)
        else:
            outputFiles.append(self)
            return GPIProxyObjectFactory(outputFiles)
开发者ID:mjmottram,项目名称:ganga,代码行数:104,代码来源:DiracFile.py

示例12: LHCbDataset

# 需要导入模块: from Ganga.GPIDev.Lib.GangaList.GangaList import GangaList [as 别名]
# 或者: from Ganga.GPIDev.Lib.GangaList.GangaList.GangaList import append [as 别名]
class LHCbDataset(GangaDataset):

    '''Class for handling LHCb data sets (i.e. inputdata for LHCb jobs).

    Example Usage:
    ds = LHCbDataset(["lfn:/some/lfn.file","pfn:/some/pfn.file"])
    ds[0] # DiracFile("/some/lfn.file") - see DiracFile docs for usage
    ds[1] # PhysicalFile("/some/pfn.file")- see PhysicalFile docs for usage
    len(ds) # 2 (number of files)
    ds.getReplicas() # returns replicas for *all* files in the data set
    ds.replicate("CERN-USER") # replicate *all* LFNs to "CERN-USER" SE
    ds.getCatalog() # returns XML catalog slice
    ds.optionsString() # returns Gaudi-sytle options 
    [...etc...]
    '''
    schema = {}
    docstr = 'List of PhysicalFile and DiracFile objects'
    schema['files'] = GangaFileItem(defvalue=[], typelist=['str', 'Ganga.GPIDev.Adapters.IGangaFile.IGangaFile'], sequence=1, doc=docstr)
    docstr = 'Ancestor depth to be queried from the Bookkeeping'
    schema['depth'] = SimpleItem(defvalue=0, doc=docstr)
    docstr = 'Use contents of file rather than generating catalog.'
    schema['XMLCatalogueSlice'] = GangaFileItem(defvalue=None, doc=docstr)
    docstr = 'Specify the dataset persistency technology'
    schema['persistency'] = SimpleItem(
        defvalue=None, typelist=['str', 'type(None)'], doc=docstr)
    schema['treat_as_inputfiles'] = SimpleItem(defvalue=False, doc="Treat the inputdata as inputfiles, i.e. copy the inputdata to the WN")

    _schema = Schema(Version(3, 0), schema)
    _category = 'datasets'
    _name = "LHCbDataset"
    _exportmethods = ['getReplicas', '__len__', '__getitem__', 'replicate',
                      'hasLFNs', 'append', 'extend', 'getCatalog', 'optionsString',
                      'getLFNs', 'getFileNames', 'getFullFileNames',
                      'difference', 'isSubset', 'isSuperset', 'intersection',
                      'symmetricDifference', 'union', 'bkMetadata',
                      'isEmpty', 'hasPFNs', 'getPFNs']  # ,'pop']

    def __init__(self, files=None, persistency=None, depth=0, fromRef=False):
        super(LHCbDataset, self).__init__()
        if files is None:
            files = []
        self.files = GangaList()
        process_files = True
        if fromRef:
            self.files._list.extend(files)
            process_files = False
        elif isinstance(files, GangaList):
            def isFileTest(_file):
                return isinstance(_file, IGangaFile)
            areFiles = all([isFileTest(f) for f in files._list])
            if areFiles:
                self.files._list.extend(files._list)
                process_files = False
        elif isinstance(files, LHCbDataset):
            self.files._list.extend(files.files._list)
            process_files = False

        if process_files:
            if isType(files, LHCbDataset):
                for this_file in files:
                    self.files.append(deepcopy(this_file))
            elif isType(files, IGangaFile):
                self.files.append(deepcopy(this_file))
            elif isType(files, (list, tuple, GangaList)):
                new_list = []
                for this_file in files:
                    if type(this_file) is str:
                        new_file = string_datafile_shortcut_lhcb(this_file, None)
                    elif isType(this_file, IGangaFile):
                        new_file = stripProxy(this_file)
                    else:
                        new_file = strToDataFile(this_file)
                    new_list.append(new_file)
                self.files.extend(new_list)
            elif type(files) is str:
                self.files.append(string_datafile_shortcut_lhcb(this_file, None), False)
            else:
                raise GangaException("Unknown object passed to LHCbDataset constructor!")

        self.files._setParent(self)

        logger.debug("Processed inputs, assigning files")

        # Feel free to turn this on again for debugging but it's potentially quite expensive
        #logger.debug( "Creating dataset with:\n%s" % self.files )
        
        logger.debug("Assigned files")

        self.persistency = persistency
        self.depth = depth
        logger.debug("Dataset Created")

    def __getitem__(self, i):
        '''Proivdes scripting (e.g. ds[2] returns the 3rd file) '''
        #this_file = self.files[i]
        # print type(this_file)
        # return this_file
        # return this_file
        # return this_file
        if type(i) == type(slice(0)):
#.........这里部分代码省略.........
开发者ID:ganga-devs,项目名称:ganga,代码行数:103,代码来源:LHCbDataset.py

示例13: __init__

# 需要导入模块: from Ganga.GPIDev.Lib.GangaList.GangaList import GangaList [as 别名]
# 或者: from Ganga.GPIDev.Lib.GangaList.GangaList.GangaList import append [as 别名]
 def __init__(self, files=[], persistency=None, depth=0):
     new_files = GangaList()
     if isType(files, LHCbDataset):
         for this_file in files:
             new_files.append(copy.deepcopy(this_file))
     elif isType(files, IGangaFile):
         new_files.append(copy.deepcopy(this_file))
     elif type(files) == type([]):
         for this_file in files:
             if type(this_file) == type(''):
                 new_files.append(string_datafile_shortcut_lhcb(this_file, None), False)
             elif isType(this_file, IGangaFile):
                 new_files.append(this_file, False)
             else:
                 new_files.append(strToDataFile(this_file))
     elif type(files) == type(''):
         new_files.append(string_datafile_shortcut_lhcb(this_file, None), False)
     else:
         from Ganga.Core.exceptions import GangaException
         raise GangaException("Unknown object passed to LHCbDataset constructor!")
     new_files._setParent(self)
     super(LHCbDataset, self).__init__()
     # Feel free to turn this on again for debugging but it's potentially quite expensive
     #logger.debug( "Creating dataset with:\n%s" % files )
     self.files = new_files
     self.persistency = persistency
     self.depth = depth
     logger.debug("Dataset Created")
开发者ID:kreczko,项目名称:ganga,代码行数:30,代码来源:LHCbDataset.py

示例14: put

# 需要导入模块: from Ganga.GPIDev.Lib.GangaList.GangaList import GangaList [as 别名]
# 或者: from Ganga.GPIDev.Lib.GangaList.GangaList.GangaList import append [as 别名]

#.........这里部分代码省略.........
            if self.defaultSE != "":
                storage_elements = [self.defaultSE]
            else:
                if configDirac['allDiracSE']:
                    storage_elements = [random.choice(configDirac['allDiracSE'])]
                else:
                    raise GangaFileError("Can't upload a file without a valid defaultSE or storageSE, please provide one")
        elif isinstance(uploadSE, list):
            storage_elements = uploadSE
        else:
            storage_elements = [uploadSE]

        outputFiles = GangaList()
        for this_file in glob.glob(os.path.join(sourceDir, self.namePattern)):
            name = this_file

            if not os.path.exists(name):
                if not self.compressed:
                    raise GangaFileError('Cannot upload file. File "%s" must exist!' % name)
                name += '.gz'
                if not os.path.exists(name):
                    raise GangaFileError('File "%s" must exist!' % name)
            else:
                if self.compressed:
                    os.system('gzip -c %s > %s.gz' % (name, name))
                    name += '.gz'
                    if not os.path.exists(name):
                        raise GangaFileError('File "%s" must exist!' % name)

            lfn = os.path.join(lfn_base, os.path.basename(this_file))

            d = DiracFile()
            d.namePattern = os.path.basename(name)
            d.compressed = self.compressed
            d.localDir = sourceDir
            stderr = ''
            stdout = ''
            logger.info('Uploading file \'%s\' to \'%s\' as \'%s\'' % (name, storage_elements[0], lfn))
            logger.debug('execute: uploadFile("%s", "%s", %s)' % (lfn, os.path.join(sourceDir, name), str([storage_elements[0]])))
            try:
                stdout = execute('uploadFile("%s", "%s", %s)' % (lfn, os.path.join(sourceDir, name), str([storage_elements[0]])), cred_req=self.credential_requirements)
            except GangaDiracError as err:
                logger.warning("Couldn't upload file '%s': \'%s\'" % (os.path.basename(name), err))
                failureReason = "Error in uploading file '%s' : '%s'" % (os.path.basename(name), err)
                if regex.search(self.namePattern) is not None:
                    d.failureReason = failureReason
                    outputFiles.append(d)
                    continue
                self.failureReason += '\n' + failureReason
                continue

            stdout_temp = stdout.get('Successful')

            if not stdout_temp:
                msg = "Couldn't upload file '%s': \'%s\'" % (os.path.basename(name), stdout)
                logger.warning(msg)
                if regex.search(self.namePattern) is not None:
                    d.failureReason = msg
                    outputFiles.append(d)
                    continue
                self.failureReason = msg
                continue
            else:
                lfn_out = stdout_temp[lfn]

            # when doing the two step upload delete the temp file
            if self.compressed or self._parent != None:
                os.remove(name)
            # need another eval as datetime needs to be included.
            guid = lfn_out.get('GUID', '')
            if regex.search(self.namePattern) is not None:
                d.lfn = lfn
                d.remoteDir = os.path.dirname(lfn)
                d.locations = lfn_out.get('allDiracSE', '')
                d.guid = guid
                outputFiles.append(d)
                continue
            else:
                self.lfn = lfn
                self.remoteDir = os.path.dirname(lfn)
                self.locations = lfn_out.get('allDiracSE', '')
                self.guid = guid

        if replicate == True:

            if len(outputFiles) == 1 or len(outputFiles) == 0:
                storage_elements.pop(0)
                for se in storage_elements:
                    self.replicate(se)
            else:
                storage_elements.pop(0)
                for this_file in outputFiles:
                    for se in storage_elements:
                        this_file.replicate(se)

        if len(outputFiles) > 0:
            return outputFiles
        else:
            outputFiles.append(self)
            return outputFiles
开发者ID:Erni1619,项目名称:ganga,代码行数:104,代码来源:DiracFile.py

示例15: TestGangaList

# 需要导入模块: from Ganga.GPIDev.Lib.GangaList.GangaList import GangaList [as 别名]
# 或者: from Ganga.GPIDev.Lib.GangaList.GangaList.GangaList import append [as 别名]
class TestGangaList(GangaGPITestCase):

    def __init__(self):

        self.ganga_list = None

        self.plain1 = []
        self.plain2 = []

        self.proxied1 = []
        self.proxied2 = []

    def _makeRandomString(self):
        str_len = random.randint(3, 10)
        s = ''
        for _ in range(str_len):
            s += random.choice(string.ascii_letters)
        return s

    def _makeRandomTFile(self):
        name = self._makeRandomString()
        subdir = self._makeRandomString()
        return TFile(name=name, subdir=subdir)

    def setUp(self):
        self.ganga_list = GangaList()

        self.plain1 = [self._makeRandomTFile() for _ in range(15)]
        self.plain2 = [self._makeRandomTFile() for _ in range(10)]

        self.proxied1 = GangaList()
        self.proxied1.extend(self.plain1[:])
        self.proxied2 = GangaList()
        self.proxied2.extend(self.plain2[:])

        assert len(getProxyAttr(self.proxied1, '_list')) == len(
            self.plain1), 'Somthings wrong with construction'
        assert len(getProxyAttr(self.proxied2, '_list')) == len(
            self.plain2), 'Somthings wrong with construction'

    def testAllListMethodsExported(self):
        """Tests that all methods on list are exposed by GangaList"""

        def getmethods(_obj):
            # get all the method names for an object
            return dir(_obj)

        list_methods = getmethods([])
        gangalist_methods = getmethods(self.ganga_list)

        missing_methods = []
        for m in list_methods:
            if not m in gangalist_methods:
                missing_methods.append(m)

        if missing_methods:
            logger.info(missing_methods)

        assert not missing_methods, \
            'Not all of lists methods are implemented: %s' % str(
                missing_methods)

    def testEq(self):
        """Tests the equality op that the rest of the tests rely on."""
        assert self.proxied1 == self.plain1, 'Proxied and non-proxied versions should be the same'

    def testNq(self):
        assert self.proxied1 != None
        assert not self.proxied1 != self.proxied1, 'Lists are the same'
        assert self.proxied1 != self.proxied2, 'Lists are different'
        assert self.plain1 != self.proxied2, 'Lists are different'

    def testNonZero(self):
        """@ExpectedFailure"""
        assert not GangaList(
        ), 'An empty GangaList should be false, just like a list'

    def testAdd(self):
        """Test __add__"""
        assert (self.plain1 + self.plain2) == (self.proxied1 + self.proxied2)
        assert isProxy(self.proxied1 + self.proxied2)

    def testAddMixed(self):
        """Test __add__ with mixed lists and GangaLists"""
        assert (self.plain1 + self.plain2) == (self.proxied1 + self.plain2)
        assert (self.plain2 + self.plain1) == (self.plain2 + self.proxied1)
        assert isProxy(self.proxied1 + self.plain2)

        assert (self.plain2 + self.plain1) == (self.plain2 + self.proxied1)
        assert (self.plain1 + self.plain2) == (self.plain1 + self.proxied2)
        assert isinstance(self.plain1 + self.proxied2, list)

    def testAddMixed2(self):

        self.plain1 = range(10)
        self.plain2 = range(10)

        assert isProxy(self.proxied2[-1]), 'Element access must get proxies'
        assert not isProxy(self.plain1[0]), 'Element access must not proxies'
        assert isProxy(
#.........这里部分代码省略.........
开发者ID:chrisburr,项目名称:ganga,代码行数:103,代码来源:TestGangaList.py


注:本文中的Ganga.GPIDev.Lib.GangaList.GangaList.GangaList.append方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。