def test_update_jobs_and_delete_old(self, builder_mock, delete_job_mock, get_jobs_mock, is_job_mock): """ Test update behaviour with --delete-old option Test update of jobs with the --delete-old option enabled, where only some jobs result in has_changed() to limit the number of times update_job is called, and have the get_jobs() method return additional jobs not in the input yaml to test that the code in cmd will call delete_job() after update_job() when '--delete-old' is set but only for the extra jobs. """ # set up some test data jobs = ['old_job001', 'old_job002'] extra_jobs = [{'name': name} for name in jobs] builder_obj = builder.Builder('http://jenkins.example.com', 'doesnot', 'matter', plugins_list={}) # get the instance created by mock and redirect some of the method # mocks to call real methods on a the above test object. b_inst = builder_mock.return_value b_inst.plugins_list = builder_obj.plugins_list b_inst.update_job.side_effect = builder_obj.update_job b_inst.delete_old_managed.side_effect = builder_obj.delete_old_managed def _get_jobs(): return builder_obj.parser.jobs + extra_jobs get_jobs_mock.side_effect = _get_jobs # override cache to ensure Jenkins.update_job called a limited number # of times self.cache_mock.return_value.has_changed.side_effect = ([True] * 2 + [False] * 2) path = os.path.join(self.fixtures_path, 'cmd-002.yaml') args = self.parser.parse_args(['update', '--delete-old', path]) with mock.patch('jenkins_jobs.builder.Jenkins.update_job') as update: with mock.patch('jenkins_jobs.builder.Jenkins.is_managed', return_value=True): cmd.execute(args, self.config) self.assertEquals( 2, update.call_count, "Expected Jenkins.update_job to be called '%d' " "times, got '%d' calls instead.\n" "Called with: %s" % (2, update.call_count, update.mock_calls)) calls = [mock.call(name) for name in jobs] self.assertEquals( 2, delete_job_mock.call_count, "Expected Jenkins.delete_job to be called '%d' " "times got '%d' calls instead.\n" "Called with: %s" % (2, delete_job_mock.call_count, delete_job_mock.mock_calls)) delete_job_mock.assert_has_calls(calls, any_order=True)
def test_cache_file(self): """ Test providing a cachefile. """ test_file = os.path.abspath(__file__) with mock.patch('os.path.join', return_value=test_file): with mock.patch('yaml.load'): jenkins_jobs.builder.JobCache("dummy").data = None
def test_save_on_exit(self): """ Test that the cache is saved on normal object deletion """ with mock.patch('jenkins_jobs.builder.JobCache.save') as save_mock: with mock.patch('os.path.isfile', return_value=False): jenkins_jobs.builder.JobCache("dummy") save_mock.assert_called_with()
def test_update_jobs_and_delete_old(self, builder_mock, delete_job_mock, get_jobs_mock, is_job_mock): """ Test update behaviour with --delete-old option Test update of jobs with the --delete-old option enabled, where only some jobs result in has_changed() to limit the number of times update_job is called, and have the get_jobs() method return additional jobs not in the input yaml to test that the code in cmd will call delete_job() after update_job() when '--delete-old' is set but only for the extra jobs. """ # set up some test data jobs = ['old_job001', 'old_job002'] extra_jobs = [{'name': name} for name in jobs] builder_obj = builder.Builder('http://jenkins.example.com', 'doesnot', 'matter', plugins_list={}) # get the instance created by mock and redirect some of the method # mocks to call real methods on a the above test object. b_inst = builder_mock.return_value b_inst.plugins_list = builder_obj.plugins_list b_inst.update_jobs.side_effect = builder_obj.update_jobs b_inst.delete_old_managed.side_effect = builder_obj.delete_old_managed def _get_jobs(): return builder_obj.parser.jobs + extra_jobs get_jobs_mock.side_effect = _get_jobs # override cache to ensure Jenkins.update_job called a limited number # of times self.cache_mock.return_value.has_changed.side_effect = ( [True] * 2 + [False] * 2) path = os.path.join(self.fixtures_path, 'cmd-002.yaml') args = ['--conf', self.default_config_file, 'update', '--delete-old', path] with mock.patch('jenkins_jobs.builder.Jenkins.update_job') as update: with mock.patch('jenkins_jobs.builder.Jenkins.is_managed', return_value=True): self.execute_jenkins_jobs_with_args(args) self.assertEquals(2, update.call_count, "Expected Jenkins.update_job to be called '%d' " "times, got '%d' calls instead.\n" "Called with: %s" % (2, update.call_count, update.mock_calls)) calls = [mock.call(name) for name in jobs] self.assertEqual(2, delete_job_mock.call_count, "Expected Jenkins.delete_job to be called '%d' " "times got '%d' calls instead.\n" "Called with: %s" % (2, delete_job_mock.call_count, delete_job_mock.mock_calls)) delete_job_mock.assert_has_calls(calls, any_order=True)
def test_delete_all_accept(self, delete_job_mock): """ Test handling the deletion of a single Jenkins job. """ args = ['--conf', self.default_config_file, 'delete-all'] with mock.patch('jenkins_jobs.builder.JenkinsManager.get_views', return_value=[None]): with mock.patch('jenkins_jobs.utils.input', return_value="y"): self.execute_jenkins_jobs_with_args(args)
def test_socket_connect_with_ssl_verify_false(self): with mock.patch('pylogbeat.socket.socket') as socket_mock: with mock.patch('pylogbeat.ssl') as ssl_mock: client = self._factor_client(ssl_enable=True, ssl_verify=False) client.connect() mocked_socket = socket_mock(socket.AF_INET, socket.SOCK_STREAM) ssl_mock.wrap_socket.assert_called_once_with( mocked_socket, keyfile=SSL_KEYFILE, certfile=SSL_CERTFILE, ca_certs=SSL_CACERTS, cert_reqs=ssl_mock.CERT_OPTIONAL)
def test_stream_input_output_no_encoding_exceed_recursion(self): """ Test that we don't have issues processing large number of jobs and outputting the result if the encoding is not set. """ console_out = io.BytesIO() input_file = os.path.join(self.fixtures_path, "large-number-of-jobs-001.yaml") with io.open(input_file, "r") as f: with mock.patch("sys.stdout", console_out): console_out.encoding = None with mock.patch("sys.stdin", f): args = ["test"] self.execute_jenkins_jobs_with_args(args)
def test_stream_output_ascii_encoding_invalid_char(self): """ Run test mode simulating using pipes for input and output using ascii encoding for output with include containing a character that cannot be converted. """ console_out = io.BytesIO() console_out.encoding = 'ascii' input_file = os.path.join(self.fixtures_path, 'unicode001.yaml') with io.open(input_file, 'r', encoding='utf-8') as f: with mock.patch('sys.stdout', console_out): with mock.patch('sys.stdin', f): e = self.assertRaises(UnicodeError, cmd.main, ['test']) self.assertIn("'ascii' codec can't encode character", str(e))
def test_stream_input_output_no_encoding_exceed_recursion(self): """ Test that we don't have issues processing large number of jobs and outputting the result if the encoding is not set. """ console_out = io.BytesIO() input_file = os.path.join(self.fixtures_path, 'large-number-of-jobs-001.yaml') with io.open(input_file, 'r') as f: with mock.patch('sys.stdout', console_out): console_out.encoding = None with mock.patch('sys.stdin', f): args = ['test'] self.execute_jenkins_jobs_with_args(args)
def test_console_output_jenkins_connection_failure_warning( self, get_plugins_mock): """ Run test mode and verify that failed Jenkins connection attempt exception does not bubble out of cmd.main. Ideally, we would also test that an appropriate message is logged to stderr but it's somewhat difficult to figure out how to actually enable stderr in this test suite. """ get_plugins_mock.side_effect = jenkins.JenkinsException( "Connection refused") with mock.patch("sys.stdout"): try: args = [ "--conf", self.default_config_file, "test", os.path.join(self.fixtures_path, "cmd-001.yaml"), ] self.execute_jenkins_jobs_with_args(args) except jenkins.JenkinsException: self.fail("jenkins.JenkinsException propagated to main") except Exception: pass # only care about jenkins.JenkinsException for now
def test_send_failure_wrong_ack_frame_type(self): with mock.patch.object(pylogbeat, 'LOGGER', new=self._mocked_logger): with mock.patch('pylogbeat.socket.socket'): client = self._factor_client() client.connect() # mock socket.recv(): version(2), frame type(A), ACK(2) window_size_packed = [b'2', b'X', b'\x00\x00\x00\x02'] client._socket.recv.side_effect = window_size_packed with self.assertRaises(pylogbeat.ConnectionException): client.send([MESSAGE, MESSAGE]) client._socket.connect.assert_called_once_with((SOCKET_HOST, SOCKET_PORT)) client._socket.settimeout.assert_called_once_with(SOCKET_TIMEOUT) # window size (replace frame type by 'W') window_size_packed[1] = b'W' client._socket.send.assert_any_call(b''.join(window_size_packed)) # logger self._mocked_logger.log.assert_any_call(logging.DEBUG, 'Sent window size: 2') self._mocked_logger.log.assert_any_call( logging.WARNING, 'Waited for ACK from server but received an ' 'unexpected frame: "0x58". Aborting.') self._mocked_logger.reset_mock()
def test_socket_connect_no_ssl_no_timeout(self): with mock.patch('pylogbeat.socket.socket'): client = self._factor_client(ssl_enable=False, timeout=None) client.connect() client._socket.connect.assert_called_once_with((SOCKET_HOST, SOCKET_PORT)) client._socket.settimeout.assert_not_called()
def test_stream_input_output_utf8_encoding(self): """ Run test mode simulating using pipes for input and output using utf-8 encoding """ console_out = io.BytesIO() input_file = os.path.join(self.fixtures_path, 'cmd-001.yaml') with io.open(input_file, 'r') as f: with mock.patch('sys.stdout', console_out): with mock.patch('sys.stdin', f): cmd.main(['test']) xml_content = io.open(os.path.join(self.fixtures_path, 'cmd-001.xml'), 'r', encoding='utf-8').read() value = console_out.getvalue().decode('utf-8') self.assertEqual(value, xml_content)
def test_stream_output_ascii_encoding_invalid_char(self): """ Run test mode simulating using pipes for input and output using ascii encoding for output with include containing a character that cannot be converted. """ console_out = io.BytesIO() console_out.encoding = 'ascii' input_file = os.path.join(self.fixtures_path, 'unicode001.yaml') with io.open(input_file, 'r', encoding='utf-8') as f: with mock.patch('sys.stdout', console_out): with mock.patch('sys.stdin', f): args = ['--conf', self.default_config_file, 'test'] jenkins_jobs = entry.JenkinsJobs(args) e = self.assertRaises(UnicodeError, jenkins_jobs.execute) self.assertIn("'ascii' codec can't encode character", str(e))
def test_delete_all_accept(self, delete_job_mock): """ Test handling the deletion of a single Jenkins job. """ args = ['--conf', self.default_config_file, 'delete-all'] with mock.patch('jenkins_jobs.utils.input', return_value="y"): self.execute_jenkins_jobs_with_args(args)
def test_stream_output_ascii_encoding_invalid_char(self): """ Run test mode simulating using pipes for input and output using ascii encoding for output with include containing a character that cannot be converted. """ console_out = io.BytesIO() console_out.encoding = "ascii" input_file = os.path.join(self.fixtures_path, "unicode001.yaml") with io.open(input_file, "r", encoding="utf-8") as f: with mock.patch("sys.stdout", console_out): with mock.patch("sys.stdin", f): args = ["--conf", self.default_config_file, "test"] jenkins_jobs = entry.JenkinsJobs(args) e = self.assertRaises(UnicodeError, jenkins_jobs.execute) self.assertIn("'ascii' codec can't encode character", str(e))
def test_skip_plugin_retrieval_if_no_config_provided(self, get_plugins_info_mock): """ Verify that retrieval of information from Jenkins instance about its plugins will be skipped when run if no config file provided. """ with mock.patch("sys.stdout"): cmd.main(["test", os.path.join(self.fixtures_path, "cmd-001.yaml")]) self.assertFalse(get_plugins_info_mock.called)
def test_delete_all_abort(self, delete_job_mock): """ Test handling the deletion of a single Jenkins job. """ args = ['--conf', self.default_config_file, 'delete-all'] with mock.patch('jenkins_jobs.utils.input', return_value="n"): self.assertRaises(SystemExit, self.execute_jenkins_jobs_with_args, args)
def test_stream_input_output_ascii_encoding(self): """ Run test mode simulating using pipes for input and output using ascii encoding with unicode input """ console_out = io.BytesIO() console_out.encoding = 'ascii' input_file = os.path.join(self.fixtures_path, 'cmd-001.yaml') with io.open(input_file, 'r') as f: with mock.patch('sys.stdout', console_out): with mock.patch('sys.stdin', f): args = ['--conf', self.default_config_file, 'test'] self.execute_jenkins_jobs_with_args(args) xml_content = io.open(os.path.join(self.fixtures_path, 'cmd-001.xml'), 'r', encoding='utf-8').read() value = console_out.getvalue().decode('ascii') self.assertEqual(value, xml_content)
def test_skip_plugin_retrieval_if_no_config_provided( self, get_plugins_info_mock): """ Verify that retrieval of information from Jenkins instance about its plugins will be skipped when run if no config file provided. """ with mock.patch('sys.stdout', new_callable=io.BytesIO): cmd.main(['test', os.path.join(self.fixtures_path, 'cmd-001.yaml')]) self.assertFalse(get_plugins_info_mock.called)
def test_stream_input_output_utf8_encoding(self): """ Run test mode simulating using pipes for input and output using utf-8 encoding """ console_out = io.BytesIO() input_file = os.path.join(self.fixtures_path, "cmd-001.yaml") with io.open(input_file, "r") as f: with mock.patch("sys.stdout", console_out): with mock.patch("sys.stdin", f): args = ["--conf", self.default_config_file, "test"] self.execute_jenkins_jobs_with_args(args) xml_content = io.open(os.path.join(self.fixtures_path, "cmd-001.xml"), "r", encoding="utf-8").read() value = console_out.getvalue().decode("utf-8") self.assertEqual(value, xml_content)
def test_console_output(self): """ Run test mode and verify that resulting XML gets sent to the console. """ console_out = io.BytesIO() with mock.patch("sys.stdout", console_out): cmd.main(["test", os.path.join(self.fixtures_path, "cmd-001.yaml")]) xml_content = codecs.open(os.path.join(self.fixtures_path, "cmd-001.xml"), "r", "utf-8").read() self.assertEqual(console_out.getvalue().decode("utf-8"), xml_content)
def test_list(self): path = os.path.join(self.fixtures_path, "cmd-002.yaml") console_out = io.BytesIO() with mock.patch("sys.stdout", console_out): self.execute_jenkins_jobs_with_args( ["--conf", self.default_config_file, "list", "-p", path] + self.globs) self.assertEqual(console_out.getvalue().decode("utf-8").rstrip(), ("\n".join(self.found)))
def test_list(self): path = os.path.join(self.fixtures_path, 'cmd-002.yaml') console_out = io.BytesIO() with mock.patch('sys.stdout', console_out): self.execute_jenkins_jobs_with_args( ['--conf', self.default_config_file, 'list', '-p', path] + self.globs) self.assertEqual(console_out.getvalue().decode('utf-8').rstrip(), ('\n'.join(self.found)))
def test_skip_plugin_retrieval_if_no_config_provided( self, get_plugins_mock): """ Verify that retrieval of information from Jenkins instance about its plugins will be skipped when run if no config file provided. """ with mock.patch('sys.stdout', new_callable=io.BytesIO): args = ['--conf', self.default_config_file, 'test', os.path.join(self.fixtures_path, 'cmd-001.yaml')] entry.JenkinsJobs(args) self.assertFalse(get_plugins_mock.called)
def test_valid_job(self): """ Run test mode and pass a valid job name """ args = ['--conf', self.default_config_file, 'test', os.path.join(self.fixtures_path, 'cmd-001.yaml'), 'foo-job'] console_out = io.BytesIO() with mock.patch('sys.stdout', console_out): self.execute_jenkins_jobs_with_args(args)
def test_console_output(self): """ Run test mode and verify that resulting XML gets sent to the console. """ console_out = io.BytesIO() with mock.patch('sys.stdout', console_out): cmd.main(['test', os.path.join(self.fixtures_path, 'cmd-001.yaml')]) xml_content = io.open(os.path.join(self.fixtures_path, 'cmd-001.xml'), 'r', encoding='utf-8').read() self.assertEqual(console_out.getvalue().decode('utf-8'), xml_content)
def test_socket_close(self): with mock.patch.object(pylogbeat, 'LOGGER', new=self._mocked_logger): with mock.patch('pylogbeat.socket.socket'): client = self._factor_client(ssl_enable=False) client.connect() client._socket.connect.assert_called_once_with((SOCKET_HOST, SOCKET_PORT)) # close existing socket client.close() self.assertIsNone(client._socket) # close already closed socket client.close() self.assertIsNone(client._socket)
def setUp(self): super(CmdTestsBase, self).setUp() # Testing the cmd module can sometimes result in the JobCache class # attempting to create the cache directory multiple times as the tests # are run in parallel. Stub out the JobCache to ensure that each # test can safely create the cache directory without risk of # interference. cache_patch = mock.patch("jenkins_jobs.builder.JobCache", autospec=True) self.cache_mock = cache_patch.start() self.addCleanup(cache_patch.stop) self.default_config_file = os.path.join(self.fixtures_path, "empty_builder.ini")
def test_parse_response(self): http_client = ElasticsearchRequestController(None, None, None, False, None) # simple text response_bytes_raw = mock.Mock() response_bytes_raw.read.return_value = b'test' # disable charset in response to force use of lstail.http.LOG_ENCODING response_bytes_raw.headers.get_charset.return_value = None response_bytes_raw.headers.get_content_charset.return_value = None decode_as_json = False result = http_client._parse_response(response_bytes_raw, decode_as_json) self.assertEqual(result, 'test') response_raw = mock.Mock() response_raw.headers.get_charset.return_value = None response_raw.headers.get_content_charset.return_value = None # None response with mock.patch('lstail.http.LOG_ENCODING', 'utf-8'): response_raw.read.return_value = None decode_as_json = True result = http_client._parse_response(response_raw, decode_as_json) self.assertEqual(result, None) # empty string response with mock.patch('lstail.http.LOG_ENCODING', 'utf-8'): response_raw.read.return_value = '' decode_as_json = True result = http_client._parse_response(response_raw, decode_as_json) self.assertEqual(result, '') # JSON, ISO encoding with mock.patch('lstail.http.LOG_ENCODING', 'iso-8859-15'): response_raw.read.return_value = '{ "foo": "bär" }'.encode( 'iso-8859-15') decode_as_json = True result = http_client._parse_response(response_raw, decode_as_json) self.assertEqual(result, dict(foo='bär'))
def test_console_output(self): """ Run test mode and verify that resulting XML gets sent to the console. """ console_out = io.BytesIO() with mock.patch('sys.stdout', console_out): args = ['--conf', self.default_config_file, 'test', os.path.join(self.fixtures_path, 'cmd-001.yaml')] self.execute_jenkins_jobs_with_args(args) xml_content = io.open(os.path.join(self.fixtures_path, 'cmd-001.xml'), 'r', encoding='utf-8').read() self.assertEqual(console_out.getvalue().decode('utf-8'), xml_content)
def test_skip_plugin_retrieval_if_disabled(self, get_plugins_info_mock): """ Verify that retrieval of information from Jenkins instance about its plugins will be skipped when run if a config file provided and disables querying through a config option. """ with mock.patch('sys.stdout', new_callable=io.BytesIO): cmd.main(['--conf', os.path.join(self.fixtures_path, 'disable-query-plugins.conf'), 'test', os.path.join(self.fixtures_path, 'cmd-001.yaml')]) self.assertFalse(get_plugins_info_mock.called)
def test_get_encoding_from_response(self): http_client = ElasticsearchRequestController(None, None, None, False, None) response_raw = mock.Mock() # headers.get_charset() returns something, so we expect something response_raw.headers.get_charset.return_value = 'foo-enc' result = http_client._get_encoding_from_response(response_raw) self.assertEqual(result, 'foo-enc') # headers.get_charset() returns None, so we fall back to headers.get_content_charset() response_raw.headers.get_charset.return_value = None response_raw.headers.get_content_charset.return_value = 'foo-content-enc' result = http_client._get_encoding_from_response(response_raw) self.assertEqual(result, 'foo-content-enc') # headers.get_charset() returns None and headers.get_content_charset() returns None, # so we expect LOG_ENCODING as fallback with mock.patch('lstail.http.LOG_ENCODING', 'some-fallback-enc'): response_raw.headers.get_charset.return_value = None response_raw.headers.get_content_charset.return_value = None result = http_client._get_encoding_from_response(response_raw) self.assertEqual(result, 'some-fallback-enc') # headers.get_charset() returns something and headers.get_content_charset() returns # something else so we expect something response_raw.headers.get_charset.return_value = 'some-enc' response_raw.headers.get_content_charset.return_value = 'some-content-enc' result = http_client._get_encoding_from_response(response_raw) self.assertEqual(result, 'some-enc') # headers.get_charset() returns None and headers.get_content_charset() returns # something so we expect something but not LOG_ENCODING with mock.patch('lstail.http.LOG_ENCODING', 'some-fallback-enc'): response_raw.headers.get_charset.return_value = None response_raw.headers.get_content_charset.return_value = 'some-content-enc' result = http_client._get_encoding_from_response(response_raw) self.assertEqual(result, 'some-content-enc')
def test_valid_job(self): """ Run test mode and pass a valid job name """ args = [ "--conf", self.default_config_file, "test", os.path.join(self.fixtures_path, "cmd-001.yaml"), "foo-job", ] console_out = io.BytesIO() with mock.patch("sys.stdout", console_out): self.execute_jenkins_jobs_with_args(args)
def test_list(self, get_jobs_mock): def _get_jobs(): return [{'name': name} for name in self.jobs] get_jobs_mock.side_effect = _get_jobs console_out = io.BytesIO() args = ['--conf', self.default_config_file, 'list'] + self.globs with mock.patch('sys.stdout', console_out): self.execute_jenkins_jobs_with_args(args) self.assertEqual(console_out.getvalue().decode('utf-8').rstrip(), ('\n'.join(self.found)))
def setUp(self): super(CmdTestsBase, self).setUp() # Testing the cmd module can sometimes result in the CacheStorage class # attempting to create the cache directory multiple times as the tests # are run in parallel. Stub out the CacheStorage to ensure that each # test can safely create the cache directory without risk of # interference. self.cache_patch = mock.patch('jenkins_jobs.builder.CacheStorage', autospec=True) self.cache_patch.start() self.config = configparser.ConfigParser() self.config.readfp(StringIO(cmd.DEFAULT_CONF))
def test_list(self, get_jobs_mock): def _get_jobs(): return [{"name": name} for name in self.jobs] get_jobs_mock.side_effect = _get_jobs console_out = io.BytesIO() args = ["--conf", self.default_config_file, "list"] + self.globs with mock.patch("sys.stdout", console_out): self.execute_jenkins_jobs_with_args(args) self.assertEqual(console_out.getvalue().decode("utf-8").rstrip(), ("\n".join(self.found)))
def test_skip_plugin_retrieval_if_disabled(self, get_plugins_mock): """ Verify that retrieval of information from Jenkins instance about its plugins will be skipped when run if a config file provided and disables querying through a config option. """ with mock.patch("sys.stdout", new_callable=io.BytesIO): args = [ "--conf", os.path.join(self.fixtures_path, "disable-query-plugins.conf"), "test", os.path.join(self.fixtures_path, "cmd-001.yaml"), ] entry.JenkinsJobs(args) self.assertFalse(get_plugins_mock.called)
def test_skip_plugin_retrieval_if_disabled(self, get_plugins_info_mock): """ Verify that retrieval of information from Jenkins instance about its plugins will be skipped when run if a config file provided and disables querying through a config option. """ with mock.patch("sys.stdout"): cmd.main( [ "--conf", os.path.join(self.fixtures_path, "disable-query-plugins.conf"), "test", os.path.join(self.fixtures_path, "cmd-001.yaml"), ] ) self.assertFalse(get_plugins_info_mock.called)
def test_update_timeout_not_set(self, jenkins_mock): """Check that timeout is left unset Test that the Jenkins object has the timeout set on it only when provided via the config option. """ path = os.path.join(self.fixtures_path, 'cmd-002.yaml') args = self.parser.parse_args(['update', path]) with mock.patch('jenkins_jobs.cmd.Builder.update_job') as update_mock: update_mock.return_value = ([], 0) cmd.execute(args, self.config) # unless the timeout is set, should only call with 3 arguments # (url, user, password) self.assertEquals(len(jenkins_mock.call_args[0]), 3)
def test_console_output_jenkins_connection_failure_warning(self, get_plugins_info_mock): """ Run test mode and verify that failed Jenkins connection attempt exception does not bubble out of cmd.main. Ideally, we would also test that an appropriate message is logged to stderr but it's somewhat difficult to figure out how to actually enable stderr in this test suite. """ get_plugins_info_mock.side_effect = jenkins.JenkinsException("Connection refused") with mock.patch("sys.stdout"): try: cmd.main(["test", os.path.join(self.fixtures_path, "cmd-001.yaml")]) except jenkins.JenkinsException: self.fail("jenkins.JenkinsException propagated to main") except: pass # only care about jenkins.JenkinsException for now
def test_update_timeout_set(self, jenkins_mock): """Check that timeout is set correctly Test that the Jenkins object has the timeout set on it only when provided via the config option. """ path = os.path.join(self.fixtures_path, 'cmd-002.yaml') args = self.parser.parse_args(['update', path]) self.config.set('jenkins', 'timeout', '0.2') with mock.patch('jenkins_jobs.cmd.Builder.update_job') as update_mock: update_mock.return_value = ([], 0) cmd.execute(args, self.config) # when timeout is set, the fourth argument to the Jenkins api init # should be the value specified from the config self.assertEquals(jenkins_mock.call_args[0][3], 0.2)
def test_update_timeout_not_set(self, jenkins_mock): """Check that timeout is left unset Test that the Jenkins object has the timeout set on it only when provided via the config option. """ path = os.path.join(self.fixtures_path, 'cmd-002.yaml') args = ['--conf', self.default_config_file, 'update', path] import_path = 'jenkins_jobs.cli.subcommand.update.Builder.update_job' with mock.patch(import_path) as update_mock: update_mock.return_value = ([], 0) self.execute_jenkins_jobs_with_args(args) # unless the timeout is set, should only call with 3 arguments # (url, user, password) self.assertEqual(len(jenkins_mock.call_args[0]), 3)
def test_update_timeout_set(self, jenkins_mock): """Check that timeout is set correctly Test that the Jenkins object has the timeout set on it only when provided via the config option. """ path = os.path.join(self.fixtures_path, 'cmd-002.yaml') config_file = os.path.join(self.fixtures_path, 'non-default-timeout.ini') args = ['--conf', config_file, 'update', path] with mock.patch('jenkins_jobs.cmd.Builder.update_job') as update_mock: update_mock.return_value = ([], 0) self.execute_jenkins_jobs_with_args(args) # when timeout is set, the fourth argument to the Jenkins api init # should be the value specified from the config self.assertEqual(jenkins_mock.call_args[0][3], 0.2)
def test_bogus_plugins_info_stub_option(self, registry_mock, generateXML_mock): """ Verify that a JenkinsJobException is raised if the plugins_info stub file does not yield a list as its top-level object. """ plugins_info_stub_yaml_file = os.path.join(self.fixtures_path, "bogus-plugins-info.yaml") args = [ "--conf", os.path.join(self.fixtures_path, "cmd-001.conf"), "test", "-p", plugins_info_stub_yaml_file, os.path.join(self.fixtures_path, "cmd-001.yaml"), ] args = self.parser.parse_args(args) with mock.patch("sys.stdout"): e = self.assertRaises(JenkinsJobsException, cmd.execute, args, self.config) self.assertIn("must contain a Yaml list", str(e))
def test_bogus_plugins_info_stub_option(self, registry_mock, generateXML_mock): """ Verify that a JenkinsJobException is raised if the plugins_info stub file does not yield a list as its top-level object. """ plugins_info_stub_yaml_file = os.path.join(self.fixtures_path, 'bogus-plugins-info.yaml') args = ['--conf', os.path.join(self.fixtures_path, 'cmd-001.conf'), 'test', '-p', plugins_info_stub_yaml_file, os.path.join(self.fixtures_path, 'cmd-001.yaml')] with mock.patch('sys.stdout'): jenkins_jobs = entry.JenkinsJobs(args) e = self.assertRaises(JenkinsJobsException, jenkins_jobs.execute) self.assertIn("must contain a Yaml list", str(e))
def test_bogus_plugins_info_stub_option(self, registry_mock, generateXML_mock): """ Verify that a JenkinsJobException is raised if the plugins_info stub file does not yield a list as its top-level object. """ plugins_info_stub_yaml_file = os.path.join(self.fixtures_path, 'bogus-plugins-info.yaml') args = ['--conf', os.path.join(self.fixtures_path, 'cmd-001.conf'), 'test', '-p', plugins_info_stub_yaml_file, os.path.join(self.fixtures_path, 'cmd-001.yaml')] stderr = StringIO() with mock.patch('sys.stderr', stderr): self.assertRaises(SystemExit, entry.JenkinsJobs, args) self.assertIn("must contain a Yaml list", stderr.getvalue())