basic_tests.py 11.1 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
from datetime import datetime
20
import logging
21
from sys import _getframe
22 23
import random
import re
24
import urlparse
25

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

29 30 31 32
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
33

34 35
from vm.models import Instance
from .config import SeleniumConfig
36
from .util import CircleSeleniumMixin
37

38
conf = SeleniumConfig()
39 40 41 42 43 44 45
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)
46 47


48
class BasicSeleniumTests(SeleniumTestCase, CircleSeleniumMixin):
49 50 51
    template_ids = []
    vm_ids = []

52 53 54
    def __init__(self, *args, **kwargs):
        super(self.__class__, self).__init__(*args, **kwargs)
        self.conf = conf
55 56 57

    @classmethod
    def setup_class(cls):
58 59
        logger.warning("Selenium test started @ %(time)s" % {
            'time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')})
60
        if conf.create_user:
61 62 63 64
            logger.warning(
                "Creating selenium test user %(name)s:%(password)s" % {
                    'name': conf.client_name,
                    'password': conf.random_pass})
65 66 67 68
            cls._user = User.objects.create(username=conf.client_name,
                                            is_superuser=True)
            cls._user.set_password(conf.random_pass)
            cls._user.save()
69 70 71

    @classmethod
    def teardown_class(cls):
72 73 74
        if conf.create_user:
            for instance in Instance.objects.all().filter(
                    ~Q(status=u'DESTROYED'), owner=cls._user):
75 76 77
                logger.warning(
                    "Destroying the test virtual machine: %(id)s" % {
                        'id': instance.pk})
78
                instance.destroy(system=True)
79 80
            logger.warning("Deleting test user %(name)s" % {
                'name': conf.client_name})
81
            cls._user.delete()
82 83
        logger.warning("Selenium test finished @ %(time)s" % {
            'time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')})
84

85
    def test_01_login(self):
86
        logger.warning("Starting test %s" % _getframe().f_code.co_name)
87 88
        title = 'Dashboard | CIRCLE'
        location = '/dashboard/'
89 90
        self.login()
        self.driver.get('%s/dashboard/' % conf.host)
91 92 93 94 95 96 97
        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):
98
        logger.warning("Starting test %s" % _getframe().f_code.co_name)
99
        self.login()
100 101 102 103 104 105
        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:
106 107 108
            logger.exception("Selenium did not found any templates")
            raise Exception(
                "Selenium did not found any templates")
109
        self.driver.get('%s/dashboard/template/%s/' % (conf.host, chosen))
110
        acces_form_css = (
111 112 113
            "form[action*='/dashboard/template/%(template_id)s/acl/']"
            "[method='post']" % {
                'template_id': chosen})
114
        acces_form = self.driver.find_element_by_css_selector(acces_form_css)
115 116 117 118 119
        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()
120 121
        user_name.send_keys(conf.client_name)
        self.select_option(user_status, 'user')
122 123
        # For strange reasons clicking on submit button doesn't work anymore
        acces_form.submit()
124
        found_users = []
125 126
        acces_form = self.driver.find_element_by_css_selector(acces_form_css)
        acl_users = acces_form.find_elements_by_css_selector(
127 128 129 130 131
            "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()
132 133 134 135
                logger.warning("'%(user)s' found in ACL "
                               "list for template %(id)s" % {
                                   'user': found_name,
                                   'id': chosen})
136
                found_users.append(found_name)
137
        self.assertIn(conf.client_name, found_users,
138 139 140
                      "Could not add user to template's ACL")

    def test_03_able_to_create_template(self):
141
        logger.warning("Starting test %s" % _getframe().f_code.co_name)
142
        self.login()
143 144 145
        template_list = None
        create_template = self.get_link_by_href('/dashboard/template/choose/')
        self.click_on_link(create_template)
146
        WebDriverWait(self.driver, conf.wait_max_sec).until(
147 148 149 150
            ec.visibility_of_element_located((
                By.ID, 'confirmation-modal')))
        template_list = self.driver.find_elements_by_class_name(
            'template-choose-list-element')
151
        logger.warning('Selenium found %(count)s template possibilities' % {
152
            'count': len(template_list)})
153 154 155 156 157 158
        (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):
159
        logger.warning("Starting test %s" % _getframe().f_code.co_name)
160
        self.login()
161 162 163 164 165 166 167
        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,
168
            "Could not found the created template in the template list")
169 170

    def test_05_create_template_from_base(self):
171
        logger.warning("Starting test %s" % _getframe().f_code.co_name)
172
        self.login()
173 174 175 176 177
        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)
178 179
        self.assertTrue(
            found,
180
            "Could not found the created template in the template list")
181

182
    def test_06_delete_templates(self):
183
        logger.warning("Starting test %s" % _getframe().f_code.co_name)
184
        success = False
185
        self.login()
Csók Tamás committed
186
        for template_id in self.template_ids:
187
            logger.warning("Deleting template %s" % template_id)
188
            self.delete_template(template_id)
189 190 191 192
        existing_templates = self.get_template_id()
        if len(existing_templates) == 0:
            success = True
        else:
193 194 195
            for template_id in self.template_ids:
                if template_id not in existing_templates:
                    self.template_ids.remove(template_id)
196 197 198 199 200 201
            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):
202
        logger.warning("Starting test %s" % _getframe().f_code.co_name)
203
        self.login()
204 205 206
        vm_list = None
        create_vm_link = self.get_link_by_href('/dashboard/vm/create/')
        create_vm_link.click()
207
        WebDriverWait(self.driver, conf.wait_max_sec).until(
208 209 210 211
            ec.visibility_of_element_located((
                By.ID, 'confirmation-modal')))
        vm_list = self.driver.find_elements_by_class_name(
            'vm-create-template-summary')
212 213
        logger.warning("Selenium found %(vm_number)s virtual machine"
                       " template possibilities" % {
214
                           'vm_number': len(vm_list)})
215 216 217 218 219
        (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):
220
        logger.warning("Starting test %s" % _getframe().f_code.co_name)
221
        self.login()
222 223 224 225 226
        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):
227
        logger.warning("Starting test %s" % _getframe().f_code.co_name)
228
        self.login()
229 230 231 232
        expected_states = ["", "none",
                           "none", "",
                           "block", "none"]
        states = self.view_change("vm")
233 234
        logger.warning('states: [%s]' % ', '.join(map(str, states)))
        logger.warning('expected: [%s]' % ', '.join(map(str, expected_states)))
235 236 237 238
        self.assertListEqual(states, expected_states,
                             "The view mode does not change for VM listing")

    def test_10_node_view_change(self):
239
        logger.warning("Starting test %s" % _getframe().f_code.co_name)
240
        self.login()
241 242 243 244
        expected_states = ["", "none",
                           "none", "",
                           "block", "none"]
        states = self.view_change("node")
245 246
        logger.warning('states: [%s]' % ', '.join(map(str, states)))
        logger.warning('expected: [%s]' % ', '.join(map(str, expected_states)))
247 248 249 250
        self.assertListEqual(states, expected_states,
                             "The view mode does not change for NODE listing")

    def test_11_delete_vm(self):
251
        logger.warning("Starting test %s" % _getframe().f_code.co_name)
252
        self.login()
253 254 255 256 257 258 259
        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")