def create_ticket_for_lineitem (self, req, id, addMesage, lineitem, summary=None): #skip line items that have a ticket if re.search('/ticket/\d+', lineitem.description): return compname = 'Estimate-'+str(id) if summary: compname = summary ensure_component(self.env, compname, req.authname) t = Ticket(self.env) # try to split on a newline or space that is less than 80 chars into the string idx = lineitem.description.find('\n', 0, 80) if idx < 0: idx = lineitem.description.find(' ', 45, 80) if idx < 0: idx = 45 summary = lineitem.description[:idx] desc = lineitem.description desc += "\n\nFrom [/Estimate?id=%s Created From Estimate %s]" % \ (lineitem.estimate_id,lineitem.estimate_id) t.values['summary'] = summary t.values['description'] = desc t.values['status'] = 'new' t.values['reporter'] = req.authname t.values['component'] = compname t.values['estimatedhours'] = avg(lineitem.low, lineitem.high) t.insert() lineitem.description+="\n\nCreated as /ticket/%s" % (t.id, ) return t
def import_tickets(self): trac_cursor = self.env.get_db_cnx().cursor() peer = SymfonyErrorPeer(self.env) owners = {} trac_cursor.execute("select owner, name from component") for name, owner in trac_cursor: owners[name] = owner for error in peer.select_grouped(): # ticket with current hash key not exists ? trac_cursor.execute("select ticket from ticket_custom where name = 'symfony_error_key' and value = '%s'" % error['hash_key']) existing = trac_cursor.fetchone() if not existing: ticket = Ticket(self.env) ticket.values['summary'] = 'Bug #' + error['hash_key'] + ' ' + error['message'] ticket.values['symfony_error_key'] = error['hash_key'] ticket.values['reporter'] = 'cron' ticket.values['resolution'] = 'new' ticket.values['status'] = 'new' ticket.values['milestone'] = '0.3.1' if error['module_name'] in owners: owner = owners[error['module_name']] else: owner = self.default_owner ticket.values['owner'] = owner ticket.insert()
def move(self, ticket_id, author, env, delete=False): """ move a ticket to another environment env: environment to move to """ tables = {"attachment": "id", "ticket_change": "ticket"} # open the environment if it is a string if isinstance(env, basestring): base_path, _project = os.path.split(self.env.path) env = open_environment(os.path.join(base_path, env), use_cache=True) # get the old ticket old_ticket = Ticket(self.env, ticket_id) # make a new ticket from the old ticket values new_ticket = Ticket(env) new_ticket.values = old_ticket.values.copy() new_ticket.insert(when=old_ticket.time_created) # copy the changelog and attachment DBs for table, _id in tables.items(): for row in get_all_dict(self.env, "SELECT * FROM %s WHERE %s=%%s" % (table, _id), str(ticket_id)): row[_id] = new_ticket.id insert_row_from_dict(env, table, row) # copy the attachments src_attachment_dir = os.path.join(self.env.path, "attachments", "ticket", str(ticket_id)) if os.path.exists(src_attachment_dir): dest_attachment_dir = os.path.join(env.path, "attachments", "ticket") if not os.path.exists(dest_attachment_dir): os.makedirs(dest_attachment_dir) dest_attachment_dir = os.path.join(dest_attachment_dir, str(new_ticket.id)) shutil.copytree(src_attachment_dir, dest_attachment_dir) # note the previous location on the new ticket new_ticket.save_changes(author, "moved from %s" % self.env.abs_href("ticket", ticket_id)) # location of new ticket new_location = env.abs_href.ticket(new_ticket.id) if delete: old_ticket.delete() else: # close old ticket and point to new one old_ticket["status"] = u"closed" old_ticket["resolution"] = u"moved" old_ticket.save_changes(author, u"moved to %s" % new_location) if env.config["trac"].get("base_url"): return new_location else: return None
def invoke(self, message, warnings): """make a new ticket on receiving email""" # local warnings _warnings = [] # get the ticket reporter reporter = self._reporter(message) # get the description and attachments mailBody, attachments = get_body_and_attachments(message) mailBody += '\n' # get the ticket fields fields = self._fields(mailBody, _warnings, reporter=reporter) # inset items from email ticket = Ticket(self.env) for key, value in fields.items(): ticket.values[key] = value # fill in default values for field in ticket.fields: name = field['name'] if name not in fields: option = 'ticket_field.%s' % name if self.env.config.has_option('mail', option): ticket.values[name] = self.env.config.get('mail', option) else: try: value = ticket.get_value_or_default(name) or '' except AttributeError: # BBB value = '' if value is not None: ticket.values[name] = value # create the ticket ticket.insert() # add attachments to the ticket add_attachments(self.env, ticket, attachments) # do whatever post-processing is necessary self.post_process(ticket) # add local warnings if _warnings: warning = """A ticket has been created but there is a problem:\n\n%s\n\nPlease edit your ticket by going here: %s""" % ('\n\n'.join([' - %s' % warning for warning in _warnings]), self.env.abs_href('ticket', ticket.id)) warnings.append(warning)
def test_remove_all(self): test_name = sys._getframe().f_code.co_name expected = self.expected_results[test_name] ticket = Ticket(self.env) ticket.populate({'reporter': 'santa', 'summary': 'Summary line', 'description': 'Lorem ipsum dolor sit amet', }) ticket.insert() self.assertEqual(1, len(self._get_docs())) rv, output = self._execute('fulltext remove') self.assertEqual(expected, output) self.assertEqual(0, len(self._get_docs()))
def parse(self, fp): msg = email.message_from_file(fp) tkt = Ticket(self.env) tkt['status'] = 'new' tkt['reporter'] = msg['from'] tkt['summary'] = msg['subject'] for part in msg.walk(): if part.get_content_type() == 'text/plain': tkt['description'] = part.get_payload(decode=1).strip() if tkt.values.get('description'): tkt.insert()
def parse(self, fp): msg = email.message_from_file(fp) tkt = Ticket(self.env) tkt["status"] = "new" tkt["reporter"] = msg["from"] tkt["summary"] = msg["subject"] for part in msg.walk(): if part.get_content_type() == "text/plain": tkt["description"] = part.get_payload(decode=1).strip() if tkt.values.get("description"): tkt.insert()
def _clone_testcase(self, db, id, status, milestone, assign=None): self.env.log.info("Cloning ticket %d (status == %s)" % (id, status)) ticket_new = Ticket(self.env, db=db) ticket_old = Ticket(self.env, tkt_id=id, db=db) for k,v in ticket_old.values.items(): self.env.log.debug("id: %d\tkey: %s\t\tvalue: %s" % (id,k,v)) ticket_new.values[k] = ticket_old.values[k] if assign and len(assign) > 0: ticket_new['owner'] = assign.strip() ticket_new.values['milestone'] = milestone ticket_new.insert() for k,v in ticket_new.values.items(): self.env.log.info("%s\t%s" % (k, v))
def _clone_testcase(self, db, id, status, milestone, assign=None): self.env.log.info("Cloning ticket %d (status == %s)" % (id, status)) ticket_new = Ticket(self.env, db=db) ticket_old = Ticket(self.env, tkt_id=id, db=db) for k, v in ticket_old.values.items(): self.env.log.debug("id: %d\tkey: %s\t\tvalue: %s" % (id, k, v)) ticket_new.values[k] = ticket_old.values[k] if assign and len(assign) > 0: ticket_new['owner'] = assign.strip() ticket_new.values['milestone'] = milestone ticket_new.insert() for k, v in ticket_new.values.items(): self.env.log.info("%s\t%s" % (k, v))
def test_can_insert_tickets_after_upgrade(self): t1 = Ticket(self.env) t1.summary = "test" t1.insert() self.assertEqual(t1.id, 1) self._enable_multiproduct() self.env.upgrade() with self.product('@'): ticket = Ticket(self.env) ticket.summary = 'test' ticket.insert() self.assertEqual(ticket.id, 2)
def test_remove_all(self): test_name = sys._getframe().f_code.co_name expected = self.expected_results[test_name] ticket = Ticket(self.env) ticket.populate({ 'reporter': 'santa', 'summary': 'Summary line', 'description': 'Lorem ipsum dolor sit amet', }) ticket.insert() self.assertEqual(1, len(self._get_docs())) rv, output = self._execute('fulltext remove') self.assertEqual(expected, output) self.assertEqual(0, len(self._get_docs()))
def submit(self, req): ticket = Ticket(self.env) # required fields ticket['aid'] = req.args['aid'] description = req.args['description'] ticket['description'] = description ticket['summary'] = req.args.get('summary', description) # other fields excluded = ['aid', 'description', 'summary'] fields = [ field['name'] for field in ticket.fields if field['name'] not in excluded ] for field in fields: arg = req.args.get(field) if arg is not None: ticket[field] = arg # create the ticket _id = ticket.insert() # yield the ticket ID return {"servicerequestid": _id}
def _insert_ticket(cls, env, summary, **kw): """Helper for inserting a ticket into the database""" ticket = Ticket(env) ticket["summary"] = summary for k, v in kw.items(): ticket[k] = v return ticket.insert()
def _do_create(self, req, db): if not req.args.get('summary'): raise TracError('Tickets must contain a summary.') ticket = Ticket(self.env, db=db) ticket.values.setdefault('reporter', util.get_reporter_id(req)) ticket.populate(req.args) ticket.insert(db=db) db.commit() # Notify try: tn = TicketNotifyEmail(self.env) tn.notify(ticket, newticket=True) except Exception, e: self.log.exception("Failure sending notification on creation of " "ticket #%s: %s" % (ticket.id, e))
def _do_create(self, req, db): if not req.args.get('summary'): raise TracError(u'Les tickets doivent contenir un intitulé.') ticket = Ticket(self.env, db=db) ticket.populate(req.args) ticket.values['reporter'] = get_reporter_id(req, 'reporter') self._validate_ticket(req, ticket) ticket.insert(db=db) db.commit() # Notify try: tn = TicketNotifyEmail(self.env) tn.notify(ticket, newticket=True) except Exception, e: self.log.exception(u"Impossible d'envoyer une notification sur la création du " u"ticket #%s: %s" % (ticket.id, e))
def _do_create(self, req, db): if not req.args.get('summary'): raise TracError('Tickets must contain a summary.') ticket = Ticket(self.env, db=db) ticket.populate(req.args) ticket.values['reporter'] = get_reporter_id(req, 'reporter') self._validate_ticket(req, ticket) ticket.insert(db=db) db.commit() # Notify try: tn = TicketNotifyEmail(self.env) tn.notify(ticket, newticket=True) except Exception, e: self.log.exception("Failure sending notification on creation of " "ticket #%s: %s" % (ticket.id, e))
def _do_create(self, req, db): if not req.args.get('summary'): raise TracError('Tickets must contain a summary.') ticket = Ticket(self.env, db=db) ticket.values.setdefault('reporter', util.get_reporter_id(req)) ticket.populate(req.args) #Check for required fields ticket.validate_required_fields(req.args) ticket.insert(db=db) db.commit() # Notify try: tn = TicketNotifyEmail(self.env) tn.notify(ticket, newticket=True) except Exception, e: self.log.exception("Failure sending notification on creation of " "ticket #%s: %s" % (ticket.id, e))
def test_ticket(self): self.env.config.set('ticket-custom', 'foo', 'text') ticket = Ticket(self.env) ticket.populate({'reporter': 'santa', 'summary': 'Summary line', 'description': 'Lorem ipsum dolor sit amet', 'foo': 'This is a custom field', 'keywords': 'alpha bravo charlie', 'cc': '[email protected], [email protected]', }) ticket.insert() so = self._get_so() self.assertEquals('%s:ticket:1' % self.basename, so.doc_id) self.assertEquals('ticket', so.realm) self.assertEquals('1', so.id) self.assertTrue('#1' in so.title) self.assertTrue('Summary line' in so.title) self.assertEquals('santa', so.author) self.assertEquals(ticket['time'], so.created) self.assertEquals(ticket['changetime'], so.changed) self.assertTrue('*****@*****.**' in so.involved) self.assertTrue('*****@*****.**' in so.involved) self.assertTrue('bravo' in so.tags) self.assertTrue('Lorem ipsum' in so.oneline) self.assertTrue('Lorem ipsum' in so.body) original_time = ticket['time'] ticket['description'] = 'No latin filler here' ticket.save_changes('Jack Sprat', 'Could eat no fat') so = self._get_so() self.assertEquals('%s:ticket:1' % self.basename, so.doc_id) self.assertEquals('ticket', so.realm) self.assertEquals('1', so.id) self.assertEquals(original_time, so.created) self.assertEquals(ticket['changetime'], so.changed) self.assertFalse('Lorem ipsum' in so.body) self.assertTrue('No latin filler here' in so.body) self.assertTrue('Could eat no fat' in so.comments)
def run(options): # # defualt value # T_STATUS = 'new' T_MILESTONE = '' # # begin to create new ticket # TRAC_ENV = os.environ.get('TRAC_ENV') or os.path.expanduser('/home/trac/glue') if not os.path.isdir(TRAC_ENV): print >>sys.stderr, "Set TRAC_ENV to the Trac project directory." #sys.exit(2) return { "status": 2 } from trac.env import open_environment from trac.ticket import Ticket t = Ticket(open_environment(TRAC_ENV)) info = dict( status=T_STATUS, owner=options["owner"], reporter=options["reporter"], cc=options["cc"], milestone=T_MILESTONE, type=options["type"], summary=options["summary"].decode(sys.getfilesystemencoding()), description = options["description"].decode(sys.getfilesystemencoding()) ) t.populate(info) num = t.insert() if not num: print >>sys.stderr, "Ticket not created" print >>sys.stderr, vals #sys.exit(1) return { "status": 1 } #print "Ticket #%d" % (num) return { "status": 0, "id": num }
def __create_new_ticket(self, page, title, owner): matched = re.compile(r'^\[(.*)\](.*)').search(title) if matched: summary = matched.group(2) owner = matched.group(1) else: summary = title owner = None ticket = Ticket(self.env) ticket.values = { 'status': 'new', 'reporter': page.author, 'summary': summary, 'owner': owner, 'description': "wiki:%s" % page.name, } return ticket.insert()
def createTicket(self, ticket_fields, env): """ Creates the ticket in trac. Keyword arguments: ticket_fields -- A dictionary with the ticket fields. Returns: The ticket number. """ ticket = Ticket(env) # Lets populate the ticket with our fields. # The ticket has already set all default values for us from trac.ini # in it's init, nice huh. # Don't write to ticket.values[] unless you know what you are doing ticket.populate(ticket_fields) # create the ticket return ticket.insert()
def _create_trac_ticket(self, fields): trac_ticket = TracTicket(self.env) for key, value in fields.items(): trac_ticket[key] = value trac_ticket.insert() return trac_ticket
def testIndexNewTicket(self): ticket = Ticket(self.env) ticket.insert() si = self.fts.backend.si_class(self.fts.backend.solr_endpoint) self.assertEquals(1, len(si.query('realm:ticket')))
def _insert_and_load_ticket(self, summary, **kw): ticket = Ticket(self.env) ticket["summary"] = summary for k, v in kw.items(): ticket[k] = v return Ticket(self.env, ticket.insert())
def generateTracTickets(self, req): """ ok, it's a post so we know we are supposed to go ahead and create some TRAC tickets...the parameters that we care about are: #users ...this will be a list... #testtemplates ... this will be a list... #testcases ... this will be a list... #version...this will be a string... #milestone...this will be a string... This method does one of two things. It will either return: "True, URL" if ticket creation based on user input was succesful or "False, ErrorMessage" if the ticket creation failed. """ #grab the parameters that we care about out of the request object testRunKeyWord = str(req.args.get('testrun_keyword')) users = req.args.get('testrun_users') testTemplates = req.args.get('testrun_selectedtemplates') testcases = req.args.get('testrun_selectedtestcases') version = str(req.args.get('testrun_selectedversion')) milestone = str(req.args.get('testrun_selectedmilestone')) testConfiguration = str(req.args.get('testrun_testconfiguration')) #-----------------------------------ERROR CHECKING ON PARAMETERS-------------------------------------------- #it might make sense to create a new method to validate the parameters passed in but for now we'll leave it. if testRunKeyWord == None: testRunKeyWord = "" testRunKeyWord = self.properties.trimOutAnyProblemStrings( testRunKeyWord ) #this is manually typed in...so it's probably a good idea to look for sqlInjection etc... if version == None: version = "" if milestone == None: milestone = "" if users == None: return False, "No users selected for test run" #check to see if the user, templates or testcases parameters is a str/unicode or a list (well if it isn't a unicode or str then it is a list) if isinstance(users, unicode): users = [users] if isinstance(users, str): users = [TracText.to_unicode(users)] if isinstance(testcases, unicode): testcases = [testcases] if isinstance(testcases, str): testcases = [testcases] if isinstance(testTemplates, unicode): testTemplates = [testTemplates] if isinstance(testTemplates, str): testTemplates = [TracText.to_unicode(testTemplates)] version = TracText.to_unicode(version).strip() milestone = TracText.to_unicode(milestone).strip() if testcases == None: testcases = [] #so we don't get a blow up later... if testTemplates == None: return False, "must select at least one testcase or test template to create a test run" elif testTemplates == None: testTemplates = [] #--------------------------------------------DONE ERROR CHECKING ----------------------------------------------- #create combined testcase list testcases = self.createCombinedTestCaseList(testTemplates, testcases, req) allTestcases, errors = self.properties.getTestCases( self, req) #fetch the testcases... if errors: return False, errors if allTestcases == None: return False, None #one last validation step errorMessages = [] for aUser in users: for testId in testcases: testId = TracText.to_unicode(testId).strip() if testId in allTestcases: continue else: self.env.log.info("Testcase : " + testId + " not found in master list ") errorMessages.append( "The test: " + testId + ", doesn't match it's file name or you've specified it wrong in the testtemplates.xml file" ) if errorMessages: return False, errorMessages #ok this is where we actually create the tickets... db = self.env.get_db_cnx() for aUser in users: for testId in testcases: testId = testId.encode('ascii', 'ignore').strip() if testId in allTestcases: test = allTestcases[testId] ticket = Ticket(self.env, db=db) ticket.populate(req.args) ticket.values[ 'reporter'] = req.authname #the reporter is whoever is logged in ticket.values['summary'] = "TestID: " + test.getId( ) + " -- " + testConfiguration ticket.values[ 'description'] = "''''''Test Details:''''''\n\n" + test.getDescription( ) + "\n\n''''''Expected result:'''''' \n\n" + test.getExpectedResult( ) ticket.values['type'] = 'testcase' ticket.values['status'] = 'new' ticket.values['action'] = 'create' ticket.values['component'] = test.getComponent() ticket.values['owner'] = aUser ticket.values['version'] = version ticket.values['milestone'] = milestone ticket.values['keywords'] = testRunKeyWord #self._validate_ticket(req, ticket) #probably should validate the ticket here. ticket.insert(db=db) db.commit() else: return False, "The test " + testId + " specified in a test template or as the testcaseID in the test file does not exist in the master test list " #ok blow away the session vars incase someone trys to refresh the created test run page...no need to recreate all the tickets again... #thanks to the haxs in the reporty.py module... for var in ('users', 'testcases', 'testtemplates', 'milestone', 'version'): if req.session.has_key(var): del req.session[var] #redirect to a custom query report showing the created tickets return True, req.base_url + "/query?status=new&status=assigned&status=reopened&status=accepted&testcase_result=&version=" + version + "&milestone=" + milestone + "&type=testcase&order=priority&group=owner"
def add_ticket(self): ticket = Ticket(self.env) ticket['summary'] = 'fnord' ticket.insert() return ticket
def move(self, ticket_id, author, env, delete=False): """ move a ticket to another environment env: environment to move to """ self.log.info( "Starting move of ticket %d to environment %r. delete: %r", ticket_id, env, delete) tables = {'attachment': 'id', 'ticket_change': 'ticket'} # open the environment if it is a string if isinstance(env, basestring): base_path, _project = os.path.split(self.env.path) env = open_environment(os.path.join(base_path, env), use_cache=True) PermissionCache(env, author).require('TICKET_CREATE') # get the old ticket old_ticket = Ticket(self.env, ticket_id) # make a new ticket from the old ticket values new_ticket = Ticket(env) new_ticket.values = old_ticket.values.copy() new_ticket.insert(when=old_ticket.values['time']) self.log.debug("Ticket inserted into target environment as id %s", new_ticket.id) # copy the changelog and attachment DBs for table, _id in tables.items(): for row in get_all_dict( self.env, "SELECT * FROM %s WHERE %s = %%s" % (table, _id), str(ticket_id)): row[_id] = new_ticket.id insert_row_from_dict(env, table, row) self.log.debug("Finished copying data from %r table", table) # copy the attachments src_attachment_dir = os.path.join(self.env.path, 'attachments', 'ticket', str(ticket_id)) if os.path.exists(src_attachment_dir): self.log.debug("Copying attachements from %r", src_attachment_dir) dest_attachment_dir = os.path.join(env.path, 'attachments', 'ticket') if not os.path.exists(dest_attachment_dir): os.makedirs(dest_attachment_dir) dest_attachment_dir = os.path.join(dest_attachment_dir, str(new_ticket.id)) shutil.copytree(src_attachment_dir, dest_attachment_dir) # note the previous location on the new ticket if delete: new_ticket.save_changes( author, 'moved from %s (ticket deleted)' % self.env.abs_href()) else: new_ticket.save_changes( author, 'moved from %s' % self.env.abs_href('ticket', ticket_id)) self.log.info("Finished making new ticket @ %r", env.abs_href('ticket', ticket_id)) if delete: self.log.debug("Deleting old ticket") old_ticket.delete() if env.base_url: return env.abs_href('ticket', new_ticket.id) else: self.log.debug("Marking old ticket as duplicate.") # location of new ticket if env.base_url: target_name = env.abs_href('ticket', new_ticket.id) else: target_name = "{0}:#{1}".format(env.project_name, new_ticket.id) # close old ticket and point to new one old_ticket['status'] = u'closed' old_ticket['resolution'] = u'duplicate' old_ticket.save_changes(author, u'moved to %s' % target_name)
def move(self, ticket_id, author, env, delete=False): """ move a ticket to another environment env: environment to move to """ tables = {'attachment': 'id', 'ticket_change': 'ticket'} # open the environment if it is a string if isinstance(env, basestring): base_path, _project = os.path.split(self.env.path) env = open_environment(os.path.join(base_path, env), use_cache=True) # get the old ticket old_ticket = Ticket(self.env, ticket_id) # make a new ticket from the old ticket values new_ticket = Ticket(env) new_ticket.values = old_ticket.values.copy() new_ticket.insert(when=old_ticket.time_created) # copy the changelog and attachment DBs for table, _id in tables.items(): for row in get_all_dict( self.env, "SELECT * FROM %s WHERE %s=%%s" % (table, _id), str(ticket_id)): row[_id] = new_ticket.id insert_row_from_dict(env, table, row) # copy the attachments src_attachment_dir = os.path.join(self.env.path, 'attachments', 'ticket', str(ticket_id)) if os.path.exists(src_attachment_dir): dest_attachment_dir = os.path.join(env.path, 'attachments', 'ticket') if not os.path.exists(dest_attachment_dir): os.makedirs(dest_attachment_dir) dest_attachment_dir = os.path.join(dest_attachment_dir, str(new_ticket.id)) shutil.copytree(src_attachment_dir, dest_attachment_dir) # note the previous location on the new ticket new_ticket.save_changes( author, 'moved from %s' % self.env.abs_href('ticket', ticket_id)) # location of new ticket new_location = env.abs_href.ticket(new_ticket.id) if delete: old_ticket.delete() else: # close old ticket and point to new one old_ticket['status'] = u'closed' old_ticket['resolution'] = u'moved' old_ticket.save_changes(author, u'moved to %s' % new_location) if env.config['trac'].get('base_url'): return new_location else: return None
def generateTracTickets( self, req ) : """ ok, it's a post so we know we are supposed to go ahead and create some TRAC tickets...the parameters that we care about are: #users ...this will be a list... #testtemplates ... this will be a list... #testcases ... this will be a list... #version...this will be a string... #milestone...this will be a string... This method does one of two things. It will either return: "True, URL" if ticket creation based on user input was succesful or "False, ErrorMessage" if the ticket creation failed. """ #grab the parameters that we care about out of the request object testRunKeyWord = str( req.args.get('testrun_keyword') ) users = req.args.get('testrun_users') testTemplates = req.args.get('testrun_selectedtemplates') testcases = req.args.get('testrun_selectedtestcases') version = str( req.args.get('testrun_selectedversion')) milestone = str( req.args.get('testrun_selectedmilestone')) testConfiguration = str( req.args.get('testrun_testconfiguration')) #-----------------------------------ERROR CHECKING ON PARAMETERS-------------------------------------------- #it might make sense to create a new method to validate the parameters passed in but for now we'll leave it. if testRunKeyWord == None : testRunKeyWord = "" testRunKeyWord = self.properties.trimOutAnyProblemStrings(testRunKeyWord) #this is manually typed in...so it's probably a good idea to look for sqlInjection etc... if version == None: version = "" if milestone == None: milestone = "" if users == None : return False, "No users selected for test run" #check to see if the user, templates or testcases parameters is a str/unicode or a list (well if it isn't a unicode or str then it is a list) if isinstance( users, unicode): users = [users] if isinstance( users, str): users = [TracText.to_unicode ( users )] if isinstance( testcases, unicode) : testcases = [testcases] if isinstance( testcases, str ): testcases = [testcases] if isinstance( testTemplates, unicode) : testTemplates = [testTemplates] if isinstance( testTemplates, str ): testTemplates = [TracText.to_unicode ( testTemplates) ] version = TracText.to_unicode ( version).strip() milestone = TracText.to_unicode ( milestone ).strip() if testcases == None : testcases = [] #so we don't get a blow up later... if testTemplates == None : return False, "must select at least one testcase or test template to create a test run" elif testTemplates == None : testTemplates = [] #--------------------------------------------DONE ERROR CHECKING ----------------------------------------------- #create combined testcase list testcases = self.createCombinedTestCaseList( testTemplates, testcases, req ) allTestcases, errors = self.properties.getTestCases( self, req ) #fetch the testcases... if errors : return False, errors if allTestcases == None : return False, None #one last validation step errorMessages = [] for aUser in users : for testId in testcases : testId = TracText.to_unicode( testId ).strip() if testId in allTestcases : continue else: self.env.log.info( "Testcase : " + testId + " not found in master list " ) errorMessages.append( "The test: " + testId + ", doesn't match it's file name or you've specified it wrong in the testtemplates.xml file" ) if errorMessages: return False, errorMessages #ok this is where we actually create the tickets... db = self.env.get_db_cnx() for aUser in users : for testId in testcases : testId = testId.encode('ascii', 'ignore').strip() if testId in allTestcases : test = allTestcases[ testId ] ticket = Ticket(self.env, db=db) ticket.populate(req.args) ticket.values['reporter'] = req.authname #the reporter is whoever is logged in ticket.values['summary'] = "TestID: " + test.getId() + " -- " + testConfiguration ticket.values['description'] = "''''''Test Details:''''''\n\n" + test.getDescription() + "\n\n''''''Expected result:'''''' \n\n" + test.getExpectedResult() ticket.values['type'] = 'testcase' ticket.values['status'] = 'new' ticket.values['action'] = 'create' ticket.values['component'] = test.getComponent() ticket.values['owner'] = aUser ticket.values['version'] = version ticket.values['milestone'] = milestone ticket.values['keywords'] = testRunKeyWord #self._validate_ticket(req, ticket) #probably should validate the ticket here. ticket.insert(db=db) db.commit() else: return False, "The test " + testId + " specified in a test template or as the testcaseID in the test file does not exist in the master test list " #ok blow away the session vars incase someone trys to refresh the created test run page...no need to recreate all the tickets again... #thanks to the haxs in the reporty.py module... for var in ('users', 'testcases', 'testtemplates','milestone','version'): if req.session.has_key(var): del req.session[var] #redirect to a custom query report showing the created tickets return True, req.base_url + "/query?status=new&status=assigned&status=reopened&status=accepted&testcase_result=&version=" + version + "&milestone=" + milestone + "&type=testcase&order=priority&group=owner"
def generateTracTickets( self, req ) : """ ok, it's a post so we know we are supposed to go ahead and create some TRAC tickets...the parameters that we care about are: #users ...this will be a list... #testtemplates ... this will be a list... #testcases ... this will be a list... #version...this will be a string... #milestone...this will be a string... This method does one of two things. It will either return: "True, URL" if ticket creation based on user input was succesful or "False, ErrorMessage" if the ticket creation failed. """ #grab the parameters that we care about out of the request object testRunDescription = str( req.args.get('testrundescription') ) users = req.args.get('users') testTemplates = req.args.get('testtemplates') testcases = req.args.get('testcases') version = str( req.args.get('selectedversion')) milestone = str( req.args.get('selectedmilestone')) #-----------------------------------ERROR CHECKING ON PARAMETERS-------------------------------------------- if version == None: version = "" if milestone == None: milestone = "" if users == None : return False, "No users selected for test run" if isinstance( users, unicode): users = [users.encode('ascii', 'ignore')] version = version.encode('ascii', 'ignore').strip() milestone = milestone.encode('ascii', 'ignore').strip() if testcases == None : testcases = [] #so we don't get a blow up later... if testTemplates == None : return False, "must select at least one testcase or test template to create a test run" return 'errorCreatingTestRun.cs', None elif testTemplates == None : testTemplates = [] #create combined testcase list testcases = self.createCombinedTestCaseList( testTemplates, testcases, req ) allTestcases = self.properties.getTestCases( self, req ) #fetch the testcases... if allTestcases == None : return False, None #--------------------------------------------DONE ERROR CHECKING ----------------------------------------------- #ok this is where we actually create the tickets... db = self.env.get_db_cnx() for aUser in users : for testId in testcases : testId = testId.encode('ascii', 'ignore').strip() if testId in allTestcases : test = allTestcases[ testId ] ticket = Ticket(self.env, db=db) ticket.populate(req.args) ticket.values['reporter'] = req.authname #the reporter is whoever is logged in ticket.values['summary'] = "TestID: " + test.getId() + " -- " + test.getSummary() ticket.values['description'] = "''''''Test Details:''''''\n\n" + test.getDescription() + "\n\n''''''Expected result:'''''' \n\n" + test.getExpectedResult() ticket.values['type'] = 'testcase' ticket.values['status'] = 'new' ticket.values['action'] = 'create' ticket.values['component'] = test.getComponent() ticket.values['owner'] = aUser ticket.values['version'] = version ticket.values['milestone'] = milestone ticket.values['keywords'] = "Test_ver" + version + "_mile_" + milestone #self._validate_ticket(req, ticket) #probably should validate the ticket here. ticket.insert(db=db) db.commit() else: return False, "The test " + testId + " specified in a test template or as the testcaseID in the test file does not exist in the master test list " #ok blow away the session vars incase someone trys to refresh the created test run page...no need to recreate all the tickets again... #thanks to the haxs in the reporty.py module... for var in ('users', 'testcases', 'testtemplates','milestone','version'): if req.session.has_key(var): del req.session[var] #redirect to a custom query report showing the created tickets return True, req.base_url + "/query?status=new&status=assigned&status=reopened&testcase_result=&version=" + version + "&milestone=" + milestone + "&type=testcase&order=priority&group=owner"