Example #1
0
 def _setUpVeterisSubsite(self):
     main = getPage("/home/")
     home = Page(slug="veteris", title="Veteris Council")
     main.add_child(instance=home)
     home.save_revision().publish()
     activities = Page(slug="activities", title="Veteris Calendar")
     home.add_child(instance=activities)
     activities.save_revision().publish()
     Site.objects.create(hostname='veteris.joy.test',
                         root_page_id=home.id,
                         is_default_site=False)
     events = CalendarPage(owner=self.user,
                           slug="veteris-events",
                           title="Veteris Events")
     home.add_child(instance=events)
     events.save_revision().publish()
     committee = RecurringEventPage(owner=self.user,
                                    slug="veteris-committee",
                                    title="Committee Meeting",
                                    repeat=Recurrence(
                                        dtstart=dt.date(1970, 1, 5),
                                        freq=MONTHLY,
                                        byweekday=[MO],
                                        until=dt.date(1978, 8, 7)),
                                    time_from=dt.time(14),
                                    time_to=dt.time(15))
     events.add_child(instance=committee)
     committee.save_revision().publish()
Example #2
0
    def setUp(self):
        super(TestMultipleSites, self).setUp()
        root = Page.objects.get(pk=1)
        root_a = Page(
            title='Home A', slug='home-a')
        root.add_child(instance=root_a)

        root_b = Page(
            title='Home B', slug='home-b')
        root.add_child(instance=root_b)

        self.index_a = NewsIndex(title='News A', slug='news-a')
        root_a.add_child(instance=self.index_a)

        self.index_b = NewsIndex(title='News B', slug='news-b')
        root_b.add_child(instance=self.index_b)

        self.site_a = Site.objects.create(
            hostname='site-a.com',
            root_page=root_a)

        self.site_b = Site.objects.create(
            hostname='site-b.org',
            root_page=root_b)

        self.item_a = NewsItem.objects.create(
            newsindex=self.index_a, title='Post A', date=dt(2015, 8, 1))
        self.item_b = NewsItem.objects.create(
            newsindex=self.index_b, title='Post B', date=dt(2015, 8, 2))
Example #3
0
    def test_restoring_page_custom_move_to(self):
        from wagtail_recycle_bin.wagtail_hooks import urlconf_time

        root_page = Page.objects.get(url_path="/")

        top = Page(title="1p", has_unpublished_changes=False, live=True)
        root_page.add_child(instance=top)

        sub_page = Page(title="1p 1u",
                        has_unpublished_changes=True,
                        live=False)
        top.add_child(instance=sub_page)

        with self.register_hook("before_delete_page", recycle_delete):
            delete_url = reverse("wagtailadmin_pages:delete",
                                 args=(sub_page.id, ))
            self.client.post(delete_url)

        sub_page.refresh_from_db()

        with self.register_hook("register_admin_urls", urlconf_time):
            restore_url = reverse(
                "wagtail_recycle_bin_move",
                args=(sub_page.id, ),
            )
            self.client.post(restore_url, {"move_page": str(root_page.id)})

        sub_page.refresh_from_db()

        self.assertIn(
            sub_page.id,
            list(root_page.get_children().values_list("id", flat=True)),
        )

        self.assertEqual(RecycleBin.objects.count(), 0)
Example #4
0
def _create_blog_post(title: str, parent: Page) -> BlogPost:
    """Abstracting this allows us to test more scenarios than just passing the
    fixture around.

    Args:
        title (str): The page title
        parent (Page): A page to attach our blog post to

    Returns:
        BlogPost: Description
    """
    p = BlogPost()
    p.title = title
    parent.add_child(instance=p)
    p.save_revision().publish()
    return p
Example #5
0
def _create_news_page(title: str, parent: Page) -> News:
    """Abstracting this allows us to test more scenarios than just passing the
    fixture around.

    Args:
        title (str): The page title
        parent (Page): A page to attach our article page to

    Returns:
        News: Description
    """
    p = News()
    p.title = title
    parent.add_child(instance=p)
    p.save_revision().publish()
    return p
Example #6
0
def _create_publication_index_page(title: str,
                                   parent: Page) -> PublicationIndexPage:
    """Abstracting this allows us to test more scenarios than just passing the
    fixture around.

    Args:
        title (str): The page title
        parent (Page): A page to attach our post index page to

    Returns:
        PublicationIndexPage: Description
    """
    p = PublicationIndexPage()
    p.title = title
    parent.add_child(instance=p)
    p.save_revision().publish()
    return p
Example #7
0
 def _setUpNovaSubsite(self):
     main = getPage("/home/")
     home = Page(slug="nova", title="Nova Homepage")
     main.add_child(instance=home)
     home.save_revision().publish()
     activities = Page(slug="activities", title="Nova Activities")
     home.add_child(instance=activities)
     activities.save_revision().publish()
     Site.objects.create(hostname='nova.joy.test',
                         root_page_id=home.id,
                         is_default_site=False)
     events = CalendarPage(owner=self.user,
                           slug="nova-events",
                           title="Nova Events")
     home.add_child(instance=events)
     events.save_revision().publish()
     committee = RecurringEventPage(owner=self.user,
                                    slug="executive-meeting",
                                    title="Executive Committee Meeting",
                                    repeat=Recurrence(dtstart=dt.date(
                                        1984, 8, 5),
                                                      freq=WEEKLY,
                                                      byweekday=[TH]),
                                    time_from=dt.time(13),
                                    time_to=dt.time(15))
     events.add_child(instance=committee)
     committee.save_revision().publish()
     event = SimpleEventPage(owner=self.user,
                             slug="rubbish-blitz",
                             title="Rubbish Blitz",
                             date=dt.date(1984, 9, 13),
                             time_from=dt.time(12, 30),
                             time_to=dt.time(17))
     events.add_child(instance=event)
     event.save_revision().publish()
     cancellation = CancellationPage(
         owner=self.user,
         slug="1984-09-13-cancellation",
         title="Cancellation for Thursday 13th of September",
         overrides=committee,
         except_date=dt.date(1984, 9, 13),
         cancellation_title="Meeting Cancelled",
         cancellation_details="The committee will be at "
         "the working bee")
     committee.add_child(instance=cancellation)
     cancellation.save_revision().publish()
Example #8
0
    def test_removing_page_unpublishes_all_sub_pages(self):
        root_page = Page.objects.get(url_path="/")

        top = Page(title="1p", has_unpublished_changes=False, live=True)
        root_page.add_child(instance=top)

        sub_page = Page(title="1p 1u",
                        has_unpublished_changes=True,
                        live=False)
        top.add_child(instance=sub_page)

        sub_page = Page(title="1p 2p",
                        has_unpublished_changes=False,
                        live=True)
        top.add_child(instance=sub_page)
        sub_page_id = sub_page.id

        sub_sub_page = Page(title="1p 2p 3u",
                            has_unpublished_changes=True,
                            live=False)
        sub_page.add_child(instance=sub_sub_page)

        self.assertEqual(top.get_descendants(inclusive=True).live().count(), 2)
        self.assertEqual(
            top.get_descendants(inclusive=True).not_live().count(), 2)

        with self.register_hook("before_delete_page", recycle_delete):
            delete_url = reverse("wagtailadmin_pages:delete", args=(top.id, ))
            self.client.post(delete_url)

        top.refresh_from_db()

        self.assertEqual(top.get_descendants(inclusive=True).live().count(), 0)
        self.assertEqual(
            top.get_descendants(inclusive=True).not_live().count(), 4)
Example #9
0
    def test_buttons(self):
        root_page = Page.objects.get(url_path="/")

        top_page = Page(title="top_page")
        root_page.add_child(instance=top_page)

        sub_page = Page(title="sub_page")
        top_page.add_child(instance=sub_page)

        sub_sub_page = Page(title="sub_sub_page")
        sub_page.add_child(instance=sub_sub_page)

        with self.register_hook("before_delete_page", recycle_delete):
            delete_url = reverse("wagtailadmin_pages:delete",
                                 args=(sub_sub_page.id, ))
            self.client.post(delete_url)

            delete_url = reverse("wagtailadmin_pages:delete",
                                 args=(top_page.id, ))
            self.client.post(delete_url)

        index = recycle_admin_url_helper.get_action_url("index")
        resp = self.client.get(index)

        # Since sub_sub_pages parent is now in the recycle bin we should not show the "Restore"-button.
        self.assertFalse(
            reverse("wagtail_recycle_bin_restore", args=(
                sub_sub_page.id, )) in str(resp.content))
        self.assertTrue(
            reverse("wagtail_recycle_bin_move", args=(
                sub_sub_page.id, )) in str(resp.content))

        # However - top page still has a parent (root) and should be able to be restored.
        self.assertTrue(
            reverse("wagtail_recycle_bin_restore", args=(
                top_page.id, )) in str(resp.content))
        self.assertTrue(
            reverse("wagtail_recycle_bin_move", args=(
                top_page.id, )) in str(resp.content))
Example #10
0
    def setUp(self):
        try:
            welcome = Page.objects.get(path='00010001')
        except:
            root = Page.objects.create(
                depth=1, path='0001', slug='root', title='Root'
            )

            welcome = Page(path='00010001', slug='welcome', title='Welcome')
            root.add_child(instance=welcome)

        staff_person = StaffPage(
            cnetid='staff-person', slug='staff-person', title='Staff Person'
        )
        welcome.add_child(instance=staff_person)

        some_unit = UnitPage(
            editor=staff_person,
            department_head=staff_person,
            page_maintainer=staff_person,
            slug='some-unit',
            title='Some Unit'
        )
        welcome.add_child(instance=some_unit)
Example #11
0
    def test_restoring_page_re_publishes(self):
        from wagtail_recycle_bin.wagtail_hooks import urlconf_time

        root_page = Page.objects.get(url_path="/")

        top = Page(title="1p", has_unpublished_changes=False, live=True)
        root_page.add_child(instance=top)

        sub_page = Page(title="1p 1u",
                        has_unpublished_changes=True,
                        live=False)
        top.add_child(instance=sub_page)

        sub_page = Page(title="1p 2p",
                        has_unpublished_changes=False,
                        live=True)
        top.add_child(instance=sub_page)
        sub_page_id = sub_page.id

        sub_sub_page = Page(title="1p 2p 3u",
                            has_unpublished_changes=True,
                            live=False)
        sub_page.add_child(instance=sub_sub_page)

        self.assertEqual(top.get_descendants(inclusive=True).live().count(), 2)
        self.assertEqual(
            top.get_descendants(inclusive=True).not_live().count(), 2)

        with self.register_hook("before_delete_page", recycle_delete):
            delete_url = reverse("wagtailadmin_pages:delete", args=(top.id, ))
            self.client.post(delete_url)

        top.refresh_from_db()

        self.assertEqual(top.get_descendants(inclusive=True).live().count(), 0)
        self.assertEqual(
            top.get_descendants(inclusive=True).not_live().count(), 4)

        with self.register_hook("register_admin_urls", urlconf_time):
            restore_url = reverse("wagtail_recycle_bin_restore",
                                  args=(top.id, ))
            self.client.get(restore_url)

        top.refresh_from_db()

        self.assertEqual(top.get_descendants(inclusive=True).live().count(), 2)
        self.assertEqual(
            top.get_descendants(inclusive=True).not_live().count(), 2)
        self.assertEqual(RecycleBin.objects.count(), 0)
        self.assertEqual(RecycleBinPage.objects.first().get_children().count(),
                         0)
Example #12
0
    def test_generate_page_data(self):
        root_page = Page.objects.get(url_path="/")

        top = Page(title="1p", has_unpublished_changes=False, live=True)
        root_page.add_child(instance=top)

        sub_page = Page(title="1p 1u", has_unpublished_changes=True, live=False)
        top.add_child(instance=sub_page)

        sub_page = Page(title="1p 2p", has_unpublished_changes=False, live=True)
        top.add_child(instance=sub_page)
        sub_page_id = sub_page.id

        sub_sub_page = Page(title="1p 2p 3u", has_unpublished_changes=True, live=False)
        sub_page.add_child(instance=sub_sub_page)

        self.assertEqual(top.get_descendants().live().count(), 1)
        self.assertEqual(top.get_descendants().not_live().count(), 2)

        self.assertEqual(
            json.loads(generate_page_data(top)), {"published": [top.id, sub_page_id]}
        )
Example #13
0
Page.add_root(instance=root_page)

blog_page = BlogPage(
    **{
        "title": "Blog Page",
        "slug": "blog-page",
        "live": True,
        "has_unpublished_changes": False,
        "url_path": "/blog/",
        "owner": admin,
        "first_published_at": "2018-08-28T04:30:35.450Z",
        "last_published_at": "2018-08-28T04:30:35.450Z",
        "body": ('<h2>The Blog</h2>'
                 '<p>This is my blog!</p>'),
    })
root_page.add_child(instance=blog_page)

news_page = NewsPage(
    **{
        "title": "News Page",
        "slug": "news-page",
        "live": True,
        "has_unpublished_changes": False,
        "url_path": "/news/",
        "owner": admin,
        "first_published_at": "2018-08-28T04:30:35.450Z",
        "last_published_at": "2018-08-28T04:30:35.450Z",
        "body": ('<h2>The News</h2>'
                 '<p>This is some news!</p>'),
    })
root_page.add_child(instance=news_page)
Example #14
0
class test_lib_news_pages_and_categories(TestCase):
    def setUp(self):
        # Create the homepage
        """try:
            self.homepage = Page.objects.get(path='00010001')
        except (Page.DoesNotExist):
            root = Page.objects.create(
                depth=1, path='0001', slug='root', title='Root'
            )
            self.homepage = Page(
                path='00010001', slug='welcome', title='Welcome'
            )
            root.add_child(instance=self.homepage)"""
        root = Page.objects.get(path='0001')
        self.homepage = Page(slug='starfleet-welcome',
                             title='Welcome to the Federation')
        root.add_child(instance=self.homepage)

        # Create a site and associate the homepage with it
        self.site = Site.objects.create(hostname='final-frontier',
                                        is_default_site=True,
                                        port=80,
                                        root_page=self.homepage,
                                        site_name='test site')

        # Necessary pages
        self.staff = StaffPage(title='Jean-Luc Picard',
                               cnetid='picard',
                               position_title='Captain of the USS Enterprise')
        self.homepage.add_child(instance=self.staff)

        self.unit = UnitPage(title='USS Enterprise (NCC-1701-D)',
                             page_maintainer=self.staff,
                             editor=self.staff,
                             display_in_dropdown=True)
        self.homepage.add_child(instance=self.unit)

        self.ask_page = AskPage(title='Ask a Betazoid (or don\'t)',
                                page_maintainer=self.staff,
                                editor=self.staff,
                                content_specialist=self.staff,
                                unit=self.unit)
        self.homepage.add_child(instance=self.ask_page)

        self.building = LocationPage(
            title='Deep Space 9',
            is_building=True,
            short_description='A space station orbiting Bajor.',
            long_description='A space station orbiting Bajor\
            that was called Terok Nor during the occupation.',
            page_maintainer=self.staff,
            editor=self.staff,
            content_specialist=self.staff,
            libcal_library_id=1357,
            unit=self.unit)
        self.homepage.add_child(instance=self.building)

        # Set location property on UnitPage already created
        self.unit.location = self.building
        self.unit.save()

        self.news_homepage = LibNewsIndexPage(
            title='Starfleet News',
            page_maintainer=self.staff,
            editor=self.staff,
            content_specialist=self.staff,
            unit=self.unit,
            slug='starfleet-news',
        )
        self.homepage.add_child(instance=self.news_homepage)

        self.news_article = LibNewsPage(
            title='Borg Attack!',
            page_maintainer=self.staff,
            editor=self.staff,
            content_specialist=self.staff,
            unit=self.unit,
            slug='borg-attack',
        )
        self.news_homepage.add_child(instance=self.news_article)

        self.factory = RequestFactory()
        self.client = Client()

    def tearDown(self):
        self.site.delete()

    def test_get_alpha_cats_with_categories(self):
        PublicNewsCategories.objects.create(text='Picard').save()
        PublicNewsCategories.objects.create(text='Borg').save()
        PublicNewsCategories.objects.create(text='Alpha Quadrant').save()
        cats = self.news_homepage.get_alpha_cats()
        self.assertEqual(cats[0], 'Alpha Quadrant')
        self.assertEqual(cats[1], 'Borg')
        self.assertEqual(cats[2], 'Picard')

    def test_get_alpha_cats_without_categories(self):
        cats = self.news_homepage.get_alpha_cats()
        self.assertEqual(cats, [])

    def test_visit_to_news_article_page(self):
        url = LibNewsPage.objects.live().first().url
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

    def test_generic_news_article_page_routing(self):
        url = self.news_article.url
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

    def test_news_article_page_routing_to_category_listing(self):
        url = '/starfleet-news/category/borg/'
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

    def test_non_existing_sub_url_on_article_page(self):
        url = '/starfleet-news/adsfasdf/'
        response = self.client.get(url)
        self.assertEqual(response.status_code, 404)
Example #15
0
class TestCollectingAreaPages(TestCase):

    def setUp(self):

        # Configuration for subjects
        subjects_json = {
            'tng': {
                'name': 'Star Trek: The Next Generation',
                'json': '{"display_in_dropdown": false, "parent_subject": [], "libguide_url": null, "see_also": [], "pk": %s, "name": "%s"}',
            },
            'ds9': {
                'name': 'Star Trek: Deep Space Nine',
                'json': '{"display_in_dropdown": false, "parent_subject": [], "libguide_url": null, "see_also": [], "pk": %s, "name": "%s"}',
            },
            'original': {
                'name': 'Star Trek: The Original Series',
                'json': '{"display_in_dropdown": false, "parent_subject": [], "libguide_url": null, "see_also": [], "pk": %s, "name": "%s"}',
            },
            'tribbles': {
                'name': 'Tribbles',
                'json': '{"display_in_dropdown": false, "parent_subject": [{"sort_order": 0, "parent": %s, "pk": %s, "child": %s}, {"sort_order": 1, "parent": %s, "pk": %s, "child": %s}], "libguide_url": "", "see_also": [], "pk": %s, "name": "%s"}',

            },
            'quadrotriticale': {
                'name': 'Quadrotriticale',
                'json': '{"display_in_dropdown": false, "parent_subject": [{"sort_order": 0, "parent": %s, "pk": %s, "child": %s}], "libguide_url": "", "see_also": [], "pk": %s, "name": "%s"}',
            }
        }

        # Create subjects to operate on
        Subject.objects.create(name=subjects_json['tng']['name']).save()
        Subject.objects.create(name=subjects_json['ds9']['name']).save()
        Subject.objects.create(name=subjects_json['original']['name']).save()
        Subject.objects.create(name=subjects_json['tribbles']['name']).save()
        Subject.objects.create(
            name=subjects_json['quadrotriticale']['name']).save()

        # Load the subjects into variables
        subjects = Subject.objects.all()
        self.tng = subjects.get(name=subjects_json['tng']['name'])
        self.ds9 = subjects.get(name=subjects_json['ds9']['name'])
        self.original = subjects.get(name=subjects_json['original']['name'])
        self.tribbles = subjects.get(name=subjects_json['tribbles']['name'])
        self.quadrotriticale = subjects.get(
            name=subjects_json['quadrotriticale']['name'])

        # Create parent / child relationships for subjects
        self.tribbles.from_json(subjects_json['tribbles']['json'] % (self.ds9.pk, self.ds9.pk, self.tribbles.pk,
                                                                     self.original.pk, self.original.pk, self.tribbles.pk, self.tribbles.pk, self.tribbles.name)).save()
        self.quadrotriticale.from_json(subjects_json['quadrotriticale']['json'] % (
            self.tribbles.pk, self.tribbles.pk, self.quadrotriticale.pk, self.quadrotriticale.pk, self.quadrotriticale.name)).save()

        # Get the default homepage
        try:
            self.space = Page.objects.get(path='00010001')
        except:
            root = Page.objects.create(
                depth=1,
                path='0001',
                slug='root',
                title='Root')

            self.space = Page(
                path='00010001',
                slug='welcome',
                title='Welcome')
            root.add_child(instance=self.space)

        # Create a site
        try:
            self.site = Site.objects.get(is_default_site=True)
        except:
            self.site = Site.objects.create(
                hostname='localhost',
                is_default_site=True,
                port=8000,
                root_page=self.space,
                site_name='test site'
            )

        # Create StaffPages
        self.captain = StaffPage(
            title='Jean-Luc Picard',
            cnetid='picard',
            position_title='Captain of the USS Enterprise'
        )
        self.space.add_child(instance=self.captain)

        self.doctor = StaffPage(
            title='Leonard McCoy',
            cnetid='grumpydoctor',
            position_title='Doctor on the USS Enterprise'
        )
        self.space.add_child(instance=self.doctor)

        # Create UnitPage
        self.ship = UnitPage(
            title='USS Enterprise (NCC-1701-D)',
            page_maintainer=self.captain,
            editor=self.captain,
            display_in_dropdown=True
        )
        self.space.add_child(instance=self.ship)

        # Create StaffPublicPages
        self.captain_public_page = StaffPublicPage(
            title=self.captain.title,
            cnetid=self.captain.cnetid,
            page_maintainer=self.captain,
            editor=self.captain,
            content_specialist=self.captain,
            unit=self.ship,
            slug='jean-luc-picard-public',
        )
        self.space.add_child(instance=self.captain_public_page)

        self.doctor_public_page = StaffPublicPage(
            title=self.doctor.title,
            cnetid=self.doctor.cnetid,
            page_maintainer=self.doctor,
            editor=self.doctor,
            content_specialist=self.doctor,
            unit=self.ship,
            slug='grumpy-leonard-mccoy',
        )
        self.space.add_child(instance=self.doctor_public_page)

        # Create a staff page email and append it
        self.captain.staff_page_email.create(
            sort_order='None',
            id=self.captain.id,
            page_id=4,
            page=self.captain,
            email='*****@*****.**'
        )
        self.captain.staff_page_phone_faculty_exchange.create(
            sort_order='None',
            id=self.captain.id,
            page_id=4,
            page=self.captain,
            phone_number='012-345-6789',
            faculty_exchange='Bridge'
        )

        # Collection pages
        self.collection_sisko = CollectionPage(
            title='Benjamin Sisko',
            page_maintainer=self.captain,
            editor=self.captain,
            content_specialist=self.captain,
            unit=self.ship,
            short_abstract='As a Starfleet officer coming up through the ranks, Sisko was mentored by Curzon Dax, a joined Trill serving as Federation ambassador to the Klingon Empire, when the two were stationed aboard the USS Livingston early in Sisko\'s career.'
        )
        self.space.add_child(instance=self.collection_sisko)

        self.collection_darvin = CollectionPage(
            title='Arne Darvin',
            page_maintainer=self.captain,
            editor=self.captain,
            content_specialist=self.captain,
            unit=self.ship,
            short_abstract='Darvin is a Klingon who poses as a Federation official to sabotage Federation attempts to colonize Sherman\'s Planet.'
        )
        self.space.add_child(instance=self.collection_darvin)

        # Link collection pages to subjects
        self.ds9.collection_pages.add(
            self.collection_sisko.collection_subject_placements.create(
                page=self.collection_sisko,
                subject=self.ds9
            ),
            bulk=False
        )

        self.tribbles.collection_pages.add(
            self.collection_darvin.collection_subject_placements.create(
                page=self.collection_darvin,
                subject=self.tribbles
            ),
            bulk=False
        )

        # Exhibit pages
        self.exhibit_worf = ExhibitPage(
            title='Lieutenant Commander Worf',
            page_maintainer=self.captain,
            editor=self.captain,
            content_specialist=self.captain,
            unit=self.ship,
            short_abstract='In 2364, Worf was assigned to the USS Enterprise-D as relief flight control and tactical officer with the rank of lieutenant junior grade.'
        )
        self.space.add_child(instance=self.exhibit_worf)

        self.exhibit_koloth = ExhibitPage(
            title='Captain Koloth',
            page_maintainer=self.captain,
            editor=self.captain,
            content_specialist=self.captain,
            unit=self.ship,
            short_abstract='Captain Koloth requested permission for his crew to board K7 for shore leave.'
        )
        self.space.add_child(instance=self.exhibit_koloth)

        # Link exhibit pages to subjects
        self.ds9.exhibit_pages.add(
            self.exhibit_worf.exhibit_subject_placements.create(
                page=self.exhibit_worf,
                subject=self.ds9
            ),
            bulk=False
        )

        self.tribbles.exhibit_pages.add(
            self.exhibit_koloth.exhibit_subject_placements.create(
                page=self.exhibit_koloth,
                subject=self.tribbles
            ),
            bulk=False
        )

        # Link staff pages to subjects
        StaffPageSubjectPlacement(
            page=self.captain,
            subject=self.ds9
        ).save()

        StaffPageSubjectPlacement(
            page=self.doctor,
            subject=self.tribbles
        ).save()

        # Make a CollectingAreaPage
        # Set the default subject to tng
        self.collecting_area = CollectingAreaPage(
            title='Star Trek',
            subject=self.ds9,
            page_maintainer=self.captain,
            editor=self.captain,
            content_specialist=self.captain,
            unit=self.ship,
            first_feature=self.collection_sisko,
            second_feature=self.collection_darvin,
            third_feature=self.exhibit_worf,
            fourth_feature=self.exhibit_koloth
        )
        self.space.add_child(instance=self.collecting_area)

    def tearDown(self):
        """
        Clear the cache between every test.
        """
        caches['default'].clear()

    def test_get_subjects_children_false_only_returns_one_top_level_subject(self):
        subject = self.collecting_area.get_subjects(children=False)
        self.assertEqual(len(subject), 1)
        self.assertEqual(subject.pop(), self.ds9)

    def test_get_subjects_children_true_returns_hierarchy(self):
        subjects = self.collecting_area.get_subjects(children=True)
        self.assertEqual(len(subjects), 3)
        self.assertEqual(subjects.difference(
            set([self.ds9, self.tribbles, self.quadrotriticale])), set([]))

    def test_get_subjects_with_a_different_subject(self):
        self.collecting_area.subject = self.original

        subject = self.collecting_area.get_subjects(children=False)
        self.assertEqual(len(subject), 1)
        self.assertEqual(subject.pop(), self.original)

        subjects = self.collecting_area.get_subjects(children=True)
        self.assertEqual(len(subjects), 3)
        self.assertEqual(subjects.difference(
            set([self.original, self.tribbles, self.quadrotriticale])), set([]))

        self.collecting_area.subject = self.tribbles

        subject = self.collecting_area.get_subjects(children=False)
        self.assertEqual(len(subject), 1)
        self.assertEqual(subject.pop(), self.tribbles)

        subjects = self.collecting_area.get_subjects(children=True)
        self.assertEqual(len(subjects), 2)
        self.assertEqual(subjects.difference(
            set([self.tribbles, self.quadrotriticale])), set([]))

    def test_get_subjects_without_a_subject(self):
        # This should never happen in the wild because
        # subject is a required field. Let's handle
        # for it anyhow
        void = CollectingAreaPage(title='Nagilum', page_maintainer=self.captain,
                                  editor=self.captain, content_specialist=self.captain, unit=self.ship)
        self.assertEqual(void.get_subjects(children=False), set([]))
        self.assertEqual(void.get_subjects(children=True), set([]))

    def test_build_related_link_normal(self):
        page = self.collecting_area
        link = page._build_related_link(self.captain.id, self.site)
        self.assertEqual(link, ('Jean-Luc Picard', '/jean-luc-picard/'))

    def test_build_related_link_no_page_does_not_blow_up(self):
        page = self.collecting_area
        link = page._build_related_link(999, self.site)
        self.assertEqual(link, ('', ''))

    def test_build_subject_specialist_normal(self):
        page = self.collecting_area
        subject_specialist = page._build_subject_specialist(
            self.captain, self.site)
        self.assertEqual(subject_specialist, ('Jean-Luc Picard', 'Captain of the USS Enterprise',
                                              '/jean-luc-picard-public/', '*****@*****.**', (('012-345-6789', 'Bridge'),), None))

    def test_build_subject_specialist_with_wrong_page_type(self):
        page = self.collecting_area
        self.assertRaises(
            TypeError, page._build_subject_specialist, self.ship, self.site)

    def test_get_related_no_children(self):
        page = self.collecting_area
        expected = {'collections': set([('Benjamin Sisko', '/benjamin-sisko/')]), 'subject_specialists': set([('Jean-Luc Picard', 'Captain of the USS Enterprise',
                                                                                                               '/jean-luc-picard-public/', '', (), None)]), 'exhibits': set([('Lieutenant Commander Worf', '/lieutenant-commander-worf/')])}
        self.assertEqual(page.get_related(self.site), expected)

    def test_get_related_with_children(self):
        page = self.collecting_area
        related = page.get_related(self.site, children=True)
        specialists = set(r[0] for r in related['subject_specialists'])
        collections = set(r[0] for r in related['collections'])
        exhibits = set(r[0] for r in related['exhibits'])
        self.assertTrue(
            'Leonard McCoy' in specialists and 'Jean-Luc Picard' in specialists)
        self.assertTrue(
            'Arne Darvin' in collections and 'Benjamin Sisko' in collections)
        self.assertTrue(
            'Lieutenant Commander Worf' in exhibits and 'Captain Koloth' in exhibits)
        self.assertEqual(len(specialists), 2)
        self.assertEqual(len(collections), 2)
        self.assertEqual(len(exhibits), 2)

    def test_get_features(self):
        page = self.collecting_area
        features = page.get_features(self.site)
        self.assertEqual(len(features), 4)
        for f in features:
            self.assertEqual(len(f), 4)
def page():
    parent_page = Page(title='My cool blog index')
    Page.add_root(instance=parent_page)
    page = Page(title='My cool blog')
    parent_page.add_child(instance=page)
    return page
    def setUp(self):
        try:
            welcome = Page.objects.get(path='00010001')
        except:
            root = Page.objects.create(depth=1,
                                       path='0001',
                                       slug='root',
                                       title='Root')

            welcome = Page(path='00010001', slug='welcome', title='Welcome')
            root.add_child(instance=welcome)

        chas = StaffPage(
            cnetid='chas',
            employee_type=3,
            slug='charles-blair',
            position_eliminated=False,
            position_title='Director, Digital Library Development Center',
            supervises_students=True,
            title='Charles Blair')
        welcome.add_child(instance=chas)

        bbusenius = StaffPage(cnetid='bbusenius',
                              employee_type=3,
                              slug='brad-busenius',
                              position_eliminated=False,
                              position_title='Web Administrator',
                              supervisor_override=chas,
                              supervises_students=False,
                              title='Brad Busenius')
        welcome.add_child(instance=bbusenius)

        byrne = StaffPage(
            cnetid='byrne',
            employee_type=3,
            slug='maura-byrne',
            position_eliminated=False,
            position_title='Applications Systems Analyst/Programmer',
            supervises_students=False,
            title='Maura Byrne')
        welcome.add_child(instance=byrne)

        eliminated_position = StaffPage(cnetid='eliminated-position',
                                        slug='eliminated-position',
                                        position_eliminated=False,
                                        title='Eliminated Position')
        welcome.add_child(instance=eliminated_position)

        elong = StaffPage(cnetid='elong',
                          slug='elisabeth-long',
                          position_eliminated=False,
                          title='Elisabeth Long')
        welcome.add_child(instance=elong)

        digital_services = UnitPage(department_head=elong,
                                    editor=elong,
                                    page_maintainer=elong,
                                    slug='digital-services',
                                    title='Digital Services')
        welcome.add_child(instance=digital_services)

        dldc = UnitPage(department_head=chas,
                        editor=chas,
                        page_maintainer=chas,
                        slug='dldc',
                        title='Digital Library Development Center')
        digital_services.add_child(instance=dldc)

        jej = StaffPage(cnetid='jej',
                        employee_type=3,
                        slug='john-jung',
                        position_eliminated=False,
                        position_title='Programmer/Analyst',
                        supervisor_override=chas,
                        supervises_students=False,
                        title='John Jung')
        welcome.add_child(instance=jej)

        StaffPageEmailAddresses.objects.create(page=jej,
                                               email='*****@*****.**')

        StaffPageEmailAddresses.objects.create(page=jej, email='*****@*****.**')

        StaffPagePhoneFacultyExchange.objects.create(
            page=jej, phone_number='773-702-1234', faculty_exchange='JRL 100')

        StaffPagePhoneFacultyExchange.objects.create(
            page=jej, phone_number='773-834-1234', faculty_exchange='JRL 101')

        StaffPageLibraryUnits.objects.create(page=jej, library_unit=dldc)

        StaffPageLibraryUnits.objects.create(page=jej,
                                             library_unit=digital_services)

        kzadrozny = StaffPage(
            cnetid='kzadrozny',
            employee_type=3,
            slug='kathy-zadrozny',
            position_eliminated=False,
            position_title='Web Developer and Graphic Design Specialist',
            supervisor_override=chas,
            supervises_students=True,
            title='Kathy Zadrozny')
        welcome.add_child(instance=kzadrozny)

        tyler = StaffPage(cnetid='tyler',
                          employee_type=3,
                          slug='tyler-danstrom',
                          position_eliminated=False,
                          position_title='Programmer/Analyst',
                          supervisor_override=chas,
                          supervises_students=False,
                          title='Tyler Danstrom')
        welcome.add_child(instance=tyler)
    def setUp(self):
        try:
            welcome = Page.objects.get(path='00010001')
        except:
            root = Page.objects.create(depth=1,
                                       path='0001',
                                       slug='root',
                                       title='Root')

            welcome = Page(path='00010001', slug='welcome', title='Welcome')
            root.add_child(instance=welcome)

        # StaffPages
        official_supervisor = StaffPage(cnetid='official_supervisor',
                                        slug='official-supervisor',
                                        title='Official Supervisor')
        welcome.add_child(instance=official_supervisor)

        another_official_supervisor = StaffPage(
            cnetid='another_official_supervisor',
            slug='another-official-supervisor',
            title='Another Official Supervisor')
        welcome.add_child(instance=another_official_supervisor)

        director = StaffPage(cnetid='director',
                             slug='director',
                             title='Director')
        welcome.add_child(instance=director)

        supervisor_override = StaffPage(cnetid='supervisor_override',
                                        slug='supervisor-override',
                                        title='Supervisor Override')
        welcome.add_child(instance=supervisor_override)

        employee_override = StaffPage(cnetid='employee_override',
                                      slug='employee_override',
                                      supervisor_override=supervisor_override,
                                      title='Employee Override')
        welcome.add_child(instance=employee_override)

        employee_no_override = StaffPage(cnetid='employee_no_override',
                                         slug='employee_no_override',
                                         title='Employee No Override')
        welcome.add_child(instance=employee_no_override)

        employee_two_units = StaffPage(cnetid='employee_two_units',
                                       slug='employee_two_units',
                                       title='Employee Two Units')
        welcome.add_child(instance=employee_two_units)

        content_specialist = StaffPage(cnetid='content_specialist',
                                       slug='content-specialist',
                                       title='Content Specialist')
        welcome.add_child(instance=content_specialist)

        editor = StaffPage(cnetid='editor', slug='editor', title='Editor')
        welcome.add_child(instance=editor)

        page_maintainer = StaffPage(cnetid='page_maintainer',
                                    slug='page-maintainer',
                                    title='Page Maintainer')
        welcome.add_child(instance=page_maintainer)

        # UnitPages
        unit_division = UnitPage(department_head=director,
                                 editor=editor,
                                 page_maintainer=page_maintainer,
                                 slug='unit-division',
                                 title='Unit Division')
        welcome.add_child(instance=unit_division)

        unit_one = UnitPage(department_head=official_supervisor,
                            display_in_dropdown=True,
                            editor=editor,
                            page_maintainer=page_maintainer,
                            slug='unit-one',
                            title='Unit One')
        unit_division.add_child(instance=unit_one)

        unit_two = UnitPage(department_head=another_official_supervisor,
                            editor=editor,
                            page_maintainer=page_maintainer,
                            slug='unit-two',
                            title='Unit Two')
        unit_division.add_child(instance=unit_two)

        # StandardPage
        standard_page = StandardPage(content_specialist=content_specialist,
                                     editor=editor,
                                     page_maintainer=page_maintainer,
                                     slug='standard-page',
                                     title='Standard Page',
                                     unit=unit_one)
        welcome.add_child(instance=standard_page)

        # assign staff to units
        StaffPageLibraryUnits.objects.create(page=director,
                                             library_unit=unit_division)

        StaffPageLibraryUnits.objects.create(page=official_supervisor,
                                             library_unit=unit_one)

        StaffPageLibraryUnits.objects.create(page=employee_no_override,
                                             library_unit=unit_one)

        StaffPageLibraryUnits.objects.create(page=employee_override,
                                             library_unit=unit_one)

        StaffPageLibraryUnits.objects.create(page=employee_two_units,
                                             library_unit=unit_one)

        StaffPageLibraryUnits.objects.create(page=employee_two_units,
                                             library_unit=unit_two)