Best Python code snippet using Kiwi_python
close-old-issues.py
Source:close-old-issues.py  
...41            auth=github_auth)42    r.raise_for_status()43    time.sleep(1)44    return r.json()45def close_issue(issue, github_auth):46    """Attempt to close an issue and return whether it succeeded."""47    closed_issue = issue.copy()48    closed_issue['state'] = 'closed'49    r = requests.post("https://api.github.com/repos/Khan/khan-exercises/"50            "issues/%s" % issue['number'],51            data=json.dumps(closed_issue), auth=github_auth)52    try:53        r.raise_for_status()54        time.sleep(1)55        return True56    except requests.HTTPError:57        # TODO(alpert): Catch IOError or something?58        return False59def post_issue_comment(issue, comment_text, github_auth):60    """Attempt to post an issue comment and return whether it succeeded."""61    closed_issue = issue.copy()62    closed_issue['state'] = 'closed'63    r = requests.post("https://api.github.com/repos/Khan/khan-exercises/"64            "issues/%s/comments" % issue['number'],65            data=json.dumps({'body': comment_text}), auth=github_auth)66    try:67        r.raise_for_status()68        time.sleep(1)69        return True70    except requests.HTTPError:71        # TODO(alpert): Catch IOError or something?72        return False73def close_old_issues(close_before, github_auth):74    notabug_taggers = collections.Counter()75    realbug_taggers = collections.Counter()76    all_issues = fetch_issues(github_auth)77    for issue in all_issues:78        # Only close issues created by KhanBugz79        if issue['user']['login'] != "KhanBugz":80            continue81        issue_created = datetime.datetime.strptime(82            issue['created_at'], "%Y-%m-%dT%H:%M:%SZ")83        if issue['comments']:84            comments = fetch_issue_comments(issue, github_auth)85            # Reverse so the last realbug/notabug comment wins86            for comment in reversed(comments):87                user = comment['user']['login']88                body = comment['body'].lower()89                if 'realbug' in body:90                    realbug_taggers[user] += 191                    break92                elif 'notabug' in body:93                    notabug_taggers[user] += 194                    if close_issue(issue, github_auth):95                        print "closed issue %s (%s)" % (issue['number'], user)96                    else:97                        print "error closing issue %s (%s)" % (issue['number'],98                                user)99                    break100        elif issue_created < close_before:101            if post_issue_comment(issue, AUTOCLOSE_MESSAGE, github_auth):102                print "added comment to old issue %s" % issue['number']103            else:104                print "error adding comment to old issue %s" % issue['number']105            if close_issue(issue, github_auth):106                print "closed old issue %s" % issue['number']107            else:108                print "error closing old issue %s" % issue['number']109    return notabug_taggers, realbug_taggers110if __name__ == '__main__':111    close_before = datetime.datetime.today() - datetime.timedelta(days=8)112    print113    print "This script will close all issues opened by KhanBugz"114    print "with 'notabug' (case-insensitive) in a comment or opened"115    print "before", close_before.date(), "with no comments."116    print117    default_user = "KhanBugz"118    github_user = (raw_input("GitHub username [%s]: " % default_user)119            or default_user)...CloseIssue_tests.py
Source:CloseIssue_tests.py  
1import unittest2from mock import Mock, patch3from jira.exceptions import JIRAError4from icinga2jira import CloseIssue, CantCloseTicketException5ANY_ISSUE = {'id': 'any id'}6ANY_TRANSITIONS = [{'name': 'Close', 'id': 45},7                   {'name': 'Start Work', 'id': 11},8]9def create_issue_mock(key):10    issue = Mock()11    issue.key.return_value = key12    return issue13class TestCloseIssue(unittest.TestCase):14    def setUp(self):15        self.jira_mock = Mock()16        self.ticket = Mock()17        self.icinga_environment = Mock()18        self.icinga_environment.get_jira_recovery_label.return_value = 'ICI#123'19        self.close_issue = CloseIssue(self.jira_mock, self.icinga_environment)20        self.print_patcher = patch('__builtin__.print')21        self.print_patcher.start()22    def tearDown(self):23        self.print_patcher.stop()24    def test_find_jira_issue_by_label(self):25        self.jira_mock.search_issues.return_value = 'found issue'26        result = self.close_issue._find_jira_issues_by_label()27        self.assertEqual('found issue', result)28        self.ticket.get_jira_recovery_label.assert_called()29        self.jira_mock.search_issues.assert_called_with("labels='ICI#123'")30    def test_set_comment(self):31        with patch.object(CloseIssue, 'create_description', return_value='comment') as create_mock:32            close_issue = CloseIssue(self.jira_mock, self.icinga_environment)33            close_issue._set_comment(ANY_ISSUE)34            create_mock.create_description.assert_called()35            self.jira_mock.add_comment.assert_called_with(ANY_ISSUE, 'comment')36    def test_get_close_transition_returns_id_of_close_transition_in_issue(self):37        self.jira_mock.transitions.return_value = ANY_TRANSITIONS38        actual_transition_id = self.close_issue._get_close_transition({'id': 'any id'})39        self.assertEqual(45, actual_transition_id)40    def test_get_close_transition_with_unicode(self):41        self.jira_mock.transitions.return_value = ANY_TRANSITIONS42        actual_transition_id = self.close_issue._get_close_transition({'id': 'any id'})43        self.assertEqual(45, actual_transition_id)44    def test_get_close_transition_raises_exception_when_no_close_transition_has_been_found(self):45        transitions = [{'name': 'Start Work', 'id': 11}]46        self.jira_mock.transitions.return_value = transitions47        self.assertRaises(CantCloseTicketException,48                          self.close_issue._get_close_transition,49                          ANY_ISSUE)50    def test_get_close_transition_raises_exception_when_no_transitions_have_been_found(self):51        self.jira_mock.transitions.return_value = []52        self.assertRaises(CantCloseTicketException,53                          self.close_issue._get_close_transition,54                          ANY_ISSUE)55    def test_close_happy_trail(self):56        transitions = [{'name': 'Close', 'id': 45}]57        self.jira_mock.transitions.return_value = transitions58        self.close_issue._close(ANY_ISSUE)59        self.jira_mock.transition_issue.assert_called_with(ANY_ISSUE, 45)60    def test_close_on_already_closed_ticket_raises_exception(self):61        self.jira_mock.transitions.return_value = []62        self.assertRaises(CantCloseTicketException, self.close_issue._close, ANY_ISSUE)63    def test_close_reraises_exception_if_jira_fails(self):64        self.jira_mock.transitions.return_value = ANY_TRANSITIONS65        self.jira_mock.transition_issue.side_effect = JIRAError66        self.assertRaises(CantCloseTicketException,67                          self.close_issue._close, ANY_ISSUE)68    def test_execute_is_called_properly_and_returns_list_of_handled_issues(self):69        find_mock = Mock(return_value=['issue1', 'issue2'])70        close_mock = Mock()71        comment_mock = Mock()72        with patch.multiple(CloseIssue,73                            _find_jira_issues_by_label=find_mock,74                            _close=close_mock,75                            _set_comment=comment_mock76        ) as values:77            close_issue = CloseIssue(self.jira_mock, self.icinga_environment)78            result = close_issue.execute()79            self.assertEqual(find_mock.call_count, 1)80            self.assertEqual(close_mock.call_count, 2)81            comment_mock.assert_called_twice_with(comment_str='comment')82            self.assertEqual(['issue1', 'issue2'], result)83    def test_execute_skips_issues_causing_CantCloseTicketException(self):84        find_mock = Mock(return_value=[create_issue_mock('a'), create_issue_mock('b')])85        close_mock = Mock(side_effect=CantCloseTicketException())86        comment_mock = Mock()87        with patch.multiple(CloseIssue,88                            _find_jira_issues_by_label=find_mock,89                            _close=close_mock,90                            _set_comment=comment_mock91        ) as values:92            close_issue = CloseIssue(self.jira_mock, self.icinga_environment)93            result = close_issue.execute()94            self.assertEqual(find_mock.call_count, 1)95            self.assertEqual(close_mock.call_count, 2)96            comment_mock.assert_not_called()...main.py
Source:main.py  
...11    def open_issue(self, channel_id):12        if self.assign_users.get(channel_id) is not None:13            raise ValueError("Already opened.")14        self.assign_users[channel_id] = []15    def close_issue(self, channel_id):16        if self.assign_users.get(channel_id) is None:17            raise ValueError("not opened.")18        del self.assign_users[channel_id]19    def assign(self, channel_id, user_id):20        if self.assign_users.get(channel_id) is None:21            raise ValueError("not opened.", 0)22        elif user_id in self.assign_users[channel_id]:23            raise ValueError("already assigned.", 1)24        if len(self.assign_users[channel_id]) >= 2:25            raise DeprecationWarning("three or more users have been assigned to the issue.")26        self.assign_users[channel_id].append(user_id)27bot = AssignBot(command_prefix="a.", description="ãã£ã³ãã«ã«issueãéãããã®issueã«assignã§ãã¾ãã\n3人以ä¸ãassignãããã¨ããã¨è¦åã表示ãã¾ãã")28@bot.command(name="open")29async def _open(ctx):30    """issueãéãã¾ãã"""31    try:32        bot.open_issue(ctx.channel.id)33    except ValueError:34        return await ctx.send("ãã§ã«ãªã¼ãã³ããã¦ãã¾ãã", delete_after=5)35    await ctx.message.add_reaction("\U0001f44d")36@bot.command()37async def assign(ctx):38    """éããã¦ããissueã«assignãã¾ãã"""39    try:40        bot.assign(ctx.channel.id, ctx.author.id)41    except ValueError as e:42        if e.args[1] == 0:43            return await ctx.send("issueããªã¼ãã³ããã¦ãã¾ããã", delete_after=5)44        elif e.args[1] == 1:45            return await ctx.send("ãã§ã«assignãã¦ãã¾ãã")46    except DeprecationWarning:47        return await ctx.send("ãã§ã«2人assignãã¦ãããããassignã§ãã¾ããã§ããã", delete_after=5)48    await ctx.message.add_reaction("\U0001f44d")49@bot.command()50async def close(ctx):51    """issueãcloseãã¾ãã"""52    try:53        bot.close_issue(ctx.channel.id)54    except ValueError:55        return await ctx.send("issueããªã¼ãã³ããã¦ãã¾ããã", delete_after=5)56    await ctx.message.add_reaction("\U0001f44d")57if __name__ == "__main__":...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
