Skip to contentSkip to conversation

Patches from Toaster reivew queue

PATCH New Michael Wood 1 participant 11 messages Apr 19, 2016

lore
Share & tools
lore
#0 lore raw

cover Patches from Toaster reivew queue

Patches from toaster-next which were held up.

Fixes for:
[YOCTO #8511]
[YOCTO #9011]
[YOCTO #9123]
[YOCTO #9209]

Elliot Smith (9):
toaster: fix sorting after hiding a column in build tables
toaster: disable/enable "Add layer" button according to input's
content
toaster: only prevent duplicate custom image names within a project
toaster: prevent exception when Project.release is null
toaster-tests: add tests for new custom image page
toaster-tests: make helper click on input before entering text
toaster: add build dashboard buttons to edit/create custom images
toaster: add modal to select custom image for editing
toaster-tests: tests for build dashboard

Michael Wood (1):
toaster: ensure ToasterTable headings are reset when order by changes

 lib/toaster/orm/models.py                          |  64 +++++-
 lib/toaster/tests/browser/selenium_helpers.py      |   6 +-
 .../tests/browser/test_builddashboard_page.py      | 251 +++++++++++++++++++++
 .../tests/browser/test_new_custom_image_page.py    | 160 +++++++++++++
 lib/toaster/toastergui/static/js/importlayer.js    |  30 ++-
 lib/toaster/toastergui/static/js/layerBtn.js       |   3 +-
 lib/toaster/toastergui/static/js/libtoaster.js     |   5 +
 .../toastergui/static/js/newcustomimage_modal.js   | 104 ++++++++-
 lib/toaster/toastergui/static/js/recipedetails.js  |   3 +-
 lib/toaster/toastergui/static/js/table.js          |   6 +-
 lib/toaster/toastergui/templates/base.html         |   1 -
 .../toastergui/templates/basebuildpage.html        | 213 +++++++++++------
 .../templates/editcustomimage_modal.html           |  71 ++++++
 .../toastergui/templates/newcustomimage_modal.html |  28 ++-
 lib/toaster/toastergui/templates/tasks.html        |   2 +-
 .../templatetags/objects_to_dictionaries_filter.py |  35 +++
 lib/toaster/toastergui/tests.py                    |  87 -------
 lib/toaster/toastergui/views.py                    | 116 ++++++----
 18 files changed, 953 insertions(+), 232 deletions(-)
 create mode 100644 lib/toaster/tests/browser/test_builddashboard_page.py
 create mode 100644 lib/toaster/tests/browser/test_new_custom_image_page.py
 create mode 100644 lib/toaster/toastergui/templates/editcustomimage_modal.html
 create mode 100644 lib/toaster/toastergui/templatetags/objects_to_dictionaries_filter.py
Signature · 1 line
2.5.0
#1 lore raw

PATCH 1/10 toaster: ensure ToasterTable headings are reset when order by changes

If a ToasterTable is ordered by an optional column and that column is subsequently hidden, the table ordering switches back to the default ordering for the table. However, the table headings don't update to reflect the new ordering. This is because the code which sets the heading weight and hides/shows the caret symbols only runs when the table is first loaded.

Store the default order by and re-apply it when the data is updated.

[YOCTO #9011]

---
 lib/toaster/toastergui/static/js/table.js | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
lib/toaster/toastergui/static/js/table.js +5 -1
index 2ae7695..f738144 100644
@@ -239,6 +239,10 @@ function tableInit(ctx){
           }
         }
 
+       if (col.field_name === tableData.default_orderby){
+         title.addClass("default-orderby");
+       }
+
       } else {
         /* Not orderable */
         header.css("font-weight", "normal");
@@ -384,7 +388,7 @@ function tableInit(ctx){
       if (col === tableParams.orderby ||
           '-' + col === tableParams.orderby){
         tableParams.orderby = null;
-        loadData(tableParams);
+        $("#"+ctx.tableName +" .default-orderby").click();
       }
     }
 
Signature · 1 line
2.5.0
#2 lore raw

PATCH 2/10 toaster: fix sorting after hiding a column in build tables

In reply to Michael Wood

From: Elliot Smith <[email protected]>

When hiding a column in the build tasks or build packages included table, if the column is set as the current order by for the table, the order by is not reset to the default. The result is that the table stays sorted by the hidden column.

Set the default_orderby for these two tables correctly to ensure the corresponding table is re-sorted when a column is hidden, if that column was being used as the order by.

[YOCTO #9011]

---
 lib/toaster/toastergui/templates/tasks.html |  2 +-
 lib/toaster/toastergui/views.py             | 50 ++++++++++++++---------------
 2 files changed, 26 insertions(+), 26 deletions(-)
lib/toaster/toastergui/templates/tasks.html +1 -1
index 23eb957..84bc103 100644
@@ -131,7 +131,7 @@
 <script type="text/javascript">
 
     $(document).ready(function() {
-        // enable blue hightlight animation for the order link
+        // highlight heading on the column for the field used for ordering
         if (location.href.search('#') > -1) {
             var task_order = location.href.split('#')[1];
             $("#" + task_order).addClass("highlight");
lib/toaster/toastergui/views.py +25 -25

83 lines not on this page · raw message

Signature · 1 line
2.5.0
#3 lore raw

PATCH 3/10 toaster: disable/enable "Add layer" button according to input's content

In reply to Michael Wood

From: Elliot Smith <[email protected]>

In the import layer page, the "Add layer" button in the layer dependencies section doesn't accurately reflect whether the layer name in the corresponding input can be added. A partial or empty layer name can leave the button active, such that when it is clicked, a previously-selected layer can be accidentally added.

Fix by keeping track of the items currently available in the typeahead, only activating the "Add layer" button when the input matches the name of one of those items.

[YOCTO #8511]

---
 lib/toaster/toastergui/static/js/importlayer.js | 30 ++++++++++++++++++++++++-
 lib/toaster/toastergui/static/js/libtoaster.js  |  5 +++++
 2 files changed, 34 insertions(+), 1 deletion(-)
lib/toaster/toastergui/static/js/importlayer.js +29 -1
index c68f366..5a59799 100644
@@ -18,10 +18,38 @@ function importLayerPageInit (ctx) {
 
   libtoaster.makeTypeahead(layerDepInput, libtoaster.ctx.layersTypeAheadUrl, { include_added: "true" }, function(item){
     currentLayerDepSelection = item;
+  });
+
+  // choices available in the typeahead
+  var layerDepsChoices = {};
+
+  // when the typeahead choices change, store an array of the available layer
+  // choices locally, to use for enabling/disabling the "Add layer" button
+  layerDepInput.on("typeahead-choices-change", function (event, data) {
+    layerDepsChoices = {};
 
-    layerDepBtn.removeAttr("disabled");
+    if (data.choices) {
+      data.choices.forEach(function (item) {
+        layerDepsChoices[item.name] = item;
+      });
+    }
   });
 
+  // disable the "Add layer" button when the layer input typeahead is empty
+  // or not in the typeahead choices
+  layerDepInput.on("input change", function () {
+    // get the choices from the typeahead
+    var choice = layerDepsChoices[$(this).val()];
+
+    if (choice) {
+      layerDepBtn.removeAttr("disabled");
+      currentLayerDepSelection = choice;
+    }
+    else {
+      layerDepBtn.attr("disabled", "disabled");
+      currentLayerDepSelection = undefined;
+    }
+  });
 
   /* We automatically add "openembedded-core" layer for convenience as a
    * dependency as pretty much all layers depend on this one
lib/toaster/toastergui/static/js/libtoaster.js +5 -0
index 8d1d20f..43930a2 100644
@@ -21,6 +21,9 @@ var libtoaster = (function (){
     var xhrReq;
 
     jQElement.typeahead({
+        // each time the typeahead's choices change, a
+        // "typeahead-choices-change" event is fired with an object
+        // containing the available choices in a "choices" property
         source: function(query, process){
           xhrParams.search = query;
 
@@ -36,6 +39,8 @@ var libtoaster = (function (){
 
             xhrReq = null;
 
+            jQElement.trigger("typeahead-choices-change", {choices: data.results});
+
             return process(data.results);
           });
         },
Signature · 1 line
2.5.0
#4 lore raw

PATCH 4/10 toaster: only prevent duplicate custom image names within a project

In reply to Michael Wood

From: Elliot Smith <[email protected]>

We currently prevent the same name being used for multiple custom images, but make the check across all projects. This means that custom image names have to be unique across all projects in the Toaster installation.

Modify how we validate the name of a custom image so that we only prevent duplication of custom image names within a project, while ensuring that the name of a custom image doesn't duplicate the name of a recipe which is not a custom image recipe.

[YOCTO #9209]

---
 .../toastergui/static/js/newcustomimage_modal.js   |  8 ++++--
 lib/toaster/toastergui/views.py                    | 33 ++++++++++++----------
 2 files changed, 24 insertions(+), 17 deletions(-)
lib/toaster/toastergui/static/js/newcustomimage_modal.js +6 -2
index 328997a..98e87f4 100644
@@ -9,6 +9,8 @@ function newCustomImageModalInit(){
   var nameInput = imgCustomModal.find('input');
 
   var invalidMsg = "Image names cannot contain spaces or capital letters. The only allowed special character is dash (-).";
+  var duplicateImageMsg = "An image with this name already exists in this project.";
+  var duplicateRecipeMsg = "A non-image recipe with this name already exists.";
 
   newCustomImgBtn.click(function(e){
     e.preventDefault();
@@ -22,8 +24,10 @@ function newCustomImageModalInit(){
           console.warn(ret.error);
           if (ret.error === "invalid-name") {
             showError(invalidMsg);
-          } else if (ret.error === "already-exists") {
-            showError("An image with this name already exists. Image names must be unique.");
+          } else if (ret.error === "image-already-exists") {
+            showError(duplicateImageMsg);
+          } else if (ret.error === "recipe-already-exists") {
+            showError(duplicateRecipeMsg);
           }
         } else {
           imgCustomModal.modal('hide');
lib/toaster/toastergui/views.py +18 -15
index a11c9da..9744f4e 100755
@@ -2409,21 +2409,24 @@ if True:
             if re.search(r'[^a-z|0-9|-]', request.POST["name"]):
                 return {"error": "invalid-name"}
 
-            # Are there any recipes with the name already?
-            for existing_recipe in Recipe.objects.filter(
-                name=request.POST["name"]):
-                try:
-                    ci = CustomImageRecipe.objects.get(pk=existing_recipe.pk)
-                    if ci.project == params["project"]:
-                        return {"error": "already-exists" }
-                    else:
-                        # It is a CustomImageRecipe but not in our project
-                        # this is fine so
-                        continue
-                except:
-                    # It isn't a CustomImageRecipe so is a recipe from
-                    # another source.
-                    return {"error": "already-exists" }
+            custom_images = CustomImageRecipe.objects.all()
+
+            # Are there any recipes with this name already in our project?
+            existing_image_recipes_in_project = custom_images.filter(
+                name=request.POST["name"], project=params["project"])
+
+            if existing_image_recipes_in_project.count() > 0:
+                return {"error": "image-already-exists"}
+
+            # Are there any recipes with this name which aren't custom
+            # image recipes?
+            custom_image_ids = custom_images.values_list('id', flat=True)
+            existing_non_image_recipes = Recipe.objects.filter(
+                Q(name=request.POST["name"]) & ~Q(pk__in=custom_image_ids)
+            )
+
+            if existing_non_image_recipes.count() > 0:
+                return {"error": "recipe-already-exists"}
 
             # create layer 'Custom layer' and verion if needed
             layer = Layer.objects.get_or_create(
Signature · 1 line
2.5.0
#5 lore raw

PATCH 5/10 toaster: prevent exception when Project.release is null

In reply to Michael Wood

From: Elliot Smith <[email protected]>

Project.release can be null. This causes an exception when calling get_all_compatible_layer_versions(), as the query to fetch the layer versions references release.branch_name.

Add a guard to the function so that an empty queryset is returned if the release isn't set for a project.

---
 lib/toaster/orm/models.py | 16 +++++++++++-----
 1 file changed, 11 insertions(+), 5 deletions(-)
lib/toaster/orm/models.py +11 -5
index 68c3072..f0a8786 100644
@@ -264,11 +264,17 @@ class Project(models.Model):
     def get_all_compatible_layer_versions(self):
         """ Returns Queryset of all Layer_Versions which are compatible with
         this project"""
-        queryset = Layer_Version.objects.filter(
-            (Q(up_branch__name=self.release.branch_name) &
-             Q(build=None) &
-             Q(project=None)) |
-             Q(project=self))
+        queryset = None
+
+        # guard on release, as it can be null
+        if self.release:
+            queryset = Layer_Version.objects.filter(
+                (Q(up_branch__name=self.release.branch_name) &
+                 Q(build=None) &
+                 Q(project=None)) |
+                 Q(project=self))
+        else:
+            queryset = Layer_Version.objects.none()
 
         return queryset
 
Signature · 1 line
2.5.0
#6 lore raw

PATCH 6/10 toaster-tests: add tests for new custom image page

In reply to Michael Wood

From: Elliot Smith <[email protected]>

Test adding a new custom image when:

1. No custom images are in the project yet.
2. User tries to add custom image which duplicates the name of an existing custom image.
3. User tries to add custom image which duplicates the name of a non-image recipe.

[YOCTO #9209]

---
 .../tests/browser/test_new_custom_image_page.py    | 160 +++++++++++++++++++++
 1 file changed, 160 insertions(+)
 create mode 100644 lib/toaster/tests/browser/test_new_custom_image_page.py
lib/toaster/tests/browser/test_new_custom_image_page.py new file +160 -0
new file mode 100644
index 0000000..8906cb2
@@ -0,0 +1,160 @@
+#! /usr/bin/env python
+# ex:ts=4:sw=4:sts=4:et
+# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
+#
+# BitBake Toaster Implementation
+#
+# Copyright (C) 2013-2016 Intel Corporation
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 as
+# published by the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along
+# with this program; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+from django.core.urlresolvers import reverse
+from tests.browser.selenium_helpers import SeleniumTestCase
+
+from orm.models import BitbakeVersion, Release, Project, ProjectLayer, Layer
+from orm.models import Layer_Version, Recipe, CustomImageRecipe
+
+class TestNewCustomImagePage(SeleniumTestCase):
+    CUSTOM_IMAGE_NAME = 'roopa-doopa'
+
+    def setUp(self):
+        release = Release.objects.create(
+            name='baz',
+            bitbake_version=BitbakeVersion.objects.create(name='v1')
+        )
+
+        # project to add new custom images to
+        self.project = Project.objects.create(name='foo', release=release)
+
+        # layer associated with the project
+        layer = Layer.objects.create(name='bar')
+        layer_version = Layer_Version.objects.create(
+            layer=layer,
+            project=self.project
+        )
+
+        # properly add the layer to the project
+        ProjectLayer.objects.create(
+            project=self.project,
+            layercommit=layer_version,
+            optional=False
+        )
+
+        # add a fake image recipe to the layer that can be customised
+        self.recipe = Recipe.objects.create(
+            name='core-image-minimal',
+            layer_version=layer_version,
+            is_image=True
+        )
+
+        # another project with a custom image already in it
+        project2 = Project.objects.create(name='whoop', release=release)
+        layer_version2 = Layer_Version.objects.create(
+            layer=layer,
+            project=project2
+        )
+        ProjectLayer.objects.create(
+            project=project2,
+            layercommit=layer_version2,
+            optional=False
+        )
+        recipe2 = Recipe.objects.create(
+            name='core-image-minimal',
+            layer_version=layer_version2,
+            is_image=True
+        )
+        CustomImageRecipe.objects.create(
+            name=self.CUSTOM_IMAGE_NAME,
+            base_recipe=recipe2,
+            layer_version=layer_version2,
+            file_path='/1/2',
+            project=project2
+        )
+
+    def _create_custom_image(self, new_custom_image_name):
+        """
+        1. Go to the 'new custom image' page
+        2. Click the button for the fake core-image-minimal
+        3. Wait for the dialog box for setting the name of the new custom
+           image
+        4. Insert new_custom_image_name into that dialog's text box
+        """
+        url = reverse('newcustomimage', args=(self.project.id,))
+        self.get(url)
+
+        self.click('button[data-recipe="%s"]' % self.recipe.id)
+
+        selector = '#new-custom-image-modal input[type="text"]'
+        self.enter_text(selector, new_custom_image_name)
+
+        self.click('#create-new-custom-image-btn')
+
+    def _check_for_custom_image(self, image_name):
+        """
+        Fetch the list of custom images for the project and check the
+        image with name image_name is listed there
+        """
+        url = reverse('projectcustomimages', args=(self.project.id,))
+        self.get(url)
+
+        self.wait_until_visible('#customimagestable')
+
+        element = self.find('#customimagestable td[class="name"] a')
+        msg = 'should be a custom image link with text %s' % image_name
+        self.assertEqual(element.text.strip(), image_name, msg)
+
+    def test_new_image(self):
+        """
+        Should be able to create a new custom image
+        """
+        custom_image_name = 'boo-image'
+        self._create_custom_image(custom_image_name)
+        self.wait_until_visible('#image-created-notification')
+        self._check_for_custom_image(custom_image_name)
+
+    def test_new_duplicates_other_project_image(self):
+        """
+        Should be able to create a new custom image if its name is the same
+        as a custom image in another project
+        """
+        self._create_custom_image(self.CUSTOM_IMAGE_NAME)
+        self.wait_until_visible('#image-created-notification')
+        self._check_for_custom_image(self.CUSTOM_IMAGE_NAME)
+
+    def test_new_duplicates_non_image_recipe(self):
+        """
+        Should not be able to create a new custom image whose name is the
+        same as an existing non-image recipe
+        """
+        self._create_custom_image(self.recipe.name)
+        element = self.wait_until_visible('#invalid-name-help')
+        self.assertRegexpMatches(element.text.strip(),
+                                 'recipe with this name already exists')
+
+    def test_new_duplicates_project_image(self):
+        """
+        Should not be able to create a new custom image whose name is the same
+        as a custom image in this project
+        """
+        # create the image
+        custom_image_name = 'doh-image'
+        self._create_custom_image(custom_image_name)
+        self.wait_until_visible('#image-created-notification')
+        self._check_for_custom_image(custom_image_name)
+
+        # try to create an image with the same name
+        self._create_custom_image(custom_image_name)
+        element = self.wait_until_visible('#invalid-name-help')
+        expected = 'An image with this name already exists in this project'
+        self.assertRegexpMatches(element.text.strip(), expected)
Signature · 1 line
2.5.0
#7 lore raw

PATCH 7/10 toaster-tests: make helper click on input before entering text

In reply to Michael Wood

From: Elliot Smith <[email protected]>

The Selenium helper's enter_text() method doesn't cause keyup events to trigger unless the element where text is being entered has been clicked.

Prefix all text entry with a click() on the element to ensure that keyup events fire.

---
 lib/toaster/tests/browser/selenium_helpers.py | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
lib/toaster/tests/browser/selenium_helpers.py +5 -1
index d3ab3ca..56dbe2b 100644
@@ -185,7 +185,11 @@ class SeleniumTestCase(StaticLiveServerTestCase):
 
     def enter_text(self, selector, value):
         """ Insert text into element matching selector """
-        field = self.wait_until_present(selector)
+        # note that keyup events don't occur until the element is clicked
+        # (in the case of <input type="text"...>, for example), so simulate
+        # user clicking the element before inserting text into it
+        field = self.click(selector)
+
         field.send_keys(value)
         return field
 
Signature · 1 line
2.5.0
#8 lore raw

PATCH 8/10 toaster: add build dashboard buttons to edit/create custom images

In reply to Michael Wood

From: Elliot Smith <[email protected]>

When a build is viewed in the dashboard, enable users to edit a custom image which was built during that build, and/or create a new custom image based on one of the image recipes built during the build.

Add methods to the Build model to enable querying for the set of image recipes built during a build.

Add buttons to the dashboard, with the "Edit custom image" button opening a basic modal for now. The "New custom image" button opens the existing new custom image modal, but is modified to show a list of images available as a base for a new custom image.

Add a new function to the new custom image modal's script which enables multiple potential custom images to be shown as radio buttons in the dialog (if there is more than 1). Modify existing code to use this new function.

Add a template filter which allows the queryset of recipes for a build to be available to client-side scripts, and from there be used to populate the new custom image modal.

[YOCTO #9123]

---
 lib/toaster/orm/models.py                          |  41 ++++
 lib/toaster/toastergui/static/js/layerBtn.js       |   3 +-
 .../toastergui/static/js/newcustomimage_modal.js   | 103 ++++++++--
 lib/toaster/toastergui/static/js/recipedetails.js  |   3 +-
 .../toastergui/templates/basebuildpage.html        | 207 +++++++++++++--------
 .../templates/editcustomimage_modal.html           |  23 +++
 .../toastergui/templates/newcustomimage_modal.html |  28 ++-
 .../templatetags/queryset_to_list_filter.py        |  26 +++
 lib/toaster/toastergui/views.py                    |   7 +-
 9 files changed, 345 insertions(+), 96 deletions(-)
 create mode 100644 lib/toaster/toastergui/templates/editcustomimage_modal.html
 create mode 100644 lib/toaster/toastergui/templatetags/queryset_to_list_filter.py
lib/toaster/orm/models.py +41 -0
index f0a8786..75e6ea3 100644
@@ -490,6 +490,47 @@ class Build(models.Model):
         tgts = Target.objects.filter(build_id = self.id).order_by( 'target' );
         return( tgts );
 
+    def get_recipes(self):
+        """
+        Get the recipes related to this build;
+        note that the related layer versions and layers are also prefetched
+        by this query, as this queryset can be sorted by these objects in the
+        build recipes view; prefetching them here removes the need
+        for another query in that view
+        """
+        layer_versions = Layer_Version.objects.filter(build=self)
+        criteria = Q(layer_version__id__in=layer_versions)
+        return Recipe.objects.filter(criteria) \
+                             .select_related('layer_version', 'layer_version__layer')
+
+    def get_custom_image_recipe_names(self):
+        """
+        Get the names of custom image recipes for this build's project
+        as a list; this is used to screen out custom image recipes from the
+        recipes for the build by name, and to distinguish image recipes from
+        custom image recipes
+        """
+        custom_image_recipes = \
+            CustomImageRecipe.objects.filter(project=self.project)
+        return custom_image_recipes.values_list('name', flat=True)
+
+    def get_image_recipes(self):
+        """
+        Returns a queryset of image recipes related to this build, sorted
+        by name
+        """
+        criteria = Q(is_image=True)
+        return self.get_recipes().filter(criteria).order_by('name')
+
+    def get_custom_image_recipes(self):
+        """
+        Returns a queryset of custom image recipes related to this build,
+        sorted by name
+        """
+        custom_image_recipe_names = self.get_custom_image_recipe_names()
+        criteria = Q(is_image=True) & Q(name__in=custom_image_recipe_names)
+        return self.get_recipes().filter(criteria).order_by('name')
+
     def get_outcome_text(self):
         return Build.BUILD_OUTCOME[int(self.outcome)][1]
 
lib/toaster/toastergui/static/js/layerBtn.js +2 -1
index aa43284..259271d 100644
@@ -76,7 +76,8 @@ function layerBtnsInit() {
     if (imgCustomModal.length == 0)
       throw("Modal new-custom-image not found");
 
-    imgCustomModal.data('recipe', $(this).data('recipe'));
+    var recipe = {id: $(this).data('recipe'), name: null}
+    newCustomImageModalSetRecipes([recipe]);
     imgCustomModal.modal('show');
   });
 }
lib/toaster/toastergui/static/js/newcustomimage_modal.js +92 -11

147 lines not on this page · raw message

lib/toaster/toastergui/static/js/recipedetails.js +2 -1
index d5f9eac..604db5f 100644
@@ -9,7 +9,8 @@ function recipeDetailsPageInit(ctx){
     if (imgCustomModal.length === 0)
       throw("Modal new-custom-image not found");
 
-    imgCustomModal.data('recipe', $(this).data('recipe'));
+    var recipe = {id: $(this).data('recipe'), name: null}
+    newCustomImageModalSetRecipes([recipe]);
     imgCustomModal.modal('show');
   });
 
lib/toaster/toastergui/templates/basebuildpage.html +133 -74

223 lines not on this page · raw message

lib/toaster/toastergui/templates/editcustomimage_modal.html new file +23 -0
new file mode 100644
index 0000000..fd998f6
@@ -0,0 +1,23 @@
+<!--
+modal dialog shown on the build dashboard, for editing an existing custom image
+-->
+<div class="modal hide fade in" aria-hidden="false" id="edit-custom-image-modal">
+  <div class="modal-header">
+    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
+    <h3>Select custom image to edit</h3>
+  </div>
+  <div class="modal-body">
+    <div class="row-fluid">
+      <span class="help-block">
+        Explanation of what this modal is for
+      </span>
+    </div>
+    <div class="control-group controls">
+      <input type="text" class="huge" placeholder="input box" required>
+      <span class="help-block error" style="display:none">Error text</span>
+    </div>
+  </div>
+  <div class="modal-footer">
+    <button class="btn btn-primary btn-large" disabled>Action</button>
+  </div>
+</div>
lib/toaster/toastergui/templates/newcustomimage_modal.html +22 -6
index b1b5148..caeb302 100644
@@ -15,18 +15,34 @@
 <div class="modal hide fade in" id="new-custom-image-modal" aria-hidden="false">
   <div class="modal-header">
     <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
-    <h3>Name your custom image</h3>
+    <h3>New custom image</h3>
   </div>
+
   <div class="modal-body">
+    <!--
+    this container is visible if there are multiple image recipes which could
+    be used as a basis for the new custom image; radio buttons are added to it
+    via newCustomImageModalSetRecipes() as required
+    -->
+    <div data-role="image-selector" style="display:none;">
+      <h4>Which image do you want to customise?</h4>
+      <div data-role="image-selector-radios"></div>
+      <span class="help-block error" id="invalid-recipe-help" style="display:none"></span>
+      <div class="air"></div>
+    </div>
+
+    <h4>Name your custom image</h4>
+
     <div class="row-fluid">
       <span class="help-block span8">Image names must be unique. They should not contain spaces or capital letters, and the only allowed special character is dash (-).<p></p>
       </span></div>
     <div class="control-group controls">
       <input type="text" class="huge" placeholder="Type the custom image name" required>
-        <span class="help-block error" id="invalid-name-help" style="display:none"></span>
-      </div>
-    </div>
-    <div class="modal-footer">
-      <button id="create-new-custom-image-btn" class="btn btn-primary btn-large" data-original-title="" title="" disabled>Create custom image</button>
+      <span class="help-block error" id="invalid-name-help" style="display:none"></span>
     </div>
+  </div>
+
+  <div class="modal-footer">
+    <button id="create-new-custom-image-btn" class="btn btn-primary btn-large" data-original-title="" title="" disabled>Create custom image</button>
+  </div>
 </div>
lib/toaster/toastergui/templatetags/queryset_to_list_filter.py new file +26 -0
new file mode 100644
index 0000000..dfc094b
@@ -0,0 +1,26 @@
+from django import template
+import json
+
+register = template.Library()
+
+def queryset_to_list(queryset, fields):
+    """
+    Convert a queryset to a list; fields can be set to a comma-separated
+    string of fields for each record included in the resulting list; if
+    omitted, all fields are included for each record, e.g.
+
+        {{ queryset | queryset_to_list:"id,name" }}
+
+    will return a list like
+
+        [{'id': 1, 'name': 'foo'}, ...]
+
+    (providing queryset has id and name fields)
+    """
+    if fields:
+        fields_list = [field.strip() for field in fields.split(',')]
+        return list(queryset.values(*fields_list))
+    else:
+        return list(queryset.values())
+
+register.filter('queryset_to_list', queryset_to_list)
lib/toaster/toastergui/views.py +4 -3
index 9744f4e..942dc31 100755
@@ -1257,7 +1257,10 @@ def recipes(request, build_id):
     if retval:
         return _redirect_parameters( 'recipes', request.GET, mandatory_parameters, build_id = build_id)
     (filter_string, search_term, ordering_string) = _search_tuple(request, Recipe)
-    queryset = Recipe.objects.filter(layer_version__id__in=Layer_Version.objects.filter(build=build_id)).select_related("layer_version", "layer_version__layer")
+
+    build = Build.objects.get(pk=build_id)
+
+    queryset = build.get_recipes()
     queryset = _get_queryset(Recipe, queryset, filter_string, search_term, ordering_string, 'name')
 
     recipes = _build_page_range(Paginator(queryset, pagesize),request.GET.get('page', 1))
@@ -1276,8 +1279,6 @@ def recipes(request, build_id):
             revlist.append(recipe_dep)
         revs[recipe.id] = revlist
 
-    build = Build.objects.get(pk=build_id)
-
     context = {
         'objectname': 'recipes',
         'build': build,
Signature · 1 line
2.5.0
#9 lore raw

PATCH 9/10 toaster: add modal to select custom image for editing

In reply to Michael Wood

From: Elliot Smith <[email protected]>

Add functionality to the placeholder button on the build dashboard to open a modal dialog displaying editable custom images, in cases where multiple custom images were built by the build. Where there is only one editable custom image, go direct to its edit page.

The images shown in the modal are custom recipes for the project which were built during the build shown in the dashboard.

This also affects the new custom image dialog, as that also has to show custom image recipes as well as image recipes built during the build. Modify the API on the Build object to support both.

Also modify and rename the queryset_to_list template filter so that it can deal with lists as well as querysets, as the new custom image modal has to show a list of image recipes which is an amalgam of two querysets.

[YOCTO #9123]

---
 lib/toaster/orm/models.py                          | 45 ++++++++------
 .../toastergui/static/js/newcustomimage_modal.js   | 15 +++--
 lib/toaster/toastergui/templates/base.html         |  1 -
 .../toastergui/templates/basebuildpage.html        | 62 +++++++++++---------
 .../templates/editcustomimage_modal.html           | 68 ++++++++++++++++++----
 .../templatetags/objects_to_dictionaries_filter.py | 35 +++++++++++
 .../templatetags/queryset_to_list_filter.py        | 26 ---------
 lib/toaster/toastergui/views.py                    | 26 +++++++--
 8 files changed, 186 insertions(+), 92 deletions(-)
 create mode 100644 lib/toaster/toastergui/templatetags/objects_to_dictionaries_filter.py
 delete mode 100644 lib/toaster/toastergui/templatetags/queryset_to_list_filter.py
lib/toaster/orm/models.py +26 -19
index 75e6ea3..0b83b99 100644
@@ -503,33 +503,37 @@ class Build(models.Model):
         return Recipe.objects.filter(criteria) \
                              .select_related('layer_version', 'layer_version__layer')
 
-    def get_custom_image_recipe_names(self):
-        """
-        Get the names of custom image recipes for this build's project
-        as a list; this is used to screen out custom image recipes from the
-        recipes for the build by name, and to distinguish image recipes from
-        custom image recipes
-        """
-        custom_image_recipes = \
-            CustomImageRecipe.objects.filter(project=self.project)
-        return custom_image_recipes.values_list('name', flat=True)
-
     def get_image_recipes(self):
         """
-        Returns a queryset of image recipes related to this build, sorted
-        by name
+        Returns a list of image Recipes (custom and built-in) related to this
+        build, sorted by name; note that this has to be done in two steps, as
+        there's no way to get all the custom image recipes and image recipes
+        in one query
         """
-        criteria = Q(is_image=True)
-        return self.get_recipes().filter(criteria).order_by('name')
+        custom_image_recipes = self.get_custom_image_recipes()
+        custom_image_recipe_names = custom_image_recipes.values_list('name', flat=True)
+
+        not_custom_image_recipes = ~Q(name__in=custom_image_recipe_names) & \
+                                   Q(is_image=True)
+
+        built_image_recipes = self.get_recipes().filter(not_custom_image_recipes)
+
+        # append to the custom image recipes and sort
+        customisable_image_recipes = list(
+            itertools.chain(custom_image_recipes, built_image_recipes)
+        )
+
+        return sorted(customisable_image_recipes, key=lambda recipe: recipe.name)
 
     def get_custom_image_recipes(self):
         """
-        Returns a queryset of custom image recipes related to this build,
+        Returns a queryset of CustomImageRecipes related to this build,
         sorted by name
         """
-        custom_image_recipe_names = self.get_custom_image_recipe_names()
-        criteria = Q(is_image=True) & Q(name__in=custom_image_recipe_names)
-        return self.get_recipes().filter(criteria).order_by('name')
+        built_recipe_names = self.get_recipes().values_list('name', flat=True)
+        criteria = Q(name__in=built_recipe_names) & Q(project=self.project)
+        queryset = CustomImageRecipe.objects.filter(criteria).order_by('name')
+        return queryset
 
     def get_outcome_text(self):
         return Build.BUILD_OUTCOME[int(self.outcome)][1]
@@ -1380,6 +1384,9 @@ class Layer(models.Model):
 
 # LayerCommit class is synced with layerindex.LayerBranch
 class Layer_Version(models.Model):
+    """
+    A Layer_Version either belongs to a single project or no project
+    """
     search_allowed_fields = ["layer__name", "layer__summary", "layer__description", "layer__vcs_url", "dirpath", "up_branch__name", "commit", "branch"]
     build = models.ForeignKey(Build, related_name='layer_version_build', default = None, null = True)
     layer = models.ForeignKey(Layer, related_name='layer_version_layer')
lib/toaster/toastergui/static/js/newcustomimage_modal.js +10 -5
index 1ae0d34..cb9ed4d 100644
@@ -12,6 +12,7 @@ for the new custom image. This will manage the addition of radio buttons
 to select the base image (or remove the radio buttons, if there is only a
 single base image available).
 */
+
 function newCustomImageModalInit(){
 
   var newCustomImgBtn = $("#create-new-custom-image-btn");
@@ -21,7 +22,8 @@ function newCustomImageModalInit(){
   var nameInput = imgCustomModal.find('input');
 
   var invalidNameMsg = "Image names cannot contain spaces or capital letters. The only allowed special character is dash (-).";
-  var duplicateNameMsg = "An image with this name already exists. Image names must be unique.";
+  var duplicateNameMsg = "A recipe with this name already exists. Image names must be unique.";
+  var duplicateImageInProjectMsg = "An image with this name already exists in this project."
   var invalidBaseRecipeIdMsg = "Please select an image to customise.";
 
   // capture clicks on radio buttons inside the modal; when one is selected,
@@ -51,9 +53,12 @@ function newCustomImageModalInit(){
           if (ret.error === "invalid-name") {
             showNameError(invalidNameMsg);
             return;
-          } else if (ret.error === "already-exists") {
+          } else if (ret.error === "recipe-already-exists") {
             showNameError(duplicateNameMsg);
             return;
+          } else if (ret.error === "image-already-exists") {
+            showNameError(duplicateImageInProjectMsg);
+            return;
           }
         } else {
           imgCustomModal.modal('hide');
@@ -112,13 +117,13 @@ function newCustomImageModalSetRecipes(baseRecipes) {
   var imageSelector = $('#new-custom-image-modal [data-role="image-selector"]');
   var imageSelectRadiosContainer = $('#new-custom-image-modal [data-role="image-selector-radios"]');
 
+  // remove any existing radio buttons + labels
+  imageSelector.remove('[data-role="image-radio"]');
+
   if (baseRecipes.length === 1) {
     // hide the radio button container
     imageSelector.hide();
 
-    // remove any radio buttons + labels
-    imageSelector.remove('[data-role="image-radio"]');
-
     // set the single recipe ID on the modal as it's the only one
     // we can build from
     imgCustomModal.data('recipe', baseRecipes[0].id);
lib/toaster/toastergui/templates/base.html +0 -1
index 192f9fb..210cf33 100644
@@ -43,7 +43,6 @@
         recipesTypeAheadUrl: {% url 'xhr_recipestypeahead' project.id as paturl%}{{paturl|json}},
         layersTypeAheadUrl: {% url 'xhr_layerstypeahead' project.id as paturl%}{{paturl|json}},
         machinesTypeAheadUrl: {% url 'xhr_machinestypeahead' project.id as paturl%}{{paturl|json}},
-
         projectBuildsUrl: {% url 'projectbuilds' project.id as pburl %}{{pburl|json}},
         xhrCustomRecipeUrl : "{% url 'xhr_customrecipe' %}",
         projectId : {{project.id}},
lib/toaster/toastergui/templates/basebuildpage.html +35 -27

88 lines not on this page · raw message

lib/toaster/toastergui/templates/editcustomimage_modal.html +58 -10

81 lines not on this page · raw message

lib/toaster/toastergui/templatetags/objects_to_dictionaries_filter.py new file +35 -0
new file mode 100644
index 0000000..0dcc7d2
@@ -0,0 +1,35 @@
+from django import template
+import json
+
+register = template.Library()
+
+def objects_to_dictionaries(iterable, fields):
+    """
+    Convert an iterable into a list of dictionaries; fields should be set
+    to a comma-separated string of properties for each item included in the
+    resulting list; e.g. for a queryset:
+
+        {{ queryset | objects_to_dictionaries:"id,name" }}
+
+    will return a list like
+
+        [{'id': 1, 'name': 'foo'}, ...]
+
+    providing queryset has id and name fields
+
+    This is mostly to support serialising querysets or lists of model objects
+    to JSON
+    """
+    objects = []
+
+    if fields:
+        fields_list = [field.strip() for field in fields.split(',')]
+        for item in iterable:
+            out = {}
+            for field in fields_list:
+                out[field] = getattr(item, field)
+            objects.append(out)
+
+    return objects
+
+register.filter('objects_to_dictionaries', objects_to_dictionaries)
lib/toaster/toastergui/templatetags/queryset_to_list_filter.py deleted +0 -26
deleted file mode 100644
index dfc094b..0000000
@@ -1,26 +0,0 @@
-from django import template
-import json
-
-register = template.Library()
-
-def queryset_to_list(queryset, fields):
-    """
-    Convert a queryset to a list; fields can be set to a comma-separated
-    string of fields for each record included in the resulting list; if
-    omitted, all fields are included for each record, e.g.
-
-        {{ queryset | queryset_to_list:"id,name" }}
-
-    will return a list like
-
-        [{'id': 1, 'name': 'foo'}, ...]
-
-    (providing queryset has id and name fields)
-    """
-    if fields:
-        fields_list = [field.strip() for field in fields.split(',')]
-        return list(queryset.values(*fields_list))
-    else:
-        return list(queryset.values())
-
-register.filter('queryset_to_list', queryset_to_list)
lib/toaster/toastergui/views.py +22 -4
index 942dc31..bd5bf63 100755
@@ -507,6 +507,7 @@ def builddashboard( request, build_id ):
 
     context = {
             'build'           : build,
+            'project'         : build.project,
             'hasImages'       : hasImages,
             'ntargets'        : ntargets,
             'targets'         : targets,
@@ -797,6 +798,7 @@ eans multiple licenses exist that cover different parts of the source',
     context = {
         'objectname': variant,
         'build'                : build,
+        'project'              : build.project,
         'target'               : Target.objects.filter( pk = target_id )[ 0 ],
         'objects'              : packages,
         'packages_sum'         : packages_sum[ 'installed_size__sum' ],
@@ -937,7 +939,10 @@ def dirinfo(request, build_id, target_id, file_path=None):
             if head != sep:
                 dir_list.insert(0, head)
 
-    context = { 'build': Build.objects.get(pk=build_id),
+    build = Build.objects.get(pk=build_id)
+
+    context = { 'build': build,
+                'project': build.project,
                 'target': Target.objects.get(pk=target_id),
                 'packages_sum': packages_sum['installed_size__sum'],
                 'objects': objects,
@@ -1211,6 +1216,7 @@ def tasks_common(request, build_id, variant, task_anchor):
                 'filter_search_display': filter_search_display,
                 'mainheading': title_variant,
                 'build': build,
+                'project': build.project,
                 'objects': task_objects,
                 'default_orderby' : default_orderby,
                 'search_term': search_term,
@@ -1282,6 +1288,7 @@ def recipes(request, build_id):
     context = {
         'objectname': 'recipes',
         'build': build,
+        'project': build.project,
         'objects': recipes,
         'default_orderby' : 'name:+',
         'recipe_deps' : deps,
@@ -1366,10 +1373,12 @@ def configuration(request, build_id):
                  'MACHINE', 'DISTRO', 'DISTRO_VERSION', 'TUNE_FEATURES', 'TARGET_FPU')
     context = dict(Variable.objects.filter(build=build_id, variable_name__in=var_names)\
                                            .values_list('variable_name', 'variable_value'))
+    build = Build.objects.get(pk=build_id)
     context.update({'objectname': 'configuration',
                     'object_search_display':'variables',
                     'filter_search_display':'variables',
-                    'build': Build.objects.get(pk=build_id),
+                    'build': build,
+                    'project': build.project,
                     'targets': Target.objects.filter(build=build_id)})
     return render(request, template, context)
 
@@ -1406,12 +1415,15 @@ def configvars(request, build_id):
         file_filter += '/bitbake.conf'
     build_dir=re.sub("/tmp/log/.*","",Build.objects.get(pk=build_id).cooker_log_path)
 
+    build = Build.objects.get(pk=build_id)
+
     context = {
                 'objectname': 'configvars',
                 'object_search_display':'BitBake variables',
                 'filter_search_display':'variables',
                 'file_filter': file_filter,
-                'build': Build.objects.get(pk=build_id),
+                'build': build,
+                'project': build.project,
                 'objects' : variables,
                 'total_count':queryset_with_search.count(),
                 'default_orderby' : 'variable_name:+',
@@ -1480,6 +1492,7 @@ def bpackage(request, build_id):
     context = {
         'objectname': 'packages built',
         'build': build,
+        'project': build.project,
         'objects' : packages,
         'default_orderby' : 'name:+',
         'tablecols':[
@@ -1554,7 +1567,12 @@ def bpackage(request, build_id):
 def bfile(request, build_id, package_id):
     template = 'bfile.html'
     files = Package_File.objects.filter(package = package_id)
-    context = {'build': Build.objects.get(pk=build_id), 'objects' : files}
+    build = Build.objects.get(pk=build_id)
+    context = {
+        'build': build,
+        'project': build.project,
+        'objects' : files
+    }
     return render(request, template, context)
 
 
Signature · 1 line
2.5.0
#10 lore raw

PATCH 10/10 toaster-tests: tests for build dashboard

In reply to Michael Wood

From: Elliot Smith <[email protected]>

Convert existing tests to Selenium.

Add basic tests to check that the modal contains radio buttons to select a custom image to edit when a build built multiple custom images, and to create a new custom image from one of the images built during the build.

[YOCTO #9123]

---
 .../tests/browser/test_builddashboard_page.py      | 251 +++++++++++++++++++++
 lib/toaster/toastergui/tests.py                    |  87 -------
 2 files changed, 251 insertions(+), 87 deletions(-)
 create mode 100644 lib/toaster/tests/browser/test_builddashboard_page.py
lib/toaster/tests/browser/test_builddashboard_page.py new file +251 -0
new file mode 100644
index 0000000..5e08749
@@ -0,0 +1,251 @@
+#! /usr/bin/env python
+# ex:ts=4:sw=4:sts=4:et
+# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
+#
+# BitBake Toaster Implementation
+#
+# Copyright (C) 2013-2016 Intel Corporation
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 as
+# published by the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along
+# with this program; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+from django.core.urlresolvers import reverse
+from django.utils import timezone
+
+from selenium_helpers import SeleniumTestCase
+
+from orm.models import Project, Release, BitbakeVersion, Build, LogMessage
+from orm.models import Layer, Layer_Version, Recipe, CustomImageRecipe
+
+class TestBuildDashboardPage(SeleniumTestCase):
+    """ Tests for the build dashboard /build/X """
+
+    def setUp(self):
+        bbv = BitbakeVersion.objects.create(name='bbv1', giturl='/tmp/',
+                                            branch='master', dirpath="")
+        release = Release.objects.create(name='release1',
+                                         bitbake_version=bbv)
+        project = Project.objects.create_project(name='test project',
+                                                 release=release)
+
+        now = timezone.now()
+
+        self.build1 = Build.objects.create(project=project,
+                                           started_on=now,
+                                           completed_on=now)
+
+        self.build2 = Build.objects.create(project=project,
+                                           started_on=now,
+                                           completed_on=now)
+
+        # exception
+        msg1 = 'an exception was thrown'
+        self.exception_message = LogMessage.objects.create(
+            build=self.build1,
+            level=LogMessage.EXCEPTION,
+            message=msg1
+        )
+
+        # critical
+        msg2 = 'a critical error occurred'
+        self.critical_message = LogMessage.objects.create(
+            build=self.build1,
+            level=LogMessage.CRITICAL,
+            message=msg2
+        )
+
+        # recipes related to the build, for testing the edit custom image/new
+        # custom image buttons
+        layer = Layer.objects.create(name='alayer')
+        layer_version = Layer_Version.objects.create(
+            layer=layer, build=self.build1
+        )
+
+        # image recipes
+        self.image_recipe1 = Recipe.objects.create(
+            name='recipeA',
+            layer_version=layer_version,
+            file_path='/foo/recipeA.bb',
+            is_image=True
+        )
+        self.image_recipe2 = Recipe.objects.create(
+            name='recipeB',
+            layer_version=layer_version,
+            file_path='/foo/recipeB.bb',
+            is_image=True
+        )
+
+        # custom image recipes for this project
+        self.custom_image_recipe1 = CustomImageRecipe.objects.create(
+            name='customRecipeY',
+            project=project,
+            layer_version=layer_version,
+            file_path='/foo/customRecipeY.bb',
+            base_recipe=self.image_recipe1,
+            is_image=True
+        )
+        self.custom_image_recipe2 = CustomImageRecipe.objects.create(
+            name='customRecipeZ',
+            project=project,
+            layer_version=layer_version,
+            file_path='/foo/customRecipeZ.bb',
+            base_recipe=self.image_recipe2,
+            is_image=True
+        )
+
+        # custom image recipe for a different project (to test filtering
+        # of image recipes and custom image recipes is correct: this shouldn't
+        # show up in either query against self.build1)
+        self.custom_image_recipe3 = CustomImageRecipe.objects.create(
+            name='customRecipeOmega',
+            project=Project.objects.create(name='baz', release=release),
+            layer_version=Layer_Version.objects.create(
+                layer=layer, build=self.build2
+            ),
+            file_path='/foo/customRecipeOmega.bb',
+            base_recipe=self.image_recipe2,
+            is_image=True
+        )
+
+        # another non-image recipe (to test filtering of image recipes and
+        # custom image recipes is correct: this shouldn't show up in either
+        # for any build)
+        self.non_image_recipe = Recipe.objects.create(
+            name='nonImageRecipe',
+            layer_version=layer_version,
+            file_path='/foo/nonImageRecipe.bb',
+            is_image=False
+        )
+
+    def _get_build_dashboard(self, build):
+        """
+        Navigate to the build dashboard for build
+        """
+        url = reverse('builddashboard', args=(build.id,))
+        self.get(url)
+
+    def _get_build_dashboard_errors(self, build):
+        """
+        Get a list of HTML fragments representing the errors on the
+        dashboard for the Build object build
+        """
+        self._get_build_dashboard(build)
+        return self.find_all('#errors div.alert-error')
+
+    def _check_for_log_message(self, build, log_message):
+        """
+        Check whether the LogMessage instance <log_message> is
+        represented as an HTML error in the dashboard page for the Build object
+        build
+        """
+        errors = self._get_build_dashboard_errors(build)
+        self.assertEqual(len(errors), 2)
+
+        expected_text = log_message.message
+        expected_id = str(log_message.id)
+
+        found = False
+        for error in errors:
+            error_text = error.find_element_by_tag_name('pre').text
+            text_matches = (error_text == expected_text)
+
+            error_id = error.get_attribute('data-error')
+            id_matches = (error_id == expected_id)
+
+            if text_matches and id_matches:
+                found = True
+                break
+
+        template_vars = (expected_text, error_text,
+                         expected_id, error_id)
+        assertion_error_msg = 'exception not found as error: ' \
+            'expected text "%s" and got "%s"; ' \
+            'expected ID %s and got %s' % template_vars
+        self.assertTrue(found, assertion_error_msg)
+
+    def _check_labels_in_modal(self, modal, expected):
+        """
+        Check that the text values of the <label> elements inside
+        the WebElement modal match the list of text values in expected
+        """
+        # labels containing the radio buttons we're testing for
+        labels = modal.find_elements_by_tag_name('label')
+
+        # because the label content has the structure
+        #   label text
+        #   <input...>
+        # we have to regex on its innerHTML, as we can't just retrieve the
+        # "label text" on its own via the Selenium API
+        labels_text = sorted(map(
+            lambda label: label.get_attribute('innerHTML'), labels
+        ))
+
+        expected = sorted(expected)
+
+        self.assertEqual(len(labels_text), len(expected))
+
+        for idx, label_text in enumerate(labels_text):
+            self.assertRegexpMatches(label_text, expected[idx])
+
+    def test_exceptions_show_as_errors(self):
+        """
+        LogMessages with level EXCEPTION should display in the errors
+        section of the page
+        """
+        self._check_for_log_message(self.build1, self.exception_message)
+
+    def test_criticals_show_as_errors(self):
+        """
+        LogMessages with level CRITICAL should display in the errors
+        section of the page
+        """
+        self._check_for_log_message(self.build1, self.critical_message)
+
+    def test_edit_custom_image_button(self):
+        """
+        A build which built two custom images should present a modal which lets
+        the user choose one of them to edit
+        """
+        self._get_build_dashboard(self.build1)
+        modal = self.driver.find_element_by_id('edit-custom-image-modal')
+
+        # recipes we expect to see in the edit custom image modal
+        expected_recipes = [
+            self.custom_image_recipe1.name,
+            self.custom_image_recipe2.name
+        ]
+
+        self._check_labels_in_modal(modal, expected_recipes)
+
+    def test_new_custom_image_button(self):
+        """
+        Check that a build with multiple images and custom images presents
+        all of them as options for creating a new custom image from
+        """
+        self._get_build_dashboard(self.build1)
+
+        # click the "new custom image" button, which populates the modal
+        selector = '[data-role="new-custom-image-trigger"] button'
+        self.click(selector)
+
+        modal = self.driver.find_element_by_id('new-custom-image-modal')
+
+        # recipes we expect to see in the new custom image modal
+        expected_recipes = [
+            self.image_recipe1.name,
+            self.image_recipe2.name,
+            self.custom_image_recipe1.name,
+            self.custom_image_recipe2.name
+        ]
+
+        self._check_labels_in_modal(modal, expected_recipes)
lib/toaster/toastergui/tests.py +0 -87

90 lines not on this page · raw message

Signature · 1 line
2.5.0