How to use page method in Playwright Internal

Best JavaScript code snippet using playwright-internal

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

page.py

Source: page.py Github

copy
1# -*- coding: utf-8 -*-
2from __future__ import with_statement
3from cms.admin.forms import PageForm
4from cms.api import create_page
5from cms.models import Page, Title
6from cms.models.placeholdermodel import Placeholder
7from cms.models.pluginmodel import CMSPlugin
8from cms.plugins.text.models import Text
9from cms.sitemaps import CMSSitemap
10from cms.test_utils.testcases import (CMSTestCase, URL_CMS_PAGE, 
11    URL_CMS_PAGE_ADD)
12from cms.test_utils.util.context_managers import (LanguageOverride, 
13    SettingsOverride)
14from cms.utils.page_resolver import get_page_from_request
15from django.conf import settings
16from django.contrib.auth.models import User
17from django.contrib.sites.models import Site
18from django.core.urlresolvers import reverse
19from django.http import HttpRequest, HttpResponse, HttpResponseNotFound
20import datetime
21import os.path
22
23class PagesTestCase(CMSTestCase):
24    
25    def test_add_page(self):
26        """
27        Test that the add admin page could be displayed via the admin
28        """
29        superuser = self.get_superuser()
30        with self.login_user_context(superuser):
31            response = self.client.get(URL_CMS_PAGE_ADD)
32            self.assertEqual(response.status_code, 200)
33
34    def test_create_page(self):
35        """
36        Test that a page can be created via the admin
37        """
38        page_data = self.get_new_page_data()
39
40        superuser = self.get_superuser()
41        with self.login_user_context(superuser):
42            response = self.client.post(URL_CMS_PAGE_ADD, page_data)
43            self.assertRedirects(response, URL_CMS_PAGE)
44            title = Title.objects.get(slug=page_data['slug'])
45            self.assertNotEqual(title, None)
46            page = title.page
47            page.published = True
48            page.save()
49            self.assertEqual(page.get_title(), page_data['title'])
50            self.assertEqual(page.get_slug(), page_data['slug'])
51            self.assertEqual(page.placeholders.all().count(), 2)
52            
53            # were public instanes created?
54            title = Title.objects.drafts().get(slug=page_data['slug'])
55
56        
57    def test_slug_collision(self):
58        """
59        Test a slug collision
60        """
61        page_data = self.get_new_page_data()
62        # create first page
63        superuser = self.get_superuser()
64        with self.login_user_context(superuser):
65            response = self.client.post(URL_CMS_PAGE_ADD, page_data)
66            self.assertRedirects(response, URL_CMS_PAGE)
67            
68            #page1 = Title.objects.get(slug=page_data['slug']).page
69            # create page with the same page_data
70            
71            response = self.client.post(URL_CMS_PAGE_ADD, page_data)
72            
73            if settings.i18n_installed:
74                self.assertEqual(response.status_code, 302)
75                # did we got right redirect?
76                self.assertEqual(response['Location'].endswith(URL_CMS_PAGE), True)
77            else:
78                self.assertEqual(response.status_code, 200)
79                self.assertEqual(response['Location'].endswith(URL_CMS_PAGE_ADD), True)
80            # TODO: check for slug collisions after move
81            # TODO: check for slug collisions with different settings         
82  
83    def test_details_view(self):
84        """
85        Test the details view
86        """
87        superuser = self.get_superuser()
88        with self.login_user_context(superuser):
89            response = self.client.get(self.get_pages_root())
90            self.assertEqual(response.status_code, 404)
91            page = create_page('test page 1', "nav_playground.html", "en")
92            response = self.client.get(self.get_pages_root())
93            self.assertEqual(response.status_code, 404)
94            self.assertTrue(page.publish())
95            create_page("test page 2", "nav_playground.html", "en", 
96                                           parent=page, published=True)
97            homepage = Page.objects.get_home()
98            self.assertTrue(homepage.get_slug(), 'test-page-1')
99            response = self.client.get(self.get_pages_root())
100            self.assertEqual(response.status_code, 200)
101
102    def test_edit_page(self):
103        """
104        Test that a page can edited via the admin
105        """
106        superuser = self.get_superuser()
107        with self.login_user_context(superuser):
108            page_data = self.get_new_page_data()
109            response = self.client.post(URL_CMS_PAGE_ADD, page_data)
110            page =  Page.objects.get(title_set__slug=page_data['slug'])
111            response = self.client.get('/admin/cms/page/%s/' %page.id)
112            self.assertEqual(response.status_code, 200)
113            page_data['title'] = 'changed title'
114            response = self.client.post('/admin/cms/page/%s/' %page.id, page_data)
115            self.assertRedirects(response, URL_CMS_PAGE)
116            self.assertEqual(page.get_title(), 'changed title')
117    
118    def test_meta_description_and_keywords_fields_from_admin(self):
119        """
120        Test that description and keywords tags can be set via the admin
121        """
122        superuser = self.get_superuser()
123        with self.login_user_context(superuser):
124            page_data = self.get_new_page_data()
125            page_data["meta_description"] = "I am a page"
126            page_data["meta_keywords"] = "page,cms,stuff"
127            response = self.client.post(URL_CMS_PAGE_ADD, page_data)
128            page =  Page.objects.get(title_set__slug=page_data['slug'])
129            response = self.client.get('/admin/cms/page/%s/' %page.id)
130            self.assertEqual(response.status_code, 200)
131            page_data['meta_description'] = 'I am a duck'
132            response = self.client.post('/admin/cms/page/%s/' %page.id, page_data)
133            self.assertRedirects(response, URL_CMS_PAGE)
134            page = Page.objects.get(title_set__slug=page_data["slug"])
135            self.assertEqual(page.get_meta_description(), 'I am a duck')
136            self.assertEqual(page.get_meta_keywords(), 'page,cms,stuff')
137
138    def test_meta_description_and_keywords_from_template_tags(self):
139        from django import template
140        superuser = self.get_superuser()
141        with self.login_user_context(superuser):
142            page_data = self.get_new_page_data()
143            page_data["title"] = "Hello"
144            page_data["meta_description"] = "I am a page"
145            page_data["meta_keywords"] = "page,cms,stuff"
146            self.client.post(URL_CMS_PAGE_ADD, page_data)
147            page =  Page.objects.get(title_set__slug=page_data['slug'])
148            self.client.post('/admin/cms/page/%s/' %page.id, page_data)
149            t = template.Template("{% load cms_tags %}{% page_attribute title %} {% page_attribute meta_description %} {% page_attribute meta_keywords %}")
150            req = HttpRequest()
151            page.published = True
152            page.save()
153            req.current_page = page 
154            req.REQUEST = {}
155            self.assertEqual(t.render(template.Context({"request": req})), "Hello I am a page page,cms,stuff")
156    
157    
158    def test_copy_page(self):
159        """
160        Test that a page can be copied via the admin
161        """
162        page_a = create_page("page_a", "nav_playground.html", "en")
163        page_a_a = create_page("page_a_a", "nav_playground.html", "en",
164                                    parent=page_a)
165        create_page("page_a_a_a", "nav_playground.html", "en", parent=page_a_a)
166        
167        page_b = create_page("page_b", "nav_playground.html", "en")
168        page_b_a = create_page("page_b", "nav_playground.html", "en", 
169                                    parent=page_b)
170        
171        count = Page.objects.drafts().count()
172        
173        superuser = self.get_superuser()
174        with self.login_user_context(superuser):
175            self.copy_page(page_a, page_b_a)
176        
177        self.assertEqual(Page.objects.drafts().count() - count, 3)
178        
179        
180    def test_language_change(self):
181        superuser = self.get_superuser()
182        with self.login_user_context(superuser):
183            page_data = self.get_new_page_data()
184            self.client.post(URL_CMS_PAGE_ADD, page_data)
185            pk = Page.objects.all()[0].pk
186            response = self.client.get("/admin/cms/page/%s/" % pk, {"language":"en" })
187            self.assertEqual(response.status_code, 200)
188            response = self.client.get("/admin/cms/page/%s/" % pk, {"language":"de" })
189            self.assertEqual(response.status_code, 200)
190        
191    def test_move_page(self):
192        superuser = self.get_superuser()
193        with self.login_user_context(superuser):
194            page_data1 = self.get_new_page_data()
195            self.client.post(URL_CMS_PAGE_ADD, page_data1)
196            page_data2 = self.get_new_page_data()
197            self.client.post(URL_CMS_PAGE_ADD, page_data2)
198            page_data3 = self.get_new_page_data()
199            self.client.post(URL_CMS_PAGE_ADD, page_data3)
200            page1 = Page.objects.all()[0]
201            page2 = Page.objects.all()[1]
202            page3 = Page.objects.all()[2]
203            # move pages
204            response = self.client.post("/admin/cms/page/%s/move-page/" % page3.pk, {"target": page2.pk, "position": "last-child"})
205            self.assertEqual(response.status_code, 200)
206            response = self.client.post("/admin/cms/page/%s/move-page/" % page2.pk, {"target": page1.pk, "position": "last-child"})
207            self.assertEqual(response.status_code, 200)
208            # check page2 path and url
209            page2 = Page.objects.get(pk=page2.pk)
210            self.assertEqual(page2.get_path(), page_data1['slug']+"/"+page_data2['slug'])
211            self.assertEqual(page2.get_absolute_url(), self.get_pages_root()+page_data1['slug']+"/"+page_data2['slug']+"/")
212            # check page3 path and url
213            page3 = Page.objects.get(pk=page3.pk)
214            self.assertEqual(page3.get_path(), page_data1['slug']+"/"+page_data2['slug']+"/"+page_data3['slug'])
215            self.assertEqual(page3.get_absolute_url(), self.get_pages_root()+page_data1['slug']+"/"+page_data2['slug']+"/"+page_data3['slug']+"/")
216            # publish page 1 (becomes home)
217            page1 = Page.objects.get(pk=page1.pk)
218            page1.publish()
219            public_page1 = page1.publisher_public
220            self.assertEqual(public_page1.get_path(), '')
221            # check that page2 and page3 url have changed
222            page2 = Page.objects.get(pk=page2.pk)
223            page2.publish()
224            public_page2 = page2.publisher_public
225            self.assertEqual(public_page2.get_absolute_url(), self.get_pages_root()+page_data2['slug']+"/")
226            page3 = Page.objects.get(pk=page3.pk)
227            page3.publish()
228            public_page3 = page3.publisher_public
229            self.assertEqual(public_page3.get_absolute_url(), self.get_pages_root()+page_data2['slug']+"/"+page_data3['slug']+"/")
230            # move page2 back to root and check path of 2 and 3
231            response = self.client.post("/admin/cms/page/%s/move-page/" % page2.pk, {"target": page1.pk, "position": "right"})
232            self.assertEqual(response.status_code, 200)
233            page1 = Page.objects.get(pk=page1.pk)
234            self.assertEqual(page1.get_path(), page_data1['slug'])
235            page2 = Page.objects.get(pk=page2.pk)
236            self.assertEqual(page2.get_path(), page_data2['slug'])
237            page3 = Page.objects.get(pk=page3.pk)
238            self.assertEqual(page3.get_path(), page_data2['slug']+"/"+page_data3['slug'])
239        
240    def test_move_page_inherit(self):
241        parent = create_page("Parent", 'col_three.html', "en")
242        child = create_page("Child", settings.CMS_TEMPLATE_INHERITANCE_MAGIC,
243                            "en", parent=parent)
244        self.assertEqual(child.get_template(), parent.get_template())
245        child.move_page(parent, 'left')
246        self.assertEqual(child.get_template(), parent.get_template())
247        
248        
249    def test_add_placeholder(self):
250        # create page
251        page = create_page("Add Placeholder", "nav_playground.html", "en",
252                           position="last-child", published=True, in_navigation=True)
253        page.template = 'add_placeholder.html'
254        page.save()
255        url = page.get_absolute_url()
256        response = self.client.get(url)
257        self.assertEqual(200, response.status_code)
258        path = os.path.join(settings.PROJECT_DIR, 'templates', 'add_placeholder.html')
259        f = open(path, 'r')
260        old = f.read()
261        f.close()
262        new = old.replace(
263            '<!-- SECOND_PLACEHOLDER -->',
264            '{% placeholder second_placeholder %}'
265        )
266        f = open(path, 'w')
267        f.write(new)
268        f.close()
269        response = self.client.get(url)
270        self.assertEqual(200, response.status_code)
271        f = open(path, 'w')
272        f.write(old)
273        f.close()
274
275    def test_sitemap_login_required_pages(self):
276        """
277        Test that CMSSitemap object contains only published,public (login_required=False) pages
278        """
279        create_page("page", "nav_playground.html", "en", login_required=True,
280                    published=True, in_navigation=True)
281        self.assertEqual(CMSSitemap().items().count(),0)
282
283    def test_edit_page_other_site_and_language(self):
284        """
285        Test that a page can edited via the admin when your current site is
286        different from the site you are editing and the language isn't available
287        for the current site.
288        """
289        site = Site.objects.create(domain='otherlang', name='otherlang')
290        # Change site for this session
291        page_data = self.get_new_page_data()
292        page_data['site'] = site.pk
293        page_data['title'] = 'changed title'
294        TESTLANG = settings.CMS_SITE_LANGUAGES[site.pk][0]
295        page_data['language'] = TESTLANG
296        superuser = self.get_superuser()
297        with self.login_user_context(superuser):
298            response = self.client.post(URL_CMS_PAGE_ADD, page_data)
299            self.assertRedirects(response, URL_CMS_PAGE)
300            page =  Page.objects.get(title_set__slug=page_data['slug'])
301            with LanguageOverride(TESTLANG):
302                self.assertEqual(page.get_title(), 'changed title')
303        
304    def test_flat_urls(self):
305        with SettingsOverride(CMS_FLAT_URLS=True):
306            home_slug = "home"
307            child_slug = "child"
308            grandchild_slug = "grandchild"
309            home = create_page(home_slug, "nav_playground.html", "en",
310                               published=True, in_navigation=True)
311            home.publish()
312            child = create_page(child_slug, "nav_playground.html", "en",
313                                parent=home, published=True, in_navigation=True)
314            child.publish()
315            grandchild = create_page(grandchild_slug, "nav_playground.html", "en",
316                                     parent=child, published=True, in_navigation=True)
317            grandchild.publish()
318            response = self.client.get(home.get_absolute_url())
319            self.assertEqual(response.status_code, 200)
320            response = self.client.get(child.get_absolute_url())
321            self.assertEqual(response.status_code, 200)
322            response = self.client.get(grandchild.get_absolute_url())
323            self.assertEqual(response.status_code, 200)
324            self.assertFalse(child.get_absolute_url() in grandchild.get_absolute_url())
325
326    def test_templates(self):
327        """
328        Test the inheritance magic for templates
329        """
330        parent = create_page("parent", "nav_playground.html", "en")
331        child = create_page("child", "nav_playground.html", "en", parent=parent)
332        child.template = settings.CMS_TEMPLATE_INHERITANCE_MAGIC
333        child.save()
334        self.assertEqual(child.template, settings.CMS_TEMPLATE_INHERITANCE_MAGIC)
335        self.assertEqual(parent.get_template_name(), child.get_template_name())
336        parent.template = settings.CMS_TEMPLATE_INHERITANCE_MAGIC
337        parent.save()
338        self.assertEqual(parent.template, settings.CMS_TEMPLATE_INHERITANCE_MAGIC)
339        self.assertEqual(parent.get_template(), settings.CMS_TEMPLATES[0][0])
340        self.assertEqual(parent.get_template_name(), settings.CMS_TEMPLATES[0][1])
341        
342    def test_delete_with_plugins(self):
343        """
344        Check that plugins and placeholders get correctly deleted when we delete
345        a page!
346        """
347        page = create_page("page", "nav_playground.html", "en")
348        page.rescan_placeholders() # create placeholders
349        placeholder = page.placeholders.all()[0]
350        plugin_base = CMSPlugin(
351            plugin_type='TextPlugin',
352            placeholder=placeholder, 
353            position=1, 
354            language=settings.LANGUAGES[0][0]
355        )
356        plugin_base.insert_at(None, position='last-child', save=False)
357                
358        plugin = Text(body='')
359        plugin_base.set_base_attr(plugin)
360        plugin.save()
361        self.assertEqual(CMSPlugin.objects.count(), 1)
362        self.assertEqual(Text.objects.count(), 1)
363        self.assertTrue(Placeholder.objects.count()  > 0)
364        page.delete()
365        self.assertEqual(CMSPlugin.objects.count(), 0)
366        self.assertEqual(Text.objects.count(), 0)
367        self.assertEqual(Placeholder.objects.count(), 0)
368        
369    def test_get_page_from_request_on_non_cms_admin(self):
370        request = self.get_request(
371            reverse('admin:sampleapp_category_change', args=(1,))
372        )
373        page = get_page_from_request(request)
374        self.assertEqual(page, None)
375        
376    def test_get_page_from_request_on_cms_admin(self):
377        page = create_page("page", "nav_playground.html", "en")
378        request = self.get_request(
379            reverse('admin:cms_page_change', args=(page.pk,))
380        )
381        found_page = get_page_from_request(request)
382        self.assertTrue(found_page)
383        self.assertEqual(found_page.pk, page.pk)
384        
385    def test_get_page_from_request_on_cms_admin_nopage(self):
386        request = self.get_request(
387            reverse('admin:cms_page_change', args=(1,))
388        )
389        page = get_page_from_request(request)
390        self.assertEqual(page, None)
391        
392    def test_get_page_from_request_cached(self):
393        mock_page = 'hello world'
394        request = self.get_request(
395            reverse('admin:sampleapp_category_change', args=(1,))
396        )
397        request._current_page_cache = mock_page
398        page = get_page_from_request(request)
399        self.assertEqual(page, mock_page)
400        
401    def test_get_page_from_request_nopage(self):
402        request = self.get_request('/')
403        page = get_page_from_request(request)
404        self.assertEqual(page, None)
405    
406    def test_get_page_from_request_with_page_404(self):
407        page = create_page("page", "nav_playground.html", "en", published=True)
408        page.publish()
409        request = self.get_request('/does-not-exist/')
410        found_page = get_page_from_request(request)
411        self.assertEqual(found_page, None)
412    
413    def test_get_page_from_request_with_page_preview(self):
414        page = create_page("page", "nav_playground.html", "en")
415        request = self.get_request('%s?preview' % page.get_absolute_url())
416        request.user.is_staff = False
417        found_page = get_page_from_request(request)
418        self.assertEqual(found_page, None)
419        superuser = self.get_superuser()
420        with self.login_user_context(superuser):
421            request = self.get_request('%s?preview&draft' % page.get_absolute_url())
422            found_page = get_page_from_request(request)
423            self.assertTrue(found_page)
424            self.assertEqual(found_page.pk, page.pk)
425        
426    def test_get_page_from_request_on_cms_admin_with_editplugin(self):
427        page = create_page("page", "nav_playground.html", "en")
428        request = self.get_request(
429            reverse('admin:cms_page_change', args=(page.pk,)) + 'edit-plugin/42/'
430        )
431        found_page = get_page_from_request(request)
432        self.assertTrue(found_page)
433        self.assertEqual(found_page.pk, page.pk)
434        
435    def test_get_page_from_request_on_cms_admin_with_editplugin_nopage(self):
436        request = self.get_request(
437            reverse('admin:cms_page_change', args=(1,)) + 'edit-plugin/42/'
438        )
439        page = get_page_from_request(request)
440        self.assertEqual(page, None)
441    
442    def test_page_already_expired(self):
443        """
444        Test that a page which has a end date in the past gives a 404, not a
445        500.
446        """
447        yesterday = datetime.date.today() - datetime.timedelta(days=1)
448        with SettingsOverride(CMS_MODERATOR=False, CMS_PERMISSION=False):
449            page = create_page('page', 'nav_playground.html', 'en',
450                               publication_end_date=yesterday, published=True)
451            resp = self.client.get(page.get_absolute_url('en'))
452            self.assertEqual(resp.status_code, 404)
453    
454    def test_existing_overwrite_url(self):
455        with SettingsOverride(CMS_MODERATOR=False, CMS_PERMISSION=False):
456            create_page('home', 'nav_playground.html', 'en', published=True)
457            create_page('boo', 'nav_playground.html', 'en', published=True)
458            data = {
459                'title': 'foo',
460                'overwrite_url': '/boo/',
461                'slug': 'foo',
462                'language': 'en',
463                'template': 'nav_playground.html',
464                'site': 1,
465            }
466            form = PageForm(data)
467            self.assertFalse(form.is_valid())
468            self.assertTrue('overwrite_url' in form.errors)
469        
470    def test_page_urls(self):
471        page1 = create_page('test page 1', 'nav_playground.html', 'en',
472            published=True)
473
474        page2 = create_page('test page 2', 'nav_playground.html', 'en',
475            published=True, parent=page1)
476
477        page3 = create_page('test page 3', 'nav_playground.html', 'en',
478            published=True, parent=page2)
479
480        page4 = create_page('test page 4', 'nav_playground.html', 'en',
481            published=True)
482
483        page5 = create_page('test page 5', 'nav_playground.html', 'en',
484            published=True, parent=page4)
485
486        self.assertEqual(page1.get_absolute_url(),
487            self.get_pages_root()+'')
488        self.assertEqual(page2.get_absolute_url(),
489            self.get_pages_root()+'test-page-2/')
490        self.assertEqual(page3.get_absolute_url(),
491            self.get_pages_root()+'test-page-2/test-page-3/')
492        self.assertEqual(page4.get_absolute_url(),
493            self.get_pages_root()+'test-page-4/')
494        self.assertEqual(page5.get_absolute_url(),
495            self.get_pages_root()+'test-page-4/test-page-5/')
496
497        page3 = self.move_page(page3, page1)
498        self.assertEqual(page3.get_absolute_url(),
499            self.get_pages_root()+'test-page-3/')
500
501        page5 = self.move_page(page5, page2)
502        self.assertEqual(page5.get_absolute_url(),
503            self.get_pages_root()+'test-page-2/test-page-5/')
504
505        page3 = self.move_page(page3, page4)
506        self.assertEqual(page3.get_absolute_url(),
507            self.get_pages_root()+'test-page-4/test-page-3/')
508    
509    def test_home_slug_not_accessible(self):
510        with SettingsOverride(CMS_MODERATOR=False, CMS_PERMISSION=False):
511            page = create_page('page', 'nav_playground.html', 'en', published=True)
512            self.assertEqual(page.get_absolute_url('en'), '/')
513            resp = self.client.get('/en/')
514            self.assertEqual(resp.status_code, HttpResponse.status_code)
515            resp = self.client.get('/en/page/')
516            self.assertEqual(resp.status_code, HttpResponseNotFound.status_code)
517
518    def test_public_home_page_replaced(self):
519        """Test that publishing changes to the home page doesn't move the public version"""
520        home = create_page('home', 'nav_playground.html', 'en', published = True, slug = 'home')
521        self.assertEqual(Page.objects.drafts().get_home().get_slug(), 'home')
522        home.publish()
523        self.assertEqual(Page.objects.public().get_home().get_slug(), 'home')
524        other = create_page('other', 'nav_playground.html', 'en', published = True, slug = 'other')
525        other.publish()
526        self.assertEqual(Page.objects.drafts().get_home().get_slug(), 'home')
527        self.assertEqual(Page.objects.public().get_home().get_slug(), 'home')
528        home = Page.objects.get(pk = home.id)
529        home.in_navigation = True
530        home.save()
531        home.publish()
532        self.assertEqual(Page.objects.drafts().get_home().get_slug(), 'home')
533        self.assertEqual(Page.objects.public().get_home().get_slug(), 'home')
534
535class NoAdminPageTests(CMSTestCase):
536    urls = 'project.noadmin_urls'
537    
538    def setUp(self):
539        admin = 'django.contrib.admin'
540        noadmin_apps = [app for app in settings.INSTALLED_APPS if not app == admin]
541        self._ctx = SettingsOverride(INSTALLED_APPS=noadmin_apps)
542        self._ctx.__enter__()
543        
544    def tearDown(self):
545        self._ctx.__exit__(None, None, None)
546    
547    def test_get_page_from_request_fakeadmin_nopage(self):
548        request = self.get_request('/admin/')
549        page = get_page_from_request(request)
550        self.assertEqual(page, None)
551
552class PreviousFilteredSiblingsTests(CMSTestCase):
553    def test_with_publisher(self):
554        home = create_page('home', 'nav_playground.html', 'en', published=True)
555        home.publish()
556        other = create_page('other', 'nav_playground.html', 'en', published=True)
557        other.publish()
558        other = Page.objects.get(pk=other.pk)
559        home = Page.objects.get(pk=home.pk)
560        self.assertEqual(other.get_previous_filtered_sibling(), home)
561        self.assertEqual(home.get_previous_filtered_sibling(), None)
562        
563    def test_multisite(self):
564        firstsite = Site.objects.create(name='first', domain='first.com')
565        secondsite = Site.objects.create(name='second', domain='second.com')
566        home = create_page('home', 'nav_playground.html', 'en', published=True, site=firstsite)
567        home.publish()
568        other = create_page('other', 'nav_playground.html', 'en', published=True, site=secondsite)
569        other.publish()
570        other = Page.objects.get(pk=other.pk)
571        home = Page.objects.get(pk=home.pk)
572        self.assertEqual(other.get_previous_filtered_sibling(), None)
573        self.assertEqual(home.get_previous_filtered_sibling(), None)
574        
575
Full Screen

permmod.py

Source: permmod.py Github

copy
1# -*- coding: utf-8 -*-
2from __future__ import with_statement
3from cms.api import (create_page, publish_page, approve_page, add_plugin, 
4    create_page_user, assign_user_to_page)
5from cms.models import Page, CMSPlugin
6from cms.models.moderatormodels import (ACCESS_DESCENDANTS, 
7    ACCESS_PAGE_AND_DESCENDANTS)
8from cms.models.permissionmodels import PagePermission, GlobalPagePermission
9from cms.test_utils.testcases import (URL_CMS_PAGE_ADD, URL_CMS_PLUGIN_REMOVE, 
10    SettingsOverrideTestCase, URL_CMS_PLUGIN_ADD, CMSTestCase)
11from cms.test_utils.util.context_managers import SettingsOverride
12from cms.utils.page_resolver import get_page_from_path
13from cms.utils.permissions import has_generic_permission
14from django.contrib.auth.models import User, Permission, AnonymousUser, Group
15from django.contrib.sites.models import Site
16from django.core.management import call_command
17
18
19class PermissionModeratorTests(SettingsOverrideTestCase):
20    """Permissions and moderator together
21    
22    Fixtures contains 3 users and 1 published page and some other stuff
23    
24    Users:
25        1. `super`: superuser
26        2. `master`: user with permissions to all applications
27        3. `slave`: user assigned to page `slave-home`
28    
29    Pages:
30        1. `home`:
31            - published page
32            - master can do anything on its subpages, but not on home!
33            
34        2. `master`:
35            - published page
36            - crated by super
37            - `master` can do anything on it and its descendants
38            - subpages:
39        
40        3.       `slave-home`:
41                    - not published
42                    - assigned slave user which can add/change/delete/
43                      move/publish/moderate this page and its descendants
44                    - `master` user want to moderate this page and all descendants
45                    
46        4. `pageA`:
47            - created by super
48            - master can add/change/delete on it and descendants 
49    """
50    settings_overrides = {
51        'CMS_PERMISSION': True,
52        'CMS_MODERATOR': True,
53    }
54    
55    def setUp(self):
56        # create super user
57        self.user_super = User(username="super", is_staff=True, is_active=True, 
58            is_superuser=True)
59        self.user_super.set_password("super")
60        self.user_super.save()
61        # create staff user
62        self.user_staff = User(username="staff", is_staff=True, is_active=True)
63        self.user_staff.set_password("staff")
64        self.user_staff.save()
65        
66        with self.login_user_context(self.user_super):
67            
68            self._home_page = create_page("home", "nav_playground.html", "en",
69                                         created_by=self.user_super)
70        
71            # master page & master user
72            
73            self._master_page = create_page("master", "nav_playground.html", "en")
74            
75            # create master user
76            master = User(username="master", email="[email protected]", is_staff=True, is_active=True)
77            master.set_password('master')
78            master.save()
79            master.user_permissions.add(Permission.objects.get(codename='add_text'))
80            master.user_permissions.add(Permission.objects.get(codename='delete_text'))
81            master.user_permissions.add(Permission.objects.get(codename='change_text'))
82            
83            self.user_master = create_page_user(self.user_super, master, grant_all=True)
84            # create non global, non staff user
85            self.user_non_global = User(username="nonglobal", is_active=True)
86            self.user_non_global.set_password("nonglobal")
87            self.user_non_global.save()
88            
89            # assign master user under home page
90            assign_user_to_page(self.home_page, self.user_master,
91                                grant_on=ACCESS_DESCENDANTS, grant_all=True)
92            
93            # and to master page
94            assign_user_to_page(self.master_page, self.user_master,
95                                grant_on=ACCESS_PAGE_AND_DESCENDANTS, grant_all=True)
96            
97            # slave page & slave user
98            
99            self._slave_page = create_page("slave-home", "nav_playground.html", "en",
100                              parent=self.master_page, created_by=self.user_super)
101        
102            slave = User(username='slave', email='[email protected]', is_staff=True)
103            slave.set_password('slave')
104            slave.save()
105            slave.user_permissions.add(Permission.objects.get(codename='add_text'))
106            slave.user_permissions.add(Permission.objects.get(codename='delete_text'))
107            slave.user_permissions.add(Permission.objects.get(codename='change_text'))
108            
109            self.user_slave = create_page_user(self.user_super, slave,  can_add_page=True,
110                                        can_change_page=True, can_delete_page=True)
111            
112            assign_user_to_page(self.slave_page, self.user_slave, grant_all=True)
113    
114            # create page_b
115            page_b = create_page("pageB", "nav_playground.html", "en", created_by=self.user_super)
116            # Normal user
117            normal = User(username='normal', email='[email protected]', is_active=True)
118            normal.set_password('normal')
119            normal.save()
120            self.user_normal = create_page_user(self.user_master, normal)
121            # it's allowed for the normal user to view the page
122            assign_user_to_page(page_b, self.user_normal, can_view=True)
123            self.user_normal = self.reload(self.user_normal)
124            # create page_a - sample page from master
125            
126            page_a = create_page("pageA", "nav_playground.html", "en",
127                                 created_by=self.user_super)
128            assign_user_to_page(page_a, self.user_master, 
129                can_add=True, can_change=True, can_delete=True, can_publish=True, 
130                can_move_page=True, can_moderate=True)
131
132            # publish after creating all drafts
133            publish_page(self.home_page, self.user_super)
134            
135            publish_page(self.master_page, self.user_super)
136            
137            self.page_b = publish_page(page_b, self.user_super)
138            # logg in as master, and request moderation for slave page and descendants
139            self.request_moderation(self.slave_page, 7)
140    
141    @property
142    def master_page(self):
143        return self.reload(self._master_page)
144    
145    @property
146    def slave_page(self):
147        return self.reload(self._slave_page)
148    
149    @property
150    def home_page(self):
151        return self.reload(self._home_page)
152    
153    def _add_plugin(self, user, page):
154        """
155        Add a plugin using the test client to check for permissions.
156        """
157        with self.login_user_context(user):
158            placeholder = page.placeholders.all()[0]
159            post_data = {
160                'language': 'en',
161                'page_id': page.pk,
162                'placeholder': placeholder.pk,
163                'plugin_type': 'TextPlugin'
164            }
165            url = URL_CMS_PLUGIN_ADD % page.pk
166            response = self.client.post(url, post_data)
167            self.assertEqual(response.status_code, 200)
168            self.assertTrue(response.content.isdigit())
169            return response.content
170
171    def test_super_can_add_page_to_root(self):
172        with self.login_user_context(self.user_super):
173            response = self.client.get(URL_CMS_PAGE_ADD)
174            self.assertEqual(response.status_code, 200)
175    
176    def test_master_can_add_page_to_root(self):
177        with self.login_user_context(self.user_master):
178            response = self.client.get(URL_CMS_PAGE_ADD)
179            self.assertEqual(response.status_code, 403)
180        
181    def test_slave_can_add_page_to_root(self):
182        with self.login_user_context(self.user_slave):
183            response = self.client.get(URL_CMS_PAGE_ADD)
184            self.assertEqual(response.status_code, 403)
185    
186    def test_moderation_on_slave_home(self):
187        self.assertEqual(self.slave_page.get_moderator_queryset().count(), 1)
188    
189    def test_slave_can_add_page_under_slave_home(self):
190        with self.login_user_context(self.user_slave):
191            # move to admin.py?
192            # url = URL_CMS_PAGE_ADD + "?target=%d&position=last-child" % slave_page.pk
193            
194            # can he even access it over get?
195            # response = self.client.get(url)
196            # self.assertEqual(response.status_code, 200)
197            
198            # add page
199            page = create_page("page", "nav_playground.html", "en",
200                               parent=self.slave_page, created_by=self.user_slave)
201            # adds user_slave as page moderator for this page
202            # public model shouldn't be available yet, because of the moderation
203            # removed test cases since Title object does not inherit from Publisher anymore
204            #self.assertObjectExist(Title.objects, slug=page_data['slug'])
205            #self.assertObjectDoesNotExist(Title.objects.public(), slug=page_data['slug'])
206            
207            # moderators and approvement ok?
208            self.assertEqual(page.get_moderator_queryset().count(), 1)
209            self.assertEqual(page.moderator_state, Page.MODERATOR_CHANGED)
210            
211            # must not have public object yet
212            self.assertFalse(page.publisher_public)
213    
214            self.assertTrue(has_generic_permission(page.pk, self.user_slave, "publish", 1))
215    
216            # publish as slave, published as user_master before 
217            publish_page(page, self.user_slave)
218            
219            # user_slave is moderator for this page
220            # approve / publish as user_slave
221            # user master should be able to approve aswell
222            page = approve_page(page, self.user_slave)
223
224    def test_page_added_by_slave_can_be_published_approved_by_user_master(self):
225        # add page
226        page = create_page("page", "nav_playground.html", "en",
227                           parent=self.slave_page, created_by=self.user_slave)
228        # same as test_slave_can_add_page_under_slave_home        
229        self.assertEqual(page.get_moderator_queryset().count(), 1)
230        self.assertEqual(page.moderator_state, Page.MODERATOR_CHANGED)
231        
232        # must not have public object yet
233        self.assertFalse(page.publisher_public)
234        
235        self.assertTrue(has_generic_permission(page.pk, self.user_master, "publish", page.site.pk))
236        # should be True user_master should have publish permissions for childred aswell
237        # don't test for published since publishing must be approved
238        publish_page(page, self.user_master)
239        
240        # user_master is moderator for top level page / but can't approve descendants?
241        # approve / publish as user_master
242        # user master should be able to approve descendants
243        page = approve_page(page, self.user_master)    
244        
245    def test_super_can_add_plugin(self):
246        self._add_plugin(self.user_super, page=self.slave_page)
247    
248    def test_master_can_add_plugin(self):
249        self._add_plugin(self.user_master, page=self.slave_page)
250    
251    def test_slave_can_add_plugin(self):
252        self._add_plugin(self.user_slave, page=self.slave_page)
253    
254    def test_same_order(self):
255        # create 4 pages
256        slugs = []
257        for i in range(0, 4):
258            page = create_page("page", "nav_playground.html", "en",
259                               parent=self.home_page)
260            slug = page.title_set.drafts()[0].slug
261            slugs.append(slug)
262        
263        # approve last 2 pages in reverse order
264        for slug in reversed(slugs[2:]):
265            page = self.assertObjectExist(Page.objects.drafts(), title_set__slug=slug)
266            page = publish_page(page, self.user_master, True)
267            self.check_published_page_attributes(page)
268    
269    def test_create_copy_publish(self):
270        # create new page to copy
271        page = create_page("page", "nav_playground.html", "en",
272                           parent=self.slave_page)
273        
274        # copy it under home page...
275        # TODO: Use page.copy_page here
276        with self.login_user_context(self.user_master):
277            copied_page = self.copy_page(page, self.home_page)
278        
279        page = publish_page(copied_page, self.user_master, True)
280        self.check_published_page_attributes(page)
281    
282    
283    def test_create_publish_copy(self):
284        # create new page to copy
285        page = create_page("page", "nav_playground.html", "en",
286                           parent=self.home_page)
287        
288        page = publish_page(page, self.user_master, True)
289        
290        # copy it under master page...
291        # TODO: Use page.copy_page here
292        with self.login_user_context(self.user_master):
293            copied_page = self.copy_page(page, self.master_page)
294        
295        self.check_published_page_attributes(page)
296        copied_page = publish_page(copied_page, self.user_master, True)
297        self.check_published_page_attributes(copied_page)
298        
299        
300    def test_subtree_needs_approvement(self):
301        # create page under slave_page
302        page = create_page("parent", "nav_playground.html", "en",
303                           parent=self.home_page)
304        self.assertFalse(page.publisher_public)
305        
306        # create subpage uner page
307        subpage = create_page("subpage", "nav_playground.html", "en", parent=page)
308        self.assertFalse(subpage.publisher_public)
309        
310        # publish both of them in reverse order 
311        subpage = publish_page(subpage, self.user_master, True) 
312        
313        # subpage should not be published, because parent is not published 
314        # yet, should be marked as `publish when parent`
315        self.assertFalse(subpage.publisher_public) 
316        
317        # pagemoderator state must be set
318        self.assertEqual(subpage.moderator_state, Page.MODERATOR_APPROVED_WAITING_FOR_PARENTS)
319        
320        # publish page (parent of subage), so subpage must be published also
321        page = publish_page(page, self.user_master, True)
322        self.assertNotEqual(page.publisher_public, None)
323        
324        # reload subpage, it was probably changed
325        subpage = self.reload_page(subpage)
326        
327        # parent was published, so subpage must be also published..
328        self.assertNotEqual(subpage.publisher_public, None) 
329        
330        #check attributes
331        self.check_published_page_attributes(page)
332        self.check_published_page_attributes(subpage)
333
334
335    def test_subtree_with_super(self):
336        # create page under root
337        page = create_page("page", "nav_playground.html", "en")
338        self.assertFalse(page.publisher_public)
339        
340        # create subpage under page
341        subpage = create_page("subpage", "nav_playground.html", "en",
342                              parent=page)
343        self.assertFalse(subpage.publisher_public)
344        
345        # tree id must be the same
346        self.assertEqual(page.tree_id, subpage.tree_id)
347        
348        # publish both of them  
349        page = self.reload(page)
350        page = publish_page(page, self.user_super, True)
351        # reload subpage, there were an tree_id change
352        subpage = self.reload_page(subpage)
353        self.assertEqual(page.tree_id, subpage.tree_id)
354        
355        subpage = publish_page(subpage, self.user_super, True)
356        # tree id must stay the same
357        self.assertEqual(page.tree_id, subpage.tree_id)
358        
359        # published pages must also have the same tree_id
360        self.assertEqual(page.publisher_public.tree_id, subpage.publisher_public.tree_id)
361        
362        #check attributes
363        self.check_published_page_attributes(page) 
364        self.check_published_page_attributes(subpage)
365        
366        
367    def test_super_add_page_to_root(self):
368        """Create page which is not under moderation in root, and check if 
369        some properties are correct.
370        """
371        # create page under root
372        page = create_page("page", "nav_playground.html", "en")
373        
374        # public must not exist
375        self.assertFalse(page.publisher_public)
376        
377        # moderator_state must be changed
378        self.assertEqual(page.moderator_state, Page.MODERATOR_CHANGED)
379    
380    
381    def test_moderator_flags(self):
382        """Add page under slave_home and check its flag
383        """
384        page = create_page("page", "nav_playground.html", "en",
385                           parent=self.slave_page)
386        
387        # moderator_state must be changed
388        self.assertEqual(page.moderator_state, Page.MODERATOR_CHANGED)
389        
390        # check publish box
391        page = publish_page(page, self.user_slave)
392        
393        # page should request approvement now
394        self.assertEqual(page.moderator_state, Page.MODERATOR_NEED_APPROVEMENT)
395        
396        # approve it by master
397
398        # approve this page - but it doesn't get published yet, because 
399        # slave home is not published
400        page = approve_page(page, self.user_master)
401        
402        # public page must not exist because of parent
403        self.assertFalse(page.publisher_public)
404        
405        # waiting for parents
406        self.assertEqual(page.moderator_state, Page.MODERATOR_APPROVED_WAITING_FOR_PARENTS)
407        
408        # publish slave page
409        slave_page = publish_page(self.slave_page, self.user_master)
410        
411        self.assertFalse(page.publisher_public)
412        self.assertFalse(slave_page.publisher_public)
413        
414        # they must be approved first
415        slave_page = approve_page(slave_page, self.user_master)
416        
417        # master is approved
418        self.assertEqual(slave_page.moderator_state, Page.MODERATOR_APPROVED)
419        
420        # reload page
421        page = self.reload_page(page)
422        
423        # page must be approved also now
424        self.assertEqual(page.moderator_state, Page.MODERATOR_APPROVED)
425        
426    def test_plugins_get_published(self):
427        # create page under root
428        page = create_page("page", "nav_playground.html", "en")
429        placeholder = page.placeholders.all()[0]
430        add_plugin(placeholder, "TextPlugin", "en", body="test")
431        # public must not exist
432        self.assertEqual(CMSPlugin.objects.all().count(), 1)
433        publish_page(page, self.user_super, True)
434        self.assertEqual(CMSPlugin.objects.all().count(), 2)
435
436    def test_remove_plugin_page_under_moderation(self):
437        # login as slave and create page
438        page = create_page("page", "nav_playground.html", "en", parent=self.slave_page)
439        self.assertEqual(page.get_moderator_queryset().count(), 1)
440        
441        # add plugin
442        placeholder = page.placeholders.all()[0]
443        plugin = add_plugin(placeholder, "TextPlugin", "en", body="test")
444        
445        self.assertEqual(page.moderator_state, Page.MODERATOR_CHANGED)
446
447        # publish page
448        page = self.reload(page)
449        page = publish_page(page, self.user_slave)
450        
451        # only the draft plugin should exist
452        self.assertEqual(CMSPlugin.objects.all().count(), 1)
453        
454        # page should require approval
455        self.assertEqual(page.moderator_state, Page.MODERATOR_NEED_APPROVEMENT)
456        
457        # master approves and publishes the page
458        # first approve slave-home
459        slave_page = self.reload(self.slave_page)
460        publish_page(slave_page, self.user_master, approve=True)
461        page = self.reload(page)
462        page = publish_page(page, self.user_master, approve=True)
463        
464        # draft and public plugins should now exist
465        self.assertEqual(CMSPlugin.objects.all().count(), 2)
466        
467        # login as slave and delete the plugin - should require moderation
468        with self.login_user_context(self.user_slave):
469            plugin_data = {
470                'plugin_id': plugin.pk
471            }
472            remove_url = URL_CMS_PLUGIN_REMOVE
473            response = self.client.post(remove_url, plugin_data)
474            self.assertEquals(response.status_code, 200)
475    
476            # there should only be a public plugin - since the draft has been deleted
477            self.assertEquals(CMSPlugin.objects.all().count(), 1)
478            
479            # reload the page as it's moderator value should have been set in pageadmin.remove_plugin
480            self.assertEqual(page.moderator_state, Page.MODERATOR_APPROVED)
481            page = self.reload_page(page)
482    
483            self.assertEqual(page.moderator_state, Page.MODERATOR_NEED_APPROVEMENT)
484    
485            # login as super user and approve/publish the page
486            page = publish_page(page, self.user_super, approve=True)
487            self.assertEqual(page.moderator_state, Page.MODERATOR_APPROVED)
488    
489            # there should now be 0 plugins
490            self.assertEquals(CMSPlugin.objects.all().count(), 0)
491
492    def test_superuser_can_view(self):
493        with self.login_user_context(self.user_super):
494            response = self.client.get("/en/pageb/")
495            self.assertEqual(response.status_code, 200)
496
497    def test_staff_can_view(self):
498        with self.login_user_context(self.user_staff):
499            response = self.client.get("/en/pageb/")
500            self.assertEqual(response.status_code, 200)
501
502    def test_user_normal_can_view(self):
503        url = self.page_b.get_absolute_url(language='en')
504        with self.login_user_context(self.user_normal):
505            response = self.client.get(url)
506            self.assertEqual(response.status_code, 200)
507        with self.login_user_context(self.user_non_global):
508            response = self.client.get(url)
509            self.assertEqual(response.status_code, 404)
510        # non logged in user
511        response = self.client.get(url)
512        self.assertEqual(response.status_code, 404)
513
514    def test_user_globalpermission(self):
515        # Global user
516        with self.login_user_context(self.user_super):
517            user_global = User(username="global", is_active=True)
518            user_global.set_password("global")
519            user_global.save()
520            user_global = create_page_user(user_global, user_global)
521            user_global.is_staff = False
522            user_global.save() # Prevent is_staff permission
523            global_page = create_page("global", "nav_playground.html", "en",
524                                      published=True)
525            global_page = publish_page(global_page, user_global, approve=True)
526            # it's allowed for the normal user to view the page
527            assign_user_to_page(global_page, user_global,
528                global_permission=True, can_view=True)
529        
530        url = global_page.get_absolute_url('en')
531
532        with self.login_user_context(user_global):
533            response = self.client.get(url)
534            self.assertEqual(response.status_code, 200)
535
536        with self.login_user_context(self.user_non_global):
537            response = self.client.get(url)
538            self.assertEqual(response.status_code, 404)
539
540    def test_anonymous_user_public_for_all(self):
541        url = self.page_b.get_absolute_url('en')
542        with SettingsOverride(CMS_PUBLIC_FOR='all'):
543            response = self.client.get(url)
544            self.assertEqual(response.status_code, 404)
545
546    def test_anonymous_user_public_for_none(self):
547        # default of when to show pages to anonymous user doesn't take
548        # global permissions into account
549        url = self.page_b.get_absolute_url('en')
550        with SettingsOverride(CMS_PUBLIC_FOR=None):
551            response = self.client.get(url)
552            self.assertEqual(response.status_code, 404)
553            
554
555class PatricksMoveTest(SettingsOverrideTestCase):
556    """
557    Fixtures contains 3 users and 1 published page and some other stuff
558    
559    Users:
560        1. `super`: superuser
561        2. `master`: user with permissions to all applications
562        3. `slave`: user assigned to page `slave-home`
563    
564    Pages:
565        1. `home`:
566            - published page
567            - master can do anything on its subpages, but not on home!
568            
569        2. `master`:
570            - published page
571            - crated by super
572            - `master` can do anything on it and its descendants
573            - subpages:
574        
575        3.       `slave-home`:
576                    - not published
577                    - assigned slave user which can add/change/delete/
578                      move/publish/moderate this page and its descendants
579                    - `master` user want to moderate this page and all descendants
580                    
581        4. `pageA`:
582            - created by super
583            - master can add/change/delete on it and descendants 
584    """
585    settings_overrides = {
586        'CMS_PERMISSION': True,
587        'CMS_MODERATOR': True,
588    }
589    
590    def setUp(self):
591        # create super user
592        self.user_super = User(username="super", is_staff=True, is_active=True, 
593            is_superuser=True)
594        self.user_super.set_password("super")
595        self.user_super.save()
596        with self.login_user_context(self.user_super):
597        
598            self._home_page = create_page("home", "nav_playground.html", "en",
599                                         created_by=self.user_super)
600            
601            # master page & master user
602            
603            self._master_page = create_page("master", "nav_playground.html", "en")
604    
605            # create master user
606            master = User.objects.create(username="master", email="[email protected]", password="master")
607            self.user_master = create_page_user(self.user_super, master, grant_all=True)
608            
609            # assign master user under home page
610            assign_user_to_page(self.home_page, self.user_master,
611                                grant_on=ACCESS_DESCENDANTS, grant_all=True)
612            
613            # and to master page
614            assign_user_to_page(self.master_page, self.user_master, grant_all=True)
615            
616            # slave page & slave user
617            
618            self._slave_page = create_page("slave-home", "nav_playground.html", "en",
619                              parent=self.master_page, created_by=self.user_super)
620            slave = User(username='slave', email='[email protected]', is_staff=True, is_active=True)
621            slave.set_password('slave')
622            slave.save()
623            self.user_slave = create_page_user(self.user_super, slave,  can_add_page=True,
624                                        can_change_page=True, can_delete_page=True)
625            
626            assign_user_to_page(self.slave_page, self.user_slave, grant_all=True)
627            
628            # create page_a - sample page from master
629            
630            page_a = create_page("pageA", "nav_playground.html", "en",
631                                 created_by=self.user_super)
632            assign_user_to_page(page_a, self.user_master, 
633                can_add=True, can_change=True, can_delete=True, can_publish=True, 
634                can_move_page=True, can_moderate=True)
635            
636            # publish after creating all drafts
637            publish_page(self.home_page, self.user_super)
638            publish_page(self.master_page, self.user_super)
639            # logg in as master, and request moderation for slave page and descendants
640            self.request_moderation(self.slave_page, 7)
641        
642        with self.login_user_context(self.user_slave):
643        
644            # all of them are under moderation... 
645            self._pa = create_page("pa", "nav_playground.html", "en", parent=self.slave_page)
646            self._pb = create_page("pb", "nav_playground.html", "en", parent=self.pa, position="right")
647            self._pc = create_page("pc", "nav_playground.html", "en", parent=self.pb, position="right")
648            
649            self._pd = create_page("pd", "nav_playground.html", "en", parent=self.pb)
650            self._pe = create_page("pe", "nav_playground.html", "en", parent=self.pd, position="right")
651            
652            self._pf = create_page("pf", "nav_playground.html", "en", parent=self.pe)
653            self._pg = create_page("pg", "nav_playground.html", "en", parent=self.pf, position="right")
654            self._ph = create_page("ph", "nav_playground.html", "en", parent=self.pf, position="right")
655            
656            self.assertFalse(self.pg.publisher_public)
657            
658            # login as master for approval
659            publish_page(self.slave_page, self.user_master, approve=True)
660            
661            # publish and approve them all
662            publish_page(self.pa, self.user_master, approve=True)
663            publish_page(self.pb, self.user_master, approve=True)
664            publish_page(self.pc, self.user_master, approve=True)
665            publish_page(self.pd, self.user_master, approve=True)
666            publish_page(self.pe, self.user_master, approve=True)
667            publish_page(self.pf, self.user_master, approve=True)
668            publish_page(self.pg, self.user_master, approve=True)
669            publish_page(self.ph, self.user_master, approve=True)
670        
671    @property
672    def master_page(self):
673        return self.reload(self._master_page)
674    
675    @property
676    def slave_page(self):
677        return self.reload(self._slave_page)
678    
679    @property
680    def home_page(self):
681        return self.reload(self._home_page)
682    
683    @property
684    def pa(self):
685        return self.reload(self._pa)
686    
687    @property
688    def pb(self):
689        return self.reload(self._pb)
690    
691    @property
692    def pc(self):
693        return self.reload(self._pc)
694    
695    @property
696    def pd(self):
697        return self.reload(self._pd)
698    
699    @property
700    def pe(self):
701        return self.reload(self._pe)
702    
703    @property
704    def pf(self):
705        return self.reload(self._pf)
706    
707    @property
708    def pg(self):
709        return self.reload(self._pg)
710    
711    @property
712    def ph(self):
713        return self.reload(self._ph)
714        
715    def test_patricks_move(self):
716        """
717        
718        Tests permmod when moving trees of pages.
719
720        1. build following tree (master node is approved and published)
721        
722                 slave-home
723                /    |    \
724               A     B     C
725                   /  \     
726                  D    E     
727                    /  |  \ 
728                   F   G   H               
729
730        2. perform move oparations:
731            1. move G under C
732            2. move E under G
733            
734                 slave-home
735                /    |    \
736               A     B     C
737                   /        \
738                  D          G
739                              \   
740                               E
741                             /   \
742                            F     H       
743        
744        3. approve nodes in following order:
745            1. approve H
746            2. approve G
747            3. approve E
748            4. approve F
749        """
750        # TODO: this takes 5 seconds to run on my MBP. That's TOO LONG!
751        
752        # perform movings under slave...
753        user_master = User.objects.get(username='master')
754        self.move_page(self.pg, self.pc)
755        # We have to reload pe when using mptt >= 0.4.2, 
756        # so that mptt realized that pg is no longer a child of pe
757        self.move_page(self.pe, self.pg)
758        
759        # check urls - they should stay them same, there wasn't approved yet
760        self.assertEqual(
761            self.pg.publisher_public.get_absolute_url(), 
762            u'%smaster/slave-home/pb/pe/pg/' % self.get_pages_root()
763        )
764        self.assertEqual(
765            self.ph.publisher_public.get_absolute_url(),
766            u'%smaster/slave-home/pb/pe/ph/' % self.get_pages_root()
767        )
768        
769        # pg & pe should require approval
770        self.assertEqual(self.pg.requires_approvement(), True)
771        self.assertEqual(self.pe.requires_approvement(), True)
772        self.assertEqual(self.ph.requires_approvement(), False)
773        
774        # login as master, and approve moves
775        approve_page(self.pg, user_master)
776        approve_page(self.pe, user_master)
777        approve_page(self.ph, user_master)
778        approve_page(self.pf, user_master)
779        
780        # public parent check after move
781        self.assertEqual(self.pg.publisher_public.parent.pk, self.pc.publisher_public_id)
782        self.assertEqual(self.pe.publisher_public.parent.pk, self.pg.publisher_public_id)
783        self.assertEqual(self.ph.publisher_public.parent.pk, self.pe.publisher_public_id)
784        
785        # check if urls are correct after move
786        self.assertEqual(
787            self.pg.publisher_public.get_absolute_url(),
788            u'%smaster/slave-home/pc/pg/' % self.get_pages_root()
789        )
790        self.assertEqual(
791            self.ph.publisher_public.get_absolute_url(),
792            u'%smaster/slave-home/pc/pg/pe/ph/' % self.get_pages_root()
793        )
794
795
796class ModeratorSwitchCommandTest(CMSTestCase):
797    def test_switch_moderator_on(self):
798        with SettingsOverride(CMS_MODERATOR=False):
799            page1 = create_page('page', 'nav_playground.html', 'en', published=True)
800        with SettingsOverride(CMS_MODERATOR=True):
801            call_command('cms', 'moderator', 'on')
802            page2 = get_page_from_path(page1.get_absolute_url().strip('/'))
803        self.assertEqual(page1.get_absolute_url(), page2.get_absolute_url())
804        
805    def test_switch_moderator_off(self):
806        with SettingsOverride(CMS_MODERATOR=True):
807            page1 = create_page('page', 'nav_playground.html', 'en', published=True)
808        with SettingsOverride(CMS_MODERATOR=False):
809            page2 = get_page_from_path(page1.get_absolute_url().strip('/'))
810        self.assertEqual(page1.get_absolute_url(), page2.get_absolute_url())
811
812
813class ViewPermissionTests(SettingsOverrideTestCase):
814    settings_overrides = {
815        'CMS_MODERATOR': False,
816        'CMS_PERMISSION': True,
817        'CMS_PUBLIC_FOR': 'all',
818    }
819
820    
821    def get_request(self, user=None):
822        attrs = {
823            'user': user or AnonymousUser(),
824            'REQUEST': {},
825            'session': {},
826        }
827        return type('Request', (object,), attrs)
828    
829    def test_public_for_all_staff(self):
830        request = self.get_request()
831        request.user.is_staff = True
832        page = Page()
833        page.pk = 1
834        self.assertTrue(page.has_view_permission(request))
835
836    def test_public_for_all_staff_assert_num_queries(self):
837        request = self.get_request()
838        request.user.is_staff = True
839        page = Page()
840        page.pk = 1
841        with self.assertNumQueries(0):
842            page.has_view_permission(request)
843
844    def test_public_for_all(self):
845        user = User.objects.create_user('user', '[email protected]', 'user')
846        request = self.get_request(user)
847        page = Page()
848        page.pk = 1
849        page.level = 0
850        page.tree_id = 1
851        self.assertTrue(page.has_view_permission(request))
852
853    def test_public_for_all_num_queries(self):
854        user = User.objects.create_user('user', '[email protected]', 'user')
855        request = self.get_request(user)
856        site = Site()
857        site.pk = 1
858        page = Page()
859        page.pk = 1
860        page.level = 0
861        page.tree_id = 1
862        with self.assertNumQueries(3):
863            """
864            The queries are:
865            The current Site
866            PagePermission query for affected pages
867            GlobalpagePermission query for user
868            """
869            page.has_view_permission(request)
870    
871    def test_unauthed(self):
872        request = self.get_request()
873        page = Page()
874        page.pk = 1
875        page.level = 0
876        page.tree_id = 1
877        self.assertTrue(page.has_view_permission(request))
878        
879    def test_unauthed_num_queries(self):
880        request = self.get_request()
881        site = Site()
882        site.pk = 1
883        page = Page()
884        page.pk = 1
885        page.level = 0
886        page.tree_id = 1
887        with self.assertNumQueries(1):
888            """
889            The query is:
890            PagePermission query for affected pages
891            """
892            page.has_view_permission(request)
893    
894    def test_authed_basic_perm(self):
895        with SettingsOverride(CMS_PUBLIC_FOR='staff'):
896            user = User.objects.create_user('user', '[email protected]', 'user')
897            user.user_permissions.add(Permission.objects.get(codename='view_page'))
898            request = self.get_request(user)
899            page = Page()
900            page.pk = 1
901            page.level = 0
902            page.tree_id = 1
903            self.assertTrue(page.has_view_permission(request))
904    
905    def test_authed_basic_perm_num_queries(self):
906        site = Site()
907        site.pk = 1
908        with SettingsOverride(CMS_PUBLIC_FOR='staff'):
909            user = User.objects.create_user('user', '[email protected]', 'user')
910            user.user_permissions.add(Permission.objects.get(codename='view_page'))
911            request = self.get_request(user)
912            page = Page()
913            page.pk = 1
914            page.level = 0
915            page.tree_id = 1
916            with self.assertNumQueries(5):
917                """
918                The queries are:
919                The site
920                PagePermission query for affected pages
921                GlobalpagePermission query for user
922                Generic django permission lookup
923                content type lookup by permission lookup
924                """
925                page.has_view_permission(request)
926    
927    def test_authed_no_access(self):
928        with SettingsOverride(CMS_PUBLIC_FOR='staff'):
929            user = User.objects.create_user('user', '[email protected]', 'user')
930            request = self.get_request(user)
931            page = Page()
932            page.pk = 1
933            page.level = 0
934            page.tree_id = 1
935            self.assertFalse(page.has_view_permission(request))
936    
937    def test_unauthed_no_access(self):
938        with SettingsOverride(CMS_PUBLIC_FOR='staff'):
939            request = self.get_request()
940            page = Page()
941            page.pk = 1
942            page.level = 0
943            page.tree_id = 1
944            self.assertFalse(page.has_view_permission(request))
945        
946    def test_unauthed_no_access_num_queries(self):
947        site = Site()
948        site.pk = 1
949        request = self.get_request()
950        page = Page()
951        page.pk = 1
952        page.level = 0
953        page.tree_id = 1
954        with self.assertNumQueries(1):
955            page.has_view_permission(request)
956    
957    def test_page_permissions(self):
958        with SettingsOverride(CMS_PUBLIC_FOR='staff'):
959            user = User.objects.create_user('user', '[email protected]', 'user')
960            request = self.get_request(user)
961            page = create_page('A', 'nav_playground.html', 'en')
962            PagePermission.objects.create(can_view=True, user=user, page=page)
963            self.assertTrue(page.has_view_permission(request))
964    
965    def test_page_permissions_view_groups(self):
966        with SettingsOverride(CMS_PUBLIC_FOR='staff'):
967            user = User.objects.create_user('user', '[email protected]', 'user')
968            group = Group.objects.create(name='testgroup')
969            group.user_set.add(user)
970            request = self.get_request(user)
971            page = create_page('A', 'nav_playground.html', 'en')
972            PagePermission.objects.create(can_view=True, group=group, page=page)
973            self.assertTrue(page.has_view_permission(request))
974            
975    def test_global_permission(self):
976        with SettingsOverride(CMS_PUBLIC_FOR='staff'):
977            user = User.objects.create_user('user', '[email protected]', 'user')
978            GlobalPagePermission.objects.create(can_view=True, user=user)
979            request = self.get_request(user)
980            page = Page()
981            page.pk = 1
982            page.level = 0
983            page.tree_id = 1
984            self.assertTrue(page.has_view_permission(request))
985
Full Screen

products.js

Source: products.js Github

copy
1var config = require('../config');
2var ProductModel = require('../models/product').Product;
3var CategoryModel = require('../models/category').Category; // will be needed for filters
4var MerchantModel = require('../models/merchant').Merchant;
5var async = require('async');
6var HttpError = require('../error').HttpError;
7
8
9function pagination(page, maxPage) { // so Code Challenge asks(less 3rd side libs): pagination is handmade
10    var pageList = [];
11    for (var i=1; i <= maxPage; i++) {
12        if ((i >= page-2) && ( i <= page+2)) { // 2 pages before and after current page
13            pageList.push(i);
14            if (pageList.length == 5) break; // 5 - number of showing pages
15        }
16    }
17    if (pageList[0] === 1) { // try to fill up to 5 page list
18        while ((pageList.length < 5 ) && (pageList.length < maxPage)) {
19            pageList.push(pageList[pageList.length - 1] + 1);
20        }
21    }
22
23    if (pageList[pageList.length - 1] === maxPage) { // try to fill up to 5 page list
24        while ((pageList.length < 5 ) && (pageList.length < maxPage)) {
25            pageList.unshift(pageList[0] - 1);
26        }
27    }
28    return pageList; // there will be shown 5 or maxPage page links
29}
30
31function getPagination (page, data, callback) {
32    ProductModel.count({}, // code for pagination
33        function (err, count) {
34            if (err) return callback(err);
35            data.count = count;
36            var maxPage=Math.ceil(count / config.perPage);
37            page = page > maxPage ? maxPage : page; // if page parameter is more then max number of pages,
38            data.maxPage = maxPage;                 // last page will be shown
39            data.page = page;
40            data.nextPageNumber = page + 1;
41            data.prevPageNumber = page - 1;
42            data.prevPage = page != 1;
43            data.nextPage = page != maxPage;
44            data.pageList = pagination(page, maxPage);
45            callback(null);
46        });
47}
48
49function getProducts (page, data, callback) {
50    ProductModel.find({})
51        .sort('-_id') // last products will be first
52        .limit(config.perPage)
53        .skip((page - 1) * config.perPage)  // as queries are parallel, if page > maxPage we will get 0 products
54        .populate('categories') // fake FK by mongoose
55        .populate('_merchant')  // get data about categories and merchants
56        .exec(function (err, products) {
57            if (err) return callback(err);
58            data.products = products;
59            callback(null);
60        });
61}
62
63// main page, show products
64exports.get = function (req, res, next) {
65    var page = parseInt(req.query.page) || 1; // if page is string, it will be = 1, so first page will be shown
66    page = page > 0 ? page : 1; // if page is not positive, there will be "mongoose skip error"
67    var data = {};
68
69    async.parallel([ // can be changed to series or waterfall if need to show last page, when page > maxPage
70        async.apply(getPagination, page, data),
71        async.apply(getProducts, page, data)
72    ], function(err, result){
73        if (err) return next(err);
74        res.render('index', data);
75    });
76};
Full Screen

LinearTransitioner.js

Source: LinearTransitioner.js Github

copy
1/**
2 * Created by 7daysofrain on 1/2/15.
3 */
4/**
5
6 USAGE
7
8 transition classes must be found in styles/linear-transitions.css
9 original code/transitions from http://tympanus.net/Development/PageTransitions/
10
11 var secNav = new LinearTransitioner(
12 $(sec),
13 {
14	leftOut: "pt-page-moveToLeftEasing pt-page-ontop",
15	leftIn: "pt-page-moveFromRight",
16	rightOut: "pt-page-moveToRightEasing pt-page-ontop",
17	rightIn: "pt-page-moveFromLeft"
18}
19 );
20 secNav.changed.add(function(index){
21    console.log("index changed: " + index)
22 });
23
24 Animation objets can be passed this way too:
25
26 {
27 	left: LinearTransitioner.CAROUSEL_TO_LEFT
28 	right: LinearTransitioner.CAROUSEL_TO_RIGHT
29 }
30
31 */
32define(['signals','jQuery','modernizr'], function(Signal)
33{
34
35	var animEndEventNames = {
36			'WebkitAnimation' : 'webkitAnimationEnd',
37			'OAnimation' : 'oAnimationEnd',
38			'msAnimation' : 'MSAnimationEnd',
39			'animation' : 'animationend'
40		},
41	// animation end event name
42		animEndEventName = animEndEventNames[ Modernizr.prefixed( 'animation' ) ],
43	// support css animations
44		support = Modernizr.cssanimations;
45
46	var LinearTransitioner = function(el,anims){
47		if(anims.hasOwnProperty("left")){
48			var anims2 =  {
49				leftOut: anims.left.outClass,
50				leftIn: anims.left.inClass,
51				rightOut: anims.right.outClass,
52				rightIn: anims.right.inClass
53			};
54		}
55		this.$element = $(el);
56		this.$pages = this.$element.children();
57		this.current = 0;
58		this.isAnimating = false;
59		this.endCurrPage = false;
60		this.endNextPage = false;
61		this.anims = anims2 || anims;
62		this.changed = new Signal();
63
64		this.$pages.addClass("pt-page").each( function() {
65			var $page = $( this );
66			$page.data( 'originalClassList', $page.attr( 'class' ) || "" );
67		} );
68
69		this.$pages.eq( this.current ).addClass( 'pt-page-current' );
70	};
71	LinearTransitioner.prototype.goto = function(index,disableAnimation){
72
73		if( this.isAnimating || this.current == index) {
74			return false;
75		}
76
77		this.isAnimating = true;
78
79		var $currPage = this.$pages.eq( this.current );
80
81
82		var outClass = this.current < index ? this.anims.leftOut : this.anims.rightOut;
83		var inClass = this.current < index ? this.anims.leftIn : this.anims.rightIn;
84		this.current = index;
85		var $nextPage = this.$pages.eq( this.current ).addClass( 'pt-page-current' );
86		this.changed.dispatch(this.current);
87
88		var scope = this;
89		if( !support || disableAnimation) {
90			this._onEndAnimation( $currPage, $nextPage );
91			return;
92		}
93		$currPage.addClass( outClass ).one( animEndEventName, function() {
94			scope.endCurrPage = true;
95			if( scope.endNextPage ) {
96				scope._onEndAnimation( $currPage, $nextPage );
97			}
98		} );
99
100		$nextPage.removeClass("pt-page-hidden").addClass( inClass ).one( animEndEventName, function() {
101			scope.endNextPage = true;
102			if( scope.endCurrPage ) {
103				scope._onEndAnimation( $currPage, $nextPage );
104			}
105		} );
106	};
107
108
109	LinearTransitioner.prototype._onEndAnimation = function( $outpage, $inpage ) {
110		setTimeout(function(){
111			this.endCurrPage = false;
112			this.endNextPage = false;
113			this._resetPage( $outpage, $inpage );
114			this.isAnimating = false;
115		}.bind(this),300);
116	}
117
118	LinearTransitioner.prototype._resetPage = function( $outpage, $inpage ) {
119		console.log("reset");
120		$outpage.attr( 'class', $outpage.data( 'originalClassList' ) + ' pt-page-hidden' );
121		$inpage.attr( 'class', $inpage.data( 'originalClassList' ) + ' pt-page-current' );
122	}
123	LinearTransitioner.prototype.next = function(){
124		if(this.current < this.$pages.length-1){
125			this.goto(this.current+1);
126		}
127	};
128	LinearTransitioner.prototype.prev = function(){
129		if(this.current > 0){
130			this.goto(this.current-1);
131		}
132	};
133	LinearTransitioner.MOVE_TO_LEFT_FROM_RIGHT = {
134		outClass: 'pt-page-moveToLeft',
135		inClass: 'pt-page-moveFromRight'
136	};
137	LinearTransitioner.MOVE_TO_RIGHT_FROM_LEFT = {
138		outClass: 'pt-page-moveToRight',
139		inClass: 'pt-page-moveFromLeft'
140	};
141	LinearTransitioner.MOVE_TO_TOP_FROM_BOTTOM = {
142		outClass: 'pt-page-moveToTop',
143		inClass: 'pt-page-moveFromBottom'
144	};
145	LinearTransitioner.MOVE_TO_BOTTOM_FROM_TOP = {
146		outClass: 'pt-page-moveToBottom',
147		inClass: 'pt-page-moveFromTop'
148	};
149	LinearTransitioner.FADE_FROM_RIGHT = {
150		outClass: 'pt-page-fade',
151		inClass: 'pt-page-moveFromRight pt-page-ontop'
152	};
153	LinearTransitioner.FADE_FROM_LEFT = {
154		outClass: 'pt-page-fade',
155		inClass: 'pt-page-moveFromLeft pt-page-ontop'
156	};
157	LinearTransitioner.FADE_FROM_BOTTOM = {
158		outClass: 'pt-page-fade',
159		inClass: 'pt-page-moveFromBottom pt-page-ontop'
160	};
161	LinearTransitioner.FADE_FROM_TOP = {
162		outClass: 'pt-page-fade',
163		inClass: 'pt-page-moveFromTop pt-page-ontop'
164	};
165	LinearTransitioner.FADE_LEFT_FADE_RIGHT = {
166		outClass: 'pt-page-moveToLeftFade',
167		inClass: 'pt-page-moveFromRightFade'
168	};
169	LinearTransitioner.FADE_RIGHT_FADE_LEFT = {
170		outClass: 'pt-page-moveToRightFade',
171		inClass: 'pt-page-moveFromLeftFade'
172	};
173	LinearTransitioner.FADE_TOP_FADE_BOTTOM = {
174		outClass: 'pt-page-moveToTopFade',
175		inClass: 'pt-page-moveFromBottomFade'
176	};
177	LinearTransitioner.FADE_BOTTOM_FADE_TOP = {
178		outClass: 'pt-page-moveToBottomFade',
179		inClass: 'pt-page-moveFromTopFade'
180	};
181	LinearTransitioner.DIFFERENTE_EASING_FROM_RIGHT = {
182		outClass: 'pt-page-moveToLeftEasing pt-page-ontop',
183		inClass: 'pt-page-moveFromRight'
184	};
185	LinearTransitioner.DIFFERENTE_EASING_FROM_LEFT = {
186		outClass: 'pt-page-moveToRightEasing pt-page-ontop',
187		inClass: 'pt-page-moveFromLeft'
188	};
189	LinearTransitioner.DIFFERENTE_EASING_FROM_BOTTOM = {
190		outClass: 'pt-page-moveToTopEasing pt-page-ontop',
191		inClass: 'pt-page-moveFromBottom'
192	};
193	LinearTransitioner.DIFFERENTE_EASING_FROM_TOP = {
194		outClass: 'pt-page-moveToBottomEasing pt-page-ontop',
195		inClass: 'pt-page-moveFromTop'
196	};
197	LinearTransitioner.SCALE_DOWN_FROM_RIGHT = {
198		outClass: 'pt-page-scaleDown',
199		inClass: 'pt-page-moveFromRight pt-page-ontop'
200	};
201	LinearTransitioner.SCALE_DOWN_FROM_LEFT = {
202		outClass: 'pt-page-scaleDown',
203		inClass: 'pt-page-moveFromLeft pt-page-ontop'
204	};
205	LinearTransitioner.SCALE_DOWN_FROM_BOTTOM = {
206		outClass: 'pt-page-scaleDown',
207		inClass: 'pt-page-moveFromBottom pt-page-ontop'
208	};
209	LinearTransitioner.SCALE_DOWN_FROM_TOP = {
210		outClass: 'pt-page-scaleDown',
211		inClass: 'pt-page-moveFromTop pt-page-ontop'
212	};
213	LinearTransitioner.SCALE_DOWN_SCALE_DOWN = {
214		outClass: 'pt-page-scaleDown',
215		inClass: 'pt-page-scaleUpDown pt-page-delay300'
216	};
217	LinearTransitioner.SCALE_UP_SCALE_UP = {
218		outClass: 'pt-page-scaleDownUp',
219		inClass: 'pt-page-scaleUp pt-page-delay300'
220	};
221	LinearTransitioner.MOVE_TO_LEFT_SCALE_UP = {
222		outClass: 'pt-page-moveToLeft pt-page-ontop',
223		inClass: 'pt-page-scaleUp'
224	};
225	LinearTransitioner.MOVE_TO_RIGHT_SCALE_UP = {
226		outClass: 'pt-page-moveToRight pt-page-ontop',
227		inClass: 'pt-page-scaleUp'
228	};
229	LinearTransitioner.MOVE_TO_TOP_SCALE_UP = {
230		outClass: 'pt-page-moveToTop pt-page-ontop',
231		inClass: 'pt-page-scaleUp'
232	};
233	LinearTransitioner.MOVE_TO_BOTTOM_SCALE_UP = {
234		outClass: 'pt-page-moveToBottom pt-page-ontop',
235		inClass: 'pt-page-scaleUp'
236	};
237	LinearTransitioner.SCALE_DOWN_SCALE_UP = {
238		outClass: 'pt-page-scaleDownCenter',
239		inClass: 'pt-page-scaleUpCenter pt-page-delay400'
240	};
241	LinearTransitioner.GLUE_LEFT_FROM_RIGHT = {
242		outClass: 'pt-page-rotateRightSideFirst',
243		inClass: 'pt-page-moveFromRight pt-page-delay200 pt-page-ontop'
244	};
245	LinearTransitioner.GLUE_RIGHT_FROM_LEFT = {
246		outClass: 'pt-page-rotateLeftSideFirst',
247		inClass: 'pt-page-moveFromLeft pt-page-delay200 pt-page-ontop'
248	};
249	LinearTransitioner.GLUE_BOTTOM_FROM_TOP = {
250		outClass: 'pt-page-rotateTopSideFirst',
251		inClass: 'pt-page-moveFromTop pt-page-delay200 pt-page-ontop'
252	};
253	LinearTransitioner.GLUE_TOP_FROM_BOTTOM = {
254		outClass: 'pt-page-rotateBottomSideFirst',
255		inClass: 'pt-page-moveFromBottom pt-page-delay200 pt-page-ontop'
256	};
257	LinearTransitioner.FLIP_RIGHT = {
258		outClass: 'pt-page-flipOutRight',
259		inClass: 'pt-page-flipInLeft pt-page-delay500'
260	};
261	LinearTransitioner.FLIP_LEFT = {
262		outClass: 'pt-page-flipOutLeft',
263		inClass: 'pt-page-flipInRight pt-page-delay500'
264	};
265	LinearTransitioner.FLIP_TOP = {
266		outClass: 'pt-page-flipOutTop',
267		inClass: 'pt-page-flipInBottom pt-page-delay500'
268	};
269	LinearTransitioner.FLIP_BOTTOM = {
270		outClass: 'pt-page-flipOutBottom',
271		inClass: 'pt-page-flipInTop pt-page-delay500'
272	};
273	LinearTransitioner.FALL = {
274		outClass: 'pt-page-rotateFall pt-page-ontop',
275		inClass: 'pt-page-scaleUp'
276	};
277	LinearTransitioner.NEWSPAPER = {
278		outClass: 'pt-page-rotateOutNewspaper',
279		inClass: 'pt-page-rotateInNewspaper pt-page-delay500'
280	};
281	LinearTransitioner.PUSH_LEFT_FROM_RIGHT = {
282		outClass: 'pt-page-rotatePushLeft',
283		inClass: 'pt-page-moveFromRight'
284	};
285	LinearTransitioner.PUSH_RIGHT_FROM_LEFT = {
286		outClass: 'pt-page-rotatePushRight',
287		inClass: 'pt-page-moveFromLeft'
288	};
289	LinearTransitioner.PUSH_TOP_FROM_BOTTOM = {
290		outClass: 'pt-page-rotatePushTop',
291		inClass: 'pt-page-moveFromBottom'
292	};
293	LinearTransitioner.PUSH_BOTTOM_FROM_TOP = {
294		outClass: 'pt-page-rotatePushBottom',
295		inClass: 'pt-page-moveFromTop'
296	};
297	LinearTransitioner.PUSH_LEFT_PULL_RIGHT = {
298		outClass: 'pt-page-rotatePushLeft',
299		inClass: 'pt-page-rotatePullRight pt-page-delay180'
300	};
301	LinearTransitioner.PUSH_RIGHT_PULL_LEFT = {
302		outClass: 'pt-page-rotatePushRight',
303		inClass: 'pt-page-rotatePullLeft pt-page-delay180'
304	};
305	LinearTransitioner.PUSH_TOP_PULL_BOTTOM = {
306		outClass: 'pt-page-rotatePushTop',
307		inClass: 'pt-page-rotatePullBottom pt-page-delay180'
308	};
309	LinearTransitioner.PUSH_BOTTOM_PULL_TOP = {
310		outClass: 'pt-page-rotatePushBottom',
311		inClass: 'pt-page-rotatePullTop pt-page-delay180'
312	};
313	LinearTransitioner.FOLD_LEFT_FROM_RIGHT = {
314		outClass: 'pt-page-rotateFoldLeft',
315		inClass: 'pt-page-moveFromRightFade'
316	};
317	LinearTransitioner.FOLD_RIGHT_FROM_LEFT = {
318		outClass: 'pt-page-rotateFoldRight',
319		inClass: 'pt-page-moveFromLeftFade'
320	};
321	LinearTransitioner.FOLD_TOP_FROM_BOTTOM = {
322		outClass: 'pt-page-rotateFoldTop',
323		inClass: 'pt-page-moveFromBottomFade'
324	};
325	LinearTransitioner.FOLD_BOTTOM_FROM_TOP= {
326		outClass: 'pt-page-rotateFoldBottom',
327		inClass: 'pt-page-moveFromTopFade'
328	};
329	LinearTransitioner.MOVE_TO_RIGHT_UNFOLD_LEFT = {
330		outClass: 'pt-page-moveToRightFade',
331		inClass: 'pt-page-rotateUnfoldLeft'
332	};
333	LinearTransitioner.MOVE_TO_LEFT_UNFOLD_RIGHT = {
334		outClass: 'pt-page-moveToLeftFade',
335		inClass: 'pt-page-rotateUnfoldRight'
336	};
337	LinearTransitioner.MOVE_TO_BOTTOM_UNFOLD_TOP = {
338		outClass: 'pt-page-moveToBottomFade',
339		inClass: 'pt-page-rotateUnfoldTop'
340	};
341	LinearTransitioner.MOVE_TO_TOP_UNFOLD_BOTTOM = {
342		outClass: 'pt-page-moveToTopFade',
343		inClass: 'pt-page-rotateUnfoldBottom'
344	};
345	LinearTransitioner.ROOM_TO_LEFT = {
346		outClass: 'pt-page-rotateRoomLeftOut pt-page-ontop',
347		inClass: 'pt-page-rotateRoomLeftIn'
348	};
349	LinearTransitioner.ROOM_TO_RIGHT = {
350		outClass: 'pt-page-rotateRoomRightOut pt-page-ontop',
351		inClass: 'pt-page-rotateRoomRightIn'
352	};
353	LinearTransitioner.ROOM_TO_TOP = {
354		outClass: 'pt-page-rotateRoomTopOut pt-page-ontop',
355		inClass: 'pt-page-rotateRoomTopIn'
356	};
357	LinearTransitioner.ROOM_TO_BOTTOM = {
358		outClass: 'pt-page-rotateRoomBottomOut pt-page-ontop',
359		inClass: 'pt-page-rotateRoomBottomIn'
360	};
361	LinearTransitioner.CUBE_TO_LEFT = {
362		outClass: 'pt-page-rotateCubeLeftOut pt-page-ontop',
363		inClass: 'pt-page-rotateCubeLeftIn'
364	};
365	LinearTransitioner.CUBE_TO_RIGHT = {
366		outClass: 'pt-page-rotateCubeRightOut pt-page-ontop',
367		inClass: 'pt-page-rotateCubeRightIn'
368	};
369	LinearTransitioner.CUBE_TO_TOP = {
370		outClass: 'pt-page-rotateCubeTopOut pt-page-ontop',
371		inClass: 'pt-page-rotateCubeTopIn'
372	};
373	LinearTransitioner.CUBE_TO_BOTTOM = {
374		outClass: 'pt-page-rotateCubeBottomOut pt-page-ontop',
375		inClass: 'pt-page-rotateCubeBottomIn'
376	};
377	LinearTransitioner.CAROUSEL_TO_LEFT = {
378		outClass: 'pt-page-rotateCarouselLeftOut pt-page-ontop',
379		inClass: 'pt-page-rotateCarouselLeftIn'
380	};
381	LinearTransitioner.CAROUSEL_TO_RIGHT = {
382		outClass: 'pt-page-rotateCarouselRightOut pt-page-ontop',
383		inClass: 'pt-page-rotateCarouselRightIn'
384	};
385	LinearTransitioner.CAROUSEL_TO_TOP = {
386		outClass: 'pt-page-rotateCarouselTopOut pt-page-ontop',
387		inClass: 'pt-page-rotateCarouselTopIn'
388	};
389	LinearTransitioner.CAROUSEL_TO_BOTTOM = {
390		outClass: 'pt-page-rotateCarouselBottomOut pt-page-ontop',
391		inClass: 'pt-page-rotateCarouselBottomIn'
392	};
393	LinearTransitioner.SIDES = {
394		outClass: 'pt-page-rotateSidesOut',
395		inClass: 'pt-page-rotateSidesIn pt-page-delay200'
396	};
397	LinearTransitioner.SLIDE = {
398		outClass: 'pt-page-rotateSlideOut',
399		inClass: 'pt-page-rotateSlideIn'
400	};
401	return LinearTransitioner;
402});
403
Full Screen

admin-layout.js

Source: admin-layout.js Github

copy
1//=require 'ui/widgets/od_autotip'
2
3$(function(){
4	//Pagination
5	//title:页面名, total:数据总数, c_page:当前显示第几页, link:此页面链接,p_page:一页显示几条数据
6	window.setPage = function(title, total, link, c_page, p_page,l){
7		var showPage = 4; //页脚处显示4个页码
8		//var pageCount = total%p_page==0? total/p_page: Math.ceil(total/p_page); //总共页码数
9		var pageCount = total;
10
11		if(pageCount<showPage) showPage = pageCount;
12		var firstPage = (c_page >= showPage/2 +1) ? Math.ceil(c_page - showPage/2) :1;
13		if((pageCount-firstPage+1)<showPage){
14			firstPage-=(showPage-(pageCount-firstPage+1));
15		}
16		var stopPage = showPage;
17		var space = c_page - firstPage;
18
19		var prePage = c_page-1>0?c_page-1:c_page;
20		var nextPage = c_page+1<=pageCount?c_page+1:c_page;
21		var first = "", last = "", prev = "", next = '';
22		var numberLink="";
23
24		//分析有没有其他参数,不能简单地往路径上添加page和per_page参数
25		link = link+window.location.search;
26		var origin = window.location.origin;
27		var pathname = window.location.pathname;
28		var page_indexs = $.getSearchIndexs('page');
29		if(page_indexs == false) {
30			//link上没有参数,可直接 加上
31			first = $('<a />').attr('href',link+'?page=1').html('&laquo; 首页');
32			last = $('<a />').attr('href',link+'?page='+pageCount).html('尾页 &raquo;');
33			prev = $('<a />').attr('href',link+'?page='+prePage).html('&laquo; 上一页');
34			next = $('<a />').attr('href',link+'?page='+nextPage).html('下一页 &raquo;');
35			numberLink=link+"?page=";
36		}
37		else if(page_indexs == undefined){
38			//如果link上没有page参数,但有其它参数,可直接 接上
39			first = $('<a />').attr('href',link+'&page=1').html('&laquo; 首页');
40			last = $('<a />').attr('href',link+'&page='+pageCount).html('尾页 &raquo;');
41			prev = $('<a />').attr('href',link+'&page='+prePage).html('&laquo; 上一页');
42			next = $('<a />').attr('href',link+'&page='+nextPage).html('下一页 &raquo;');
43			numberLink=link+"&page=";
44		}
45		else{
46			//如果link上有page参数,找到其相应位置,修改之
47			var params =  decodeURI(window.location.search.substring(1));
48			var str1 = $.verifyToString(params.substring(0, page_indexs[0]));
49			var str2 = $.verifyToString(params.substring(page_indexs[1]+1, params.length));
50			var pre_deal_params = str1+"page="+prePage+ str2;
51			var next_deal_params = str1+"page="+nextPage+ str2;
52			var pre_url = origin + pathname + '?' + pre_deal_params;
53			var next_url = origin + pathname + '?' + next_deal_params;
54			prev = $('<a />').attr('href',pre_url).html('&laquo; 上一页');
55			next = $('<a />').attr('href',next_url).html('下一页 &raquo;');
56			first = $('<a />').attr('href',origin + pathname +'?'+str1+'page=1'+str2).html('&laquo; 首页');
57			last = $('<a />').attr('href',origin + pathname +'?'+str1+'page='+pageCount+str2).html('尾页 &raquo;');
58			numberLink=origin + pathname + '?' + str1+"page=";
59		}
60
61		$('.'+title+' .pagination').append(first).append(prev);
62		var a=new Array(); var tempPage = firstPage;
63		for(var i=0; i<stopPage; i++){
64			a[i] = $('<a />').addClass('number').html(tempPage);
65			a[i].attr('href',numberLink+tempPage);
66			if(i-space==0) a[i].addClass('current');
67			$('.'+title+' .pagination').append(a[i]);
68			tempPage++;
69		};
70		$('.'+title+' .pagination').append(next).append(last);
71	};
72
73	//切换标签
74	window.changeTab = function(tab){//传入要显示的标签 $标题
75		tab.parent().siblings().find("a").removeClass('current');
76		tab.addClass('current');
77		var currentTab = tab.attr('href');
78		$(currentTab).siblings().hide();
79		$(currentTab).show();
80		return false;
81	}
82
83	//时间显示处理 time="yyyy-MM-dd hh:mm";
84	window.formatTime =  function(time,format){
85		var o = {
86			"M+" : time.getMonth() + 1,
87			"d+" : time.getDate(),
88			"h+" : time.getHours(),
89			"m+" : time.getMinutes(),
90			"s+" : time.getSeconds(),
91			"q+" : Math.floor((time.getMonth() + 3) / 3),
92			"S" : time.getMilliseconds()
93		}
94		if (/(y+)/.test(format))
95		{
96			format = format.replace(RegExp.$1, (time.getFullYear() + "").substr(4- RegExp.$1.length));
97		}
98		for (var k in o)
99		{
100			if (new RegExp("(" + k + ")").test(format))
101			{
102				format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]: ("00" + o[k]).substr(("" + o[k]).length));
103			}
104		}
105		return format;
106	}
107
108	//省略字符串
109	window.subStr = function(str,l){
110		if(str.length <= l)
111			return str;
112		else{
113			return str.substring(0,l)+'...';
114		}
115	}
116
117	//获得URL的参数
118	window.getUrlVar = function(){
119	    var vars = [], hash;
120	    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
121	    for(var i = 0; i < hashes.length; i++)
122	    {
123	      hash = hashes[i].split('=');
124	      vars.push(hash[0]);
125	      vars[hash[0]] = hash[1];
126	    }
127	    return vars;
128  }
129
130   $.getSearchIndexs = function(key){
131		var params =  decodeURI(window.location.search.substring(1));
132		if(params == false | params == '') return false;
133		var tmp_page_index = params.indexOf(key, 0);
134		var page_start_index = undefined;
135		while(tmp_page_index >= 0)
136		{
137			if (params[tmp_page_index-1] == undefined || params[tmp_page_index-1]== '&')
138			{
139				page_start_index = tmp_page_index;
140				break;
141			}
142			else{
143				tmp_page_index = params.indexOf(key, tmp_page_index + key.length);
144			}
145		}
146		var page_end_index = undefined;
147		if(page_start_index != undefined){
148			var page_end_index  = params.indexOf('&', page_start_index);
149			if(page_end_index < 0){
150				page_end_index = params.length - 1;
151			}else{
152				page_end_index = page_end_index - 1;
153			}
154		}
155		if(page_start_index != undefined && page_end_index != undefined){
156			var arr = new Array(page_start_index, page_end_index);
157			return arr;
158		}else{
159			return undefined;
160		}
161	}
162
163	$.verifyToString =  function(key){
164		if(key == undefined || key == null ){return "";}
165		return key;
166	}
167
168	window.getLinkUrl = function(param,value){
169		var origin = window.location.origin;
170		var pathname = window.location.pathname;
171		var param_indexs = $.getSearchIndexs(param);
172		var params =  decodeURI(window.location.search.substring(1));
173		var str1 = $.verifyToString(params.substring(0, param_indexs[0]));
174		var str2 = $.verifyToString(params.substring(param_indexs[1]+1, params.length));
175
176		return origin+pathname+ '?' +str1+param+"="+value+str2;
177	}
178});
179
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Internal on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)