test_models.py 15.1 KB
Newer Older
Őry Máté committed
1
from datetime import datetime
2
from mock import Mock, MagicMock, patch, call
3
import types
4

5
from celery.contrib.abortable import AbortableAsyncResult
Őry Máté committed
6
from django.contrib.auth.models import User
7
from django.test import TestCase
Őry Máté committed
8
from django.utils.translation import ugettext_lazy as _
9

Őry Máté committed
10
from ..models import (
11
    Lease, Node, Interface, Instance, InstanceTemplate, InstanceActivity,
12
)
Bach Dániel committed
13
from ..models.instance import find_unused_port, ActivityInProgressError
14
from ..operations import (
15
    DeployOperation, DestroyOperation, FlushOperation, MigrateOperation,
Dudás Ádám committed
16
)
17 18 19 20 21 22 23 24 25 26 27 28


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


class TemplateTestCase(TestCase):
32

33
    def test_template_creation(self):
34 35
        template = InstanceTemplate(name='My first template',
                                    access_method='ssh', )
Őry Máté committed
36
        template.clean()
37
        # TODO add images & net
38 39


40 41 42 43 44 45
class InstanceTestCase(TestCase):

    def test_is_running(self):
        inst = Mock(state='RUNNING')
        assert Instance.is_running.getter(inst)

46 47 48 49 50 51 52 53 54 55 56
    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:
            ia.create.side_effect = ActivityInProgressError(MagicMock())
            Instance.vm_state_changed(inst, 'STOPPED')
        self.assertEquals(inst.node, node)
        self.assertEquals(inst.vnc_port, port)

Őry Máté committed
57 58 59
    def test_deploy_destroyed(self):
        inst = Mock(destroyed_at=datetime.now(), spec=Instance,
                    InstanceDestroyedError=Instance.InstanceDestroyedError)
Dudás Ádám committed
60 61 62 63
        deploy_op = DeployOperation(inst)
        with patch.object(DeployOperation, 'create_activity'):
            with self.assertRaises(Instance.InstanceDestroyedError):
                deploy_op(system=True)
Őry Máté committed
64

Őry Máté committed
65
    def test_destroy_destroyed(self):
Dudás Ádám committed
66 67 68 69 70 71
        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
72 73
        self.assertFalse(inst.save.called)

Őry Máté committed
74
    def test_destroy_sets_destroyed(self):
Dudás Ádám committed
75 76
        inst = Mock(destroyed_at=None, spec=Instance,
                    InstanceDestroyedError=Instance.InstanceDestroyedError)
Őry Máté committed
77 78
        inst.node = MagicMock(spec=Node)
        inst.disks.all.return_value = []
Dudás Ádám committed
79 80 81
        destroy_op = DestroyOperation(inst)
        with patch.object(DestroyOperation, 'create_activity'):
            destroy_op(system=True)
Őry Máté committed
82 83 84
        self.assertTrue(inst.destroyed_at)
        inst.save.assert_called()

85
    def test_migrate_with_scheduling(self):
Dudás Ádám committed
86
        inst = Mock(destroyed_at=None, spec=Instance)
87 88
        inst.interface_set.all.return_value = []
        inst.node = MagicMock(spec=Node)
Dudás Ádám committed
89 90 91 92 93 94
        migrate_op = MigrateOperation(inst)
        with patch('vm.models.instance.vm_tasks.migrate') as migr:
            act = MagicMock()
            with patch.object(MigrateOperation, 'create_activity',
                              return_value=act):
                migrate_op(system=True)
95 96

            migr.apply_async.assert_called()
Dudás Ádám committed
97
            self.assertIn(call.sub_activity(u'scheduling'), act.mock_calls)
98 99 100
            inst.select_node.assert_called()

    def test_migrate_wo_scheduling(self):
Dudás Ádám committed
101
        inst = MagicMock(destroyed_at=None, spec=Instance)
102 103
        inst.interface_set.all.return_value = []
        inst.node = MagicMock(spec=Node)
Dudás Ádám committed
104 105
        migrate_op = MigrateOperation(inst)
        with patch('vm.models.instance.vm_tasks.migrate') as migr:
106
            inst.select_node.side_effect = AssertionError
Dudás Ádám committed
107 108 109 110
            act = MagicMock()
            with patch.object(MigrateOperation, 'create_activity',
                              return_value=act):
                migrate_op(to_node=inst.node, system=True)
111 112

            migr.apply_async.assert_called()
Dudás Ádám committed
113
            self.assertNotIn(call.sub_activity(u'scheduling'), act.mock_calls)
114

115 116 117 118 119 120 121
    def test_status_icon(self):
        inst = MagicMock(spec=Instance)
        inst.status = 'dummy-value'
        self.assertEqual(Instance.get_status_icon(inst), 'icon-question-sign')
        inst.status = 'RUNNING'
        self.assertEqual(Instance.get_status_icon(inst), 'icon-play')

122

123 124 125 126 127 128
class InterfaceTestCase(TestCase):

    def test_interface_create(self):
        from firewall.models import Vlan, Domain
        owner = User()
        owner.save()
Bach Dániel committed
129
        i = Instance(id=10, owner=owner, access_method='rdp')
130 131 132 133 134 135
        d = Domain(owner=owner)
        d.save()
        v = Vlan(vid=55, network4='127.0.0.1/8',
                 network6='2001::1/32', domain=d)
        v.save()
        Interface.create(i, v, managed=True, owner=owner)
Őry Máté committed
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159


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
160 161 162 163 164 165 166 167 168 169 170


class NodeTestCase(TestCase):

    def test_state(self):
        node = Mock(spec=Node)
        node.online = True
        node.enabled = True
        node.STATES = Node.STATES
        self.assertEqual(Node.get_state(node), "ONLINE")
        assert isinstance(Node.get_status_display(node), _("").__class__)
171 172 173 174 175 176 177 178 179


class InstanceActivityTestCase(TestCase):

    def test_create_concurrency_check(self):
        instance = MagicMock(spec=Instance)
        instance.activity_log.filter.return_value.exists.return_value = True

        with self.assertRaises(ActivityInProgressError):
Dudás Ádám committed
180
            InstanceActivity.create('test', instance, concurrency_check=True)
181 182 183 184

    def test_create_no_concurrency_check(self):
        instance = MagicMock(spec=Instance)
        instance.activity_log.filter.return_value.exists.return_value = True
185 186 187 188 189 190 191 192 193 194 195 196
        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:
            mocked_create('test', instance, concurrency_check=False)
        except ActivityInProgressError:
            raise AssertionError("'create' method checked for concurrent "
                                 "activities.")
197 198 199 200 201 202 203 204 205 206 207 208 209

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

        with self.assertRaises(ActivityInProgressError):
            InstanceActivity.create_sub(iaobj, "test", concurrency_check=True)

    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

210 211
        create_sub_func = InstanceActivity.create_sub
        with patch('vm.models.activity.InstanceActivity'):
Dudás Ádám committed
212
            try:
213
                create_sub_func(iaobj, 'test', concurrency_check=False)
Dudás Ádám committed
214 215 216
            except ActivityInProgressError:
                raise AssertionError("'create_sub' method checked for "
                                     "concurrent activities.")
217

218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
    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))

265 266 267 268 269 270 271 272 273 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
    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
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
    def test_disable_enabled(self):
        node = MagicMock(spec=Node, enabled=True)
        with patch('vm.models.node.node_activity') as nac:
            na = MagicMock()
            nac.return_value = na
            na.__enter__.return_value = MagicMock()
            Node.disable(node)
        self.assertFalse(node.enabled)
        node.save.assert_called_once()
        na.assert_called()

    def test_disable_disabled(self):
        node = MagicMock(spec=Node, enabled=False)
        with patch('vm.models.node.node_activity') as nac:
            na = MagicMock()
            na.__enter__.side_effect = AssertionError
            nac.return_value = na
            Node.disable(node)
        self.assertFalse(node.enabled)

    def test_disable_enabled_sub(self):
        node = MagicMock(spec=Node, enabled=True)
        act = MagicMock()
        subact = MagicMock()
        act.sub_activity.return_value = subact
        Node.disable(node, base_activity=act)
        self.assertFalse(node.enabled)
        subact.__enter__.assert_called()

    def test_flush(self):
Dudás Ádám committed
334 335
        insts = [MagicMock(spec=Instance, migrate=MagicMock()),
                 MagicMock(spec=Instance, migrate=MagicMock())]
336 337 338 339
        node = MagicMock(spec=Node, enabled=True)
        node.instance_set.all.return_value = insts
        user = MagicMock(spec=User)
        flush_op = FlushOperation(node)
Őry Máté committed
340

341 342
        with patch.object(FlushOperation, 'create_activity') as create_act:
            act = create_act.return_value = MagicMock()
Őry Máté committed
343

344
            flush_op(user=user)
Őry Máté committed
345

346
            create_act.assert_called()
Őry Máté committed
347 348 349 350 351
            node.disable.assert_called_with(user, act)
            for i in insts:
                i.migrate.assert_called()

    def test_flush_disabled_wo_user(self):
Dudás Ádám committed
352 353
        insts = [MagicMock(spec=Instance, migrate=MagicMock()),
                 MagicMock(spec=Instance, migrate=MagicMock())]
354 355 356
        node = MagicMock(spec=Node, enabled=False)
        node.instance_set.all.return_value = insts
        flush_op = FlushOperation(node)
Őry Máté committed
357

358 359
        with patch.object(FlushOperation, 'create_activity') as create_act:
            act = create_act.return_value = MagicMock()
Őry Máté committed
360

361
            flush_op(system=True)
Őry Máté committed
362

363
            create_act.assert_called()
Őry Máté committed
364 365 366 367
            node.disable.assert_called_with(None, act)
            # ^ should be called, but real method no-ops if disabled
            for i in insts:
                i.migrate.assert_called()