basic_tests.py 9.46 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
# 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/>.
19
import logging
20 21
import random
import re
22
import urlparse
23

24 25
from django.contrib.auth.models import User
from django.db.models import Q
Csók Tamás committed
26

27 28 29 30
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.ui import WebDriverWait
from selenose.cases import SeleniumTestCase
31

32 33 34
from vm.models import Instance
from .config import SeleniumConfig
from .util import CircleSeleniumMixin, SeleniumMixin
35

36
conf = SeleniumConfig()
37 38 39 40 41 42 43
log_formatter = logging.Formatter(conf.log_format)
logger = logging.getLogger(conf.logger_name)
fileHandler = logging.handlers.RotatingFileHandler(
    conf.log_file, maxBytes=conf.log_size, backupCount=conf.log_backup)
fileHandler.setFormatter(log_formatter)
fileHandler.setLevel(logging.WARNING)
logger.addHandler(fileHandler)
44 45


46 47 48 49 50 51
class BasicSeleniumTests(SeleniumTestCase, SeleniumMixin, CircleSeleniumMixin):
    def __init__(self, *args, **kwargs):
        super(self.__class__, self).__init__(*args, **kwargs)
        self.conf = conf
        self.template_ids = []
        self.vm_ids = []
52 53 54

    @classmethod
    def setup_class(cls):
55 56 57 58 59
        if conf.create_user:
            cls._user = User.objects.create(username=conf.client_name,
                                            is_superuser=True)
            cls._user.set_password(conf.random_pass)
            cls._user.save()
60 61 62

    @classmethod
    def teardown_class(cls):
63 64 65 66 67
        if conf.create_user:
            for instance in Instance.objects.all().filter(
                    ~Q(status=u'DESTROYED'), owner=cls._user):
                instance.destroy(system=True)
            cls._user.delete()
68

69 70 71
    def test_01_login(self):
        title = 'Dashboard | CIRCLE'
        location = '/dashboard/'
72 73
        self.login()
        self.driver.get('%s/dashboard/' % conf.host)
74 75 76 77 78 79 80
        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):
81
        self.login()
82 83 84 85 86 87
        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:
88 89 90
            logger.exception("Selenium did not found any templates")
            raise Exception(
                "Selenium did not found any templates")
91
        self.driver.get('%s/dashboard/template/%s/' % (conf.host, chosen))
92 93 94 95 96 97 98 99 100
        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()
101 102
        user_name.send_keys(conf.client_name)
        self.select_option(user_status, 'user')
103 104
        # For strange reasons clicking on submit button doesn't work anymore
        acces_form.submit()
105 106 107 108 109 110 111
        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()
112 113 114 115
                logger.warning("'%(user)s' found in ACL "
                               "list for template %(id)s" % {
                                   'user': found_name,
                                   'id': chosen})
116
                found_users.append(found_name)
117
        self.assertIn(conf.client_name, found_users,
118 119 120
                      "Could not add user to template's ACL")

    def test_03_able_to_create_template(self):
121
        self.login()
122 123 124
        template_list = None
        create_template = self.get_link_by_href('/dashboard/template/choose/')
        self.click_on_link(create_template)
125
        WebDriverWait(self.driver, conf.wait_max_sec).until(
126 127 128 129
            ec.visibility_of_element_located((
                By.ID, 'confirmation-modal')))
        template_list = self.driver.find_elements_by_class_name(
            'template-choose-list-element')
130
        logger.warning('Selenium found %(count)s template possibilities' % {
131
            'count': len(template_list)})
132 133 134 135 136 137
        (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):
138
        self.login()
139 140 141 142 143 144 145
        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,
146
            "Could not found the created template in the template list")
147 148

    def test_05_create_template_from_base(self):
149
        self.login()
150 151 152 153 154
        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)
155 156
        self.assertTrue(
            found,
157
            "Could not found the created template in the template list")
158

159 160
    def test_06_delete_templates(self):
        success = False
161
        self.login()
Csók Tamás committed
162
        for template_id in self.template_ids:
163
            logger.warning("Deleting template %s" % template_id)
164
            self.delete_template(template_id)
165 166 167 168
        existing_templates = self.get_template_id()
        if len(existing_templates) == 0:
            success = True
        else:
169 170 171
            for template_id in self.template_ids:
                if template_id not in existing_templates:
                    self.template_ids.remove(template_id)
172 173 174 175 176 177
            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):
178
        self.login()
179 180 181
        vm_list = None
        create_vm_link = self.get_link_by_href('/dashboard/vm/create/')
        create_vm_link.click()
182
        WebDriverWait(self.driver, conf.wait_max_sec).until(
183 184 185 186
            ec.visibility_of_element_located((
                By.ID, 'confirmation-modal')))
        vm_list = self.driver.find_elements_by_class_name(
            'vm-create-template-summary')
187 188 189
        logger.warning("Selenium found %(vm_number)s virtual machine template "
                       " possibilities" % {
                           'vm_number': len(vm_list)})
190 191 192 193 194
        (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):
195
        self.login()
196 197 198 199 200
        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):
201
        self.login()
202 203 204 205
        expected_states = ["", "none",
                           "none", "",
                           "block", "none"]
        states = self.view_change("vm")
206 207
        logger.warning('states: [%s]' % ', '.join(map(str, states)))
        logger.warning('expected: [%s]' % ', '.join(map(str, expected_states)))
208 209 210 211
        self.assertListEqual(states, expected_states,
                             "The view mode does not change for VM listing")

    def test_10_node_view_change(self):
212
        self.login()
213 214 215 216
        expected_states = ["", "none",
                           "none", "",
                           "block", "none"]
        states = self.view_change("node")
217 218
        logger.warning('states: [%s]' % ', '.join(map(str, states)))
        logger.warning('expected: [%s]' % ', '.join(map(str, expected_states)))
219 220 221 222
        self.assertListEqual(states, expected_states,
                             "The view mode does not change for NODE listing")

    def test_11_delete_vm(self):
223
        self.login()
224 225 226 227 228 229 230
        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")