diff --git a/jenkins/__init__.py b/jenkins/__init__.py index 4a04cfa..59c88fa 100644 --- a/jenkins/__init__.py +++ b/jenkins/__init__.py @@ -516,6 +516,17 @@ class Jenkins(object): except JenkinsException: return False + def assert_node_exists(self, name, + exception_message='node[%s] does not exist'): + ''' + :param name: Name of Jenkins node, ``str`` + :param exception_message: Message to use for the exception. Formatted + with ``name`` + :throws: :class:`JenkinsException` whenever the node does not exist + ''' + if not self.node_exists(name): + raise JenkinsException(exception_message % name) + def delete_node(self, name): '''Delete Jenkins node permanently. @@ -599,8 +610,7 @@ class Jenkins(object): self.jenkins_open(Request( self.server + CREATE_NODE % urlencode(params))) - if not self.node_exists(name): - raise JenkinsException('create[%s] failed' % (name)) + self.assert_node_exists(name, 'create[%s] failed') def get_build_console_output(self, name, number): '''Get build console text. diff --git a/tests/test_jenkins.py b/tests/test_jenkins.py index f4dc4da..136e37c 100644 --- a/tests/test_jenkins.py +++ b/tests/test_jenkins.py @@ -824,6 +824,25 @@ class JenkinsTest(unittest.TestCase): str(context_manager.exception), 'node[test_node] does not exist') + @patch.object(jenkins.Jenkins, 'jenkins_open') + def test_assert_node_exists__node_missing(self, jenkins_mock): + jenkins_mock.side_effect = [None] + j = jenkins.Jenkins('http://example.com/', 'test', 'test') + + with self.assertRaises(jenkins.JenkinsException) as context_manager: + j.assert_node_exists('NonExistentNode') + self.assertEqual( + str(context_manager.exception), + 'node[NonExistentNode] does not exist') + + @patch.object(jenkins.Jenkins, 'jenkins_open') + def test_assert_node_exists__node_exists(self, jenkins_mock): + jenkins_mock.side_effect = [ + json.dumps({'name': 'ExistingNode'}) + ] + j = jenkins.Jenkins('http://example.com/', 'test', 'test') + j.assert_node_exists('ExistingNode') + @patch.object(jenkins.Jenkins, 'jenkins_open') def test_delete_node(self, jenkins_mock): node_info = {