From e237d7eb74ca33cb493cf01af88ecf6cc918d0f1 Mon Sep 17 00:00:00 2001 From: Kien Ha Date: Mon, 4 Jul 2016 19:19:55 -0400 Subject: [PATCH] Add valid set of options parameters to convert_xml Valid options provides a way to check if the value the user input is from a list of available options. Change-Id: I22409602fb526a83c0525772d68da1dbd28dd11b Signed-off-by: Kien Ha --- jenkins_jobs/modules/helpers.py | 14 +++++++++++++- tests/modules/test_helpers.py | 14 ++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/jenkins_jobs/modules/helpers.py b/jenkins_jobs/modules/helpers.py index 1c37c43d2..51ad2a109 100644 --- a/jenkins_jobs/modules/helpers.py +++ b/jenkins_jobs/modules/helpers.py @@ -492,11 +492,19 @@ def convert_mapping_to_xml(parent, data, mapping, fail_required=False): configuring the XML tag for the parameter. We recommend for new plugins to set fail_required=True and instead of optional parameters provide a default value for all paramters that are not required instead. + + valid_options provides a way to check if the value the user input is from a + list of available options. When the user pass a value that is not supported + from the list, it raise an InvalidAttributeError. """ for elem in mapping: - (optname, xmlname, val) = elem + (optname, xmlname, val) = elem[:3] val = data.get(optname, val) + valid_options = [] + if len(elem) == 4: + valid_options = elem[3] + # Use fail_required setting to allow support for optional parameters # we will phase this out in the future as we rework plugins so that # optional parameters use a default setting instead. @@ -509,6 +517,10 @@ def convert_mapping_to_xml(parent, data, mapping, fail_required=False): if val is None and fail_required is False: continue + if valid_options: + if val not in valid_options: + raise InvalidAttributeError(optname, val, valid_options) + if type(val) == bool: val = str(val).lower() XML.SubElement(parent, xmlname).text = str(val) diff --git a/tests/modules/test_helpers.py b/tests/modules/test_helpers.py index b0bcb603f..a59fa3e77 100644 --- a/tests/modules/test_helpers.py +++ b/tests/modules/test_helpers.py @@ -18,6 +18,7 @@ from testtools.matchers import Equals import xml.etree.ElementTree as XML import yaml +from jenkins_jobs.errors import InvalidAttributeError from jenkins_jobs.errors import MissingAttributeError from jenkins_jobs.modules.helpers import convert_mapping_to_xml from tests.base import LoggingFixture @@ -68,3 +69,16 @@ class TestCaseTestHelpers(LoggingFixture, testtools.TestCase): required_data, required_mappings, fail_required=True) + + # Test invalid user input + user_input_root = XML.Element('testUserInput') + user_input_data = yaml.load("user-input-string: bye") + valid_inputs = ['hello'] + user_input_mappings = [('user-input-string', 'userInputString', + 'user-input', valid_inputs)] + + self.assertRaises(InvalidAttributeError, + convert_mapping_to_xml, + user_input_root, + user_input_data, + user_input_mappings)