test_models.py 17 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# 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/>.

Őry Máté committed
18
from datetime import datetime
19
from mock import Mock, MagicMock, patch, call
20
import types
21

22
from celery.contrib.abortable import AbortableAsyncResult
Őry Máté committed
23
from django.contrib.auth.models import User
24
from django.test import TestCase
Őry Máté committed
25
from django.utils.translation import ugettext_lazy as _
26

Bach Dániel committed
27 28
from common.tests.celery_mock import MockCeleryMixin

Őry Máté committed
29
from ..models import (
30
    Lease, Node, Interface, Instance, InstanceTemplate, InstanceActivity,
31
)
Bach Dániel committed
32
from ..models.instance import find_unused_port, ActivityInProgressError
33
from ..operations import (
Őry Máté committed
34 35
    RemoteOperationMixin, DeployOperation, DestroyOperation, FlushOperation,
    MigrateOperation,
Dudás Ádám committed
36
)
37 38 39 40 41 42 43 44 45 46 47 48


class PortFinderTestCase(TestCase):

    def test_find_unused_port_without_used_ports(self):
        port = find_unused_port(port_range=(1000, 2000))
        assert port is not None

    def test_find_unused_port_with_fully_saturated_range(self):
        r = (10, 20)
        port = find_unused_port(port_range=r, used_ports=range(*r))
        assert port is None
49 50 51


class TemplateTestCase(TestCase):
52

53
    def test_template_creation(self):
54 55
        template = InstanceTemplate(name='My first template',
                                    access_method='ssh', )
Őry Máté committed
56
        template.clean()
57
        # TODO add images & net
58 59


60 61 62
class InstanceTestCase(TestCase):

    def test_is_running(self):
Dudás Ádám committed
63 64
        inst = MagicMock(status='RUNNING')
        self.assertTrue(Instance.is_running.fget(inst))
65

66 67 68 69 70 71
    def test_mon_stopped_while_activity_running(self):
        node = Mock()
        port = Mock()
        inst = MagicMock(spec=Instance, node=node, vnc_port=port)
        inst.save.side_effect = AssertionError
        with patch('vm.models.instance.InstanceActivity') as ia:
Guba Sándor committed
72 73
            ia.create.side_effect = ActivityInProgressError.create(MagicMock())
            Instance.status = 'STOPPED'
74 75 76
        self.assertEquals(inst.node, node)
        self.assertEquals(inst.vnc_port, port)

Őry Máté committed
77 78 79
    def test_deploy_destroyed(self):
        inst = Mock(destroyed_at=datetime.now(), spec=Instance,
                    InstanceDestroyedError=Instance.InstanceDestroyedError)
Dudás Ádám committed
80 81 82 83
        deploy_op = DeployOperation(inst)
        with patch.object(DeployOperation, 'create_activity'):
            with self.assertRaises(Instance.InstanceDestroyedError):
                deploy_op(system=True)
Őry Máté committed
84

Őry Máté committed
85
    def test_destroy_destroyed(self):
Dudás Ádám committed
86 87 88 89 90 91
        inst = Mock(destroyed_at=datetime.now(), spec=Instance,
                    InstanceDestroyedError=Instance.InstanceDestroyedError)
        destroy_op = DestroyOperation(inst)
        with patch.object(DestroyOperation, 'create_activity'):
            with self.assertRaises(Instance.InstanceDestroyedError):
                destroy_op(system=True)
Őry Máté committed
92 93
        self.assertFalse(inst.save.called)

Őry Máté committed
94
    def test_destroy_sets_destroyed(self):
Őry Máté committed
95
        inst = Mock(destroyed_at=None, spec=Instance, _delete_vm=Mock(),
Dudás Ádám committed
96
                    InstanceDestroyedError=Instance.InstanceDestroyedError)
Őry Máté committed
97 98
        inst.node = MagicMock(spec=Node)
        inst.disks.all.return_value = []
Dudás Ádám committed
99 100 101
        destroy_op = DestroyOperation(inst)
        with patch.object(DestroyOperation, 'create_activity'):
            destroy_op(system=True)
Őry Máté committed
102 103 104
        self.assertTrue(inst.destroyed_at)
        inst.save.assert_called()

105
    def test_migrate_with_scheduling(self):
Dudás Ádám committed
106
        inst = Mock(destroyed_at=None, spec=Instance)
107 108
        inst.interface_set.all.return_value = []
        inst.node = MagicMock(spec=Node)
109
        inst.status = 'RUNNING'
Dudás Ádám committed
110
        migrate_op = MigrateOperation(inst)
Őry Máté committed
111 112
        with patch('vm.operations.vm_tasks.migrate') as migr, \
                patch.object(RemoteOperationMixin, "_operation"):
Dudás Ádám committed
113 114 115 116
            act = MagicMock()
            with patch.object(MigrateOperation, 'create_activity',
                              return_value=act):
                migrate_op(system=True)
117 118

            migr.apply_async.assert_called()
119
            inst.allocate_node.assert_called()
120 121 122
            inst.select_node.assert_called()

    def test_migrate_wo_scheduling(self):
Dudás Ádám committed
123
        inst = MagicMock(destroyed_at=None, spec=Instance)
124 125
        inst.interface_set.all.return_value = []
        inst.node = MagicMock(spec=Node)
126
        inst.status = 'RUNNING'
Dudás Ádám committed
127
        migrate_op = MigrateOperation(inst)
Őry Máté committed
128 129
        with patch('vm.operations.vm_tasks.migrate') as migr, \
                patch.object(RemoteOperationMixin, "_operation"):
130
            inst.select_node.side_effect = AssertionError
Dudás Ádám committed
131 132 133 134
            act = MagicMock()
            with patch.object(MigrateOperation, 'create_activity',
                              return_value=act):
                migrate_op(to_node=inst.node, system=True)
135 136

            migr.apply_async.assert_called()
137
            inst.allocate_node.assert_called()
138

Bach Dániel committed
139 140 141 142
    def test_migrate_with_error(self):
        inst = Mock(destroyed_at=None, spec=Instance)
        inst.interface_set.all.return_value = []
        inst.node = MagicMock(spec=Node)
143
        inst.status = 'RUNNING'
Bach Dániel committed
144 145 146
        e = Exception('abc')
        setattr(e, 'libvirtError', '')
        migrate_op = MigrateOperation(inst)
Őry Máté committed
147 148 149
        migrate_op.rollback = Mock()
        with patch('vm.operations.vm_tasks.migrate') as migr, \
                patch.object(RemoteOperationMixin, '_operation') as remop:
Bach Dániel committed
150
            act = MagicMock()
Őry Máté committed
151
            remop.side_effect = e
Bach Dániel committed
152 153 154 155
            with patch.object(MigrateOperation, 'create_activity',
                              return_value=act):
                self.assertRaises(Exception, migrate_op, system=True)

Őry Máté committed
156
            remop.assert_called()
Bach Dániel committed
157
            migr.apply_async.assert_called()
158 159
            self.assertIn(call.sub_activity(
                u'scheduling', readable_name=u'schedule'), act.mock_calls)
Őry Máté committed
160
            migrate_op.rollback.assert_called()
Bach Dániel committed
161 162
            inst.select_node.assert_called()

163 164 165
    def test_status_icon(self):
        inst = MagicMock(spec=Instance)
        inst.status = 'dummy-value'
Kálmán Viktor committed
166
        self.assertEqual(Instance.get_status_icon(inst), 'fa-question')
167
        inst.status = 'RUNNING'
Kálmán Viktor committed
168
        self.assertEqual(Instance.get_status_icon(inst), 'fa-play')
169

170

Bach Dániel committed
171
class InterfaceTestCase(MockCeleryMixin, TestCase):
172 173 174 175 176

    def test_interface_create(self):
        from firewall.models import Vlan, Domain
        owner = User()
        owner.save()
Bach Dániel committed
177
        i = Instance(id=10, owner=owner, access_method='rdp')
178 179
        d = Domain(owner=owner)
        d.save()
180
        v = Vlan(name='vlan', vid=55, network4='127.0.0.1/8',
181
                 network6='2001::1/32', domain=d)
182
        v.full_clean()
183 184
        v.save()
        Interface.create(i, v, managed=True, owner=owner)
Őry Máté committed
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208


class LeaseTestCase(TestCase):

    fixtures = ['lease.json']

    def test_methods(self):
        from datetime import timedelta
        td = timedelta(seconds=1)
        l = Lease.objects.get(pk=1)

        assert "never" not in unicode(l)
        assert l.delete_interval > td
        assert l.suspend_interval > td

        l.delete_interval = None
        assert "never" in unicode(l)
        assert l.delete_interval is None

        l.delete_interval = td * 2
        assert "never" not in unicode(l)

        l.suspend_interval = None
        assert "never" in unicode(l)
Őry Máté committed
209 210 211 212 213 214 215 216


class NodeTestCase(TestCase):

    def test_state(self):
        node = Mock(spec=Node)
        node.online = True
        node.enabled = True
217
        node.schedule_enabled = True
Őry Máté committed
218
        node.STATES = Node.STATES
219 220
        node._get_state = lambda: Node._get_state(node)
        self.assertEqual(Node.get_state(node), "ACTIVE")
Őry Máté committed
221
        assert isinstance(Node.get_status_display(node), _("x").__class__)
222 223 224 225 226 227


class InstanceActivityTestCase(TestCase):

    def test_create_concurrency_check(self):
        instance = MagicMock(spec=Instance)
Őry Máté committed
228 229
        instance.activity_log.filter.return_value.__iter__.return_value = iter(
            [MagicMock(spec=InstanceActivity, interruptible=False)])
230 231 232
        instance.activity_log.filter.return_value.exists.return_value = True

        with self.assertRaises(ActivityInProgressError):
233 234
            InstanceActivity.create('test', instance, readable_name="test",
                                    concurrency_check=True)
235 236 237 238

    def test_create_no_concurrency_check(self):
        instance = MagicMock(spec=Instance)
        instance.activity_log.filter.return_value.exists.return_value = True
239 240 241 242 243 244 245 246
        mock_instance_activity_cls = MagicMock(spec=InstanceActivity,
                                               ACTIVITY_CODE_BASE='test')

        original_create = InstanceActivity.create
        mocked_create = types.MethodType(original_create.im_func,
                                         mock_instance_activity_cls,
                                         original_create.im_class)
        try:
247 248
            mocked_create('test', instance, readable_name="test",
                          concurrency_check=False)
249 250 251
        except ActivityInProgressError:
            raise AssertionError("'create' method checked for concurrent "
                                 "activities.")
252 253 254 255 256 257

    def test_create_sub_concurrency_check(self):
        iaobj = MagicMock(spec=InstanceActivity)
        iaobj.children.filter.return_value.exists.return_value = True

        with self.assertRaises(ActivityInProgressError):
258 259
            InstanceActivity.create_sub(iaobj, "test", readable_name="test",
                                        concurrency_check=True)
260 261 262 263 264 265

    def test_create_sub_no_concurrency_check(self):
        iaobj = MagicMock(spec=InstanceActivity)
        iaobj.activity_code = 'test'
        iaobj.children.filter.return_value.exists.return_value = True

266 267
        create_sub_func = InstanceActivity.create_sub
        with patch('vm.models.activity.InstanceActivity'):
Dudás Ádám committed
268
            try:
269 270
                create_sub_func(iaobj, 'test', readable_name="test",
                                concurrency_check=False)
Dudás Ádám committed
271 272 273
            except ActivityInProgressError:
                raise AssertionError("'create_sub' method checked for "
                                     "concurrent activities.")
274

275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
    def test_is_abortable(self):
        get_op = MagicMock(return_value=MagicMock(abortable=True))
        instance = MagicMock(get_operation_from_activity_code=get_op)
        iaobj = MagicMock(spec=InstanceActivity, activity_code='test',
                          finished=False, instance=instance, task_uuid='test')
        self.assertTrue(InstanceActivity.is_abortable.fget(iaobj))

    def test_not_abortable_when_not_associated_with_task(self):
        get_op = MagicMock(return_value=MagicMock(abortable=True))
        instance = MagicMock(get_operation_from_activity_code=get_op)
        iaobj = MagicMock(spec=InstanceActivity, activity_code='test',
                          finished=False, instance=instance, task_uuid=None)
        self.assertFalse(InstanceActivity.is_abortable.fget(iaobj))

    def test_not_abortable_when_finished(self):
        get_op = MagicMock(return_value=MagicMock(abortable=True))
        instance = MagicMock(get_operation_from_activity_code=get_op)
        iaobj = MagicMock(spec=InstanceActivity, activity_code='test',
                          finished=True, instance=instance, task_uuid='test')
        self.assertFalse(InstanceActivity.is_abortable.fget(iaobj))

    def test_not_abortable_when_operation_not_abortable(self):
        get_op = MagicMock(return_value=MagicMock(abortable=False))
        instance = MagicMock(get_operation_from_activity_code=get_op)
        iaobj = MagicMock(spec=InstanceActivity, activity_code='test',
                          finished=False, instance=instance, task_uuid='test')
        self.assertFalse(InstanceActivity.is_abortable.fget(iaobj))

    def test_not_abortable_when_no_matching_operation(self):
        get_op = MagicMock(return_value=None)
        instance = MagicMock(get_operation_from_activity_code=get_op)
        iaobj = MagicMock(spec=InstanceActivity, activity_code='test',
                          finished=False, instance=instance, task_uuid='test')
        self.assertFalse(InstanceActivity.is_abortable.fget(iaobj))

    def test_not_aborted_when_not_associated_with_task(self):
        iaobj = MagicMock(task_uuid=None)
        self.assertFalse(InstanceActivity.is_aborted.fget(iaobj))

    def test_is_aborted_when_associated_task_is_aborted(self):
        expected = object()
        iaobj = MagicMock(task_uuid='test')
        with patch.object(AbortableAsyncResult, 'is_aborted',
                          return_value=expected):
            self.assertEquals(expected,
                              InstanceActivity.is_aborted.fget(iaobj))

322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
    def test_is_abortable_for_activity_owner_if_not_abortable(self):
        iaobj = MagicMock(spec=InstanceActivity, is_abortable=False,
                          user=MagicMock(spec=User, is_superuser=False))
        self.assertFalse(InstanceActivity.is_abortable_for(iaobj, iaobj.user))

    def test_is_abortable_for_instance_owner(self):
        get_op = MagicMock(return_value=MagicMock(abortable=True))
        instance = MagicMock(get_operation_from_activity_code=get_op,
                             owner=MagicMock(spec=User, is_superuser=False))
        iaobj = MagicMock(spec=InstanceActivity, activity_code='test',
                          finished=False, instance=instance, task_uuid='test',
                          user=MagicMock(spec=User, is_superuser=False))
        self.assertTrue(
            InstanceActivity.is_abortable_for(iaobj, iaobj.instance.owner))

    def test_is_abortable_for_activity_owner(self):
        get_op = MagicMock(return_value=MagicMock(abortable=True))
        instance = MagicMock(get_operation_from_activity_code=get_op)
        iaobj = MagicMock(spec=InstanceActivity, activity_code='test',
                          finished=False, instance=instance, task_uuid='test',
                          user=MagicMock(spec=User, is_superuser=False))
        self.assertTrue(InstanceActivity.is_abortable_for(iaobj, iaobj.user))

    def test_not_abortable_for_foreign(self):
        get_op = MagicMock(return_value=MagicMock(abortable=True))
        instance = MagicMock(get_operation_from_activity_code=get_op)
        iaobj = MagicMock(spec=InstanceActivity, activity_code='test',
                          finished=False, instance=instance, task_uuid='test')
        self.assertFalse(InstanceActivity.is_abortable_for(
            iaobj, MagicMock(spec=User, is_superuser=False)))

    def test_is_abortable_for_superuser(self):
        get_op = MagicMock(return_value=MagicMock(abortable=True))
        instance = MagicMock(get_operation_from_activity_code=get_op)
        iaobj = MagicMock(spec=InstanceActivity, activity_code='test',
                          finished=False, instance=instance, task_uuid='test')
        su = MagicMock(spec=User, is_superuser=True)
        self.assertTrue(InstanceActivity.is_abortable_for(iaobj, su))

Őry Máté committed
361
    def test_disable_enabled(self):
Őry Máté committed
362 363 364
        node = MagicMock(spec=Node, enabled=True, online=True)
        node.instance_set.exists.return_value = False
        Node._ops['disable'](node).check_precond()
Őry Máté committed
365 366 367

    def test_disable_disabled(self):
        node = MagicMock(spec=Node, enabled=False)
Őry Máté committed
368 369
        with self.assertRaises(Exception):
            Node._ops['disable'](node).check_precond()
Őry Máté committed
370 371

    def test_flush(self):
Őry Máté committed
372 373 374
        insts = [MagicMock(spec=Instance, migrate=MagicMock()),
                 MagicMock(spec=Instance, migrate=MagicMock())]
        insts[0].name = insts[1].name = "x"
Őry Máté committed
375
        node = MagicMock(spec=Node, enabled=True, schedule_enabled=True)
376 377
        node.instance_set.all.return_value = insts
        user = MagicMock(spec=User)
Bach Dániel committed
378
        user.is_superuser = MagicMock(return_value=True)
Őry Máté committed
379 380 381 382 383
        with patch.object(FlushOperation, 'create_activity') as create_act, \
                patch.object(
                    Node._ops['passivate'], 'create_activity') as create_act2:
            FlushOperation(node)(user=user)
            node.schedule_enabled = True
384
            create_act.assert_called()
Őry Máté committed
385
            create_act2.assert_called()
Őry Máté committed
386 387
            for i in insts:
                i.migrate.assert_called()
Őry Máté committed
388
            user.is_superuser.assert_called()
Őry Máté committed
389 390

    def test_flush_disabled_wo_user(self):
Őry Máté committed
391 392 393
        insts = [MagicMock(spec=Instance, migrate=MagicMock()),
                 MagicMock(spec=Instance, migrate=MagicMock())]
        insts[0].name = insts[1].name = "x"
Őry Máté committed
394
        node = MagicMock(spec=Node, enabled=False, schedule_enabled=False)
395 396
        node.instance_set.all.return_value = insts
        flush_op = FlushOperation(node)
Őry Máté committed
397

398
        with patch.object(FlushOperation, 'create_activity') as create_act:
Őry Máté committed
399
            create_act.return_value = MagicMock()
400 401
            flush_op(system=True)
            create_act.assert_called()
Őry Máté committed
402 403
            for i in insts:
                i.migrate.assert_called()