Make sensible default choices for fields

This commit makes some sensible default choices for fields
when adding and application to an environment. These are applied
to the image and keypairs fields.

In both cases, if only one option is available, then make that
the initial value selected.

In the images case, we take it a step further and if there is
only one image, make that the only choice, dropping the
'Select Image' option completely.

Change-Id: I24462374a50c1b8d83970f10278362f3dc5daf8b
This commit is contained in:
Andy Botting 2019-08-14 15:08:12 +10:00
parent be8d112153
commit a8848d9a2f
2 changed files with 20 additions and 3 deletions

View File

@ -440,6 +440,9 @@ class KeyPairChoiceField(DynamicChoiceField):
for keypair in sorted(keypairs, key=lambda e: e.name):
self.choices.append((keypair.name, keypair.name))
if len(keypairs) == 1:
self.initial = keypairs[0].name
class SecurityGroupChoiceField(DynamicChoiceField):
"""This widget allows to select a security group for VMs"""
@ -501,8 +504,11 @@ class ImageChoiceField(ChoiceField):
for id_, title in sorted(six.iteritems(image_map),
key=lambda e: e[1].title):
image_choices.append((id_, title))
if image_choices:
image_choices.insert(0, ("", _("Select Image")))
# If only one choice, select it as only option
if len(image_choices) != 1:
image_choices.insert(0, ("", _("Select Image")))
else:
image_choices.insert(0, ("", _("No images available")))

View File

@ -624,7 +624,10 @@ class TestImageChoiceField(unittest.TestCase):
status='active'),
# Test whether second continue statement works.
mock.Mock(id='bar_image_id', murano_property={
'title': 'foo_image_title', 'type': 'jpg'},
'title': 'bar_image_title', 'type': 'png'},
status='active'),
mock.Mock(id='baz_image_id', murano_property={
'title': 'baz_image_title', 'type': 'jpg'},
status='active')
]
image_choice_field = fields.ImageChoiceField()
@ -634,9 +637,17 @@ class TestImageChoiceField(unittest.TestCase):
self.assertEqual(("", _("Select Image")),
image_choice_field.choices[0])
self.assertEqual("foo_image_id", image_choice_field.choices[1][0])
self.assertEqual("bar_image_id", image_choice_field.choices[1][0])
self.assertIsInstance(image_choice_field.choices[1][1], fields.Choice)
# Test that 'Select Image' is dropped if only one result
image_choice_field.image_type = 'jpg'
image_choice_field.choices = []
image_choice_field.update(self.request)
self.assertEqual('baz_image_id', image_choice_field.choices[0][0])
self.assertIsInstance(image_choice_field.choices[0][1], fields.Choice)
# Test whether first continue statement works.
mock_get_murano_images.return_value = [
mock.Mock(murano_property={