Example #1
0
    def test_building(self, patched_job_name, patched_job_info, patched_build_info, get_jobs_patched, patched_time):
        get_jobs_patched.return_value = [{'name': 'Job1', 'color': 'blue'}]
        JenkinsCli(self.args).building(self.args)
        self.assertFalse(patched_job_info.called)
        self.assertFalse(patched_build_info.called)
        self.patched_print.assert_called_once_with("Nothing is being built now")
        self.patched_print.reset_mock()

        get_jobs_patched.return_value = [{'name': 'Job1', 'color': 'blue_anime'},
                                         {'name': 'Job5', 'color': 'red_anime'}]
        patched_job_info.return_value = {'lastBuild': {}}
        JenkinsCli(self.args).building(self.args)
        self.assertFalse(patched_build_info.called)
        self.patched_print.assert_has_calls([mock.call("Job1 estimated time left unknown")],
                                            [mock.call("Job5 estimated time left unknown")])
        self.patched_print.reset_mock()

        patched_job_info.return_value = {'lastBuild': {'number': 2}}

        def info_side_effect(name, number):
            return {'timestamp': TS * 1000, 'estimatedDuration': 0, 'fullDisplayName': 'FDN ' + name}

        patched_build_info.side_effect = info_side_effect
        JenkinsCli(self.args).building(self.args)
        self.patched_print.assert_has_calls([mock.call("FDN Job1 estimated time left %s" % timedelta(seconds=TS))],
                                            [mock.call("FDN Job5 estimated time left %s" % timedelta(seconds=TS))])
Example #2
0
    def test_setbranch(self, patched_get_job_name, patched_get_job_config,
                       patched_reconfig_job):
        patched_get_job_config.return_value = EMPTY_SCM_XML
        self.args.job_name = 'Job1'
        self.args.branch_name = 'b1'
        JenkinsCli(self.args).setbranch(self.args)
        self.assertFalse(patched_reconfig_job.called)
        self.patched_print.assert_called_once_with("Cannot set branch name")
        self.patched_print.reset_mock()

        patched_get_job_config.return_value = GIT_SCM_XML
        JenkinsCli(self.args).setbranch(self.args)
        self.assertEqual(patched_reconfig_job.call_args[0][0], 'Job1')
        self.assertIn('b1', str(patched_reconfig_job.call_args[0][1]))
        self.assertNotIn('cli-tests', patched_reconfig_job.call_args[1])
        self.patched_print.assert_called_once_with("Done")
        patched_reconfig_job.reset_mock()
        self.patched_print.reset_mock()

        patched_get_job_config.return_value = HG_SCM_XML
        JenkinsCli(self.args).setbranch(self.args)
        self.assertEqual(patched_reconfig_job.call_args[0][0], 'Job1')
        self.assertIn('b1', str(patched_reconfig_job.call_args[0][1]))
        self.assertNotIn('v123', patched_reconfig_job.call_args[1])
        self.patched_print.assert_called_once_with("Done")
        patched_reconfig_job.reset_mock()
        self.patched_print.reset_mock()
Example #3
0
    def test_read_settings_from_file(self):
        current_folder = os.getcwd()
        local_folder_filename = os.path.join(current_folder, JenkinsCli.SETTINGS_FILE_NAME)
        home_folder_filename = os.path.join(os.path.expanduser("~"), JenkinsCli.SETTINGS_FILE_NAME)
        self.assertFalse(os.path.exists(local_folder_filename))
        self.assertFalse(os.path.exists(home_folder_filename))

        self.fs.CreateFile(home_folder_filename,
                           contents=self.HOME_FILE_CONTENT)
        self.assertTrue(os.path.exists(home_folder_filename))
        settings_dict = JenkinsCli.read_settings_from_file()
        self.assertEqual(settings_dict,
                         {"host": 'https://jenkins.host.com',
                          "username": "******",
                          "some weird settings": "value = value"
                          })

        self.fs.CreateFile(local_folder_filename,
                           contents=self.LOCAL_FILE_CONTENT)
        self.assertTrue(os.path.exists(local_folder_filename))
        settings_dict = JenkinsCli.read_settings_from_file()
        self.assertEqual(settings_dict,
                         {"host": 'http://jenkins.localhosthost.ua',
                          "username": "******",
                          "password": "******",
                          "other_setting": "some_value"
                          })
Example #4
0
    def test_info(self, patched_get_job_name, patched_get_job_info, patched_get_job_config):
        self.args.job_name = "Job1"
        patched_get_job_info.return_value = {}
        patched_get_job_config.return_value = EMPTY_SCM_XML
        JenkinsCli(self.args).info(self.args)
        arg = JenkinsCli.INFO_TEMPLATE % ('Not Built', 'Not Built', 'Not Built', 'Not Built', 'No', 'UnknownVCS', 'Unknown branch')
        self.patched_print.assert_called_once_with(arg)
        self.patched_print.reset_mock()

        job_info = {'lastBuild': {'fullDisplayName': 'FDN (cur)',
                                  'result': 'Done',
                                  'timestamp': TS * 1000,
                                  'building': True},
                    'lastSuccessfulBuild': {'fullDisplayName': 'FDN (last)'}}
        patched_get_job_info.return_value = job_info
        patched_get_job_config.return_value = GIT_SCM_XML
        JenkinsCli(self.args).info(self.args)
        arg = JenkinsCli.INFO_TEMPLATE % ('FDN (cur)', 'Done', 'FDN (last)', datetime.fromtimestamp(TS), 'Yes', 'Git', 'cli-tests')
        self.patched_print.assert_called_once_with(arg)
        self.patched_print.reset_mock()

        job_info['building'] = False
        patched_get_job_info.return_value = job_info
        patched_get_job_config.return_value = HG_SCM_XML
        JenkinsCli(self.args).info(self.args)
        arg = JenkinsCli.INFO_TEMPLATE % ('FDN (cur)', 'Done', 'FDN (last)', datetime.fromtimestamp(TS), 'Yes', 'Mercurial', 'v123')
        self.patched_print.assert_called_once_with(arg)
Example #5
0
    def test_read_settings_from_file(self):
        current_folder = os.getcwd()
        local_folder_filename = os.path.join(current_folder,
                                             JenkinsCli.SETTINGS_FILE_NAME)
        home_folder_filename = os.path.join(os.path.expanduser("~"),
                                            JenkinsCli.SETTINGS_FILE_NAME)
        self.assertFalse(os.path.exists(local_folder_filename))
        self.assertFalse(os.path.exists(home_folder_filename))

        self.fs.CreateFile(home_folder_filename,
                           contents=self.HOME_FILE_CONTENT)
        self.assertTrue(os.path.exists(home_folder_filename))
        settings_dict = JenkinsCli.read_settings_from_file()
        self.assertEqual(
            settings_dict, {
                "host": 'https://jenkins.host.com',
                "username": "******",
                "some weird settings": "value = value"
            })

        self.fs.CreateFile(local_folder_filename,
                           contents=self.LOCAL_FILE_CONTENT)
        self.assertTrue(os.path.exists(local_folder_filename))
        settings_dict = JenkinsCli.read_settings_from_file()
        self.assertEqual(
            settings_dict, {
                "host": 'http://jenkins.localhosthost.ua',
                "username": "******",
                "password": "******",
                "other_setting": "some_value"
            })
Example #6
0
    def test_check_job(self, patched_get_job_name):
        patched_get_job_name.return_value = None
        exep = None
        try:
            JenkinsCli(self.args)._check_job('Job1')
        except Exception as e:
            exep = e
        self.assertEqual(type(exep), CliException)

        patched_get_job_name.return_value = 'Job1'
        job_name = JenkinsCli(self.args)._check_job('Job1')
        self.assertEqual(job_name, 'Job1')
Example #7
0
    def test_stop(self, patched_job_name, patched_job_info, patched_stop_build):
        self.args.job_name = 'Job1'
        patched_job_info.return_value = {'lastBuild': {}}
        JenkinsCli(self.args).stop(self.args)
        self.assertFalse(patched_stop_build.called)
        self.patched_print.assert_called_once_with("%s job is not running" % 'Job1')
        self.patched_print.reset_mock()

        patched_job_info.return_value = {'lastBuild': {'building': True, 'number': 22}}
        JenkinsCli(self.args).stop(self.args)
        patched_stop_build.assert_called_once_with('Job1', 22)
        self.patched_print.assert_called_once_with("Job1: stopped")
Example #8
0
    def test_get_scm_name_and_node(self):
        root = ElementTree.fromstring(GIT_SCM_XML.encode('utf-8'))
        name, branch_node = JenkinsCli(self.args)._get_scm_name_and_node(root)
        self.assertEqual(name, 'Git')
        self.assertEqual(branch_node.text, 'cli-tests')

        root = ElementTree.fromstring(HG_SCM_XML.encode('utf-8'))
        name, branch_node = JenkinsCli(self.args)._get_scm_name_and_node(root)
        self.assertEqual(name, 'Mercurial')
        self.assertEqual(branch_node.text, 'v123')

        root = ElementTree.fromstring(EMPTY_SCM_XML.encode('utf-8'))
        name, branch_node = JenkinsCli(self.args)._get_scm_name_and_node(root)
        self.assertEqual(name, 'UnknownVCS')
        self.assertEqual(branch_node, None)
Example #9
0
 def test_jobs(self, patched_get_jobs):
     jobs = [{'name': 'Job1',
              'color': 'blue'},
             {'name': 'Job2',
              'color': 'disabled'}]
     patched_get_jobs.return_value = jobs
     self.args.a = False
     JenkinsCli(self.args).jobs(self.args)
     arg1 = "%sS..%s Job1" % (STATUSES_COLOR[jobs[0]['color']]['color'], ENDCOLLOR)
     arg2 = "%sD..%s Job2" % (STATUSES_COLOR[jobs[1]['color']]['color'], ENDCOLLOR)
     self.patched_print.assert_has_calls([mock.call(arg1)], [mock.call(arg2)])
     self.patched_print.reset_mock()
     self.args.a = True
     JenkinsCli(self.args).jobs(self.args)
     self.patched_print.assert_called_once_with(arg1)
Example #10
0
 def test_queue(self, patched_get_queue_info):
     queue_list = [{
         u'task': {
             u'url': u'http://your_url/job/my_job/',
             u'color': u'aborted_anime',
             u'name': u'my_job'
         },
         u'stuck':
         False,
         u'actions': [{
             u'causes': [{
                 u'shortDescription': u'Started by timer'
             }]
         }],
         u'why':
         u'Build #2,532 is already in progress (ETA:10 min)'
     }, {
         u'task': {
             u'url': u'http://your_url/job/my_job/',
             u'color': u'aborted_anime',
             u'name': u'my_job2'
         },
         u'stuck':
         False,
         u'actions': [{
             u'causes': [{
                 u'shortDescription': u'Started by timer'
             }]
         }],
         u'why':
         u'Build #234 is already in progress (ETA:10 min)'
     }]
     patched_get_queue_info.return_value = []
     JenkinsCli(self.args).queue(self.args)
     self.patched_print.assert_called_once_with(JenkinsCli.QUEUE_EMPTY_TEXT)
     patched_get_queue_info.reset_mock()
     patched_get_queue_info.return_value = queue_list
     JenkinsCli(self.args).queue(self.args)
     args = [
         "%s %s" % (job['task']['name'], job['why']) for job in queue_list
     ]
     self.patched_print.assert_has_calls([mock.call(args[0])],
                                         [mock.call(args[1])])
Example #11
0
    def test_auth_has_file_settings(self, patched_init,
                                    read_settings_from_file):
        read_settings_from_file.return_value = {'username': '******'}
        exep = None
        try:
            JenkinsCli.auth()
        except Exception as e:
            exep = e
        self.assertEqual(type(exep), CliException)
        self.assertEqual(patched_init.called, False)

        host_from_file = 'http://low.priority.com'
        username = '******'
        password = '******'
        read_settings_from_file.return_value = {
            'host': host_from_file,
            'username': username,
            'password': password
        }
        JenkinsCli.auth()
        patched_init.assert_called_once_with(host_from_file, username,
                                             password,
                                             socket._GLOBAL_DEFAULT_TIMEOUT)
        patched_init.reset_mock()

        host = 'http://localhost:5055'
        JenkinsCli.auth(host=host)
        patched_init.assert_called_once_with(host, username, password,
                                             socket._GLOBAL_DEFAULT_TIMEOUT)
        patched_init.reset_mock()
Example #12
0
def main():
    parser = load_parser()
    args = parser.parse_args()

    try:
        if args.jenkins_command is None:
            parser.print_help()
        else:
            JenkinsCli(args).run_command(args)
    except JenkinsException as e:
        print("Jenkins server response: %s:" % e)
    except KeyboardInterrupt:
        print("Aborted")
    except CliException as e:
        print(e)
        print("Read jenkins --help")
Example #13
0
    def test_read_settings_from_file_alt_environment(self):
        # make sure we are in the fake fs
        current_folder = os.getcwd()
        local_folder_filename = os.path.join(current_folder, JenkinsCli.SETTINGS_FILE_NAME)
        self.assertFalse(os.path.exists(local_folder_filename))

        # create the fake config file
        self.fs.CreateFile(local_folder_filename,
                           contents=self.MULTIENV_FILE_CONTENT)
        self.assertTrue(os.path.exists(local_folder_filename))

        # read the config from the file
        settings_dict = JenkinsCli.read_settings_from_file(environment='alternative')

        # test and that the alternative environment is used, with the missing
        #   values being provided from the DEFAULT environmtne
        self.assertEqual(settings_dict,
                         {"host": 'http://jenkins.localhosthost.ua',
                          "username": "******",
                          "password": "******",
                          "other_setting": "some_value",
                          'some default settings': 'value = value'
                          })
Example #14
0
    def test_auth_no_file_settings(self, patched_init, read_settings_from_file):
        exep = None
        try:
            JenkinsCli.auth()
        except Exception as e:
            exep = e
        self.assertEqual(type(exep), CliException)
        self.assertEqual(patched_init.called, False)

        host = 'http://localhost:5055'
        JenkinsCli.auth(host=host)
        patched_init.assert_called_once_with(host, None, None, socket._GLOBAL_DEFAULT_TIMEOUT)
        patched_init.reset_mock()

        username = '******'
        password = '******'
        JenkinsCli.auth(host=host, username=username, password=password)
        patched_init.assert_called_once_with(host, username, password, socket._GLOBAL_DEFAULT_TIMEOUT)
Example #15
0
    def test_auth_no_file_settings(self, patched_init, read_settings_from_file):
        exep = None
        try:
            JenkinsCli.auth()
        except Exception as e:
            exep = e
        self.assertEqual(type(exep), CliException)
        self.assertEqual(patched_init.called, False)

        host = 'http://localhost:5055'
        JenkinsCli.auth(host=host)
        patched_init.assert_called_once_with(host, None, None, socket._GLOBAL_DEFAULT_TIMEOUT)
        patched_init.reset_mock()

        username = '******'
        password = '******'
        JenkinsCli.auth(host=host, username=username, password=password)
        patched_init.assert_called_once_with(host, username, password, socket._GLOBAL_DEFAULT_TIMEOUT)
Example #16
0
    def test_auth_has_file_settings(self, patched_init, read_settings_from_file):
        read_settings_from_file.return_value = {'username': '******'}
        exep = None
        try:
            JenkinsCli.auth()
        except Exception as e:
            exep = e
        self.assertEqual(type(exep), CliException)
        self.assertEqual(patched_init.called, False)

        host_from_file = 'http://low.priority.com'
        username = '******'
        password = '******'
        read_settings_from_file.return_value = {'host': host_from_file, 'username': username, 'password': password}
        JenkinsCli.auth()
        patched_init.assert_called_once_with(host_from_file, username, password, socket._GLOBAL_DEFAULT_TIMEOUT)
        patched_init.reset_mock()

        host = 'http://localhost:5055'
        JenkinsCli.auth(host=host)
        patched_init.assert_called_once_with(host, username, password, socket._GLOBAL_DEFAULT_TIMEOUT)
        patched_init.reset_mock()
Example #17
0
def main():
    parser = argparse.ArgumentParser(
        prog='jenkins',
        description=
        'Host, username and password may be specified either by the command line arguments '
        'or in the configuration file (.jenkins-cli). Command line arguments have the highest priority, '
        'after that the .jenkins-cli file from current folder is used. If there is no'
        '.jenkins-cli file in the current folder, settings will be read from .jenkins-cli located in the home'
        'folder')
    parser.add_argument('--host',
                        metavar='jenkins-url',
                        help='Jenkins Host',
                        default=None)
    parser.add_argument('--username',
                        metavar='username',
                        help='Jenkins Username',
                        default=None)
    parser.add_argument('--password',
                        metavar='password',
                        help='Jenkins Password',
                        default=None)
    parser.add_argument('--version',
                        '-v',
                        action='version',
                        version='jenkins-cli %s' % version)

    subparsers = parser.add_subparsers(title='Available commands',
                                       dest='jenkins_command')

    jobs_parser = subparsers.add_parser(
        'jobs',
        help='Show all jobs and their statuses',
        formatter_class=argparse.RawTextHelpFormatter,
        description="Status description:\n\n" + "\n".join(get_jobs_legend()))
    jobs_parser.add_argument('-a',
                             help='show only active jobs',
                             default=False,
                             action='store_true')
    jobs_parser.add_argument('-p',
                             help='show only jobs in build progress',
                             default=False,
                             action='store_true')

    subparsers.add_parser('queue', help='Show builds queue')

    subparsers.add_parser('building', help='Build executor status')

    builds_parser = subparsers.add_parser('builds',
                                          help='Show builds for the job')
    builds_parser.add_argument('job_name', help='Job name of the builds')

    start_parser = subparsers.add_parser('start', help='Start job')
    start_parser.add_argument('job_name', help='Job to start', nargs='*')

    start_parser = subparsers.add_parser('info', help='Job info')
    start_parser.add_argument('job_name', help='Job to get info for')

    set_branch = subparsers.add_parser(
        'setbranch', help='Set VCS branch (Mercurial or Git)')
    set_branch.add_argument('job_name', help='Job to set branch for')
    set_branch.add_argument('branch_name', help='Name of the VCS branch')

    stop_parser = subparsers.add_parser('stop', help='Stop job')
    stop_parser.add_argument('job_name', help='Job to stop')

    console_parser = subparsers.add_parser('console',
                                           help='Show console for the build')
    console_parser.add_argument('job_name', help='Job to show console for')
    console_parser.add_argument(
        '-b',
        '--build',
        help=
        'job build number to show console for (if omitted, last build number is used)',
        default='')
    console_parser.add_argument(
        '-n',
        help='show first n lines only(if n is negative, show last n lines)',
        type=int)
    console_parser.add_argument('-i',
                                help='interactive console',
                                default=False,
                                action='store_true')

    console_parser = subparsers.add_parser('changes',
                                           help="Show build's changes")
    console_parser.add_argument('job_name', help='Job to show changes for')
    console_parser.add_argument(
        '-b',
        '--build',
        help=
        'job build number to show changes for (if omitted, last build number is used)',
        default='')

    args = parser.parse_args()
    try:
        if args.jenkins_command is None:
            parser.print_help()
        else:
            JenkinsCli(args).run_command(args)
    except JenkinsException as e:
        print("Jenkins server response: %s:" % e)
    except KeyboardInterrupt:
        print("Aborted")
    except CliException as e:
        print(e)
        print("Read jenkins --help")
Example #18
0
 def test_start(self, patched_job_name, patched_build_job):
     self.args.job_name = ['Job1']
     JenkinsCli(self.args).start(self.args)
     patched_build_job.assert_called_once_with('Job1')
     self.patched_print.assert_called_once_with("%s: %s" %
                                                ('Job1', 'started'))