1. Alejandro Núñez Liz
  2. django-cms-mycmsproject-toporojo

Source

django-cms-mycmsproject-toporojo / cms / tests / admin.py

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  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
 128
 129
 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
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 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
 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
 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
 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
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 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
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 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
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
# -*- coding: utf-8 -*-
from __future__ import with_statement
from cms.admin.change_list import CMSChangeList
from cms.admin.dialog.forms import (ModeratorForm, PermissionForm, 
    PermissionAndModeratorForm)
from cms.admin.dialog.views import _form_class_selector
from cms.admin.forms import PageForm
from cms.admin.pageadmin import contribute_fieldsets, contribute_list_filter
from cms.api import create_page, create_title, add_plugin
from cms.apphook_pool import apphook_pool, ApphookPool
from cms.models.moderatormodels import PageModeratorState
from cms.models.pagemodel import Page
from cms.models.permissionmodels import GlobalPagePermission
from cms.models.placeholdermodel import Placeholder
from cms.models.titlemodels import Title
from cms.plugins.text.models import Text
from cms.test_utils import testcases as base
from cms.test_utils.testcases import (CMSTestCase, URL_CMS_PAGE_DELETE, 
    URL_CMS_PAGE, URL_CMS_TRANSLATION_DELETE)
from cms.test_utils.util.context_managers import SettingsOverride
from cms.test_utils.util.mock import AttributeObject
from django.conf import settings
from django.contrib import admin
from django.contrib.admin.sites import site
from django.contrib.auth.models import User, Permission, AnonymousUser
from django.contrib.sites.models import Site
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.http import (Http404, HttpResponseBadRequest, HttpResponseForbidden, 
    HttpResponse)
from django.test.client import Client, RequestFactory
from django.utils.encoding import smart_str
from menus.menu_pool import menu_pool
from types import MethodType
from unittest import TestCase


class AdminTestsBase(CMSTestCase):
    
    def setUp(self):
        self.request_factory = RequestFactory()
        
    @property
    def admin_class(self):
        return site._registry[Page]
        
    def _get_guys(self, admin_only=False):
        admin = self.get_superuser()
        if admin_only:
            return admin
        with self.login_user_context(admin):
            USERNAME = 'test'
            
            normal_guy = User.objects.create_user(USERNAME, 'test@test.com', USERNAME)
            normal_guy.is_staff = True
            normal_guy.is_active = True
            normal_guy.save()
            normal_guy.user_permissions = Permission.objects.filter(
                codename__in=['change_page', 'change_title', 'add_page', 'add_title', 'delete_page', 'delete_title']
            )
            gpp = GlobalPagePermission.objects.create(
                user=normal_guy,
                can_change=True,
                can_delete=True,
                can_change_advanced_settings=False,
                can_publish=True,
                can_change_permissions=False,
                can_move_page=True,
                can_moderate=True,
            )
            gpp.sites = Site.objects.all()
        return admin, normal_guy
        
class AdminTestCase(AdminTestsBase):
            
    def test_edit_does_not_reset_page_adv_fields(self):
        """
        Makes sure that if a non-superuser with no rights to edit advanced page
        fields edits a page, those advanced fields are not touched.
        """
        OLD_PAGE_NAME = 'Test Page'
        NEW_PAGE_NAME = 'Test page 2'
        REVERSE_ID = 'Test'
        OVERRIDE_URL = 'my/override/url'
        
        admin, normal_guy = self._get_guys()
        
        site = Site.objects.get(pk=1)
    
        # The admin creates the page
        page = create_page(OLD_PAGE_NAME, "nav_playground.html", "en",
                           site=site, created_by=admin)
        page.reverse_id = REVERSE_ID
        page.save()
        title = page.get_title_obj()
        title.has_url_overwrite = True
        title.path = OVERRIDE_URL
        title.save()
        
        self.assertEqual(page.get_title(), OLD_PAGE_NAME)
        self.assertEqual(page.reverse_id, REVERSE_ID)
        self.assertEqual(title.overwrite_url, OVERRIDE_URL)
        
        # The user edits the page (change the page name for ex.)
        page_data = {
            'title': NEW_PAGE_NAME, 
            'slug': page.get_slug(), 
            'language': title.language,
            'site': page.site.pk, 
            'template': page.template,
        }
        # required only if user haves can_change_permission
        page_data['pagepermission_set-TOTAL_FORMS'] = 0
        page_data['pagepermission_set-INITIAL_FORMS'] = 0
        page_data['pagepermission_set-MAX_NUM_FORMS'] = 0
        page_data['pagepermission_set-2-TOTAL_FORMS'] = 0
        page_data['pagepermission_set-2-INITIAL_FORMS'] = 0
        page_data['pagepermission_set-2-MAX_NUM_FORMS'] = 0
        
        with self.login_user_context(normal_guy):
            resp = self.client.post(base.URL_CMS_PAGE_CHANGE % page.pk, page_data, 
                                    follow=True)
            self.assertEqual(resp.status_code, 200)
            self.assertTemplateNotUsed(resp, 'admin/login.html')
            page = Page.objects.get(pk=page.pk)
            
            self.assertEqual(page.get_title(), NEW_PAGE_NAME)
            self.assertEqual(page.reverse_id, REVERSE_ID)
            title = page.get_title_obj()
            self.assertEqual(title.overwrite_url, OVERRIDE_URL)
            
            # The admin edits the page (change the page name for ex.)
            page_data = {
                'title': OLD_PAGE_NAME, 
                'slug': page.get_slug(), 
                'language': title.language,
                'site': page.site.pk, 
                'template': page.template,
                'reverse_id': page.reverse_id,
            }
            # required only if user haves can_change_permission
            page_data['pagepermission_set-TOTAL_FORMS'] = 0
            page_data['pagepermission_set-INITIAL_FORMS'] = 0
            page_data['pagepermission_set-MAX_NUM_FORMS'] = 0
            page_data['pagepermission_set-2-TOTAL_FORMS'] = 0
            page_data['pagepermission_set-2-INITIAL_FORMS'] = 0
            page_data['pagepermission_set-2-MAX_NUM_FORMS'] = 0
        
        with self.login_user_context(admin):
            resp = self.client.post(base.URL_CMS_PAGE_CHANGE % page.pk, page_data, 
                                    follow=True)
            self.assertEqual(resp.status_code, 200)
            self.assertTemplateNotUsed(resp, 'admin/login.html')
            page = Page.objects.get(pk=page.pk)
            
            self.assertEqual(page.get_title(), OLD_PAGE_NAME)
            self.assertEqual(page.reverse_id, REVERSE_ID)
            title = page.get_title_obj()
            self.assertEqual(title.overwrite_url, None)
            
    def test_edit_does_not_reset_apphook(self):
        """
        Makes sure that if a non-superuser with no rights to edit advanced page
        fields edits a page, those advanced fields are not touched.
        """
        OLD_PAGE_NAME = 'Test Page'
        NEW_PAGE_NAME = 'Test page 2'
        REVERSE_ID = 'Test'
        APPLICATION_URLS = 'project.sampleapp.urls'
        
        admin, normal_guy = self._get_guys()
        
        site = Site.objects.get(pk=1)
    
        # The admin creates the page
        page = create_page(OLD_PAGE_NAME, "nav_playground.html", "en",
                           site=site, created_by=admin)
        page.reverse_id = REVERSE_ID
        page.save()
        title = page.get_title_obj()
        title.has_url_overwrite = True
        title.application_urls = APPLICATION_URLS
        title.save()
        
        self.assertEqual(page.get_title(), OLD_PAGE_NAME)
        self.assertEqual(page.reverse_id, REVERSE_ID)
        self.assertEqual(title.application_urls, APPLICATION_URLS)
        
        # The user edits the page (change the page name for ex.)
        page_data = {
            'title': NEW_PAGE_NAME, 
            'slug': page.get_slug(), 
            'language': title.language,
            'site': page.site.pk, 
            'template': page.template,
        }
        # required only if user haves can_change_permission
        page_data['pagepermission_set-TOTAL_FORMS'] = 0
        page_data['pagepermission_set-INITIAL_FORMS'] = 0
        page_data['pagepermission_set-MAX_NUM_FORMS'] = 0
        page_data['pagepermission_set-2-TOTAL_FORMS'] = 0
        page_data['pagepermission_set-2-INITIAL_FORMS'] = 0
        page_data['pagepermission_set-2-MAX_NUM_FORMS'] = 0
        
        with self.login_user_context(normal_guy):
            resp = self.client.post(base.URL_CMS_PAGE_CHANGE % page.pk, page_data, 
                                    follow=True)
            self.assertEqual(resp.status_code, 200)
            self.assertTemplateNotUsed(resp, 'admin/login.html')
            page = Page.objects.get(pk=page.pk)
            
            self.assertEqual(page.get_title(), NEW_PAGE_NAME)
            self.assertEqual(page.reverse_id, REVERSE_ID)
            title = page.get_title_obj()
            self.assertEqual(title.application_urls, APPLICATION_URLS)
            
            # The admin edits the page (change the page name for ex.)
            page_data = {
                'title': OLD_PAGE_NAME, 
                'slug': page.get_slug(), 
                'language': title.language,
                'site': page.site.pk, 
                'template': page.template,
                'reverse_id': page.reverse_id,
            }
            # required only if user haves can_change_permission
            page_data['pagepermission_set-TOTAL_FORMS'] = 0
            page_data['pagepermission_set-INITIAL_FORMS'] = 0
            page_data['pagepermission_set-MAX_NUM_FORMS'] = 0
            page_data['pagepermission_set-2-TOTAL_FORMS'] = 0
            page_data['pagepermission_set-2-INITIAL_FORMS'] = 0
            page_data['pagepermission_set-2-MAX_NUM_FORMS'] = 0
        
        with self.login_user_context(admin):
            resp = self.client.post(base.URL_CMS_PAGE_CHANGE % page.pk, page_data, 
                                    follow=True)
            self.assertEqual(resp.status_code, 200)
            self.assertTemplateNotUsed(resp, 'admin/login.html')
            page = Page.objects.get(pk=page.pk)
            
            self.assertEqual(page.get_title(), OLD_PAGE_NAME)
            self.assertEqual(page.reverse_id, REVERSE_ID)
            title = page.get_title_obj()
            self.assertEqual(title.application_urls, '')

    def test_delete(self):
        admin = self._get_guys(True)
        page = create_page("delete-page", "nav_playground.html", "en",
                           created_by=admin, published=True)
        child = create_page('child-page', "nav_playground.html", "en",
                            created_by=admin, published=True, parent=page)
        with self.login_user_context(admin):
            data = {'post': 'yes'}
            response = self.client.post(URL_CMS_PAGE_DELETE % page.pk, data)
            self.assertRedirects(response, URL_CMS_PAGE)
            self.assertRaises(Page.DoesNotExist, self.reload, page)
            self.assertRaises(Page.DoesNotExist, self.reload, child)
        
    def test_admin_dialog_form_no_moderation_or_permissions(self):
        with SettingsOverride(CMS_MODERATOR=False, CMS_PERMISSION=False):
            result = _form_class_selector()
            self.assertEqual(result, None)
            
    def test_admin_dialog_form_permission_only(self):
        with SettingsOverride(CMS_MODERATOR=False, CMS_PERMISSION=True):
            result = _form_class_selector()
            self.assertEqual(result, PermissionForm)
            
    def test_admin_dialog_form_moderation_only(self):
        with SettingsOverride(CMS_MODERATOR=True, CMS_PERMISSION=False):
            result = _form_class_selector()
            self.assertEqual(result, ModeratorForm)
            
    def test_admin_dialog_form_moderation_and_permisison(self):
        with SettingsOverride(CMS_MODERATOR=True, CMS_PERMISSION=True):
            result = _form_class_selector()
            self.assertEqual(result, PermissionAndModeratorForm)

    def test_search_fields(self):
        superuser = self._get_guys(admin_only=True)
        from django.contrib.admin import site
        with self.login_user_context(superuser):
            for model, admin in site._registry.items():
                if model._meta.app_label != 'cms':
                    continue
                if not admin.search_fields:
                    continue
                url = reverse('admin:cms_%s_changelist' % model._meta.module_name)
                response = self.client.get('%s?q=1' % url)
                errmsg = response.content
                self.assertEqual(response.status_code, 200, errmsg)

    def test_delete_translation(self):
        admin = self._get_guys(True)
        page = create_page("delete-page-translation", "nav_playground.html", "en",
                           created_by=admin, published=True)
        create_title("de", "delete-page-translation-2", page, slug="delete-page-translation-2")
        with self.login_user_context(admin):
            response = self.client.get(URL_CMS_TRANSLATION_DELETE % page.pk, {'language': 'de'})
            self.assertEqual(response.status_code, 200)
            response = self.client.post(URL_CMS_TRANSLATION_DELETE % page.pk, {'language': 'de'})
            self.assertRedirects(response, URL_CMS_PAGE)
    
    def test_change_template(self):
        admin, staff = self._get_guys()
        request = self.get_request('/admin/cms/page/1/', 'en')
        pageadmin = site._registry[Page]
        with self.login_user_context(staff):
            self.assertRaises(Http404, pageadmin.change_template, request, 1)
            page = create_page('test-page', 'nav_playground.html', 'en')
            response = pageadmin.change_template(request, page.pk)
            self.assertEqual(response.status_code, 403)
        url = reverse('admin:cms_page_change_template', args=(page.pk,))
        with self.login_user_context(admin):
            response = self.client.post(url, {'template': 'doesntexist'})
            self.assertEqual(response.status_code, 400)
            self.assertEqual(response.content, "template not valid")
            response = self.client.post(url, {'template': settings.CMS_TEMPLATES[0][0]})
            self.assertEqual(response.status_code, 200)
            self.assertEqual(response.content, 'ok')
            
    def test_get_permissions(self):
        page = create_page('test-page', 'nav_playground.html', 'en')
        url = reverse('admin:cms_page_get_permissions', args=(page.pk,))
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'admin/login.html')
        admin = self._get_guys(True)
        with self.login_user_context(admin):
            response = self.client.get(url)
            self.assertEqual(response.status_code, 200)
            self.assertTemplateNotUsed(response, 'admin/login.html')
            
    def test_changelist_items(self):
        admin = self._get_guys(True)
        first_level_page = create_page('level1',  'nav_playground.html', 'en')
        second_level_page_top = create_page('level21', "nav_playground.html", "en",
                            created_by=admin, published=True, parent= first_level_page)
        second_level_page_bottom = create_page('level22', "nav_playground.html", "en",
                            created_by=admin, published=True, parent= self.reload(first_level_page))
        third_level_page = create_page('level3', "nav_playground.html", "en",
                            created_by=admin, published=True, parent= second_level_page_top)
        self.assertEquals(Page.objects.all().count(), 4)
        
        url = reverse('admin:cms_%s_changelist' % Page._meta.module_name)
        request = self.request_factory.get(url)
        
        request.session = {}
        request.user = admin
        
        page_admin = site._registry[Page]

        cl_params = [request, page_admin.model, page_admin.list_display,
                            page_admin.list_display_links, page_admin.list_filter,
                            page_admin.date_hierarchy, page_admin.search_fields, 
                            page_admin.list_select_related, page_admin.list_per_page]
        if hasattr(page_admin, 'list_max_show_all'): # django 1.4
            cl_params.append(page_admin.list_max_show_all)
        cl_params.extend([page_admin.list_editable, page_admin])
        cl = CMSChangeList(*tuple(cl_params))
        
        cl.set_items(request)
        
        
        root_page = cl.get_items()[0]

        self.assertEqual(root_page, first_level_page)
        self.assertEqual(root_page.get_children()[0], second_level_page_top)
        self.assertEqual(root_page.get_children()[1], second_level_page_bottom)
        self.assertEqual(root_page.get_children()[0].get_children()[0], third_level_page)

    def test_changelist_tree(self):
        """ This test checks for proper jstree cookie unquoting.

        It should be converted to a selenium test to actually test the jstree behaviour.
        Cookie set below is just a forged example (from live session)
        """
        admin = self._get_guys(True)
        first_level_page = create_page('level1',  'nav_playground.html', 'en')
        second_level_page_top = create_page('level21', "nav_playground.html", "en",
                            created_by=admin, published=True, parent= first_level_page)
        second_level_page_bottom = create_page('level22', "nav_playground.html", "en",
                            created_by=admin, published=True, parent= self.reload(first_level_page))
        third_level_page = create_page('level3', "nav_playground.html", "en",
                            created_by=admin, published=True, parent= second_level_page_top)

        url = reverse('admin:cms_%s_changelist' % Page._meta.module_name)
        client = Client()
        client.login(username='admin', password='admin')
        client.cookies['djangocms_nodes_open'] = 'page_1%2Cpage_2'
        response = client.get(url)
        self.assertEquals(response.status_code, 200)
        self.assertEquals(response.context["open_menu_trees"], [1,2])
        # tests descendants method for the lazy load ajax call
        url = "%s%d/descendants/" % (url, first_level_page.pk)
        response = client.get(url)
        self.assertEquals(response.status_code, 200)
        # should include both direct descendant pages
        self.assertTrue('id="page_2"' in response.content)
        self.assertTrue('id="page_3"' in response.content)
        # but not any further down the tree
        self.assertFalse('id="page_4"' in response.content)


class AdminFieldsetTests(TestCase):
    def validate_attributes(self, a, b, ignore=None):
        attrs = ['advanced_fields', 'hidden_fields', 'general_fields',
                 'template_fields', 'additional_hidden_fields', 'fieldsets']
        if not ignore:
            ignore = []
        for attr in attrs:
            if attr in ignore:
                continue
            a_attr = getattr(a, attr)
            b_attr = getattr(b, attr)
            self.assertEqual(a_attr, b_attr)
        
    def test_no_moderator(self):
        with SettingsOverride(CMS_MODERATOR=True):
            control = AttributeObject()
            contribute_fieldsets(control)
        with SettingsOverride(CMS_MODERATOR=False):
            nomod = AttributeObject()
            contribute_fieldsets(nomod)
        self.validate_attributes(control, nomod, ['fieldsets', 'additional_hidden_fields'])
        self.assertEqual(control.additional_hidden_fields, ['moderator_state', 'moderator_message'])
        self.assertEqual(nomod.additional_hidden_fields, [])
    
    def test_no_menu_title_overwrite(self):
        with SettingsOverride(CMS_MENU_TITLE_OVERWRITE=True):
            control = AttributeObject()
            contribute_fieldsets(control)
        with SettingsOverride(CMS_MENU_TITLE_OVERWRITE=False):
            experiment = AttributeObject()
            contribute_fieldsets(experiment)
        self.validate_attributes(control, experiment, ['fieldsets', 'general_fields'])
        self.assertEqual(control.general_fields[0], ('title', 'menu_title'))
        self.assertEqual(experiment.general_fields[0], 'title')
    
    def test_no_softroot(self):
        with SettingsOverride(CMS_SOFTROOT=True):
            control = AttributeObject()
            contribute_fieldsets(control)
        with SettingsOverride(CMS_SOFTROOT=False):
            experiment = AttributeObject()
            contribute_fieldsets(experiment)
        self.validate_attributes(control, experiment, ['fieldsets', 'advanced_fields'])
        self.assertTrue('soft_root' in control.advanced_fields)
        self.assertFalse('soft_root' in experiment.advanced_fields)
    
    def test_dates(self):
        with SettingsOverride(CMS_SHOW_START_DATE=False, CMS_SHOW_END_DATE=False):
            control = AttributeObject()
            contribute_fieldsets(control)
        with SettingsOverride(CMS_SHOW_START_DATE=True, CMS_SHOW_END_DATE=True):
            experiment1 = AttributeObject()
            contribute_fieldsets(experiment1)
        with SettingsOverride(CMS_SHOW_START_DATE=True, CMS_SHOW_END_DATE=False):
            experiment2 = AttributeObject()
            contribute_fieldsets(experiment2)
        with SettingsOverride(CMS_SHOW_START_DATE=False, CMS_SHOW_END_DATE=True):
            experiment3 = AttributeObject()
            contribute_fieldsets(experiment3)
        self.validate_attributes(control, experiment1, ['fieldsets', 'general_fields'])
        self.validate_attributes(control, experiment2, ['fieldsets', 'general_fields'])
        self.validate_attributes(control, experiment3, ['fieldsets', 'general_fields'])
        self.assertFalse(('publication_date', 'publication_end_date') in control.general_fields, control.general_fields)
        self.assertTrue(('publication_date', 'publication_end_date') in experiment1.general_fields, experiment1.general_fields)
        self.assertFalse(('publication_date', 'publication_end_date') in experiment2.general_fields, experiment2.general_fields)
        self.assertFalse(('publication_date', 'publication_end_date') in experiment3.general_fields, experiment3.general_fields)
        self.assertFalse('publication_end_date' in experiment1.general_fields, experiment1.general_fields)
        self.assertFalse('publication_end_date' in experiment2.general_fields, experiment2.general_fields)
        self.assertTrue('publication_end_date' in experiment3.general_fields, experiment3.general_fields)
        self.assertFalse('publication_date' in experiment1.general_fields, experiment1.general_fields)
        self.assertTrue('publication_date' in experiment2.general_fields, experiment2.general_fields)
        self.assertFalse('publication_date' in experiment3.general_fields, experiment3.general_fields)
    
    def test_no_seo(self):
        with SettingsOverride(CMS_SEO_FIELDS=True):
            control = AttributeObject()
            contribute_fieldsets(control)
        with SettingsOverride(CMS_SEO_FIELDS=False):
            experiment = AttributeObject()
            contribute_fieldsets(experiment)
        self.validate_attributes(control, experiment, ['fieldsets', 'seo_fields'])
        self.assertEqual(control.seo_fields, ['page_title', 'meta_description', 'meta_keywords'])
        self.assertFalse(experiment.seo_fields, [])
    
    def test_url_overwrite(self):
        with SettingsOverride(CMS_URL_OVERWRITE=False):
            control = AttributeObject()
            contribute_fieldsets(control)
        with SettingsOverride(CMS_URL_OVERWRITE=True):
            experiment = AttributeObject()
            contribute_fieldsets(experiment)
        self.validate_attributes(control, experiment, ['fieldsets', 'advanced_fields'])
        self.assertFalse('overwrite_url' in control.advanced_fields, control.advanced_fields)
        self.assertTrue('overwrite_url' in experiment.advanced_fields, experiment.advanced_fields)
        
    def test_no_cms_enabled_menus(self):
        control = AttributeObject()
        contribute_fieldsets(control)
        old_menus = menu_pool.menus.copy()
        menu_pool.menus = {}
        experiment = AttributeObject()
        contribute_fieldsets(experiment)
        menu_pool.menus = old_menus
        self.validate_attributes(control, experiment, ['fieldsets', 'advanced_fields'])
        self.assertTrue('navigation_extenders' in control.advanced_fields, control.advanced_fields)
        self.assertFalse('navigation_extenders' in experiment.advanced_fields, experiment.advanced_fields)
        
    def test_redirects(self):
        with SettingsOverride(CMS_REDIRECTS=False):
            control = AttributeObject()
            contribute_fieldsets(control)
        with SettingsOverride(CMS_REDIRECTS=True):
            experiment = AttributeObject()
            contribute_fieldsets(experiment)
        self.validate_attributes(control, experiment, ['fieldsets', 'advanced_fields'])
        self.assertFalse('redirect' in control.advanced_fields, control.advanced_fields)
        self.assertTrue('redirect' in experiment.advanced_fields, experiment.advanced_fields)
        
        
    def test_no_apphooks(self):
        def func_true(self):
            return True
        def func_false(self):
            return False
        old_get_apphooks = apphook_pool.get_apphooks
        apphook_pool.get_apphooks = MethodType(func_true, apphook_pool, ApphookPool)
        control = AttributeObject()
        contribute_fieldsets(control)
        apphook_pool.get_apphooks = MethodType(func_false, apphook_pool, ApphookPool)
        experiment = AttributeObject()
        contribute_fieldsets(experiment)
        self.validate_attributes(control, experiment, ['fieldsets', 'advanced_fields'])
        self.assertTrue('application_urls' in control.advanced_fields, control.advanced_fields)
        self.assertFalse('application_urls' in experiment.advanced_fields, control.advanced_fields)
        apphook_pool.get_apphooks = old_get_apphooks
        

class AdminListFilterTests(TestCase):
    def test_no_moderator(self):
        with SettingsOverride(CMS_MODERATOR=True):
            control = AttributeObject()
            contribute_list_filter(control)
        with SettingsOverride(CMS_MODERATOR=False):
            experiment = AttributeObject()
            contribute_list_filter(experiment)
        self.assertTrue('moderator_state' in control.list_filter, control.list_filter)
        self.assertFalse('moderator_state' in experiment.list_filter, experiment.list_filter)
    
    def test_no_softroot(self):
        with SettingsOverride(CMS_SOFTROOT=True):
            control = AttributeObject()
            contribute_list_filter(control)
        with SettingsOverride(CMS_SOFTROOT=False):
            experiment = AttributeObject()
            contribute_list_filter(experiment)
        self.assertTrue('soft_root' in control.list_filter, control.list_filter)
        self.assertFalse('soft_root' in experiment.list_filter, experiment.list_filter)


class AdminTests(AdminTestsBase):
    # TODO: needs tests for actual permissions, not only superuser/normaluser
    
    def setUp(self):
        super(AdminTests, self).setUp()
        create_page("testpage", "nav_playground.html", "en")
    
    def get_admin(self):
        usr = User(username="admin", email="admin@django-cms.org", is_staff=True, is_superuser=True)
        usr.set_password("admin")
        usr.save()
        return usr
    
    def get_permless(self):
        usr = User(username="permless", email="permless@django-cms.org", is_staff=True)
        usr.set_password("permless")
        usr.save()
        return usr
    
    def get_page(self):
        return Page.objects.get(pk=1)
    
    def test_get_moderation_state(self):
        page = self.get_page()
        permless = self.get_permless()
        admin = self.get_admin()
        with self.login_user_context(permless):
            request = self.get_request()
            self.assertRaises(Http404, self.admin_class.get_moderation_states,
                              request, page.pk)
        with self.login_user_context(admin):
            request = self.get_request()
            response = self.admin_class.get_moderation_states(request, page.pk)
            self.assertEqual(response.status_code, 200)
            
    def test_remove_delete(self):
        page = self.get_page()
        permless = self.get_permless()
        admin = self.get_admin()
        with self.login_user_context(permless):
            request = self.get_request()
            self.assertRaises(PermissionDenied, self.admin_class.remove_delete_state,
                              request, page.pk)
        PageModeratorState.objects.create(page=page, user=admin, action="DEL")
        with self.login_user_context(admin):
            self.assertEqual(page.pagemoderatorstate_set.get_delete_actions().count(), 1)
            request = self.get_request()
            response = self.admin_class.remove_delete_state(request, page.pk)
            self.assertEqual(response.status_code, 302)
            page = self.reload(page)
            self.assertEqual(page.pagemoderatorstate_set.get_delete_actions().count(), 0)
    
    def test_change_status(self):
        page = self.get_page()
        permless = self.get_permless()
        with self.login_user_context(permless):
            request = self.get_request()
            response = self.admin_class.change_status(request, 1)
            self.assertEqual(response.status_code, 405)
        with self.login_user_context(permless):
            request = self.get_request(post_data={'no': 'data'})
            response = self.admin_class.change_status(request, page.pk)
            self.assertEqual(response.status_code, 403)
    
    def test_change_innavigation(self):
        page = self.get_page()
        permless = self.get_permless()
        admin = self.get_admin()
        with self.login_user_context(permless):
            request = self.get_request()
            response = self.admin_class.change_innavigation(request, page.pk)
            self.assertEqual(response.status_code, 405)
        with self.login_user_context(permless):
            request = self.get_request(post_data={'no':'data'})
            self.assertRaises(Http404, self.admin_class.change_innavigation,
                              request, page.pk + 100)
        with self.login_user_context(permless):
            request = self.get_request(post_data={'no':'data'})
            response = self.admin_class.change_innavigation(request, page.pk)
            self.assertEqual(response.status_code, 403)
        with self.login_user_context(admin):
            request = self.get_request(post_data={'no':'data'})
            old = page.in_navigation
            response = self.admin_class.change_innavigation(request, page.pk)
            self.assertEqual(response.status_code, 200)
            page = self.reload(page)
            self.assertEqual(old, not page.in_navigation)

    def test_change_moderation(self):
        page = self.get_page()
        permless = self.get_permless()
        admin = self.get_admin()
        with self.login_user_context(permless):
            request = self.get_request()
            response = self.admin_class.change_moderation(request, page.pk)
            self.assertEqual(response.status_code, 405)
        with self.login_user_context(admin):
            request = self.get_request(post_data={'wrongarg': 'blah'})
            self.assertRaises(Http404, self.admin_class.change_moderation,
                              request, 1)
        with self.login_user_context(admin):
            request = self.get_request(post_data={'moderate': '0'})
            response = self.admin_class.change_moderation(request, page.pk)
            self.assertEqual(response.status_code, 200)
        # TODO: Shouldn't this raise 404?
        with self.login_user_context(admin):
            request = self.get_request(post_data={'moderate': 'zero'})
            response = self.admin_class.change_moderation(request, page.pk)
            self.assertEqual(response.status_code, 200)
        with self.login_user_context(admin):
            request = self.get_request(post_data={'moderate': '1'})
            response = self.admin_class.change_moderation(request, page.pk)
            self.assertEqual(response.status_code, 200)
        with self.login_user_context(admin):
            request = self.get_request(post_data={'moderate': '10'})
            self.assertRaises(Http404, self.admin_class.change_moderation,
                              request, page.pk)

    def test_approve_page_requires_perms(self):
        permless = self.get_permless()
        with self.login_user_context(permless):
            request = self.get_request()
            self.assertRaises(Http404, self.admin_class.approve_page,
                              request, 1)

    def test_publish_page_requires_perms(self):
        permless = self.get_permless()
        with self.login_user_context(permless):
            request = self.get_request()
            response = self.admin_class.publish_page(request, 1)
            self.assertEqual(response.status_code, 403)
    
    def test_remove_plugin_requires_post(self):
        admin = self.get_admin()
        with self.login_user_context(admin):
            request = self.get_request()
            self.assertRaises(Http404, self.admin_class.remove_plugin, request)
    
    def test_move_plugin(self):
        ph = Placeholder.objects.create(slot='test')
        plugin = add_plugin(ph, 'TextPlugin', 'en', body='test')
        page = self.get_page()
        source, target = list(page.placeholders.all())[:2]
        pageplugin = add_plugin(source, 'TextPlugin', 'en', body='test')
        permless = self.get_permless()
        admin = self.get_admin()
        with self.login_user_context(permless):
            request = self.get_request()
            response = self.admin_class.move_plugin(request)
            self.assertEqual(response.status_code, 200)
            self.assertEqual(response.content, "error")
            request = self.get_request(post_data={'not_usable': '1'})
            response = self.admin_class.move_plugin(request)
            self.assertEqual(response.status_code, 200)
            self.assertEqual(response.content, "error")
        with self.login_user_context(admin):
            request = self.get_request(post_data={'plugin_id': plugin.pk})
            self.assertRaises(Http404, self.admin_class.move_plugin, request)
        with self.login_user_context(admin):
            request = self.get_request(post_data={'ids': plugin.pk})
            self.assertRaises(Http404, self.admin_class.move_plugin, request)
        with self.login_user_context(admin):
            request = self.get_request(post_data={'plugin_id': pageplugin.pk,
                                                  'placeholder': 'invalid-placeholder'})
            response = self.admin_class.move_plugin(request)
            self.assertEqual(response.status_code, 200)
            self.assertEqual(response.content, "error")
        with self.login_user_context(permless):
            request = self.get_request(post_data={'plugin_id': pageplugin.pk,
                                                  'placeholder': target.slot})
            self.assertEquals(self.admin_class.move_plugin(request).status_code, HttpResponseForbidden.status_code)
        with self.login_user_context(admin):
            request = self.get_request(post_data={'plugin_id': pageplugin.pk,
                                                  'placeholder': target.slot})
            response = self.admin_class.move_plugin(request)
            self.assertEqual(response.status_code, 200)
            self.assertEqual(response.content, "ok")
        with self.login_user_context(permless):
            request = self.get_request(post_data={'ids': pageplugin.pk,
                                                  'placeholder': target.slot})
            self.assertEquals(self.admin_class.move_plugin(request).status_code, HttpResponseForbidden.status_code)
        with self.login_user_context(admin):
            request = self.get_request(post_data={'ids': pageplugin.pk,
                                                  'placeholder': target.slot})
            response = self.admin_class.move_plugin(request)
            self.assertEqual(response.status_code, 200)
            self.assertEqual(response.content, "ok")
    
    def test_preview_page(self):
        permless = self.get_permless()
        with self.login_user_context(permless):
            request = self.get_request()
            self.assertRaises(Http404, self.admin_class.preview_page, request,
                              404)
        page = self.get_page()
        page.publisher_public_id = None
        page.save()
        with self.login_user_context(permless):
            request = self.get_request('/?public=true')
            self.assertRaises(Http404, self.admin_class.preview_page, request,
                              page.pk)
        page = self.get_page()
        page.publisher_public = page
        page.save()
        base_url = page.get_absolute_url()
        with self.login_user_context(permless):
            request = self.get_request('/?public=true')
            response = self.admin_class.preview_page(request, page.pk)
            self.assertEqual(response.status_code, 302)
            self.assertEqual(response['Location'], '%s?preview=1' % base_url)
            request = self.get_request()
            response = self.admin_class.preview_page(request, page.pk)
            self.assertEqual(response.status_code, 302)
            self.assertEqual(response['Location'], '%s?preview=1&draft=1' % base_url)
            site = Site.objects.create(domain='django-cms.org', name='django-cms')
            page.site = site
            page.save()
            response = self.admin_class.preview_page(request, page.pk)
            self.assertEqual(response.status_code, 302)
            self.assertEqual(response['Location'],
                        'http://django-cms.org%s?preview=1&draft=1' % base_url)
    
    def test_too_many_plugins_global(self):
        conf = {
            'body': {
                'limits': {
                    'global': 1,
                },
            },
        }
        admin = self.get_admin()
        url = reverse('admin:cms_page_add_plugin')
        with SettingsOverride(CMS_MODERATOR=False, CMS_PERMISSION=False,
                              CMS_PLACEHOLDER_CONF=conf):
            page = create_page('somepage', 'nav_playground.html', 'en')
            body = page.placeholders.get(slot='body')
            add_plugin(body, 'TextPlugin', 'en', body='text')
            with self.login_user_context(admin):
                data = {
                    'plugin_type': 'TextPlugin',
                    'placeholder': body.pk,
                    'language': 'en',
                }
                response = self.client.post(url, data)
                self.assertEqual(response.status_code, HttpResponseBadRequest.status_code)
    
    def test_too_many_plugins_type(self):
        conf = {
            'body': {
                'limits': {
                    'TextPlugin': 1,
                },
            },
        }
        admin = self.get_admin()
        url = reverse('admin:cms_page_add_plugin')
        with SettingsOverride(CMS_MODERATOR=False, CMS_PERMISSION=False,
                              CMS_PLACEHOLDER_CONF=conf):
            page = create_page('somepage', 'nav_playground.html', 'en')
            body = page.placeholders.get(slot='body')
            add_plugin(body, 'TextPlugin', 'en', body='text')
            with self.login_user_context(admin):
                data = {
                    'plugin_type': 'TextPlugin',
                    'placeholder': body.pk,
                    'language': 'en',
                }
                response = self.client.post(url, data)
                self.assertEqual(response.status_code, HttpResponseBadRequest.status_code)


class NoDBAdminTests(TestCase):
    
    @property
    def admin_class(self):
        return site._registry[Page]
        
    def test_lookup_allowed_site__exact(self):
        self.assertTrue(self.admin_class.lookup_allowed('site__exact', '1'))
            
    def test_lookup_allowed_published(self):
        self.assertTrue(self.admin_class.lookup_allowed('published', value='1'))


class PluginPermissionTests(AdminTestsBase):
    
    def setUp(self):
        super(PluginPermissionTests, self).setUp()
        self._page = create_page('test page', 'nav_playground.html', 'en')
        self._placeholder = self._page.placeholders.all()[0]
        
    def _get_admin(self):
        admin = User(
            username='admin',
            email='admin@admin.com',
            is_active=True,
            is_staff=True,
        )
        admin.set_password('admin')
        admin.save()
        return admin
    
    def _get_page_admin(self):
        return admin.site._registry[Page]
    
    def _give_permission(self, user, model, permission_type, save=True):
        codename = '%s_%s' % (permission_type, model._meta.object_name.lower())
        user.user_permissions.add(Permission.objects.get(codename=codename))
    
    def _give_cms_permissions(self, user, save=True):
        for perm_type in ['add', 'change', 'delete']:
            for model in [Page, Title]:
                self._give_permission(user, model, perm_type, False)
        gpp = GlobalPagePermission.objects.create(
            user=user,
            can_change=True,
            can_delete=True,
            can_change_advanced_settings=False,
            can_publish=True,
            can_change_permissions=False,
            can_move_page=True,
            can_moderate=True,
        )
        gpp.sites = Site.objects.all()
        if save:
            user.save()

    def _create_plugin(self):
        plugin = add_plugin(self._placeholder, 'TextPlugin', 'en')
        return plugin
        
    def test_plugin_add_requires_permissions(self):
        """User tries to add a plugin but has no permissions. He can add the plugin after he got the permissions"""
        admin = self._get_admin()
        self._give_cms_permissions(admin)
        client = Client()
        client.login(username='admin', password='admin')
        url = reverse('admin:cms_page_add_plugin')
        data = {
            'plugin_type': 'TextPlugin',
            'placeholder': self._placeholder.pk,
            'language': 'en',
        }
        response = client.post(url, data)
        self.assertEqual(response.status_code, HttpResponseForbidden.status_code)
        self._give_permission(admin, Text, 'add')
        response = client.post(url, data)
        self.assertEqual(response.status_code, HttpResponse.status_code)

    def test_plugin_edit_requires_permissions(self):
        """User tries to edit a plugin but has no permissions. He can edit the plugin after he got the permissions"""
        plugin = self._create_plugin()
        _, normal_guy = self._get_guys()
        client = Client()
        client.login(username='test', password='test')
        url = reverse('admin:cms_page_edit_plugin', args=[plugin.id])
        response = client.post(url, dict())
        self.assertEqual(response.status_code, HttpResponseForbidden.status_code)
        # After he got the permissions, he can edit the plugin
        self._give_permission(normal_guy, Text, 'change')
        response = client.post(url, dict())
        self.assertEqual(response.status_code, HttpResponse.status_code)

    def test_plugin_remove_requires_permissions(self):
        """User tries to remove a plugin but has no permissions. He can remove the plugin after he got the permissions"""
        plugin = self._create_plugin()
        _, normal_guy = self._get_guys()
        client = Client()
        client.login(username='test', password='test')
        url = reverse('admin:cms_page_remove_plugin')
        data = dict(plugin_id=plugin.id)
        response = client.post(url, data)
        self.assertEqual(response.status_code, HttpResponseForbidden.status_code)
        # After he got the permissions, he can edit the plugin
        self._give_permission(normal_guy, Text, 'delete')
        response = client.post(url, data)
        self.assertEqual(response.status_code, HttpResponse.status_code)

    def test_plugin_move_requires_permissions(self):
        """User tries to move a plugin but has no permissions. He can move the plugin after he got the permissions"""
        plugin = self._create_plugin()
        _, normal_guy = self._get_guys()
        client = Client()
        client.login(username='test', password='test')
        url = reverse('admin:cms_page_move_plugin')
        data = dict(plugin_id=plugin.id,
                    placeholder=self._placeholder)
        response = client.post(url, data)
        self.assertEqual(response.status_code, HttpResponseForbidden.status_code)
        # After he got the permissions, he can edit the plugin
        self._give_permission(normal_guy, Text, 'change')
        response = client.post(url, data)
        self.assertEqual(response.status_code, HttpResponse.status_code)

    def test_plugins_copy_requires_permissions(self):
        """User tries to copy plugin but has no permissions. He can copy plugins after he got the permissions"""
        plugin = self._create_plugin()
        _, normal_guy = self._get_guys()
        client = Client()
        client.login(username='test', password='test')
        url = reverse('admin:cms_page_copy_plugins')
        data = dict(plugin_id=plugin.id,
                    placeholder=self._placeholder.pk,
                    language='fr',
                    copy_from='en')
        response = client.post(url, data)
        self.assertEqual(response.status_code, HttpResponseForbidden.status_code)
        # After he got the permissions, he can edit the plugin
        self._give_permission(normal_guy, Text, 'add')
        response = client.post(url, data)
        self.assertEqual(response.status_code, HttpResponse.status_code)


class AdminFormsTests(AdminTestsBase):
    def test_clean_overwrite_url(self):
        user = AnonymousUser()
        user.is_superuser = True
        user.pk = 1
        request = type('Request', (object,), {'user': user})
        with SettingsOverride(CMS_MODERATOR=False):
            data = {
                'title': 'TestPage',
                'slug': 'test-page',
                'language': 'en',
                'overwrite_url': '/overwrite/url/',
                'site': Site.objects.get_current().pk,  
                'template': settings.CMS_TEMPLATES[0][0],
                'published': True
            }
            
            form = PageForm(data)
            self.assertTrue(form.is_valid(), form.errors.as_text())
            # WTF? WHY DOES form.save() not handle this stuff???
            instance = form.save()
            instance.permission_user_cache = user
            instance.permission_advanced_settings_cache = True
            Title.objects.set_or_create(request, instance, form, 'en')
            form = PageForm(data, instance=instance)
            self.assertTrue(form.is_valid(), form.errors.as_text())

    def test_reverse_id_error_location(self):
        ''' Test moving the reverse_id validation error to a field specific one '''

        # this is the Reverse ID we'll re-use to break things.
        dupe_id = 'p1'
        site = Site.objects.get_current()
        page1 = create_page('Page 1', 'nav_playground.html', 'en', reverse_id=dupe_id)
        # Assemble a bunch of data to test the page form
        page2_data = {
            'title': 'Page 2',
            'slug': 'page-2',
            'language': 'en',
            'site': site.pk,
            'template': settings.CMS_TEMPLATES[0][0],
            'reverse_id': dupe_id,
        }
        form = PageForm(data=page2_data, files=None)
        self.assertTrue(not form.is_valid())
        # reverse_id is the only item that is in __all__ as every other field
        # has it's own clean method. Moving it to be a field error means
        # __all__ is now not available.
        self.assertTrue('__all__' not in form.errors)
        # In moving it to it's own field, it should be in form.errors, and
        # the values contained therein should match these.
        self.assertTrue('reverse_id' in form.errors)
        self.assertEqual(1, len(form.errors['reverse_id']))
        self.assertEqual([u'A page with this reverse URL id exists already.'],
            form.errors['reverse_id'])

        admin = self._get_guys(admin_only=True)
        # reset some of page2_data so we can use cms.api.create_page
        page2_data['reverse_id'] = None
        page2_data['site'] = site
        page2 = create_page(**page2_data)
        with self.login_user_context(admin):
            # re-reset the page2_data for the admin form instance.
            page2_data['reverse_id'] = dupe_id
            page2_data['site'] = site.pk
            # This is needed to avoid management form tampering errors.
            page2_data['pagepermission_set-TOTAL_FORMS'] = 0
            page2_data['pagepermission_set-INITIAL_FORMS'] = 0
            page2_data['pagepermission_set-MAX_NUM_FORMS'] = 0
            page2_data['pagepermission_set-2-TOTAL_FORMS'] = 0
            page2_data['pagepermission_set-2-INITIAL_FORMS'] = 0
            page2_data['pagepermission_set-2-MAX_NUM_FORMS'] = 0
            # post to the admin change form for page 2, and test that the
            # reverse_id form row has an errors class. Django's admin avoids
            # collapsing these, so that the error is visible.
            resp = self.client.post(base.URL_CMS_PAGE_CHANGE % page2.pk, page2_data)
            self.assertTrue('<div class="form-row errors reverse_id">' in resp.content)


class AdminPageEditContentSizeTests(AdminTestsBase):
    """
    System user count influences the size of the page edit page,
    but the users are only 2 times present on the page
    
    The test relates to extra=0 
    at PagePermissionInlineAdminForm and ViewRestrictionInlineAdmin
    """
    
    def test_editpage_contentsize(self):
        """
        Expected a username only 2 times in the content, but a relationship
        between usercount and pagesize
        """
        with SettingsOverride(CMS_MODERATOR=False, CMS_PERMISSION=True):
            admin = self.get_superuser()
            PAGE_NAME = 'TestPage'
            USER_NAME = 'test_size_user_0'
            site = Site.objects.get(pk = 1)
            page = create_page(PAGE_NAME, "nav_playground.html", "en", site=site, created_by=admin)
            page.save()
            self._page = page
            with self.login_user_context(admin):
                url = base.URL_CMS_PAGE_CHANGE % self._page.pk
                response = self.client.get(url)
                self.assertEqual(response.status_code, 200)
                old_response_size = len(response.content)
                old_user_count = User.objects.count()
                # create additionals user and reload the page
                User.objects.create(username=USER_NAME, is_active=True)
                user_count = User.objects.count()
                more_users_in_db = old_user_count < user_count 
                # we have more users
                self.assertTrue(more_users_in_db,"New users got NOT created")
                response = self.client.get(url)
                new_response_size = len(response.content)
                page_size_grown = old_response_size < new_response_size
                # expect that the pagesize gets influenced by the useramount of the system
                self.assertTrue(page_size_grown,"Page size has not grown after user creation")
                # usernames are only 2 times in content
                text = smart_str(response.content, response._charset)
                foundcount = text.count(USER_NAME)
                # 2 forms contain usernames as options
                self.assertEqual(foundcount, 2, "Username %s appeared %s times in response.content, expected 2 times" % (USER_NAME, foundcount))