diff --git a/jenkins/__init__.py b/jenkins/__init__.py index da5ec75..6e96380 100644 --- a/jenkins/__init__.py +++ b/jenkins/__init__.py @@ -527,6 +527,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. @@ -612,8 +623,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): ''' diff --git a/tests/test_jenkins.py b/tests/test_jenkins.py index f47a2e4..8c7e599 100644 --- a/tests/test_jenkins.py +++ b/tests/test_jenkins.py @@ -926,6 +926,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 = {