pythonrallypyral

Preferred method to copy a defect using Rally REST API in Python


I'd like to be able to query Rally for an existing defect and then copy that defect changing only a couple of fields while maintaining all attachments. Is there a simple way to do this? I tried calling rally.create and passing the existing defect object, but it failed to serialize all members into JSON. Ultimately, it would be nice if pyral was extended to include this kind of functionality.

Instead, I've written some code to copy each python-native attribute of the existing defect and then use .ref for everything else. It seems to be working quite well. I've leveraged Mark W's code for copying attachments and that's working great also. One remaining frustration is that copying the iteration isn't working. When I call .ref on the Iteration attribute, I get this:

>>> s
<pyral.entity.Defect object at 0x029A74F0>
>>> s.Iteration
<pyral.entity.Iteration object at 0x029A7710>
>>> s.Iteration.ref
No classFor item for |UserIterationCapacity|
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\python27\lib\site-packages\pyral\entity.py", line 119, in __getattr__
    hydrateAnInstance(self._context, item, existingInstance=self)
  File "c:\python27\lib\site-packages\pyral\restapi.py", line 77, in hydrateAnInstance
    return hydrator.hydrateInstance(item, existingInstance=existingInstance)
  File "c:\python27\lib\site-packages\pyral\hydrate.py", line 62, in hydrateInstance
    self._setAppropriateAttrValueForType(instance, attrName, attrValue, 1)
  File "c:\python27\lib\site-packages\pyral\hydrate.py", line 128, in _setAppropriateAttrValueForType
    elements = [self._unravel(element) for element in attrValue]
  File "c:\python27\lib\site-packages\pyral\hydrate.py", line 162, in _unravel
    return self._basicInstance(thing)
  File "c:\python27\lib\site-packages\pyral\hydrate.py", line 110, in _basicInstance
    raise KeyError(itemType)
KeyError: u'UserIterationCapacity'
>>>

Does this look like an issue with Rally or perhaps an issue with a custom field that our project admin might have caused? I was able to work around it by building the ref from the oid:

newArtifact["Iteration"] = { "_ref": "iteration/" + currentArtifact.Iteration.oid }

This feels kludgy to me though.


Solution

  • Final solution including Mark W's code for copying attachments

    def getDataCopy( data ):
    
        """ Given a piece of data, figure out how to copy it.  If it's a native python type
            like a string or numeric, just return the value.  If it's a rally object, return
            the ref to it.  If it's a list, iterate and call ourself recursively for the
            list members. """
    
        if isinstance( data, types.ListType ):
            copyData = []
            for entry in data:
                copyData.append( getDataCopy(entry) )
    
        elif hasattr( data, "ref" ):
            copyData = { "_ref": data.ref }
    
        else:
            copyData = data
    
        return copyData
    
    def getArtifactCopy( artifact ):
    
        """ Build a dictionary based on the values in the specified artifact.  This dictionary
            can then be passed to a rallyConn.put() call to actually create the new entry in
            Rally.  Attachments and Tasks must be copied seperately, since they require creation
            of additional artifacts """
    
        newArtifact = {}
    
        for attrName in artifact.attributes():
    
            # Skip the attributes that we can't or shouldn't handle directly
            if attrName.startswith("_") or attrName == "oid" or attrName == "Iteration" or attrName == "Attachments":
                continue
    
            attrValue = getattr( artifact, attrName )
            newArtifact[attrName] = getDataCopy( attrValue )
    
        if getattr( artifact, "Iteration", None ) != None:
            newArtifact["Iteration"] = { "_ref": "iteration/" + artifact.Iteration.oid }
    
        return newArtifact
    
    def copyAttachments( rallyConn, oldArtifact, newArtifact ):
    
        """ For each attachment in the old artifact, create new attachments and attach them to the new artifact"""
    
        # Copy Attachments
        source_attachments = rallyConn.getAttachments(oldArtifact)
    
        for source_attachment in source_attachments:
    
            # First copy the content
            source_attachment_content = source_attachment.Content
            target_attachment_content_fields = { "Content": base64.encodestring(source_attachment_content) }
    
            try:
                target_attachment_content = rallyConn.put( 'AttachmentContent', target_attachment_content_fields )
                print "\t===> Copied AttachmentContent: %s" % target_attachment_content.ref
            except pyral.RallyRESTAPIError, details:
                sys.stderr.write('ERROR: %s \n' % details)
                sys.exit(2)
    
            # Next copy the attachment object
            target_attachment_fields = {
                "Name": source_attachment.Name,
                "Description": source_attachment.Description,
                "Content": target_attachment_content.ref,
                "ContentType": source_attachment.ContentType,
                "Size": source_attachment.Size,
                "User": source_attachment.User.ref
            }
    
            # Attach it to the new artifact
            target_attachment_fields["Artifact"] = newArtifact.ref
    
            try:
                target_attachment = rallyConn.put( source_attachment._type, target_attachment_fields)
                print "\t===> Copied Attachment: '%s'" % target_attachment.Name
            except pyral.RallyRESTAPIError, details:
                sys.stderr.write('ERROR: %s \n' % details)
                sys.exit(2)
    
    def copyTasks( rallyConn, oldArtifact, newArtifact ):
    
        """ Iterate over the old artifacts tasks and create new ones, attaching them to the new artifact """
    
        for currentTask in oldArtifact.Tasks:
    
            newTask = getArtifactCopy( currentTask )
    
            # Assign the new task to the new artifact
            newTask["WorkProduct"] = newArtifact.ref
    
            # Push the new task into rally
            newTaskObj = rallyConn.put( currentTask._type, newTask )
    
            # Copy any attachments the task had
            copyAttachments( rallyConn, currentTask, newTaskObj )
    
    def copyDefect( rallyConn, currentDefect, addlUpdates = {} ):
    
        """ Copy a defect including its attachments and tasks.  Add the new defect as a
            duplicate to the original """
    
        newArtifact = getArtifactCopy( currentDefect )
    
        # Add the current defect as a duplicate for the new one
        newArtifact["Duplicates"].append( { "_ref": currentDefect.ref } )
    
        # Copy in any updates that might be needed
        for (attrName, attrValue) in addlUpdates.items():
            newArtifact[attrName] = attrValue
    
        print "Copying %s: %s..." % (currentDefect.Project.Name, currentDefect.FormattedID),
        newDefect = rallyConn.create( currentDefect._type, newArtifact )
    
        print "done, new item", newDefect.FormattedID
    
        print "\tCopying attachments"
        copyAttachments( rallyConn, currentDefect, newDefect )
    
        print "\tCopying tasks"
        copyTasks( rallyConn, currentDefect, newDefect )