Пример #1
0
def process():
    if select==1:
        inb=Inbound()
        inb.load_to_db()
    if select ==2:
        iss=Issue()
        iss.issue()
Пример #2
0
    def __init__(self, parser, bugelem, mapToBE={}, dontprocess=set(), mapFromBE=None):
        """Initialises a new issue taken from an XML backing. mapToBE should be a dictionary
        mapping the source XML element tags to BE element names and outputs if necessary i.e
        mapToBE={'xmltag':('befield', lambda xmlelem:xmlelem.text)}
        Current BE issue fields:

        uuid: UUID
        [short-name]: string
        severity: string from ["minor", "wishlist", "serious", "major", "critical", "fatal", "target"]
        status: string from ["unconfirmed", "open", "test", "closed", "fixed", "feedback", "wontfix"]
        [assigned]: string
        [reporter]: string
        [creator]: string
        time: datetime string (e.g. Tue, 21 Jul 2009 18:32:12 +0000)
        summary: string
        [extra-strings]: list of strings
        """
        if mapFromBE is None: mapFromBE={v[0]:(k, v[1]) for k, v in mapToBE.iteritems()}
        IssueBase.__init__(self, parser)
        self.__element=bugelem
        self.__elementhash=0
        self.__mapToBE=mapToBE
        self.__dontprocess=dontprocess
        self.__mapFromBE=mapFromBE
        self.__setUUID()
Пример #3
0
    def test_output(self):
        """
        Test the different outputs including UTF-16 characters and issue without parent issue
        """
        work_logs = [
            WorkLog("MYB-7", datetime(2020, 1, 20), 3600, "René Doe"),
            WorkLog("MYB-5", datetime(2020, 1, 18), 3600, "John Doe"),
            WorkLog("MYB-5", datetime(2020, 1, 18), 5400, "John Doe"),
            WorkLog("MYB-5", datetime(2020, 1, 12), 3600, "John Doe")
        ]

        issues = [
            Issue(10005, "MYB-5", "Summary of issue MYB-5", "MYB-3",
                  "Summary of the parent issue of MYB-5"),
            Issue(10007, "MYB-7", "Summary of issue MYB-7", None, None)
        ]

        stdout = sys.stdout
        with open('jira-time-report-console.txt', 'w') as sys.stdout:
            jiratimereport.process_work_logs("console", issues, work_logs)
        sys.stdout = stdout
        self.assertTrue(
            filecmp.cmp('console_output.txt', 'jira-time-report-console.txt'))

        jiratimereport.process_work_logs("csv", issues, work_logs)
        self.assertTrue(filecmp.cmp('csv_output.csv', 'jira-time-report.csv'))

        jiratimereport.process_work_logs("excel", issues, work_logs)
        self.assertTrue(filecmp.cmp('excel_output.xlsx', 'excel_output.xlsx'))
Пример #4
0
Файл: bugz.py Проект: mtvee/bgz
 def do_add( self, args ):
     """ add an issue 
     
     bgz add [type]
     
     where type is:
             (b)ug | (t)ask | (f)eature
     """            
     self._check_status()
     # default type
     if len(args) < 1:
         args = ['bug']
         
     if len(args) and args[0][0] in Issue.types.keys() or args[0][0] == 'p':
         type = args[0][0]
     else:
         type = self._read_input( 'Type: (b)ug, (f)eature, (t)ask | (p)roject?', 'b', ('b','t','f','p'))
         
     if type =='p':
         self._add_project( self.BGZ_DIR )
         return
     print 'Adding new ' + Issue.types[type].lower()
     title = self._read_input('Title')
     author = self._read_input('Author',self.opts['user.name'])
     #desc = self._read_multiline('Descr')
     desc = self._external_edit('\n\n### ' + title )
     
     issue = Issue( self.BGZ_DIR )
     issue['Title'] = title
     issue['Description'] = desc
     issue['Type'] = type
     issue['Author'] = author
     issue.save()        
     self._log( 'Added: ' + str(issue) )
Пример #5
0
def profileIssueCall(id):
    user_name = id
    users = mongo.db.userlist
    exiting_user = users.find_one({'USERNAME': user_name})
    user = User(exiting_user['NAMES'], exiting_user['USERNAME'],
                exiting_user['MAIL'])

    issue_array = []
    i = mongo.db.Issues
    issuelist = i.find({}).sort('date', -1)
    problemsdb = mongo.db.problems
    for issue in issuelist:
        if issue['UserName'] == id:
            if issue['ProblemID'] != 'CodeFlask':
                pb = problemsdb.find_one({'myid': issue['ProblemID']})
                issue_array.append(
                    Issue(issue['IssueID'], issue['UserName'], issue['Title'],
                          issue['ProblemID'], pb['name'], issue['text'],
                          issue['date'], issue['commentNumber']))
            else:
                issue_array.append(
                    Issue(issue['IssueID'], issue['UserName'], issue['Title'],
                          issue['ProblemID'], 'CodeFlask', issue['text'],
                          issue['date'], issue['commentNumber']))

    return user, issue_array
Пример #6
0
    def test_output(self):
        """
        Test the different outputs including UTF-16 characters and issue without parent issue
        """
        work_logs = [
            WorkLog("MYB-7", datetime(2020, 1, 20), 3600, "René Doe"),
            WorkLog("MYB-5", datetime(2020, 1, 18), 3600, "John Doe"),
            WorkLog("MYB-5", datetime(2020, 1, 18), 5400, "John Doe"),
            WorkLog("MYB-5", datetime(2020, 1, 12), 3600, "John Doe")
        ]

        issue_myb_5 = Issue(10005, "MYB-5", "Summary of issue MYB-5", "MYB-3",
                            "Summary of the parent issue of MYB-5", 3600, 900,
                            datetime(2020, 1, 15))
        issue_myb_5.issue_start_date = datetime(2020, 1, 10)
        issue_myb_7 = Issue(10007, "MYB-7", "Summary of issue MYB-7", None,
                            None, None, None, None)

        issues = [issue_myb_5, issue_myb_7]

        stdout = sys.stdout
        with open('jira-time-report-console.txt', 'w') as sys.stdout:
            jiratimereport.process_work_logs("console", issues, work_logs)
        sys.stdout = stdout
        self.assertTrue(
            filecmp.cmp('console_output.txt', 'jira-time-report-console.txt'))

        jiratimereport.process_work_logs("csv", issues, work_logs)
        self.assertTrue(filecmp.cmp('csv_output.csv', 'jira-time-report.csv'))

        jiratimereport.process_work_logs("excel", issues, work_logs)
        expected_excel = pd.read_excel('excel_output.xlsx')
        actual_excel = pd.read_excel('jira-time-report.xlsx')
        self.assertTrue(expected_excel.equals(actual_excel))
Пример #7
0
    def test_get_updated_issues_multiple_pages(self):
        """
        Test the multiple pages response when retrieving Jira issues (pagination)
        """
        with open("issues_multiple_first_page.json", "r") as issues_first_file:
            mock_response_first_page = issues_first_file.read()

        with open("issues_multiple_second_page.json",
                  "r") as issues_second_file:
            mock_response_second_page = issues_second_file.read()

        with requests_mock.Mocker() as m:
            m.register_uri('GET', '/rest/api/2/search',
                           [{
                               'text': mock_response_first_page
                           }, {
                               'text': mock_response_second_page
                           }])
            issues = jiratimereport.get_updated_issues("https://jira_url",
                                                       "user_name",
                                                       "api_token", "MYB",
                                                       "2020-01-10",
                                                       "2020-01-20", "")

        issues_expected_result = [
            Issue(10005, "MYB-5", "Summary of issue MYB-5", "MYB-3",
                  "Summary of the parent issue of MYB-5"),
            Issue(10004, "MYB-4", "Summary of issue MYB-4", "MYB-3",
                  "Summary of the parent issue of MYB-4"),
            Issue(10006, "MYB-6", "Summary of issue MYB-6", "MYB-3",
                  "Summary of the parent issue of MYB-6")
        ]

        self.assertListEqual(issues_expected_result, issues,
                             "Issues lists are unequal")
Пример #8
0
def confirm_issue_creation(update, context):
    user = update.message.from_user
    logger.info(
        f"Palavra secreta digitada por {user.first_name}: {update.message.text}"
    )
    logger.info(f"The user data context: {context.user_data}")
    issue = Issue(context.user_data['project'], context.user_data['title'],
                  context.user_data['description'])

    if update.message.text == SECRET_KEY:
        message = f'Acertou mizerávi\n\n'
        if issue.create_issue():
            message += f'Issue Criada :)\n'
        else:
            message += f'Desculpa pelo vacilo!\n' \
                       f'Tive um problema para criar a issue\n'

        if issue.create_card():
            message += f'Card Criado :)'
        else:
            message += f'Desculpa pelo vacilo!\n' \
                       f'Tive um problema para criar o card'
    else:
        message = f'Errrrooouu!'

    update.message.reply_text(message, reply_markup=None)
    # Tell ConversationHandler that the conversation has ended
    return ConversationHandler.END
Пример #9
0
    def test_get_updated_issues_one_page(self):
        """
        Test the single page response when retrieving Jira issues
        """
        with open("issues_one_page.json", "r") as issues_file:
            mock_response = issues_file.read()

        with requests_mock.Mocker() as m:
            m.register_uri('GET', '/rest/api/2/search', text=mock_response)
            issues = jiratimereport.get_updated_issues("https://jira_url",
                                                       "user_name",
                                                       "api_token", "MYB",
                                                       "2020-01-10",
                                                       "2020-01-20", "")

        issues_expected_result = [
            Issue(10005, "MYB-5", "Summary of issue MYB-5", "MYB-3",
                  "Summary of the parent issue of MYB-5", 3600, 900,
                  datetime(2020, 1, 20)),
            Issue(10004, "MYB-4", "Summary of issue MYB-4", "MYB-3",
                  "Summary of the parent issue of MYB-4", 7200, 600, None)
        ]

        self.assertListEqual(issues_expected_result, issues,
                             "Issues lists are unequal")
Пример #10
0
Файл: bugz.py Проект: mtvee/bgz
 def do_time( self, args ):
     """ add or report time 
     
     bgz time
         report on time for this week (Monday - Sunday)
         
     bgz time add ID
         add a new time entry for the given ID
         
     bgz time DATERANGE
         report on time for a DATERANGE
         a DATERANGE can be:
         tw | [thisw]eek = this week (Monday - Sunday)
         lw | [lastw]eek = last week (Monday - Sunday)
         [y]esterday     = (midnight - midnight)
         [t]oday | [n]ow = (midnight - now)
         DD/MM/YYYY[:DD/MM/YYYY]
     """
     self._check_status()
     if len(args) == 0:
         args.append("thisweek")
     if args[0] == 'add':
         if len(args) < 2:
             return False
         dur = self._read_input( "Duration (0:0)", None, lambda x: re.match("\d?:\d+", x) )
         if len(dur) and self.do_comment(args[1:], 'time ' + dur ):
             return True
         else:
             return False
     else:
         # QnD report
         dts = dateparse.DateParser().parse_date_range( args[0] )
         s = 'Time Report'
         s += ' - ' + dts[0].strftime("%Y-%m-%d") + " / " + dts[1].strftime("%Y-%m-%d")
         print '-' * len(s)
         print s
         print '-' * len(s)
         projects = self._read_projects()
         gtotal = [0,0]
         for proj in projects:
             puthdr = True
             issue = Issue( proj )
             files = os.listdir( proj )
             for file in files:
                 if not issue.load( file ):
                     continue
                 tm = issue.time_total( dts ) 
                 if tm[0] > 0 or tm[1] > 0:
                     gtotal[0] += tm[0]
                     gtotal[1] += tm[1]
                     if puthdr:
                         print 'Project: ' + proj[:-(len(proj)-proj.rfind('.'))]
                         puthdr = False
                     print issue.rep( dts )
         gtotal[0] += gtotal[1]/60
         gtotal[1] = gtotal[1] % 60
         t = 'Total: %d:%02d'  % (gtotal[0],gtotal[1])
         print '=' * len(t)
         print t
Пример #11
0
def analysis2list(xml_txt):
    try:
        import xml.etree.cElementTree as ET
    except:
        import xml.etree.ElementTree as ET
    try:
        root = ET.fromstringlist(xml_txt)
        res = []
        for item in root.iter('item'):
            dict = {}
            for key in key_dic:
                iss_item = item.find(key)
                if iss_item is None:
                    continue
                else:
                    dict[key] = iss_item.text
            res.append(dict)

        issue_res = []
        for issue_dic in res:
            issue = Issue(issue_dic)
            issue_res.append(issue)
        return issue_res
    except:
        print('analysis xml failure.')
        return None
Пример #12
0
 def filter(cls, pid=None, account=None, issue=None):
     (all_pids, all_accounts, all_issues) = (False, False, False)
     if not pid:
         all_pids = True
     if account:
         uid = account.id
     else: 
         uid = None
         all_accounts = True
     if issue:
         iid = issue.id
     else:
         iid = None
         all_issues = True
     result = []
     with cls.db.conn.cursor() as curs:
         curs.execute('''SELECT maturity.id, maturity.matures, contract_type.id,
                         contract_type.issue, issue.url, issue.title,
                         position.account, position.quantity, position.basis,
                         position.created, position.modified, position.id
                         FROM maturity JOIN contract_type ON maturity.id = contract_type.matures
                         JOIN issue ON issue.id = contract_type.issue
                         JOIN position ON contract_type.id = position.contract_type
                         WHERE (position.id = %s OR %s)
                         AND (account = %s OR %s)
                         AND (issue = %s OR %s)
                         ''', (pid, all_pids, uid, all_accounts, iid, all_issues))
         for row in curs.fetchall():
             (mid, matures, cid, iid, url, title, uid, quantity, basis, created, modified, pid) = row
             account = Account(uid=uid)
             issue = Issue(url=url, iid=iid, title=title)
             maturity = Maturity(matures, mid)
             ctype = ContractType(issue, maturity, cid)
             result.append(cls(pid, account, ctype, quantity, basis, created, modified))
     return result
Пример #13
0
    def err(tid, message, pos="start", scope=""):
        # When token ID points to end-of-parsing token,
        # reset the id to the last true token before it.
        if tokens[tid]["kind"] == "tkEOP": tid = ttids[-1]

        token = tokens[tid]
        line = token["line"]
        index = token[pos]
        # msg = f"{message}"
        col = index - LINESTARTS[line]

        if message.endswith(":"): message += f" '{tkstr(tid)}'"

        # # Add token debug information.
        # dbeugmsg = "\n\n\033[1mToken\033[0m: "
        # dbeugmsg += "\n - tid: " + str(token["tid"])
        # dbeugmsg += "\n - kind: " + token["kind"]
        # dbeugmsg += "\n - line: " + str(token["line"])
        # dbeugmsg += "\n - start: " + str(token["start"])
        # dbeugmsg += "\n - end: " + str(token["end"])
        # dbeugmsg += "\n __val__: [" + tkstr(tid) + "]"

        # dbeugmsg += "\n\n\033[1mExpected\033[0m: "
        # for n in NEXT:
        #     if not n: n = "\"\""
        #     dbeugmsg += "\n - " + n
        # dbeugmsg += "\n\n\033[1mScopes\033[0m: "
        # for s in SCOPE:
        #     dbeugmsg += "\n - " + s
        # decor = "-" * 15
        # msg += "\n\n" + decor + " TOKEN_DEBUG_INFO " + decor
        # msg += dbeugmsg
        # msg += "\n\n" + decor + " TOKEN_DEBUG_INFO " + decor

        Issue().error(S["filename"], line, col, message)
Пример #14
0
def _post_issue(success_redirect_name='index', error_template='new_issue.html'):
    error = None
    respond_with_json = request_wants_json(request)
    issue = get_object_by_form_or_json(Issue.var_names)
    if not issue['page_url']:
        error = "Please enter the URL that contains the issue."
    else:
        if not issue['img_url']:
            error = "Please enter the URL for the image file."
    if error is None:
        if is_logged_in():        
            reporter_user_id = session['user_id']
        elif issue['creator']:
            reporter_user_id = issue['creator']
        else:
            reporter_user_id = None
        issue = Issue.add_or_update_issue(reporter_user_id, issue)
        if respond_with_json:
            return smart_jsonify(issue)
        else:
            flash('The issue was successfully reported.')
            return redirect(url_for(success_redirect_name))
    else:
        if respond_with_json:
            return smart_jsonify(error=error)
        else:
            return make_response(render_template(error_template, error=error, issue=issue))
Пример #15
0
def xml_to_issues(f):
    """Extract issue data from xml file to make an issue list
    
    Parameters
    ----------
    file : string 
        XML file path
    
    Returns
    -------
    issues : list
        issues list
    """
    parser = etree.XMLParser(ns_clean=True, remove_comments=True)
    tree = etree.parse(f, parser)
    root = tree.getroot()
    
    issues = []
    issues_e = root.find('issues') # find all issues
    for issue_e in issues_e:
        attachments = []
        _id = issue_e.find('id').text
        title = issue_e.find('title').text
        description = issue_e.find('description').text
        for item in issue_e.findall('.//attachment'):
            attachments.append(item.text)            
        comments = issue_e.find('comments').text
        commenters = issue_e.find('commenters').text
        issues.append(Issue(_id, title, description, attachments, int(comments), int(commenters)))
        
    return issues
Пример #16
0
    def test_get_work_logs_multiple_pages(self):
        """
        Test the multiple pages response when retrieving Jira work logs (pagination)
        """
        with open("work_logs_multiple_first_page.json",
                  "r") as issues_first_file:
            mock_response_first_page = issues_first_file.read()

        with open("work_logs_multiple_second_page.json",
                  "r") as issues_second_file:
            mock_response_second_page = issues_second_file.read()

        issues = [
            Issue(10005, "MYB-5", "Summary of issue MYB-5", "MYB-3",
                  "Summary of the parent issue of MYB-5", 3600, 900,
                  datetime(2020, 1, 20))
        ]

        with requests_mock.Mocker() as m:
            m.register_uri('GET', '/rest/api/2/issue/MYB-5/worklog/',
                           [{
                               'text': mock_response_first_page
                           }, {
                               'text': mock_response_second_page
                           }])
            work_logs, issues = jiratimereport.get_work_logs(
                "https://jira_url", "user_name", "api_token", "2020-01-10",
                "2020-01-20", "", issues)

        work_logs_expected_result = [
            WorkLog("MYB-5", datetime(2020, 1, 12), 3600, "John Doe"),
            WorkLog("MYB-5", datetime(2020, 1, 18), 3600, "John Doe"),
            WorkLog("MYB-5", datetime(2020, 1, 18), 5400, "John Doe")
        ]

        self.assertListEqual(work_logs_expected_result, work_logs,
                             "Work Log lists are unequal")

        issue_myb_5 = Issue(10005, "MYB-5", "Summary of issue MYB-5", "MYB-3",
                            "Summary of the parent issue of MYB-5", 3600, 900,
                            datetime(2020, 1, 20))
        issue_myb_5.issue_start_date = datetime(2020, 1, 12)

        issues_expected_result = [issue_myb_5]

        self.assertListEqual(issues_expected_result, issues,
                             "Issue lists are unequal")
Пример #17
0
def scrape_lucene(url_prefix, _id, attributes):
    """Scrape LUCENE issues
    
    Parameters
    ----------
    url_prefix : string
        Issue tracking system URL prefixx
        
    _id : string
        Issue id
        
    attributes : dictionary
        Contains all HTML attributes needed to scrape data
    
    Returns
    -------
    issue : an Issue instance
    """
    
    status_id = attributes['status-id']
    title_id = attributes['title-id']
    description_id = attributes['description-id']
    comment_regex = attributes['comment-regex']
    
    url = url_prefix + str(_id)
    print('Scraping url: %s' % url)

    try:
        result = requests.get(url)
        if result.status_code != 200:
            print('Can\'t access URL!')
        
        soup = BeautifulSoup(result.content, 'lxml')
        status = soup.find(id=status_id).text
        status = ' '.join(status.split())
        if status != 'New Feature' and status != 'Improvement': # not a requirement
            print('[{0}] Not requirement - {1}\n'.format(_id, status))
            return None
        
        # Only accept issue that contains a certain number of comments
        comments = soup.find_all(id=re.compile(comment_regex))
        if len(comments) < MINIMUM_COMMENTS:
            print('[{0}] Issue has only {1} comments!\n'.format(_id, len(comments)))
            return None
        else:
            print('[{0}] Issue has {1} comments!\n'.format(_id, len(comments)))
        # Count number of commenters participating in the discussion
        commenters = count_commenters(_id, comments, ('a', {'class':'user-hover user-avatar'}))
        if commenters is None:
            return None
            
        title = ' '.join(soup.find(id=title_id).text.split())
        description = ' '.join(soup.find(id=description_id).text.split())
    except Exception as err:
        print('[{0}] Exception happened! {1}\n'.format(_id, err))
        return None
    
    print('[{0}] Completed!\n'.format(_id))
    return Issue(str(_id), title, description, [], len(comments), len(commenters))
Пример #18
0
def index():
    issues = None
    if is_logged_in():
        issues = Issue.get_issues_by_user(get_current_user())
        for i in issues:
            i['complaint_count'] = sum(i['reporters'].values())
            i['img_filename'] = get_full_filename_from_url(i['img_url'])
    return render_template('home.html', issues=issues)
Пример #19
0
def checkTense(content):
    suggests = tense.tensecheck(content)
    issuesOfArticle = []
    for i in suggests:
        issue = Issue(2, 2, [i[0]], [i[1]], i[2], i[3])
        print(i)
        issuesOfArticle.append(issue)
    return issuesOfArticle
Пример #20
0
 def _set_queried_issues(self):
     all_issues = [
         Issue(issue_dict) for issue_dict in self._issue_dicts.values()
     ]
     queried_issues = list(
         filter(singletons.query().filter_issue, all_issues))
     queried_issues.sort()
     self._queried_issues = queried_issues
    def setUp(self):

        #creating agents for testing
        self.agent1 = Agent('kanishk', True, time(9,20,0), ['web developer','analyst'])
        self.agent2 = Agent('ayushya', True, time(8,20,0),['developer','analyst'])
        self.agent3 = Agent('shivi', True, time(1,13,0),['writer', 'support'])
        self.agent4 = Agent('prateek', True, time(14,33,0),['support','sales'])
        self.agent5 = Agent('alex', True, time(6,29,0),['marketing','analyst','support'])
        self.agent6 = Agent('shreya', True, time(2,0,0),['mobile developer','analyst'])
        self.agent7 = Agent('sonam', True, time(0,24,0),['frontend developer', 'support', 'backend developer'])
        self.agent8 = Agent('priya', False, time(3,59,0),['backend develper','ml engineer'])
        self.agent9 = Agent('bablu', True, time(19,44,0),['frontend developer','cloud computing'])

        #list of agents
        self.agent_list = [self.agent1, self.agent2, self.agent3, self.agent4, self.agent5, self.agent6, self.agent7, self.agent8, self.agent9]

        #creating issues for testing
        self.issue1 = Issue(roles= ['support'])
        self.issue2 = Issue(roles = ['marketing'])
        self.issue3 = Issue(roles= ['frontend developer', 'backend developer'])
        self.issue4 = Issue(roles = ['cloud computing'])
        self.issue5 = Issue(roles= ['ml engineer'])
        self.issue6 = Issue(roles = ['writer','support'])
        self.issue7 = Issue(roles = ['cloud architect', 'deeplearning'])
        
        #list of issues
        self.issue_list = [self.issue1, self.issue2, self.issue3, self.issue4, self.issue5, self.issue6, self.issue7]

        #creating agent_ selector ojects
        self.agent_selector1 = AgentSelector('all_available', self.agent_list, self.issue_list)
        self.agent_selector2 = AgentSelector('least_busy', self.agent_list, self.issue_list)
        self.agent_selector3 = AgentSelector('random', self.agent_list, self.issue_list)
Пример #22
0
    def filter(cls, account=None, issue=None, ticker=False):
        all_events = not ticker
        (all_accounts, all_issues) = (False, False)
        if issue:
            iid = issue.id
        else:
            iid = None
            all_issues = True
        if account:
            uid = account.id
        else:
            uid = None
            all_accounts = True

        result = []
        # Cursor object for the database driver. Database can have different
        # queries. curs points to this particular query. curs.execute runs a
        # SQL statement that you pass to the database. The result of this
        # execution can then be "fetched".
        with cls.db.conn.cursor() as curs:
            curs.execute(
                '''SELECT issue, url, title, maturity, matures,
                            id, class, created,
                            contract_type, side, price, quantity, message
                            FROM message_overview
                            WHERE (%s OR issue = %s)
                            AND (%s OR recipient = %s)
                            AND (%s OR (side = true AND
                                (class = 'contract_created' OR class = 'contract_resolved')
                                AND quantity > 0))
                            ORDER BY created DESC''',
                (all_issues, iid, all_accounts, uid, all_events))
            for row in curs.fetchall():
                (iid, url, title, maturity_id, matures, mid, mclass, created,
                 cid, side, price, quantity, text) = row
                if ticker and (not url or not title or not matures
                               or not maturity_id):
                    pass
                    # continue #FIXME
                (issue, maturity, contract_type) = (None, None, None)
                if iid:
                    issue = Issue(iid=iid, url=url, title=title)
                if maturity_id and matures:
                    maturity = Maturity(matures, maturity_id)
                if issue and maturity:
                    contract_type = ContractType(issue, maturity, cid=cid)
                result.append(
                    cls(mclass,
                        account=account,
                        contract_type=contract_type,
                        side=side,
                        price=price,
                        quantity=quantity,
                        text=text,
                        created=created,
                        mid=mid))
            return result
Пример #23
0
    def test_convert_json_to_issues(self):
        """
        Test the conversion of json issues to object issues
        """
        with open("convert_json_to_issues.json", "r") as issues_file:
            response_json = json.loads(issues_file.read())

        issues = jiratimereport.convert_json_to_issues(response_json)

        issues_expected_result = [
            Issue(10005, "MYB-5", "Summary of issue MYB-5", "MYB-3",
                  "Summary of the parent issue of MYB-5"),
            Issue(10004, "MYB-4", "Summary of issue MYB-4", "MYB-3",
                  "Summary of the parent issue of MYB-4")
        ]

        self.assertListEqual(issues_expected_result, issues,
                             "Issues lists are unequal")
Пример #24
0
    def hint(tid, message):
        token = tokens[tid]
        line = token["line"]
        index = token["start"]
        col = index - LINESTARTS[line]

        if message.endswith(":"): message += f" '{tkstr(tid)}'"

        Issue().hint(S["filename"], line, col, message)
Пример #25
0
    def test_get_work_logs_one_page(self):
        """
        Test the single page response when retrieving Jira work logs
        """
        with open("work_logs_first_issue_one_page.json",
                  "r") as first_issue_file:
            mock_response_first_issue = first_issue_file.read()

        with open("work_logs_second_issue_one_page.json",
                  "r") as second_issue_file:
            mock_response_second_issue = second_issue_file.read()

        issues = [
            Issue(10005, "MYB-5", "Summary of issue MYB-5", "MYB-3",
                  "Summary of the parent issue of MYB-5", 3600, 900,
                  datetime(2020, 1, 20)),
            Issue(10004, "MYB-4", "Summary of issue MYB-4", "MYB-3",
                  "Summary of the parent issue of MYB-4", 7200, 600, None)
        ]

        with requests_mock.Mocker() as m:
            m.register_uri('GET',
                           '/rest/api/2/issue/MYB-5/worklog/',
                           text=mock_response_first_issue)
            m.register_uri('GET',
                           '/rest/api/2/issue/MYB-4/worklog/',
                           text=mock_response_second_issue)
            work_logs, issues = jiratimereport.get_work_logs(
                "https://jira_url", "user_name", "api_token", "2020-01-10",
                "2020-01-20", "", issues)

        work_logs_expected_result = [
            WorkLog("MYB-5", datetime(2020, 1, 18), 3600, "John Doe"),
            WorkLog("MYB-5", datetime(2020, 1, 18), 5400, "John Doe"),
            WorkLog("MYB-4", datetime(2020, 1, 12), 3600, "John Doe")
        ]

        self.assertListEqual(work_logs_expected_result, work_logs,
                             "Work Log lists are unequal")

        issue_myb_5 = Issue(10005, "MYB-5", "Summary of issue MYB-5", "MYB-3",
                            "Summary of the parent issue of MYB-5", 3600, 900,
                            datetime(2020, 1, 20))
        issue_myb_5.issue_start_date = datetime(2020, 1, 18)
        issue_myb_4 = Issue(10004, "MYB-4", "Summary of issue MYB-4", "MYB-3",
                            "Summary of the parent issue of MYB-4", 7200, 600,
                            None)
        issue_myb_4.issue_start_date = datetime(2020, 1, 12)

        issues_expected_result = [issue_myb_5, issue_myb_4]

        self.assertListEqual(issues_expected_result, issues,
                             "Issue lists are unequal")
Пример #26
0
def issues():
    if request.method == 'GET':
        issues = Issue.get_issues_by_params(params=None)
        for i in issues:
            i['complaint_count'] = sum(i['reporters'].values())
            i['img_filename'] = get_full_filename_from_url(i['img_url'])
        return render_template('issues.html', issues=issues)
    elif request.method == 'POST':
        return _post_issue(success_redirect_name='issues', error_template='issues.html')
    else:
        return ''
Пример #27
0
def checkThirdPersonSingular(content):
    res = single_three.check(content)
    issues = []
    for sentence_entries in res:
        for entry in sentence_entries:
            le = entry[0]
            ri = entry[1]
            rep = entry[2]
            issue = Issue(2, 1, [le], [ri], rep, 4)
            issues.append(issue)
    return issues
Пример #28
0
    def __init__(self, username='', password='', repo_name_or_slug=''):
        self.username = username
        self.password = password
        self.repo_slug = repo_name_or_slug.lower().replace(
            r'[^a-z0-9_-]+', '-')
        self.repo_tree = {}

        self.repository = Repository(self)
        self.service = Service(self)
        self.ssh = SSH(self)
        self.issue = Issue(self)
Пример #29
0
Файл: bugz.py Проект: mtvee/bgz
 def do_purge( self, args ):
     """ move closed issues to 'PROJECT/.bugz/purged' directory
     
     bgz purge
     """
     self._check_status()
     ppath = os.path.join(self.BGZ_DIR, 'purged')
     if not os.path.exists( ppath ):
         try:
             os.mkdir( ppath )
         except:
             raise BugzError( 'abort: unable to create ' + ppath )
     count = 0
     for file in os.listdir( self.BGZ_DIR ):
         issue = Issue(self.BGZ_DIR)
         if not issue.load( file ):
             continue
         if issue['Status'][0] == 'c':
             shutil.move(os.path.join(self.BGZ_DIR,file), ppath)
             count += 1
     self._log( 'purged %d issue(s)' % (count) )
Пример #30
0
Файл: bugz.py Проект: mtvee/bgz
 def _find_issue( self, uid ):
     """ find an issue with a partial uid """
     if uid.startswith('g'):
         if not os.path.exists(os.path.join(self.BGZ_DIR,'general.' + self.opts['user.name'])):
             gen = Issue(self.BGZ_DIR)
             gen['Id'] = 'general.' + self.opts['user.name']
             gen['Title'] = 'General Project Catchall'
             gen['Author'] = self.opts['user.name']
             gen['Type'] = 'task'
             gen['Status'] = 'open'
             gen.save()
     flist = self._find_issues( uid )
     if len(flist) == 1:
         iss = Issue(self.BGZ_DIR)
         if not iss.load( flist[0] ):
             return None
         return iss
     elif len(flist) > 1:
         print 'Please be more specific: '
         for f in flist:
             print f
     return None
Пример #31
0
def vvariable(S):
    token = S["tokens"][S["tid"]]
    start = token["start"]
    end = token["end"]
    line = token["line"]
    index = token["start"]

    # Error when variable starts with a number.
    if S["text"][start + 1].isdigit():
        message = "Unexpected: '" + S["text"][start + 1] + "'"
        message += "\n\033[1;36mInfo\033[0m: Variable cannot begin with a number."
        Issue().error(S["filename"], line, index - S["LINESTARTS"][line],
                      message)
Пример #32
0
def convert_json_to_issues(response_json):
    """
    Convert JSON issues into Issue objects
    :param response_json: the JSON text as received from Jira
    :return: a list of Issues
    """
    issues = []
    for issue_json in response_json['issues']:
        issues.append(Issue(int(issue_json['id']),
                            issue_json['key'],
                            issue_json['fields']['summary'],
                            issue_json['fields']['parent']['key'] if 'parent' in issue_json['fields'] else None,
                            issue_json['fields']['parent']['fields']['summary'] if 'parent' in issue_json['fields'] else None))

    return issues
Пример #33
0
Файл: bugz.py Проект: mtvee/bgz
 def do_status( self, args ):
     """ get the database status 
     
     bgz status [all]
     """
     self._check_status()
     files = os.listdir( self.BGZ_DIR )
     counts = {'new':0,'open':0,'closed':0}
     issues = {}
     for file in files:
         issue = Issue(self.BGZ_DIR)
         if not issue.load( file ):
             continue
         counts[issue['Status']] += 1
         if not issues.has_key( issue['Type'][0] ):
             issues[issue['Type'][0]] = []
             
         if next((a for a in args if a == 'all'),None):
             issues[issue['Type'][0]].append( issue )
         elif issue['Status'][0] != 'c':
             issues[issue['Type'][0]].append( issue )
     print 'Status: ',
     for k in counts.keys():
         pre = ""
         post = ""
         if self.opts.ansi:
             post = "\033[0m"    # reset
             if k[0] == 'n':
                 pre = "\033[31m"    # red     
             elif k[0] == 'c':
                 pre = "\033[32m"    # green   
             elif k[0] == 'o':
                 pre = "\033[33m"    # yellow                 
         print pre + k + post + "/" + str(counts[k]) + " ",
     print
     self._show_issues( issues )
Пример #34
0
 def resolvable(cls):
     result = []
     with cls.db.conn.cursor() as curs:
         curs.execute(
             '''SELECT DISTINCT maturity.matures, maturity.id, issue.url, issue.title, issue.id, contract_type.id
                         FROM maturity JOIN contract_type on maturity.id = contract_type.matures
                         JOIN issue ON issue.id = contract_type.issue
                         JOIN position ON contract_type.id = position.contract_type
                         WHERE maturity.matures < NOW()
                         ORDER BY maturity.matures''')
         for row in curs.fetchall():
             (matures, mid, url, title, iid, cid) = row
             issue = Issue(url=url, iid=iid, title=title)
             maturity = Maturity(matures, mid)
             result.append(cls(issue, maturity, cid))
     return result
Пример #35
0
 def lookup(cls, iid, mid):
     with cls.db.conn.cursor() as curs:
         curs.execute(
             '''INSERT INTO contract_type (issue, matures) VALUES (%s, %s)
                         ON CONFLICT (issue, matures) DO UPDATE set matures = %s RETURNING id''',
             (iid, mid, mid))
         cid = curs.fetchone()[0]
         curs.execute(
             '''SELECT maturity.matures, issue.url, issue.title
                         FROM maturity JOIN contract_type on maturity.id = contract_type.matures
                         JOIN issue ON issue.id = contract_type.issue
                         WHERE contract_type.id = %s''', (cid, ))
         (matures, url, title) = curs.fetchone()
         issue = Issue(url=url, iid=iid, title=title)
         maturity = Maturity(matures, mid)
         return cls(issue, maturity, cid)
Пример #36
0
    def __init__(self, username='', password='', repo_name_or_slug=''):
        self.username = username
        self.password = password
        self.repo_slug = repo_name_or_slug
        self.repo_tree = {}
        self.URLS = URLS

        self.repository = Repository(self)
        self.service = Service(self)
        self.ssh = SSH(self)
        self.issue = Issue(self)

        self.access_token = None
        self.access_token_secret = None
        self.consumer_key = None
        self.consumer_secret = None
        self.oauth = None
Пример #37
0
def vsetting_aval(S):
    token = S["tokens"][S["tid"]]
    start = token["start"]
    end = token["end"]
    line = token["line"]
    index = token["start"]

    values = ["true", "false"]

    value = StringBuilder()
    for i in range(start, end + 1):
        value.append(S["text"][i])

    # Warn if values is not a supported values.
    if str(value) not in values:
        message = "Invalid setting value: '" + str(value) + "'"
        Issue().error(S["filename"], line, index - S["LINESTARTS"][line],
                      message)
Пример #38
0
Файл: bugz.py Проект: mtvee/bgz
 def do_show( self, args ):
     """ show stuff 
     
     bgz show [partial_UUID]
     bgz show [a:author] [s:status] [ty:type] [ti:title] [d:date_range] 
     bgz show all
     """
     self._check_status()
     files = os.listdir( self.BGZ_DIR )
     issues = {}
     for file in files:
         issue = Issue(self.BGZ_DIR)
         if not issue.load( file ):
             continue
         if len(args) and args[0].find(':') != -1:
             hitcount = 0
             for arg in args:
                 tmp = arg.split(':')
                 if tmp[0].startswith('s'): 
                     if issue['Status'][0] == tmp[1][0]:
                         hitcount = hitcount + 1
                 elif tmp[0].startswith('ty'):
                     if issue['Type'][0] == tmp[1][0]:
                         hitcount = hitcount + 1
                 elif tmp[0].startswith('ti'):
                     if issue['Title'].find( tmp[1] ) != -1:
                         hitcount = hitcount + 1
                 elif tmp[0].startswith('a'):
                     if issue['Author'].find( tmp[1] ) != -1:
                         hitcount = hitcount + 1
                 elif tmp[0].startswith('d'):
                     # date range
                     dts = dateparse.DateParser().parse_date_range( tmp[1] )
                     if issue.date() >= dts[0] and issue.date() <= dts[1]:
                         hitcount = hitcount + 1
                 else:
                     raise BugzError( "Unknown qualifier: " + tmp[0] )
             # if all the args hit, then print it
             if hitcount == len( args ):
                 if not issues.has_key( issue['Type'] ):
                     issues[issue['Type'][0]] = []
                 issues[issue['Type'][0]].append( issue )
         elif len(args) and args[0] == 'all':
             if not issues.has_key( issue['Type'] ):
                 issues[issue['Type'][0]] = []
             issues[issue['Type'][0]].append( issue )
         else:
             if len(args):
                 if file.startswith( args[0] ):
                     issue.show()
                     return
     self._show_issues( issues )
Пример #39
0
    def __init__(self, issue, download_directory):

        self.issue = issue
        cwd = os.getcwd()
        subprocess.call(["git", "checkout", "-b", str(issue)])
        Issue(issue, download_directory, [])

        os.chdir(
            os.path.join(cwd, "..", "..", "..", "hoops_3df", "demo", "common",
                         "sanity"))

        f, name, desc = imp.find_module("diet_smoke", [
            os.path.join(cwd, "..", "..", "..", "hoops_3df", "demo", "common",
                         "sanity")
        ])
        module = imp.load_module("diet_smoke", f, name, desc)

        self.prompt_filename()
        module.Diet_Smoke([issue])
Пример #40
0
    def newBill(self, details=None):
        if details:
            self.bill = details
            return
        numTopics = srandom.randint(1, len(issueTopics) / 4)
        # contents = {srandom.choice(issueTopics):srandom.randint(-10, 10) for i in xrange(numTopics)}
        contents = {}
        for i in xrange(numTopics):
            randtopic = srandom.choice(issueTopics)
            while randtopic in contents.keys():
                randtopic = srandom.choice(issueTopics)
            # need to start with fiscal impact, then translate that to voter pref impact

            # currently calculates preference or impact to voter pref
            b = itbounds[randtopic]
            contents[randtopic] = srandom.randint(-10, 10)  # b[0], b[1])
        self.bill = Issue(kv=contents)
        self.billPassed = False
        print self.name, ' bill: ', self.bill.topics
Пример #41
0
    def test_issue_from_args(self):

        I.issue_from_args(["jonmorehouse/repo/1"])
Пример #42
0
def fetch_issues_from_bitbucket(from_user, from_repo, from_password=None, log_level=LOG_LEVEL_ERRORS, fetch_limit=50, stop_at_index=None, start=0):
	'''
	Loads all issues form a Bitbucket repository, and returns a list of Issue objects.
	'''

	# Issues
	issues = []

	# Connect to the Bitbucket repo
	bb = Bitbucket(username=from_user, password=from_password or '', repo_name_or_slug=from_repo)
	success, bb_repo = bb.repository.get()

	# If error, raise
	if not success:
		if log_level >= LOG_LEVEL_ERRORS:
			print(u'Can\' connect to Bitbucket: {0}'.format(bb_repo))
		raise Exception(u'Can\' connect to Bitbucket: {0}'.format(bb_repo))

	# Log
	if log_level >= LOG_LEVEL_INFO:
		print(u'Connected to Bitbucket Repository: {owner}/{slug} ({name})'.format(owner=bb_repo.get('owner'), slug=bb_repo.get('slug'), name=bb_repo.get('name')))

	# Iterate until we fetch all the issues
	while True:

		# Load issues
		success, bb_all_issues = bb.issue.all(params={'sort':'local_id', 'start':str(start), 'limit':str(fetch_limit)})

		# If error, raise
		if not success:
			if log_level >= LOG_LEVEL_ERRORS:
				print(u'Can\'t fetch issues from Bitbucket: {0}'.format(bb_all_issues))
			raise Exception(u'Can\'t fetch issues from Bitbucket: {0}'.format(bb_all_issues))

		# Log
		if log_level >= LOG_LEVEL_DEBUG:
			print(u'Fetched {count} (total: {total}) issues from Bitbucket: {issues}'.format(
				count=len(bb_all_issues['issues']),
				total=bb_all_issues['count'],
				issues=' '.join('#{id}'.format(id=bb_issue['local_id']) for bb_issue in bb_all_issues['issues']),
			))

		# Iterate on issues
		for bb_issue in bb_all_issues['issues']:

			# try/catch to show the issue ID if fails
			try:
				# Load comments
				success, bb_comments = bb.issue.comment.all(issue_id=bb_issue['local_id'])

				# Create Issue
				issue = Issue(bb_issue_and_comments = (bb_issue, bb_comments,))

				# Append issue
				issues.append(issue)

				# Log
				if log_level >= LOG_LEVEL_DEBUG:
					print(issue.__unicode__())
				elif log_level >= LOG_LEVEL_INFO:
					print('Issue ID {id}: {title} ({count} comment(s))'.format(id=bb_issue['local_id'], title=issue.title, count=len(issue.comments)))

			except Exception, e:
				print(u'Cannot create issue ID: {0}'.format(bb_issue.get('local_id')))
				raise

		# Increment start
		start += len(bb_all_issues['issues'])

		# Break when all is loaded
		if start >= bb_all_issues['count'] or (stop_at_index and start >= stop_at_index):
			break