basic_tests.py 32.2 KB
Newer Older
1 2
#!/usr/bin/env python
# -*- coding: utf-8 -*-
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# Copyright 2014 Budapest University of Technology and Economics (BME IK)
#
# This file is part of CIRCLE Cloud.
#
# CIRCLE is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# CIRCLE 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 CIRCLE.  If not, see <http://www.gnu.org/licenses/>.
from selenose.cases import SeleniumTestCase
20 21 22 23
from django.contrib.auth.models import User
import random
import urlparse
import re
24
import time
25
import logging
26
from selenium.webdriver.support.ui import WebDriverWait
27
from selenium.webdriver.support import expected_conditions as ec
28
from selenium.webdriver.support.select import Select
29
from selenium.webdriver.common.by import By
Csók Tamás committed
30
from datetime import datetime
31
from selenium.common.exceptions import NoSuchElementException
32
logging.getLogger(__name__)
Csók Tamás committed
33 34
random_pass = "".join([random.choice(
    '0123456789abcdefghijklmnopqrstvwxyz') for n in xrange(10)])
35 36
random_accents = random_pass + "".join([random.choice(
    u"áéíöóúűÁÉÍÖÓÜÚŰ") for n in xrange(5)])
Csók Tamás committed
37
wait_max_sec = 10
38
host = 'https:127.0.0.1'
39
client_name = 'test_%s' % random_accents
40 41


42
class UtilityMixin(object):
Csók Tamás committed
43
    def login(self, username, password='password', location=None):
44
        driver = self.driver
Csók Tamás committed
45 46 47 48 49
        if location is None:
            location = '/dashboard/'
        driver.get('%s%s' % (host, location))
        #  Only if we aren't logged in already
        if location not in urlparse.urlparse(self.driver.current_url).path:
50
            try:
Csók Tamás committed
51 52 53
                name_input = driver.find_element_by_id("id_username")
                password_input = driver.find_element_by_id("id_password")
                submit_input = driver.find_element_by_id("submit-id-submit")
54
            except:
Csók Tamás committed
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
                inputs = driver.find_elements_by_tag_name("input")
                for current_input in inputs:
                    input_type = current_input.get_attribute("type")
                    if input_type == "text":
                        name_input = current_input
                    if input_type == "password":
                        password_input = current_input
                    if input_type == "submit":
                        submit_input = current_input
            try:
                name_input.clear()
                name_input.send_keys(username)
                password_input.clear()
                password_input.send_keys(password)
                submit_input.click()
                try:
                    # If selenium runs only in a small (virtual) screen
                    driver.find_element_by_class_name('navbar-toggle').click()
                    WebDriverWait(self.driver, wait_max_sec).until(
74
                        ec.element_to_be_clickable((
Csók Tamás committed
75 76 77 78 79
                            By.CSS_SELECTOR,
                            "a[href*='/dashboard/profile/']")))
                except:
                    time.sleep(0.5)
            except:
80
                logging.exception('Selenium cannot find the form controls')
81

82 83 84 85 86 87 88 89 90 91
    def list_options(self, select):
        try:
            option_dic = {}
            select = Select(select)
            for option in select.options:
                key = option.get_attribute('value')
                if key is not None and key:
                    option_dic[key] = [option.text]
            return option_dic
        except:
92
            logging.exception(
93 94 95
                'Selenium cannot list the select possibilities')

    def select_option(self, select, what=None):
96 97 98 99 100
        """
        From an HTML select imput type try to choose the specified one.
        Select is a selenium web element type. What represent both the
        text of the option and it's ID.
        """
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
        try:
            my_choice = None
            options = self.list_options(select)
            select = Select(select)
            if what is not None:
                for key, value in options.iteritems():
                    if what in key:
                        my_choice = key
                    else:
                        if isinstance(value, list):
                            for single_value in value:
                                if what in single_value:
                                    my_choice = key
                        else:
                            if what in value:
                                my_choice = key
            if my_choice is None:
                my_choose_list = options.keys()
                my_choice = my_choose_list[random.randint(
                    0, len(my_choose_list) - 1)]
            select.select_by_value(my_choice)
        except:
123
            logging.exception(
Csók Tamás committed
124
                'Selenium cannot select the chosen one')
125

126
    def get_link_by_href(self, target_href, attributes=None):
127
        try:
128 129 130
            links = self.driver.find_elements_by_tag_name('a')
            for link in links:
                href = link.get_attribute('href')
131
                if href is not None and href:
132 133 134 135 136
                    if target_href in href:
                        perfect_fit = True
                        if isinstance(attributes, dict):
                            for key, target_value in attributes.iteritems():
                                attr_check = link.get_attribute(key)
137
                                if attr_check is not None and attr_check:
138 139 140 141
                                    if target_value not in attr_check:
                                        perfect_fit = False
                        if perfect_fit:
                            return link
142
        except:
143
            logging.exception(
144
                'Selenium cannot find the href=%s link' % target_href)
145

146 147 148 149 150 151 152
    def click_on_link(self, link):
        """
        There are situations when selenium built in click() function
        doesn't work as intended, that's when this function is used.
        Fires a click event via javascript injection.
        """
        try:
153
            # Javascript function to simulate a click on a link
154 155 156 157 158 159 160 161 162 163 164 165 166 167
            javascript = (
                "var link = arguments[0];"
                "var cancelled = false;"
                "if(document.createEvent) {"
                "   var event = document.createEvent(\"MouseEvents\");"
                "   event.initMouseEvent("
                "       \"click\", true, true, window, 0, 0, 0, 0, 0,"
                "       false,false,false,false,0,null);"
                "   cancelled = !link.dispatchEvent(event);"
                "} else if(link.fireEvent) {"
                "   cancelled = !link.fireEvent(\"onclick\");"
                "} if (!cancelled) {"
                "   window.location = link.href;"
                "}")
168
            self.driver.execute_script(javascript, link)
169
        except:
170
            logging.exception(
171 172 173
                'Selenium cannot inject javascript to the page')

    def wait_and_accept_operation(self, argument=None):
174 175 176 177 178
        """
        Accepts the operation confirmation pop up window.
        Fills out the text inputs before accepting if argument is given.
        """
        try:
179
            accept = WebDriverWait(self.driver, wait_max_sec).until(
180 181
                ec.element_to_be_clickable((
                    By.CLASS_NAME, "modal-accept")))
182 183 184 185 186 187 188 189 190 191 192 193
            if argument is not None:
                possible = self.driver.find_elements_by_css_selector(
                    "div.controls > input[type='text']")
                if isinstance(argument, list):
                    for x in range(0, len(possible)):
                        possible[x].clear()
                        possible[x].send_keys(argument[x % len(argument)])
                else:
                    for form in possible:
                        form.clear()
                        form.send_keys(argument)
            accept.click()
194
        except:
195 196
            logging.exception(
                'Selenium cannot accept the operation confirmation')
197 198 199 200 201 202 203 204 205 206 207 208 209 210

    def save_template_from_vm(self, name):
        try:
            WebDriverWait(self.driver, wait_max_sec).until(
                ec.element_to_be_clickable((
                    By.CSS_SELECTOR,
                    "a[href$='/op/deploy/']")))
            self.click_on_link(self.get_link_by_href("/op/deploy/"))
            self.wait_and_accept_operation()
            recent_deploy = self.recently(self.get_timeline_elements(
                "vm.Instance.deploy"))
            if not self.check_operation_result(recent_deploy):
                print ("Selenium cannot deploy the "
                       "chosen template virtual machine")
211
                logging.exception('Cannot deploy the virtual machine')
212 213 214 215 216 217 218 219 220 221
            self.click_on_link(WebDriverWait(self.driver, wait_max_sec).until(
                ec.element_to_be_clickable((
                    By.CSS_SELECTOR,
                    "a[href$='/op/shut_off/']"))))
            self.wait_and_accept_operation()
            recent_shut_off = self.recently(self.get_timeline_elements(
                "vm.Instance.shut_off"))
            if not self.check_operation_result(recent_shut_off):
                print ("Selenium cannot shut off the "
                       "chosen template virtual machine")
222
                logging.exception('Cannot shut off the virtual machine')
223 224 225 226 227 228 229
            self.click_on_link(WebDriverWait(self.driver, wait_max_sec).until(
                ec.element_to_be_clickable((
                    By.CSS_SELECTOR,
                    "a[href$='/op/save_as_template/']"))))
            self.wait_and_accept_operation(name)
            return name
        except:
230
            logging.exception(
231
                'Selenium cannot save a vm as a template')
232 233 234 235 236

    def create_base_template(self, name=None, architecture="x86-64",
                             method=None, op_system=None, lease=None,
                             network="vm"):
        if name is None:
237
            name = "template_new_%s" % client_name
238
        if op_system is None:
239
            op_system = "!os %s" % client_name
240 241 242 243
        try:
            self.driver.get('%s/dashboard/template/choose/' % host)
            self.driver.find_element_by_css_selector(
                "input[type='radio'][value='base_vm']").click()
Csók Tamás committed
244 245
            self.driver.find_element_by_id(
                "template-choose-next-button").click()
246
            template_name = WebDriverWait(self.driver, wait_max_sec).until(
247
                ec.visibility_of_element_located((
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
                    By.ID, 'id_name')))
            template_name.clear()
            template_name.send_keys(name)
            self.select_option(self.driver.find_element_by_id(
                "id_arch"), architecture)
            self.select_option(self.driver.find_element_by_id(
                "id_access_method"), method)
            system_name = self.driver.find_element_by_id("id_system")
            system_name.clear()
            system_name.send_keys(op_system)
            self.select_option(self.driver.find_element_by_id(
                "id_lease"), lease)
            self.select_option(self.driver.find_element_by_id(
                "id_networks"), network)
            self.driver.find_element_by_css_selector(
                "input.btn[type='submit']").click()
264
            return self.save_template_from_vm(name)
265
        except:
266
            logging.exception(
267 268
                'Selenium cannot create a base template virtual machine')

269 270 271 272 273 274 275
    def get_template_id(self, name=None, from_all=False):
        """
        In default settings find all templates ID in the template list.
        If name is specified searches that specific template's ID
        from_all sets whether to use owned templates or all of them
        Returns list of the templates ID
        """
276 277
        try:
            self.driver.get('%s/dashboard/template/list/' % host)
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
            css_selector_of_a_template = ("a[data-original-title]"
                                          "[href*='/dashboard/template/']")
            if from_all:
                self.select_option(self.driver.find_element_by_id(
                    'id_stype'), "all")
                self.driver.find_element_by_css_selector(
                    "button[type='submit']").click()
                try:
                    WebDriverWait(self.driver, wait_max_sec).until(
                        ec.presence_of_element_located((
                            By.CSS_SELECTOR, css_selector_of_a_template)))
                except:
                    print "Selenium could not locate any templates"
            template_table = self.driver.find_element_by_css_selector(
                "table[class*='template-list-table']")
            templates = template_table.find_elements_by_css_selector("td.name")
294 295
            found_template_ids = []
            for template in templates:
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
                if name is None or name in template.text:
                    try:
                        template_link = template.find_element_by_css_selector(
                            css_selector_of_a_template)
                        template_id = re.search(
                            r'\d+',
                            template_link.get_attribute("outerHTML")).group()
                        found_template_ids.append(template_id)
                        print ("Found '%(name)s' template's ID as %(id)s" % {
                            'name': template.text,
                            'id': template_id})
                    except NoSuchElementException:
                        pass
                    except:
                        raise
311 312 313 314 315 316
            if not found_template_ids and name is not None:
                print ("Selenium could not find the specified "
                       "%(name)s template in the list" % {
                           'name': name})
            return found_template_ids
        except:
317
            logging.exception(
318 319
                'Selenium cannot found the template\'s id')

320 321 322 323
    def check_operation_result(self, operation_id, restore=True):
        """
        Returns wheter the operation_id result is success (returns: boolean)
        """
Csók Tamás committed
324
        try:
325 326 327 328 329 330 331 332 333
            if restore:
                url_base = urlparse.urlparse(self.driver.current_url)
                url_save = ("%(host)s%(url)s" % {
                    'host': host,
                    'url': urlparse.urljoin(url_base.path, url_base.query)})
                if url_base.fragment:
                    url_save = ("%(url)s#%(fragment)s" % {
                        'url': url_save,
                        'fragment': url_base.fragment})
Csók Tamás committed
334 335 336 337
            self.driver.get('%(host)s/dashboard/vm/activity/%(id)s/' % {
                'host': host,
                'id': operation_id})
            result = WebDriverWait(self.driver, wait_max_sec).until(
338
                ec.visibility_of_element_located((
Csók Tamás committed
339
                    By.ID, "activity_status")))
340 341 342
            print ("%(id)s result text is '%(result)s'" % {
                'id': operation_id,
                'result': result.text})
Csók Tamás committed
343 344
            if (result.text == "success"):
                out = True
345 346 347
            elif (result.text == "wait"):
                time.sleep(2)
                out = self.check_operation_result(operation_id, False)
Csók Tamás committed
348 349
            else:
                out = False
350 351 352
            if restore:
                print "Restoring to %s url" % url_save
                self.driver.get(url_save)
Csók Tamás committed
353 354
            return out
        except:
355
            logging.exception(
Csók Tamás committed
356 357 358 359 360 361 362 363 364 365 366
                'Selenium cannot check the result of an operation')

    def recently(self, timeline_dict, second=90):
        try:
            if isinstance(timeline_dict, dict):
                for key, value in timeline_dict.iteritems():
                    time = datetime.strptime(key, '%Y-%m-%d %H:%M')
                    delta = datetime.now() - time
                    if delta.total_seconds() <= second:
                        return value
        except:
367
            logging.exception(
Csók Tamás committed
368 369
                'Selenium cannot filter timeline activities to recent')

370
    def get_timeline_elements(self, code=None):
Csók Tamás committed
371
        try:
372 373 374 375 376 377 378 379 380 381
            if code is None:
                css_activity_selector = "div[data-activity-code]"
                code = "all activity"
            else:
                css_activity_selector = ("div[data-activity-code="
                                         "'%(code)s']" % {
                                             'code': code})
            WebDriverWait(self.driver, wait_max_sec).until(
                ec.element_to_be_clickable((
                    By.CSS_SELECTOR, "a[href*='#activity']"))).click()
Csók Tamás committed
382 383
            activity_dict = {}
            timeline = WebDriverWait(self.driver, wait_max_sec).until(
384
                ec.visibility_of_element_located((
Csók Tamás committed
385 386
                    By.ID, "activity-timeline")))
            searched_activity = timeline.find_elements_by_css_selector(
387
                css_activity_selector)
Csók Tamás committed
388 389 390 391 392 393 394 395 396 397 398 399
            print "Found activity list for %s:" % code
            for activity in searched_activity:
                activity_id = activity.get_attribute('data-activity-id')
                activity_text = activity.text
                key = re.search(
                    r'\d+-\d+-\d+ \d+:\d+,', activity_text).group()[:-1]
                print ("%(id)s @ %(activity)s" % {
                    'id': activity_id,
                    'activity': key})
                activity_dict[key] = activity_id
            return activity_dict
        except:
400
            logging.exception('Selenium cannot find the searched activity')
Csók Tamás committed
401 402

    def create_template_from_base(self, delete_disk=True, name=None):
403
        try:
Csók Tamás committed
404
            if name is None:
405
                name = "template_from_base_%s" % client_name
Csók Tamás committed
406 407 408 409 410 411 412 413 414 415 416 417
            self.driver.get('%s/dashboard/template/choose/' % host)
            choice_list = []
            choices = self.driver.find_elements_by_css_selector(
                "input[type='radio']")
            choice_list = [item for item in choices if (
                'test' not in item.get_attribute('value')
                and item.get_attribute('value') != 'base_vm')]
            chosen = random.randint(0, len(choice_list) - 1)
            choice_list[chosen].click()
            self.driver.find_element_by_id(
                "template-choose-next-button").click()
            if delete_disk:
418 419
                self.click_on_link(
                    self.get_link_by_href("#resources"))
Csók Tamás committed
420
                disks = WebDriverWait(self.driver, wait_max_sec).until(
421
                    ec.visibility_of_element_located((
Csók Tamás committed
422 423 424 425
                        By.ID, 'vm-details-resources-disk')))
                disk_list = disks.find_elements_by_css_selector(
                    "h4[class*='list-group-item-heading']")
                if len(disk_list) > 0:
426 427
                    self.click_on_link(
                        self.get_link_by_href("/op/remove_disk/"))
Csók Tamás committed
428 429
                    self.wait_and_accept_operation()
                    WebDriverWait(self.driver, wait_max_sec).until(
430
                        ec.visibility_of_element_located((
Csók Tamás committed
431 432 433 434 435 436 437
                            By.ID, "_activity")))
                    recent_remove_disk = self.recently(
                        self.get_timeline_elements(
                            "vm.Instance.remove_disk"))
                    if not self.check_operation_result(recent_remove_disk):
                        print ("Selenium cannot delete disk "
                               "of the chosen template")
438
                        logging.exception('Cannot delete disk')
439
                return self.save_template_from_vm(name)
440
        except:
441 442
            logging.exception(
                'Selenium cannot start a template from a base one')
443 444 445 446

    def delete_template(self, template_id):
        try:
            self.driver.get('%s/dashboard/template/%s/' % (host, template_id))
447
            url = urlparse.urlparse(self.driver.current_url)
448 449 450 451 452
            self.click_on_link(
                self.get_link_by_href(
                    "/dashboard/template/delete/%s/" % template_id))
            self.wait_and_accept_operation()
            WebDriverWait(self.driver, wait_max_sec).until(
453
                ec.visibility_of_element_located((
454 455 456
                    By.CLASS_NAME, 'alert-success')))
            url = urlparse.urlparse(self.driver.current_url)
            if "/template/list/" not in url.path:
457 458
                logging.exception(
                    'System does not redirect to template listing')
459
        except:
460
            logging.exception('Selenium cannot delete the desired template')
Csók Tamás committed
461

462 463 464 465 466 467 468 469 470
    def create_random_vm(self):
        try:
            self.driver.get('%s/dashboard/vm/create/' % host)
            vm_list = []
            pk = None
            vm_list = self.driver.find_elements_by_class_name(
                'vm-create-template-summary')
            choice = random.randint(0, len(vm_list) - 1)
            vm_list[choice].click()
471
            WebDriverWait(self.driver, wait_max_sec).until(
472
                ec.element_to_be_clickable((
473
                    By.CLASS_NAME, 'vm-create-start'))).click()
Csók Tamás committed
474
            WebDriverWait(self.driver, wait_max_sec).until(
475
                ec.visibility_of_element_located((
476 477 478 479 480
                    By.CLASS_NAME, 'alert-success')))
            url = urlparse.urlparse(self.driver.current_url)
            pk = re.search(r'\d+', url.path).group()
            return pk
        except:
481
            logging.exception('Selenium cannot start a VM')
482

483
    def view_change(self, target_box):
484 485 486 487 488 489 490 491 492 493 494 495
        driver = self.driver
        driver.get('%s/dashboard/' % host)
        list_view = driver.find_element_by_id('%s-list-view' % target_box)
        graph_view = driver.find_element_by_id('%s-graph-view' % target_box)
        js_script = 'return arguments[0].style.display;'
        required_attributes = {'data-index-box': target_box}
        graph_view_link = self.get_link_by_href(
            '#index-graph-view',
            required_attributes).find_element_by_tag_name('i')
        list_view_link = self.get_link_by_href(
            '#index-list-view',
            required_attributes).find_element_by_tag_name('i')
496
        self.click_on_link(list_view_link)
497 498
        states = [driver.execute_script(js_script, list_view),
                  driver.execute_script(js_script, graph_view)]
499
        self.click_on_link(graph_view_link)
500 501
        states.extend([driver.execute_script(js_script, list_view),
                       driver.execute_script(js_script, graph_view)])
502
        self.click_on_link(list_view_link)
503 504
        states.extend([driver.execute_script(js_script, list_view),
                       driver.execute_script(js_script, graph_view)])
505 506 507 508
        return states

    def delete_vm(self, pk):
        try:
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
            # For relability reasons instead of using the JS operatation
            self.driver.get("%(host)s/dashboard/vm/%(id)s/op/destroy/" % {
                'host': host,
                'id': pk})
            self.wait_and_accept_operation()
            try:
                status_span = WebDriverWait(self.driver, wait_max_sec).until(
                    ec.visibility_of_element_located((
                        By.ID, 'vm-details-state')))
                WebDriverWait(status_span, wait_max_sec).until(
                    ec.visibility_of_element_located((
                        By.CLASS_NAME, 'fa-trash-o')))
            except:
                # Selenium can time-out by not realising the JS refresh
                recent_destroy_vm = self.recently(
                    self.get_timeline_elements("vm.Instance.destroy"))
                if not self.check_operation_result(recent_destroy_vm):
                    print ("Selenium cannot destroy "
                           "the chosen %(id)s vm" % {
                               'id': pk})
529
                    logging.exception('Cannot destroy the specified vm')
530 531 532 533 534 535 536 537 538
            self.driver.get('%s/dashboard/vm/%s/' % (host, pk))
            try:
                WebDriverWait(self.driver, wait_max_sec).until(
                    ec.visibility_of_element_located((
                        By.CSS_SELECTOR,
                        "span[data-status*='DESTROYED']")))
                return True
            except:
                return False
539
        except:
540
            logging.exception("Selenium can not destroy a VM")
541 542 543


class VmDetailTest(UtilityMixin, SeleniumTestCase):
Csók Tamás committed
544
    template_ids = []
545
    vm_ids = []
546 547 548

    @classmethod
    def setup_class(cls):
549
        cls._user = User.objects.create(username=client_name,
550 551 552 553 554 555 556
                                        is_superuser=True)
        cls._user.set_password(random_accents)
        cls._user.save()

    @classmethod
    def teardown_class(cls):
        cls._user.delete()
557

558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
    def test_01_login(self):
        title = 'Dashboard | CIRCLE'
        location = '/dashboard/'
        self.login(client_name, random_accents)
        self.driver.get('%s/dashboard/' % host)
        url = urlparse.urlparse(self.driver.current_url)
        (self.assertIn('%s' % title, self.driver.title,
                       '%s is not found in the title' % title) or
            self.assertEqual(url.path, '%s' % location,
                             'URL path is not equal with %s' % location))

    def test_02_add_template_rights(self):
        self.login(client_name, random_accents)
        template_pool = self.get_template_id(from_all=True)
        if len(template_pool) > 1:
            chosen = template_pool[random.randint(0, len(template_pool) - 1)]
        elif len(template_pool) == 1:
            chosen = template_pool[0]
        else:
            print "Selenium did not found any templates"
578
            logging.exception(
579 580 581 582 583 584 585 586 587 588 589 590 591
                "System did not meet required conditions to continue")
        self.driver.get('%s/dashboard/template/%s/' % (host, chosen))
        acces_form = self.driver.find_element_by_css_selector(
            "form[action*='/dashboard/template/%(template_id)s/acl/']"
            "[method='post']" % {
                'template_id': chosen})
        user_name = acces_form.find_element_by_css_selector(
            "input[type='text'][id='id_name']")
        user_status = acces_form.find_element_by_css_selector(
            "select[name='level']")
        user_name.clear()
        user_name.send_keys(client_name)
        self.select_option(user_status)
592 593
        # For strange reasons clicking on submit button doesn't work anymore
        acces_form.submit()
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
        found_users = []
        acl_users = self.driver.find_elements_by_css_selector(
            "a[href*='/dashboard/profile/']")
        for user in acl_users:
            user_text = re.split(r':[ ]?', user.text)
            if len(user_text) == 2:
                found_name = re.search(r'[\w\W]+(?=\))', user_text[1]).group()
                print ("'%(user)s' found in ACL list for template %(id)s" % {
                    'user': found_name,
                    'id': chosen})
                found_users.append(found_name)
        self.assertIn(client_name, found_users,
                      "Could not add user to template's ACL")

    def test_03_able_to_create_template(self):
        self.login(client_name, random_accents)
        template_list = None
        create_template = self.get_link_by_href('/dashboard/template/choose/')
        self.click_on_link(create_template)
        WebDriverWait(self.driver, wait_max_sec).until(
            ec.visibility_of_element_located((
                By.ID, 'confirmation-modal')))
        template_list = self.driver.find_elements_by_class_name(
            'template-choose-list-element')
        print 'Selenium found %s template possibilities' % len(template_list)
        (self.assertIsNotNone(
            template_list, "Selenium can not find the create template list") or
            self.assertGreater(len(template_list), 0,
                               "The create template list is empty"))

    def test_04_create_base_template(self):
        self.login(client_name, random_accents)
        created_template_id = self.get_template_id(
            self.create_base_template())
        found = created_template_id is not None
        if found:
            self.template_ids.extend(created_template_id)
        self.assertTrue(
            found,
633
            "Could not found the created template in the template list")
634 635 636

    def test_05_create_template_from_base(self):
        self.login(client_name, random_accents)
637 638 639 640 641
        created_template_id = self.get_template_id(
            self.create_template_from_base())
        found = created_template_id is not None
        if found:
            self.template_ids.extend(created_template_id)
642 643
        self.assertTrue(
            found,
644
            "Could not found the created template in the template list")
645

646 647 648
    def test_06_delete_templates(self):
        success = False
        self.login(client_name, random_accents)
Csók Tamás committed
649
        for template_id in self.template_ids:
650
            print "Deleting template %s" % template_id
651
            self.delete_template(template_id)
652 653 654 655
        existing_templates = self.get_template_id()
        if len(existing_templates) == 0:
            success = True
        else:
656 657 658
            for template_id in self.template_ids:
                if template_id not in existing_templates:
                    self.template_ids.remove(template_id)
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
            if len(self.template_ids) == 0:
                success = True
        self.assertTrue(
            success, "Could not delete (all) the test template(s)")

    def test_07_able_to_create_vm(self):
        self.login(client_name, random_accents)
        vm_list = None
        create_vm_link = self.get_link_by_href('/dashboard/vm/create/')
        create_vm_link.click()
        WebDriverWait(self.driver, wait_max_sec).until(
            ec.visibility_of_element_located((
                By.ID, 'confirmation-modal')))
        vm_list = self.driver.find_elements_by_class_name(
            'vm-create-template-summary')
        print ("Selenium found %(vm_number)s virtual machine template "
               " possibilities" % {
                   'vm_number': len(vm_list)})
        (self.assertIsNotNone(
            vm_list, "Selenium can not find the VM list") or
            self.assertGreater(len(vm_list), 0, "The create VM list is empty"))

    def test_08_create_vm(self):
        self.login(client_name, random_accents)
        pk = self.create_random_vm()
        self.vm_ids.append(pk)
        self.assertIsNotNone(pk, "Can not create a VM")

    def test_09_vm_view_change(self):
        self.login(client_name, random_accents)
        expected_states = ["", "none",
                           "none", "",
                           "block", "none"]
        states = self.view_change("vm")
        print 'states: [%s]' % ', '.join(map(str, states))
        print 'expected: [%s]' % ', '.join(map(str, expected_states))
        self.assertListEqual(states, expected_states,
                             "The view mode does not change for VM listing")

    def test_10_node_view_change(self):
        self.login(client_name, random_accents)
        expected_states = ["", "none",
                           "none", "",
                           "block", "none"]
        states = self.view_change("node")
        print 'states: [%s]' % ', '.join(map(str, states))
        print 'expected: [%s]' % ', '.join(map(str, expected_states))
        self.assertListEqual(states, expected_states,
                             "The view mode does not change for NODE listing")

    def test_11_delete_vm(self):
        self.login(client_name, random_accents)
        succes = True
        for vm in self.vm_ids:
            if not self.delete_vm(vm):
                succes = False
            else:
                self.vm_ids.remove(vm)
        self.assertTrue(succes, "Can not delete all VM")