test_mockedviews.py 26.7 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/>.

18
import unittest
19 20
import warnings

21 22 23 24
from factory import Factory, Sequence
from mock import patch, MagicMock

from django.contrib.auth.models import User
25
from django.core.exceptions import PermissionDenied
26
from django.core.signing import TimestampSigner, JSONSerializer, b64_encode
27
from django.http import HttpRequest, Http404, QueryDict
28
from django.utils import baseconv
29

30
from ..models import Profile
31
from ..views import InstanceActivityDetail, InstanceActivity
Őry Máté committed
32
from ..views import vm_ops, vm_mass_ops, Instance, UnsubscribeFormView
33
from ..views import AclUpdateView
34
from .. import views
35 36


37 38 39 40 41 42 43
class QuerySet(list):
    model = MagicMock()

    def get(self, *args, **kwargs):
        return self.pop()


44 45 46 47 48 49 50 51 52 53 54
class ViewUserTestCase(unittest.TestCase):

    def test_404(self):
        view = InstanceActivityDetail.as_view()
        request = FakeRequestFactory(superuser=True)
        with self.assertRaises(Http404):
            view(request, pk=1234)

    def test_not_superuser(self):
        request = FakeRequestFactory(superuser=False)
        with patch.object(InstanceActivityDetail, 'get_object') as go:
Dóbé Péter committed
55 56
            go.return_value = MagicMock(spec=InstanceActivity,
                                        activity_code='test.test')
57 58
            go.return_value._meta.object_name = "InstanceActivity"
            view = InstanceActivityDetail.as_view()
Őry Máté committed
59
            self.assertEquals(view(request, pk=1234).status_code, 200)
60 61 62 63 64

    def test_found(self):
        request = FakeRequestFactory(superuser=True)

        with patch.object(InstanceActivityDetail, 'get_object') as go:
Dóbé Péter committed
65 66
            act = MagicMock(spec=InstanceActivity,
                            activity_code='test.test')
67
            act._meta.object_name = "InstanceActivity"
Kálmán Viktor committed
68
            act.user.pk = 1
69 70 71 72 73
            go.return_value = act
            view = InstanceActivityDetail.as_view()
            self.assertEquals(view(request, pk=1234).render().status_code, 200)


74 75 76 77 78
class ExpiredSigner(TimestampSigner):
    def timestamp(self):
        return baseconv.base62.encode(1)

    @classmethod
Őry Máté committed
79 80
    def dumps(cls, obj, key=None, salt='django.core.signing',
              serializer=JSONSerializer, compress=False):
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
            data = serializer().dumps(obj)
            base64d = b64_encode(data)
            return cls(key, salt=salt).sign(base64d)


class SubscribeTestCase(unittest.TestCase):

    @patch.object(views.UnsubscribeFormView, 'get_queryset')
    @patch.object(views.UnsubscribeFormView, 'form_valid')
    def test_change(self, iv, gq):
            view = views.UnsubscribeFormView.as_view()
            p = MagicMock(spec=Profile, email_notifications=True)
            gq.return_value.get.return_value = p
            token = UnsubscribeFormView.get_token(MagicMock(pk=1))
            request = FakeRequestFactory(POST={})
            self.assertEquals(view(request, token=token), iv.return_value)
            gq.return_value.get.assert_called_with(user_id=1)

    @patch.object(views.UnsubscribeFormView, 'get_queryset')
    @patch.object(views.UnsubscribeFormView, 'form_valid')
    def test_change_to_true(self, iv, gq):
            view = views.UnsubscribeFormView.as_view()
            p = MagicMock(spec=Profile, email_notifications=False)
            gq.return_value.get.return_value = p
            token = UnsubscribeFormView.get_token(MagicMock(pk=1))
            request = FakeRequestFactory(POST={'email_notifications': 'on'})
            self.assertEquals(view(request, token=token), iv.return_value)
            gq.return_value.get.assert_called_with(user_id=1)

    def test_404_for_invalid_token(self):
        view = UnsubscribeFormView.as_view()
        request = FakeRequestFactory()
        with self.assertRaises(Http404):
            view(request, token="foo:bar")

    def test_redirect_for_old_token(self):
        oldtoken = ExpiredSigner.dumps(1, salt=UnsubscribeFormView.get_salt())
        view = UnsubscribeFormView.as_view()
        request = FakeRequestFactory()
        assert view(request, token=oldtoken)['location']

    def test_post_redirect_for_old_token(self):
        oldtoken = ExpiredSigner.dumps(1, salt=UnsubscribeFormView.get_salt())
        view = UnsubscribeFormView.as_view()
        request = FakeRequestFactory(POST={})
        assert view(request, token=oldtoken)['location']

Őry Máté committed
128

129
class VmOperationViewTestCase(unittest.TestCase):
130

131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
    def test_available(self):
        request = FakeRequestFactory(superuser=True)
        view = vm_ops['destroy']

        with patch.object(view, 'get_object') as go:
            inst = MagicMock(spec=Instance)
            inst._meta.object_name = "Instance"
            inst.destroy = Instance._ops['destroy'](inst)
            go.return_value = inst
            self.assertEquals(
                view.as_view()(request, pk=1234).render().status_code, 200)

    def test_unpermitted(self):
        request = FakeRequestFactory()
        view = vm_ops['destroy']

        with patch.object(view, 'get_object') as go:
            inst = MagicMock(spec=Instance)
            inst._meta.object_name = "Instance"
            inst.destroy = Instance._ops['destroy'](inst)
            inst.has_level.return_value = False
            go.return_value = inst
            with self.assertRaises(PermissionDenied):
                view.as_view()(request, pk=1234).render()

156
    def test_migrate(self):
157 158
        request = FakeRequestFactory(
            POST={'to_node': 1, 'live_migration': True}, superuser=True)
159
        view = vm_ops['migrate']
160
        node = MagicMock(pk=1, name='node1')
161 162

        with patch.object(view, 'get_object') as go, \
Őry Máté committed
163
                patch('dashboard.views.util.messages') as msg, \
164
                patch.object(view, 'get_form_kwargs') as form_kwargs:
165 166 167 168 169
            inst = MagicMock(spec=Instance)
            inst._meta.object_name = "Instance"
            inst.migrate = Instance._ops['migrate'](inst)
            inst.migrate.async = MagicMock()
            inst.has_level.return_value = True
170 171
            form_kwargs.return_value = {
                'default': 100, 'choices': QuerySet([node])}
172 173 174
            go.return_value = inst
            assert view.as_view()(request, pk=1234)['location']
            assert not msg.error.called
175 176
            inst.migrate.async.assert_called_once_with(
                to_node=node, live_migration=True, user=request.user)
177 178

    def test_migrate_failed(self):
179
        request = FakeRequestFactory(POST={'to_node': 1}, superuser=True)
180
        view = vm_ops['migrate']
181
        node = MagicMock(pk=1, name='node1')
182 183

        with patch.object(view, 'get_object') as go, \
Őry Máté committed
184
                patch('dashboard.views.util.messages') as msg, \
185
                patch.object(view, 'get_form_kwargs') as form_kwargs:
186 187 188 189 190 191
            inst = MagicMock(spec=Instance)
            inst._meta.object_name = "Instance"
            inst.migrate = Instance._ops['migrate'](inst)
            inst.migrate.async = MagicMock()
            inst.migrate.async.side_effect = Exception
            inst.has_level.return_value = True
192 193
            form_kwargs.return_value = {
                'default': 100, 'choices': QuerySet([node])}
194 195
            go.return_value = inst
            assert view.as_view()(request, pk=1234)['location']
196
            assert inst.migrate.async.called
197 198
            assert msg.error.called

199
    def test_migrate_wo_permission(self):
200
        request = FakeRequestFactory(POST={'to_node': 1}, superuser=False)
201
        view = vm_ops['migrate']
202
        node = MagicMock(pk=1, name='node1')
203 204

        with patch.object(view, 'get_object') as go, \
205
                patch.object(view, 'get_form_kwargs') as form_kwargs:
206 207 208 209 210
            inst = MagicMock(spec=Instance)
            inst._meta.object_name = "Instance"
            inst.migrate = Instance._ops['migrate'](inst)
            inst.migrate.async = MagicMock()
            inst.has_level.return_value = True
211 212
            form_kwargs.return_value = {
                'default': 100, 'choices': QuerySet([node])}
213 214 215
            go.return_value = inst
            with self.assertRaises(PermissionDenied):
                assert view.as_view()(request, pk=1234)['location']
216
            assert not inst.migrate.async.called
217

218
    def test_migrate_template(self):
219
        """check if GET dialog's template can be rendered"""
Bach Dániel committed
220
        request = FakeRequestFactory(superuser=True)
221 222 223 224 225 226 227 228 229 230
        view = vm_ops['migrate']

        with patch.object(view, 'get_object') as go:
            inst = MagicMock(spec=Instance)
            inst._meta.object_name = "Instance"
            inst.migrate = Instance._ops['migrate'](inst)
            inst.has_level.return_value = True
            go.return_value = inst
            self.assertEquals(
                view.as_view()(request, pk=1234).render().status_code, 200)
231

Őry Máté committed
232
    def test_save_as_wo_name(self):
Bach Dániel committed
233
        request = FakeRequestFactory(POST={}, has_perms_mock=True)
Őry Máté committed
234 235 236
        view = vm_ops['save_as_template']

        with patch.object(view, 'get_object') as go, \
Őry Máté committed
237
                patch('dashboard.views.util.messages') as msg:
Őry Máté committed
238
            inst = MagicMock(spec=Instance)
Őry Máté committed
239
            inst.name = "asd"
Őry Máté committed
240 241 242 243 244
            inst._meta.object_name = "Instance"
            inst.save_as_template = Instance._ops['save_as_template'](inst)
            inst.save_as_template.async = MagicMock()
            inst.has_level.return_value = True
            go.return_value = inst
245
            assert view.as_view()(request, pk=1234)
Őry Máté committed
246 247 248
            assert not msg.error.called

    def test_save_as_w_name(self):
249 250
        request = FakeRequestFactory(POST={'name': 'foobar'},
                                     has_perms_mock=True)
Őry Máté committed
251 252 253
        view = vm_ops['save_as_template']

        with patch.object(view, 'get_object') as go, \
Őry Máté committed
254
                patch('dashboard.views.util.messages') as msg:
Őry Máté committed
255
            inst = MagicMock(spec=Instance)
Őry Máté committed
256
            inst.name = "asd"
Őry Máté committed
257 258 259 260 261 262 263 264 265
            inst._meta.object_name = "Instance"
            inst.save_as_template = Instance._ops['save_as_template'](inst)
            inst.save_as_template.async = MagicMock()
            inst.has_level.return_value = True
            go.return_value = inst
            assert view.as_view()(request, pk=1234)['location']
            assert not msg.error.called

    def test_save_as_template(self):
Bach Dániel committed
266
        request = FakeRequestFactory(has_perms_mock=True)
Őry Máté committed
267 268 269 270 271 272 273 274 275 276 277 278
        view = vm_ops['save_as_template']

        with patch.object(view, 'get_object') as go:
            inst = MagicMock(spec=Instance)
            inst._meta.object_name = "Instance"
            inst.name = 'foo'
            inst.save_as_template = Instance._ops['save_as_template'](inst)
            inst.has_level.return_value = True
            go.return_value = inst
            rend = view.as_view()(request, pk=1234).render()
            self.assertEquals(rend.status_code, 200)

Őry Máté committed
279

Őry Máté committed
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 322
class VmMassOperationViewTestCase(unittest.TestCase):

    def test_available(self):
        request = FakeRequestFactory(superuser=True)
        view = vm_mass_ops['destroy']

        with patch.object(view, 'get_object') as go:
            inst = MagicMock(spec=Instance)
            inst._meta.object_name = "Instance"
            inst.destroy = Instance._ops['destroy'](inst)
            go.return_value = [inst]
            self.assertEquals(
                view.as_view()(request, pk=1234).render().status_code, 200)

    def test_unpermitted_choice(self):
        "User has user level, but not the needed ownership."
        request = FakeRequestFactory()
        view = vm_mass_ops['destroy']

        with patch.object(view, 'get_object') as go:
            inst = MagicMock(spec=Instance)
            inst._meta.object_name = "Instance"
            inst.has_level = lambda self, l: {"user": True, "owner": False}[l]
            inst.destroy = Instance._ops['destroy'](inst)
            inst.destroy._operate = MagicMock()
            go.return_value = [inst]
            view.as_view()(request, pk=1234).render()
            assert not inst.destroy._operate.called

    def test_unpermitted(self):
        request = FakeRequestFactory()
        view = vm_mass_ops['destroy']

        with patch.object(view, 'get_object') as go:
            inst = MagicMock(spec=Instance)
            inst._meta.object_name = "Instance"
            inst.destroy = Instance._ops['destroy'](inst)
            inst.has_level.return_value = False
            go.return_value = [inst]
            with self.assertRaises(PermissionDenied):
                view.as_view()(request, pk=1234).render()

    def test_migrate(self):
323
        request = FakeRequestFactory(POST={'to_node': 1}, superuser=True)
Őry Máté committed
324 325 326
        view = vm_mass_ops['migrate']

        with patch.object(view, 'get_object') as go, \
Őry Máté committed
327 328
                patch('dashboard.views.util.messages') as msg, \
                patch('dashboard.views.vm.messages') as msg2:
Őry Máté committed
329 330 331 332 333 334 335 336
            inst = MagicMock(spec=Instance)
            inst._meta.object_name = "Instance"
            inst.migrate = Instance._ops['migrate'](inst)
            inst.migrate.async = MagicMock()
            inst.has_level.return_value = True
            go.return_value = [inst]
            assert view.as_view()(request, pk=1234)['location']
            assert not msg.error.called
Őry Máté committed
337
            assert not msg2.error.called
Őry Máté committed
338 339

    def test_migrate_failed(self):
340
        request = FakeRequestFactory(POST={'to_node': 1}, superuser=True)
Őry Máté committed
341 342 343
        view = vm_mass_ops['migrate']

        with patch.object(view, 'get_object') as go, \
Őry Máté committed
344
                patch('dashboard.views.vm.messages') as msg:
Őry Máté committed
345 346 347 348 349 350 351 352 353 354 355
            inst = MagicMock(spec=Instance)
            inst._meta.object_name = "Instance"
            inst.migrate = Instance._ops['migrate'](inst)
            inst.migrate.async = MagicMock()
            inst.migrate.async.side_effect = Exception
            inst.has_level.return_value = True
            go.return_value = [inst]
            assert view.as_view()(request, pk=1234)['location']
            assert msg.error.called

    def test_migrate_wo_permission(self):
356
        request = FakeRequestFactory(POST={'to_node': 1}, superuser=False)
Őry Máté committed
357 358
        view = vm_mass_ops['migrate']

Őry Máté committed
359
        with patch.object(view, 'get_object') as go:
Őry Máté committed
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
            inst = MagicMock(spec=Instance)
            inst._meta.object_name = "Instance"
            inst.migrate = Instance._ops['migrate'](inst)
            inst.migrate.async = MagicMock()
            inst.has_level.return_value = True
            go.return_value = [inst]
            with self.assertRaises(PermissionDenied):
                assert view.as_view()(request, pk=1234)['location']

    def test_migrate_template(self):
        """check if GET dialog's template can be rendered"""
        request = FakeRequestFactory(superuser=True)
        view = vm_mass_ops['migrate']

        with patch.object(view, 'get_object') as go:
            inst = MagicMock(spec=Instance)
            inst._meta.object_name = "Instance"
            inst.migrate = Instance._ops['migrate'](inst)
            inst.has_level.return_value = True
            go.return_value = [inst]
            self.assertEquals(
                view.as_view()(request, pk=1234).render().status_code, 200)


384 385 386 387 388 389 390 391 392 393
class RenewViewTest(unittest.TestCase):

    def test_renew_template(self):
        request = FakeRequestFactory(has_perms_mock=True)
        view = vm_ops['renew']

        with patch.object(view, 'get_object') as go:
            inst = MagicMock(spec=Instance)
            inst._meta.object_name = "Instance"
            inst.name = 'foo'
Bach Dániel committed
394
            inst.lease = MagicMock(pk=99)
395 396 397 398 399 400 401 402 403 404 405
            inst.renew = Instance._ops['renew'](inst)
            inst.has_level.return_value = True
            go.return_value = inst
            rend = view.as_view()(request, pk=1234).render()
            self.assertEquals(rend.status_code, 200)

    def test_renew_by_owner_wo_param(self):
        request = FakeRequestFactory(POST={}, has_perms_mock=True)
        view = vm_ops['renew']

        with patch.object(view, 'get_object') as go, \
Őry Máté committed
406
                patch('dashboard.views.util.messages') as msg:
407 408
            inst = MagicMock(spec=Instance)
            inst._meta.object_name = "Instance"
Bach Dániel committed
409
            inst.lease = MagicMock(pk=99)
410 411 412 413
            inst.renew = Instance._ops['renew'](inst)
            inst.renew.async = MagicMock()
            inst.has_level.return_value = True
            go.return_value = inst
414 415 416 417
            assert view.as_view()(request, pk=1234)
            assert not msg.error.called
            assert inst.renew.async.called_with(user=request.user, lease=None)
            assert inst.renew.async.return_value.get.called
418 419 420 421 422 423 424
            # success would redirect

    def test_renew_by_owner_w_param(self):
        request = FakeRequestFactory(POST={'length': 1}, has_perms_mock=True)
        view = vm_ops['renew']

        with patch.object(view, 'get_object') as go, \
Őry Máté committed
425
                patch('dashboard.views.util.messages') as msg:
426 427
            inst = MagicMock(spec=Instance)
            inst._meta.object_name = "Instance"
Bach Dániel committed
428
            inst.lease = MagicMock(pk=99)
429 430 431 432 433 434 435 436 437 438 439
            inst.renew = Instance._ops['renew'](inst)
            inst.renew.async = MagicMock()
            inst.has_level.return_value = True
            go.return_value = inst
            assert view.as_view()(request, pk=1234)
            assert not msg.error.called

    def test_renew_get_by_anon_wo_key(self):
        request = FakeRequestFactory(authenticated=False)
        view = vm_ops['renew']

Őry Máté committed
440
        with patch.object(view, 'get_object') as go:
441 442 443 444 445 446 447 448 449 450 451 452 453
            inst = MagicMock(spec=Instance)
            inst._meta.object_name = "Instance"
            inst.renew = Instance._ops['renew'](inst)
            inst.renew.async = MagicMock()
            inst.has_level.return_value = False
            go.return_value = inst
            self.assertIn('login',
                          view.as_view()(request, pk=1234)['location'])

    def test_renew_get_by_nonowner_wo_key(self):
        request = FakeRequestFactory(has_perms_mock=True)
        view = vm_ops['renew']

Őry Máté committed
454
        with patch.object(view, 'get_object') as go:
455 456 457 458 459 460 461 462 463 464 465 466 467
            inst = MagicMock(spec=Instance)
            inst._meta.object_name = "Instance"
            inst.renew = Instance._ops['renew'](inst)
            inst.renew.async = MagicMock()
            inst.has_level.return_value = False
            go.return_value = inst
            with self.assertRaises(PermissionDenied):
                assert view.as_view()(request, pk=1234)

    def test_renew_post_by_nonowner_wo_key(self):
        request = FakeRequestFactory(POST={'length': 1}, has_perms_mock=True)
        view = vm_ops['renew']

Őry Máté committed
468
        with patch.object(view, 'get_object') as go:
469 470
            inst = MagicMock(spec=Instance, pk=11)
            inst._meta.object_name = "Instance"
Bach Dániel committed
471
            inst.lease = MagicMock(pk=99)
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
            inst.renew = Instance._ops['renew'](inst)
            inst.renew.async = MagicMock()
            inst.has_level.return_value = False
            go.return_value = inst
            with self.assertRaises(PermissionDenied):
                assert view.as_view()(request, pk=1234)

    def test_renew_get_by_nonowner_w_key(self):
        user = FakeRequestFactory(superuser=True).user
        view = vm_ops['renew']
        inst = MagicMock(spec=Instance, pk=11)
        inst._meta.object_name = "Instance"
        inst.renew = Instance._ops['renew'](inst)
        inst.renew.async = MagicMock()
        key = view.get_token_url(inst, user).split('?')[1].split('=')[1]
        request = FakeRequestFactory(GET={'k': key})  # other user!

        with patch.object(view, 'get_object') as go, \
                patch('dashboard.views.User.objects') as gu, \
                patch('dashboard.views.Lease.get_objects_with_level') as gol:
            gol.return_value = views.Lease.objects.all()
            gu.get.return_value = user
            go.return_value = inst
            assert view.as_view()(request, pk=1234).render().status_code == 200

    def test_renew_post_by_anon_w_key(self):
        user = FakeRequestFactory(authenticated=True).user
        view = vm_ops['renew']
        inst = MagicMock(spec=Instance, pk=11)
        inst._meta.object_name = "Instance"
        inst.renew = Instance._ops['renew'](inst)
        inst.renew.async = MagicMock()
        inst.has_level = lambda user, level: user.is_authenticated()
        key = view.get_token_url(inst, user).split('?')[1].split('=')[1]
        request = FakeRequestFactory(GET={'k': key}, authenticated=False)

        with patch.object(view, 'get_object') as go, \
                patch('dashboard.views.Lease.get_objects_with_level') as gol:
            go.return_value = inst
            gol.return_value = views.Lease.objects.all()
            assert view.as_view()(request, pk=1234).render().status_code == 200

    def test_renew_post_by_anon_w_invalid_key(self):
        view = vm_ops['renew']
        key = "invalid"
        inst = MagicMock(spec=Instance, pk=11)
        inst._meta.object_name = "Instance"
        inst.renew = Instance._ops['renew'](inst)
        inst.renew.async = MagicMock()
        inst.has_level.return_value = False
        request = FakeRequestFactory(GET={'k': key}, authenticated=False)
        with patch.object(view, 'get_object') as go:
            go.return_value = inst
            self.assertIn('login',
                          view.as_view()(request, pk=1234)['location'])

    def test_renew_post_by_anon_w_expired_key(self):

        def side(max_age=None, *args, **kwargs):
            if max_age:
                raise views.signing.BadSignature

        user = FakeRequestFactory(authenticated=False).user
        view = vm_ops['renew']
        inst = MagicMock(spec=Instance, pk=11)
        inst._meta.object_name = "Instance"
        inst.renew = Instance._ops['renew'](inst)
        inst.renew.async = MagicMock()
        inst.has_level.return_value = False
        key = view.get_token_url(inst, user).split('?')[1].split('=')[1]
        with patch('dashboard.views.signing.loads') as loader, \
                patch.object(view, 'get_object') as go:
            loader.return_value = (inst.pk, user.pk)

            loader.side_effect = side
            request = FakeRequestFactory(GET={'k': key}, user=user)
            go.return_value = inst
            self.assertIn('login',
                          view.as_view()(request, pk=1234)['location'])


553 554 555 556 557 558 559 560 561 562 563 564 565
class AclUpdateViewTest(unittest.TestCase):
    def test_has_next_level(self):
        data = {None: 'user', 'user': 'operator', 'operator': 'owner',
                'owner': 'owner'}
        for k, v in data.items():
            inst = MagicMock(spec=Instance)
            inst.has_level.return_value = True
            inst.ACL_LEVELS = Instance.ACL_LEVELS

            self.assertTrue(AclUpdateView.has_next_level('dummy', inst, k))
            inst.has_level.assert_called_with('dummy', v)

    def test_set_level_mod_owner(self):
Őry Máté committed
566
        with patch('dashboard.views.util.messages') as msg:
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
            request = FakeRequestFactory(POST={})

            inst = MagicMock(spec=Instance)
            inst.owner = request.user

            v = AclUpdateView()
            v.instance = inst
            v.request = request
            v.get_level = MagicMock(return_value='owner')
            v.check_auth = MagicMock(side_effect=Exception(''))

            v.set_level(request.user, 'user')
            v.get_level.assert_called_with(request.user)
            assert not v.check_auth.called
            assert msg.warning.called

    def test_set_level_permitted(self):
        data = (('user', 'owner', ('user', 'operator', 'owner'), False),
                (None, None, ('user', ), True),
                ('user', None, ('user', ), True),
                (None, 'user', ('user', ), True),
                ('operator', 'owner', ('user', 'operator'), True),
                (None, 'user', ('user', 'operator'), False))

        for old_level, new_level, allowed_levels, fail in data:
Őry Máté committed
592
            with patch('dashboard.views.util.messages') as msg:
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
                def has_level(user, level):
                    return level in allowed_levels

                request = FakeRequestFactory(POST={})

                inst = MagicMock(spec=Instance)
                inst.has_level.side_effect = has_level
                inst.ACL_LEVELS = Instance.ACL_LEVELS

                v = AclUpdateView()
                v.instance = inst
                v.request = request
                v.is_owner = True
                v.get_level = MagicMock(return_value=old_level)

                v.set_level(request.user, new_level)

                v.get_level.assert_called_with(request.user)
                assert (new_level == old_level) ^ inst.has_level.called
                assert fail ^ inst.set_level.called
                assert fail ^ msg.success.called

    def test_readd(self):
        request = FakeRequestFactory(POST={'name': 'user0', 'level': 'user'})
Őry Máté committed
617
        with patch('dashboard.views.util.messages') as msg:
618 619 620 621 622 623 624 625
            with patch.object(AclUpdateView, 'get_object') as go:
                view = AclUpdateView.as_view()
                inst = MagicMock(spec=Instance)
                go.return_value = inst
                view(request)
                assert msg.warning.called


626
def FakeRequestFactory(user=None, **kwargs):
627 628 629 630
    ''' FakeRequestFactory, FakeMessages and FakeRequestContext are good for
    mocking out django views; they are MUCH faster than the Django test client.
    '''

631 632
    if user is None:
        user = UserFactory()
633 634
        auth = kwargs.pop('authenticated', True)
        user.is_authenticated = lambda: auth
635 636 637 638
        user.is_superuser = kwargs.pop('superuser', False)
        if kwargs.pop('has_perms_mock', False):
            user.has_perms = MagicMock(return_value=True)
        user.save()
639 640 641

    request = HttpRequest()
    request.user = user
642
    request.session = kwargs.pop('session', {})
643
    if kwargs.get('POST') is not None:
644
        request.method = 'POST'
645 646
        request.POST = QueryDict('', mutable=True)
        request.POST.update(kwargs.pop('POST'))
647 648
    else:
        request.method = 'GET'
649 650 651 652
    request.GET = QueryDict('', mutable=True)
    request.GET.update(kwargs.pop('GET', {}))

    if len(kwargs):
653 654
        warnings.warn("FakeRequestFactory kwargs unused: " + unicode(kwargs),
                      stacklevel=2)
655 656 657 658 659 660 661 662 663 664 665

    return request


class UserFactory(Factory):
    ''' using the excellent factory_boy library '''
    FACTORY_FOR = User
    username = Sequence(lambda i: 'test%d' % i)
    first_name = 'John'
    last_name = 'Doe'
    email = Sequence(lambda i: 'test%d@example.com' % i)