# Path: privagal/gallery/factories.py
# class GalleryFactory(PageFactory):
# 
#     class Meta:
#         model = Gallery
# 
#     date = fuzzy.FuzzyDate(datetime.date(2016, 1, 1))
#     body = factory.LazyAttribute(
#         lambda x: "<p>{}</p>".format(faker.paragraph()))
# 
#     @factory.post_generation
#     def images(self, created, extracted, **kwargs):
#         """
#         Usage example:
#         >>> GalleryFactory(images__images=[ImageFactory()])
#         """
#         images = kwargs.pop('images', [])
#         if not images:
#             images = [ImageFactory() for i in range(0, 3)]
# 
#         self.images = [ImageGalleryFactory.build(page=self, image=i) for i in images]
# 
# Path: privagal/gallery/models.py
# class Gallery(AuthTokenPageMixin, Page):
#     date = models.DateField("Post date", default=timezone.now)
#     body = RichTextField(blank=True)
# 
#     content_panels = Page.content_panels + [
#         FieldPanel('date'),
#         FieldPanel('body', classname="full"),
#         InlinePanel('images', label=_('Images')),
#     ]
# 
#     parent_page_types = ['timeline.Timeline']
#     subpage_types = []
# 
#     class Meta:
#         db_table = 'privagal_gallery'
#         verbose_name = _("Gallery")
# 
#     def delete(self, *args, **kwargs):
#         with transaction.atomic():
#             # We need to call model instance method BEFORE deleting the
#             # instance itself to delete image in cascade. This is worst for
#             # performance than using QuerySet manager but it keep it stupid.
#             for image in self.images.all():
#                 image.delete()
#             super(Gallery, self).delete(*args, **kwargs)
# 
#     @property
#     def image_teaser(self):
#         return self.images.first()
# 
#     @property
#     def teaser(self):
#         return loader.render_to_string(
#             'gallery/gallery_teaser.html',
#             {
#                 PAGE_TEMPLATE_VAR: self,
#             },
#         )
# 
#     def serve_download(self, request):
#         file = self._get_archive()
#         return sendfile(request, file.filename, attachment=True)
# 
#     def _get_archive(self):
#         directory = os.path.join(settings.MEDIA_ROOT, 'archives')
#         if not os.path.exists(directory):
#             os.makedirs(directory)
# 
#         filepath = os.path.join(
#             directory, '{gallery.date}-{gallery.pk}.zip'.format(gallery=self))
#         # Force the moment, don't use cache but recreate it each time. Anyway,
#         # store it in global private directory to be served by sendfile.
#         return self._generate_zipfile(filepath)
# 
#     def _generate_zipfile(self, filepath):
#         zf = zipfile.ZipFile(filepath, mode='w')
#         for image in self.images.all().prefetch_related('image'):
#             zf.write(
#                 image.image.file.path, os.path.basename(image.image.file.name))
#         zf.close()
#         return zf
# 
# Path: privagal/timeline/factories.py
# class TimelineFactory(PageFactory):
# 
#     class Meta:
#         model = Timeline
# 
#     @factory.post_generation
#     def create(self, created, extracted, **kwargs):
#         """
#         Timeline doesn't really need a known parent but only the root page so
#         BUILD_STRATEGY isn't really required. Anyway, this is more simple to
#         achieve it in that way (instead of setting CREATE_STRATEGY and playing
#         with a lazy path attribute and MP tree...)
#         """
#         if extracted is False:
#             return
#         root = self.get_first_root_node()
#         root.add_child(instance=self)
# 
#     @factory.post_generation
#     def galleries(self, created, extracted, **kwargs):
#         galleries = extracted or []
#         for gallery in galleries:
#             self.add_child(instance=gallery)
# 
# Path: privagal/timeline/models.py
# class Timeline(AuthTokenPageMixin, Page):
# 
#     parent_page_types = []
#     subpage_types = ['gallery.Gallery']
# 
#     paginate_by = 20
# 
#     class Meta:
#         db_table = 'privagal_timeline'
# 
#     def get_context(self, request, *args, **kwargs):
#         context = super(Timeline, self).get_context(request, *args, **kwargs)
# 
#         search_query = request.GET.get('query', None)
#         context['search_query'] = search_query
# 
#         paginator, page = self.get_galleries(request, search_query)
#         context['page_obj'] = page
#         context['object_list'] = page.object_list
#         context['is_paginated'] = page.has_other_pages()
# 
#         return context
# 
#     def get_galleries(self, request, search_query):
#         qs = (
#             Gallery.objects
#             .live()
#             .prefetch_related(
#                 Prefetch(
#                     'images',
#                     queryset=ImageGallery.objects.select_related('image'),
#                 )
#             )
#             .order_by('-date')
#         )
# 
#         if search_query:
#             qs = qs.search(search_query, order_by_relevance=False)
# 
#         return paginate(request, qs, per_page=self.paginate_by)


from django.test import TestCase
from wagtail.wagtailcore.models import Page
from privagal.gallery.factories import GalleryFactory
from privagal.gallery.models import Gallery
from privagal.timeline.factories import TimelineFactory
from privagal.timeline.models import Timeline
# -*- coding: utf-8 -*-
from __future__ import unicode_literals





class PageFactoryTestCase(TestCase):
    """
    Test abstract page factory with real models for now (instead of migrating
    conditionnally a dummy page model). In fact, it must be a Wagtail feature,
    not a Privagal feature!
    """

    def tearDown(self):
        Page.objects.type(Timeline).exclude(slug='timeline').delete()

    def test_slug(self):
        page = TimelineFactory()
        self.assertEqual(page.slug, 'timeline_%d' % (int(TimelineFactory._counter.seq) - 1))

    def test_next(self):
        """
        However, this feature may live in factory.DjangoModelFactory itself!
        """
        TimelineFactory()
        # Mimic natural reset (for e.g: in Python shell)

# Path: privagal/gallery/factories.py
# class GalleryFactory(PageFactory):
# 
#     class Meta:
#         model = Gallery
# 
#     date = fuzzy.FuzzyDate(datetime.date(2016, 1, 1))
#     body = factory.LazyAttribute(
#         lambda x: "<p>{}</p>".format(faker.paragraph()))
# 
#     @factory.post_generation
#     def images(self, created, extracted, **kwargs):
#         """
#         Usage example:
#         >>> GalleryFactory(images__images=[ImageFactory()])
#         """
#         images = kwargs.pop('images', [])
#         if not images:
#             images = [ImageFactory() for i in range(0, 3)]
# 
#         self.images = [ImageGalleryFactory.build(page=self, image=i) for i in images]
# 
# Path: privagal/gallery/models.py
# class Gallery(AuthTokenPageMixin, Page):
#     date = models.DateField("Post date", default=timezone.now)
#     body = RichTextField(blank=True)
# 
#     content_panels = Page.content_panels + [
#         FieldPanel('date'),
#         FieldPanel('body', classname="full"),
#         InlinePanel('images', label=_('Images')),
#     ]
# 
#     parent_page_types = ['timeline.Timeline']
#     subpage_types = []
# 
#     class Meta:
#         db_table = 'privagal_gallery'
#         verbose_name = _("Gallery")
# 
#     def delete(self, *args, **kwargs):
#         with transaction.atomic():
#             # We need to call model instance method BEFORE deleting the
#             # instance itself to delete image in cascade. This is worst for
#             # performance than using QuerySet manager but it keep it stupid.
#             for image in self.images.all():
#                 image.delete()
#             super(Gallery, self).delete(*args, **kwargs)
# 
#     @property
#     def image_teaser(self):
#         return self.images.first()
# 
#     @property
#     def teaser(self):
#         return loader.render_to_string(
#             'gallery/gallery_teaser.html',
#             {
#                 PAGE_TEMPLATE_VAR: self,
#             },
#         )
# 
#     def serve_download(self, request):
#         file = self._get_archive()
#         return sendfile(request, file.filename, attachment=True)
# 
#     def _get_archive(self):
#         directory = os.path.join(settings.MEDIA_ROOT, 'archives')
#         if not os.path.exists(directory):
#             os.makedirs(directory)
# 
#         filepath = os.path.join(
#             directory, '{gallery.date}-{gallery.pk}.zip'.format(gallery=self))
#         # Force the moment, don't use cache but recreate it each time. Anyway,
#         # store it in global private directory to be served by sendfile.
#         return self._generate_zipfile(filepath)
# 
#     def _generate_zipfile(self, filepath):
#         zf = zipfile.ZipFile(filepath, mode='w')
#         for image in self.images.all().prefetch_related('image'):
#             zf.write(
#                 image.image.file.path, os.path.basename(image.image.file.name))
#         zf.close()
#         return zf
# 
# Path: privagal/timeline/factories.py
# class TimelineFactory(PageFactory):
# 
#     class Meta:
#         model = Timeline
# 
#     @factory.post_generation
#     def create(self, created, extracted, **kwargs):
#         """
#         Timeline doesn't really need a known parent but only the root page so
#         BUILD_STRATEGY isn't really required. Anyway, this is more simple to
#         achieve it in that way (instead of setting CREATE_STRATEGY and playing
#         with a lazy path attribute and MP tree...)
#         """
#         if extracted is False:
#             return
#         root = self.get_first_root_node()
#         root.add_child(instance=self)
# 
#     @factory.post_generation
#     def galleries(self, created, extracted, **kwargs):
#         galleries = extracted or []
#         for gallery in galleries:
#             self.add_child(instance=gallery)
# 
# Path: privagal/timeline/models.py
# class Timeline(AuthTokenPageMixin, Page):
# 
#     parent_page_types = []
#     subpage_types = ['gallery.Gallery']
# 
#     paginate_by = 20
# 
#     class Meta:
#         db_table = 'privagal_timeline'
# 
#     def get_context(self, request, *args, **kwargs):
#         context = super(Timeline, self).get_context(request, *args, **kwargs)
# 
#         search_query = request.GET.get('query', None)
#         context['search_query'] = search_query
# 
#         paginator, page = self.get_galleries(request, search_query)
#         context['page_obj'] = page
#         context['object_list'] = page.object_list
#         context['is_paginated'] = page.has_other_pages()
# 
#         return context
# 
#     def get_galleries(self, request, search_query):
#         qs = (
#             Gallery.objects
#             .live()
#             .prefetch_related(
#                 Prefetch(
#                     'images',
#                     queryset=ImageGallery.objects.select_related('image'),
#                 )
#             )
#             .order_by('-date')
#         )
# 
#         if search_query:
#             qs = qs.search(search_query, order_by_relevance=False)
# 
#         return paginate(request, qs, per_page=self.paginate_by)


# Path: privagal/core/tests/test_factories.py
from django.test import TestCase
from wagtail.wagtailcore.models import Page
from privagal.gallery.factories import GalleryFactory
from privagal.gallery.models import Gallery
from privagal.timeline.factories import TimelineFactory
from privagal.timeline.models import Timeline

# -*- coding: utf-8 -*-
from __future__ import unicode_literals





class PageFactoryTestCase(TestCase):
    """
    Test abstract page factory with real models for now (instead of migrating
    conditionnally a dummy page model). In fact, it must be a Wagtail feature,
    not a Privagal feature!
    """

    def tearDown(self):
        Page.objects.type(Timeline).exclude(slug='timeline').delete()

    def test_slug(self):
        page = TimelineFactory()
        self.assertEqual(page.slug, 'timeline_%d' % (int(TimelineFactory._counter.seq) - 1))

    def test_next(self):
        """
        However, this feature may live in factory.DjangoModelFactory itself!
        """
        TimelineFactory()
        # Mimic natural reset (for e.g: in Python shell)

        TimelineFactory.reset_sequence()