Пример #1
0
class ImageTest(TestCase):
    def setUp(self):
        self.gallery = GalleryFactory()
        self.image = ImageFactory(gallery=self.gallery)

    def tearDown(self):
        self.image.delete()
        self.gallery.delete()

    def test_get_absolute_url(self):
        absolute_url = f"{settings.MEDIA_URL}/{self.image.physical}".replace(
            "//", "/")

        self.assertEqual(absolute_url, self.image.get_absolute_url())

    def test_get_extension(self):
        self.assertEqual("jpg", self.image.get_extension())

    def test_save_and_delete_image(self):
        test_image = ImageFactory(gallery=self.gallery)
        image_path = test_image.physical.path
        self.assertTrue(os.path.isfile(image_path))

        test_image.delete()
        self.assertFalse(os.path.isfile(image_path))
Пример #2
0
 def setUp(self):
     self.gallery = GalleryFactory()
     self.profile1 = ProfileFactory()
     self.profile2 = ProfileFactory()
     self.profile3 = ProfileFactory()
     self.user_gallery1 = UserGalleryFactory(user=self.profile1.user, gallery=self.gallery, mode="W")
     self.user_gallery2 = UserGalleryFactory(user=self.profile2.user, gallery=self.gallery, mode="R")
Пример #3
0
class UserGalleryTest(TestCase):
    def setUp(self):
        self.profile = ProfileFactory()
        self.gallery = GalleryFactory()
        self.image1 = ImageFactory(gallery=self.gallery)
        self.image2 = ImageFactory(gallery=self.gallery)
        self.user_gallery = UserGalleryFactory(user=self.profile.user,
                                               gallery=self.gallery)

    def tearDown(self):
        self.image1.delete()
        self.image2.delete()
        self.user_gallery.delete()
        self.gallery.delete()

    def test_can_write(self):
        self.user_gallery.mode = "W"

        self.assertTrue(self.user_gallery.can_write())
        self.assertFalse(self.user_gallery.can_read())

    def test_can_read(self):
        self.user_gallery.mode = "R"

        self.assertFalse(self.user_gallery.can_write())
        self.assertTrue(self.user_gallery.can_read())

    def test_get_images(self):
        self.assertEqual(2, len(self.user_gallery.get_images()))

        self.assertEqual(self.image1, self.user_gallery.get_images()[0])
        self.assertEqual(self.image2, self.user_gallery.get_images()[1])
Пример #4
0
 def setUp(self):
     self.profile = ProfileFactory()
     self.gallery = GalleryFactory()
     self.image1 = ImageFactory(gallery=self.gallery)
     self.image2 = ImageFactory(gallery=self.gallery)
     self.user_gallery = UserGalleryFactory(user=self.profile.user,
                                            gallery=self.gallery)
Пример #5
0
    def setUp(self):
        self.profile = ProfileFactory()
        self.other = ProfileFactory()
        self.new_participant = ProfileFactory()
        self.client = APIClient()
        client_oauth2 = create_oauth2_client(self.profile.user)
        authenticate_client(self.client, client_oauth2,
                            self.profile.user.username, "hostel77")

        self.gallery = GalleryFactory()
        UserGalleryFactory(user=self.profile.user, gallery=self.gallery)
        self.image = ImageFactory(gallery=self.gallery)

        self.gallery_other = GalleryFactory()
        UserGalleryFactory(user=self.other.user, gallery=self.gallery_other)
        self.image_other = ImageFactory(gallery=self.gallery_other)

        self.gallery_shared = GalleryFactory()
        UserGalleryFactory(user=self.other.user, gallery=self.gallery_shared)
        UserGalleryFactory(user=self.profile.user,
                           gallery=self.gallery_shared,
                           mode=GALLERY_READ)
        self.image_shared = ImageFactory(gallery=self.gallery_shared)

        tuto = PublishableContentFactory(
            type="TUTORIAL",
            author_list=[self.profile.user, self.new_participant.user])
        self.gallery_tuto = tuto.gallery
Пример #6
0
class EditImageViewTest(TestCase):
    def setUp(self):
        self.gallery = GalleryFactory()
        self.image = ImageFactory(gallery=self.gallery)
        self.profile1 = ProfileFactory()
        self.profile2 = ProfileFactory()
        self.profile3 = ProfileFactory()
        self.user_gallery1 = UserGalleryFactory(user=self.profile1.user, gallery=self.gallery, mode="W")
        self.user_gallery2 = UserGalleryFactory(user=self.profile2.user, gallery=self.gallery, mode="R")

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

    def test_fail_member_no_permission_can_edit_image(self):
        self.client.force_login(self.profile3.user)

        with (settings.BASE_DIR / "fixtures" / "logo.png").open("rb") as fp:

            self.client.post(
                reverse("gallery-image-edit", args=[self.gallery.pk, self.image.pk]),
                {"title": "modify with no perms", "legend": "test legend", "physical": fp},
                follow=True,
            )

        image_test = Image.objects.get(pk=self.image.pk)
        self.assertNotEqual("modify with no perms", image_test.title)
        image_test.delete()

    def test_success_member_edit_image(self):
        self.client.force_login(self.profile1.user)

        for filename in (
            settings.BASE_DIR / "fixtures" / "logo.png",
            settings.BASE_DIR / "assets" / "licenses" / "copyright.svg",
        ):
            with self.subTest(filename):
                nb_files = len(os.listdir(self.gallery.get_gallery_path()))

                with open(filename, "rb") as fp:
                    response = self.client.post(
                        reverse("gallery-image-edit", args=[self.gallery.pk, self.image.pk]),
                        {"title": "edit title", "legend": "dit legend", "physical": fp},
                        follow=True,
                    )
                self.assertEqual(200, response.status_code)
                # Check that 1 image and 2 thumbnails have been saved in the gallery
                self.assertEqual(nb_files + 3, len(os.listdir(self.gallery.get_gallery_path())))

                self.image.refresh_from_db()
                self.assertEqual("edit title", self.image.title)

    def test_access_permission(self):
        self.client.force_login(self.profile1.user)

        response = self.client.get(reverse("gallery-image-edit", args=[self.gallery.pk, self.image.pk]))

        self.assertEqual(200, response.status_code)
Пример #7
0
 def setUp(self):
     self.profile1 = ProfileFactory()
     self.profile2 = ProfileFactory()
     self.profile3 = ProfileFactory()
     self.gallery1 = GalleryFactory()
     self.gallery2 = GalleryFactory()
     self.image1 = ImageFactory(gallery=self.gallery1)
     self.image2 = ImageFactory(gallery=self.gallery1)
     self.image3 = ImageFactory(gallery=self.gallery2)
     self.user_gallery1 = UserGalleryFactory(user=self.profile1.user, gallery=self.gallery1)
     self.user_gallery2 = UserGalleryFactory(user=self.profile1.user, gallery=self.gallery2)
     self.user_gallery3 = UserGalleryFactory(user=self.profile2.user, gallery=self.gallery1, mode="R")
Пример #8
0
    def test_delete_gallery_with_image(self):
        test_gallery = GalleryFactory()
        test_image = ImageFactory(gallery=test_gallery)

        path_gallery = test_gallery.get_gallery_path()
        self.assertTrue(os.path.isdir(path_gallery))
        path_image = test_image.physical.path
        self.assertTrue(os.path.isfile(path_image))

        # Destroy the gallery and the image
        test_gallery.delete()
        self.assertFalse(os.path.isdir(path_gallery))
        self.assertFalse(os.path.isfile(path_image))
Пример #9
0
    def test_list_galeries_belong_to_member(self):
        profile = ProfileFactory()
        gallery = GalleryFactory()
        GalleryFactory()
        UserGalleryFactory(user=profile.user, gallery=gallery)

        self.client.force_login(profile.user)

        response = self.client.get(reverse("gallery-list"), follow=True)
        self.assertEqual(200, response.status_code)

        self.assertEqual(1, len(response.context["galleries"]))
        self.assertEqual(
            UserGallery.objects.filter(user=profile.user).first().gallery, response.context["galleries"].first()
        )
Пример #10
0
 def setUp(self):
     self.profile1 = ProfileFactory()
     self.profile2 = ProfileFactory()
     self.profile3 = ProfileFactory()
     self.gallery1 = GalleryFactory()
     self.gallery2 = GalleryFactory()
     self.image1 = ImageFactory(gallery=self.gallery1)
     self.image2 = ImageFactory(gallery=self.gallery1)
     self.image3 = ImageFactory(gallery=self.gallery2)
     self.user_gallery1 = UserGalleryFactory(user=self.profile1.user, gallery=self.gallery1)
     self.user_gallery2 = UserGalleryFactory(user=self.profile1.user, gallery=self.gallery2)
     self.user_gallery3 = UserGalleryFactory(user=self.profile2.user, gallery=self.gallery1, mode="R")
     default_gallery_u1 = GalleryFactory(title="default", slug="default", subtitle="bla")
     UserGalleryFactory(user=self.profile1.user, gallery=default_gallery_u1, is_default=True)
     default_gallery_u2 = GalleryFactory(title="default", slug="default", subtitle="bla")
     UserGalleryFactory(user=self.profile2.user, gallery=default_gallery_u2, is_default=True)
Пример #11
0
    def test_fail_gallery_details_no_permission(self):
        """fail when a user has no permission at all"""
        gallery = GalleryFactory()
        UserGalleryFactory(gallery=gallery, user=self.profile1.user)

        self.client.force_login(self.profile2.user)

        response = self.client.get(reverse("gallery-details", args=[gallery.pk, gallery.slug]))
        self.assertEqual(403, response.status_code)
Пример #12
0
    def test_success_gallery_details_permission_authorized(self):
        gallery = GalleryFactory()
        UserGalleryFactory(gallery=gallery, user=self.profile1.user)
        UserGalleryFactory(gallery=gallery, user=self.profile2.user)

        self.client.force_login(self.profile2.user)

        response = self.client.get(reverse("gallery-details", args=[gallery.pk, gallery.slug]))
        self.assertEqual(200, response.status_code)
Пример #13
0
    def test_get_list_of_gallery(self):

        gallery = GalleryFactory()
        UserGalleryFactory(user=self.profile.user, gallery=gallery)
        response = self.client.get(reverse("api:gallery:list"))

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data.get("count"), 1)
        self.assertIsNone(response.data.get("next"))
        self.assertIsNone(response.data.get("previous"))
Пример #14
0
 def test_get_tuto_count(self):
     # Start with 0
     self.assertEqual(self.user1.get_tuto_count(), 0)
     # Create Tuto !
     minituto = PublishableContentFactory(type="TUTORIAL")
     minituto.authors.add(self.user1.user)
     minituto.gallery = GalleryFactory()
     minituto.save()
     # Should be 1
     self.assertEqual(self.user1.get_tuto_count(), 1)
Пример #15
0
class GalleryTest(TestCase):
    def setUp(self):
        self.profile = ProfileFactory()
        self.gallery = GalleryFactory()
        self.image1 = ImageFactory(gallery=self.gallery)
        self.image2 = ImageFactory(gallery=self.gallery)
        self.user_gallery = UserGalleryFactory(user=self.profile.user,
                                               gallery=self.gallery)

    def tearDown(self):
        self.image1.delete()
        self.image2.delete()
        self.user_gallery.delete()
        self.gallery.delete()

    def test_get_absolute_url(self):
        absolute_url = reverse("gallery-details",
                               args=[self.gallery.pk, self.gallery.slug])
        self.assertEqual(absolute_url, self.gallery.get_absolute_url())

    def test_get_linked_users(self):
        self.assertEqual(1, len(self.gallery.get_linked_users()))
        self.assertEqual(self.user_gallery, self.gallery.get_linked_users()[0])

    def test_get_images(self):
        self.assertEqual(2, len(self.gallery.get_images()))
        self.assertEqual(self.image1, self.gallery.get_images()[0])
        self.assertEqual(self.image2, self.gallery.get_images()[1])

    def test_get_last_image(self):
        self.assertEqual(self.image2, self.gallery.get_last_image())

    def test_delete_empty_gallery(self):
        test_gallery = GalleryFactory()
        path = test_gallery.get_gallery_path()
        test_gallery.delete()
        self.assertFalse(os.path.isdir(path))

    def test_delete_gallery_with_image(self):
        test_gallery = GalleryFactory()
        test_image = ImageFactory(gallery=test_gallery)

        path_gallery = test_gallery.get_gallery_path()
        self.assertTrue(os.path.isdir(path_gallery))
        path_image = test_image.physical.path
        self.assertTrue(os.path.isfile(path_image))

        # Destroy the gallery and the image
        test_gallery.delete()
        self.assertFalse(os.path.isdir(path_gallery))
        self.assertFalse(os.path.isfile(path_image))
Пример #16
0
 def test_get_draft_tutos(self):
     # Start with 0
     self.assertEqual(len(self.user1.get_draft_tutos()), 0)
     # Create Tuto !
     drafttuto = PublishableContentFactory(type="TUTORIAL")
     drafttuto.authors.add(self.user1.user)
     drafttuto.gallery = GalleryFactory()
     drafttuto.save()
     # Should be 1
     drafttutos = self.user1.get_draft_tutos()
     self.assertEqual(len(drafttutos), 1)
     self.assertEqual(drafttuto, drafttutos[0])
Пример #17
0
    def setUp(self):
        self.profile = ProfileFactory()
        self.other = ProfileFactory()
        self.client = APIClient()
        client_oauth2 = create_oauth2_client(self.profile.user)
        authenticate_client(self.client, client_oauth2,
                            self.profile.user.username, "hostel77")

        self.gallery = GalleryFactory()
        UserGalleryFactory(user=self.profile.user, gallery=self.gallery)
        self.image = ImageFactory(gallery=self.gallery)

        self.gallery_other = GalleryFactory()
        UserGalleryFactory(user=self.other.user, gallery=self.gallery_other)
        self.image_other = ImageFactory(gallery=self.gallery_other)

        self.gallery_shared = GalleryFactory()
        UserGalleryFactory(user=self.other.user, gallery=self.gallery_shared)
        UserGalleryFactory(user=self.profile.user,
                           gallery=self.gallery_shared,
                           mode=GALLERY_READ)
        self.image_shared = ImageFactory(gallery=self.gallery_shared)
Пример #18
0
 def test_get_beta_tutos(self):
     # Start with 0
     self.assertEqual(len(self.user1.get_beta_tutos()), 0)
     # Create Tuto !
     betatetuto = PublishableContentFactory(type="TUTORIAL")
     betatetuto.authors.add(self.user1.user)
     betatetuto.gallery = GalleryFactory()
     betatetuto.sha_beta = "whatever"
     betatetuto.save()
     # Should be 1
     betatetutos = self.user1.get_beta_tutos()
     self.assertEqual(len(betatetutos), 1)
     self.assertEqual(betatetuto, betatetutos[0])
Пример #19
0
 def test_get_public_tutos(self):
     # Start with 0
     self.assertEqual(len(self.user1.get_public_tutos()), 0)
     # Create Tuto !
     publictuto = PublishableContentFactory(type="TUTORIAL")
     publictuto.authors.add(self.user1.user)
     publictuto.gallery = GalleryFactory()
     publictuto.sha_public = "whatever"
     publictuto.save()
     # Should be 0 because publication was not used
     publictutos = self.user1.get_public_tutos()
     self.assertEqual(len(publictutos), 0)
     PublishedContentFactory(author_list=[self.user1.user])
     self.assertEqual(len(self.user1.get_public_tutos()), 1)
Пример #20
0
    def setUp(self):
        self.profile = ProfileFactory()
        self.other = ProfileFactory()
        self.client = APIClient()
        client_oauth2 = create_oauth2_client(self.profile.user)
        authenticate_client(self.client, client_oauth2,
                            self.profile.user.username, "hostel77")

        self.gallery = GalleryFactory()

        tuto = PublishableContentFactory(type="TUTORIAL",
                                         author_list=[self.profile.user])
        self.gallery_tuto = tuto.gallery

        caches[extensions_api_settings.DEFAULT_USE_CACHE].clear()
Пример #21
0
    def _generate(cls, create, attrs):
        # These parameters are only used inside _generate() and won't be saved in the database,
        # which is why we use attrs.pop() (they are removed from attrs).
        light = attrs.pop("light", True)
        author_list = attrs.pop("author_list", None)
        add_license = attrs.pop("add_license", True)
        add_category = attrs.pop("add_category", True)

        # This parameter will be saved in the database,
        # which is why we use attrs.get() (it stays in attrs).
        licence = attrs.get("licence", None)

        auths = author_list or []
        if add_license:
            given_licence = licence or Licence.objects.first()
            if isinstance(given_licence, str) and given_licence:
                given_licence = Licence.objects.filter(
                    title=given_licence).first() or Licence.objects.first()
            licence = given_licence or LicenceFactory()

        text = text_content
        if not light:
            text = tricky_text_content

        intro_content = attrs.pop("intro", text)
        conclusion_content = attrs.pop("conclusion", text)

        publishable_content = super()._generate(create, attrs)
        publishable_content.gallery = GalleryFactory()
        publishable_content.licence = licence
        for auth in auths:
            publishable_content.authors.add(auth)

        if add_category:
            publishable_content.subcategory.add(SubCategoryFactory())

        publishable_content.save()

        for author in publishable_content.authors.all():
            UserGalleryFactory(user=author,
                               gallery=publishable_content.gallery,
                               mode="W")

        init_new_repo(publishable_content, intro_content, conclusion_content)

        return publishable_content
Пример #22
0
    def test_delete_image_from_other_user(self):
        """if user try to remove images from another user without permission"""
        profile4 = ProfileFactory()
        gallery4 = GalleryFactory()
        image4 = ImageFactory(gallery=gallery4)
        UserGalleryFactory(user=profile4.user, gallery=gallery4)
        self.assertEqual(1, Image.objects.filter(pk=image4.pk).count())

        self.client.force_login(self.profile1.user)

        self.client.post(
            reverse("gallery-image-delete", kwargs={"pk_gallery": self.gallery1.pk}),
            {"gallery": self.gallery1.pk, "delete": "", "image": image4.pk},
            follow=True,
        )

        self.assertEqual(1, Image.objects.filter(pk=image4.pk).count())
        image4.delete()
Пример #23
0
    def test_get_avatar_url(self):
        # if no url was specified -> gravatar !
        self.assertEqual(
            self.user1.get_avatar_url(),
            "https://secure.gravatar.com/avatar/{}?d=identicon".format(
                md5(self.user1.user.email.lower().encode()).hexdigest()),
        )
        # if an url is specified -> take it !
        user2 = ProfileFactory()
        testurl = "http://test.com/avatar.jpg"
        user2.avatar_url = testurl
        self.assertEqual(user2.get_avatar_url(), testurl)

        # if url is relative, send absolute url
        gallerie_avtar = GalleryFactory()
        image_avatar = ImageFactory(gallery=gallerie_avtar)
        user2.avatar_url = image_avatar.physical.url
        self.assertNotEqual(user2.get_avatar_url(), image_avatar.physical.url)
        self.assertIn("http", user2.get_avatar_url())
Пример #24
0
 def test_success_initial_content(self):
     author = ProfileFactory().user
     author2 = ProfileFactory().user
     tutorial = PublishedContentFactory(author_list=[author, author2])
     gallery = GalleryFactory()
     image = ImageFactory(gallery=gallery)
     tutorial.image = image
     tutorial.save()
     staff = StaffProfileFactory()
     self.client.force_login(staff.user)
     response = self.client.get(
         "{}{}".format(
             reverse("featured-resource-create"), f"?content_type=published_content&content_id={tutorial.pk}"
         )
     )
     initial_dict = response.context["form"].initial
     self.assertEqual(initial_dict["title"], tutorial.title)
     self.assertEqual(initial_dict["authors"], f"{author}, {author2}")
     self.assertEqual(initial_dict["type"], _("Un tutoriel"))
     self.assertEqual(initial_dict["url"], f"http://testserver{tutorial.get_absolute_url_online()}")
     self.assertEqual(initial_dict["image_url"], "http://testserver{}".format(image.physical["featured"].url))
Пример #25
0
def load_gallery(cli, size, fake, *_, **__):
    """
    Load galleries
    """
    nb_galleries = size * 1
    nb_images = size * 3
    cli.stdout.write(f"Nombres de galéries à créer par utilisateur: {nb_galleries}")
    cli.stdout.write(f"Nombres d'images à créer par gallerie: {nb_images}")
    tps1 = time.time()
    nb_users = User.objects.count()
    if nb_users == 0:
        cli.stdout.write(
            "Il n'y a aucun membre actuellement. " "Vous devez rajouter les membres dans vos fixtures (member)"
        )
        return
    profiles = list(Profile.objects.all())
    for user_index in range(0, nb_users):
        for gallery_index in range(0, nb_galleries):
            gal = GalleryFactory(title=fake.text(max_nb_chars=80), subtitle=fake.text(max_nb_chars=200))
            UserGalleryFactory(user=profiles[user_index].user, gallery=gal)
            __push_images_into_gallery(gal, user_index, gallery_index, nb_galleries, nb_images, nb_users)
    tps2 = time.time()
    cli.stdout.write(f"\nFait en {tps2 - tps1} sec")
Пример #26
0
class NewImageViewTest(TestCase):
    def setUp(self):
        self.gallery = GalleryFactory()
        self.profile1 = ProfileFactory()
        self.profile2 = ProfileFactory()
        self.profile3 = ProfileFactory()
        self.user_gallery1 = UserGalleryFactory(user=self.profile1.user, gallery=self.gallery, mode="W")
        self.user_gallery2 = UserGalleryFactory(user=self.profile2.user, gallery=self.gallery, mode="R")

    def test_success_new_image_write_permission(self):
        self.client.force_login(self.profile1.user)
        self.assertEqual(0, len(self.gallery.get_images()))

        for filename in (
            settings.BASE_DIR / "fixtures" / "logo.png",
            settings.BASE_DIR / "assets" / "licenses" / "copyright.svg",
        ):
            with self.subTest(filename):
                with open(filename, "rb") as fp:
                    response = self.client.post(
                        reverse("gallery-image-new", args=[self.gallery.pk]),
                        {"title": "Test title", "legend": "Test legend", "physical": fp},
                        follow=True,
                    )

                self.assertEqual(200, response.status_code)
                self.assertEqual(1, len(self.gallery.get_images()))
                self.assertEqual(3, len(os.listdir(self.gallery.get_gallery_path())))  # New image and thumbnail
                self.gallery.get_images()[0].delete()

    def test_fail_new_image_with_read_permission(self):
        self.client.force_login(self.profile2.user)
        self.assertEqual(0, len(self.gallery.get_images()))

        with (settings.BASE_DIR / "fixtures" / "logo.png").open("rb") as fp:
            response = self.client.post(
                reverse("gallery-image-new", args=[self.gallery.pk]),
                {"title": "Test title", "legend": "Test legend", "physical": fp},
                follow=True,
            )

        self.assertEqual(403, response.status_code)
        self.assertEqual(0, len(self.gallery.get_images()))

    def test_fail_new_image_with_no_permission(self):
        self.client.force_login(self.profile3.user)
        self.assertEqual(0, len(self.gallery.get_images()))

        with (settings.BASE_DIR / "fixtures" / "logo.png").open("rb") as fp:
            response = self.client.post(
                reverse("gallery-image-new", args=[self.gallery.pk]),
                {"title": "Test title", "legend": "Test legend", "physical": fp},
                follow=True,
            )

        self.assertEqual(403, response.status_code)
        self.assertEqual(0, len(self.gallery.get_images()))

    def test_fail_gallery_not_exist(self):
        self.client.force_login(self.profile1.user)

        with (settings.BASE_DIR / "fixtures" / "logo.png").open("rb") as fp:
            response = self.client.post(
                reverse("gallery-image-new", args=[156]),
                {"title": "Test title", "legend": "Test legend", "physical": fp},
                follow=True,
            )

        self.assertEqual(404, response.status_code)

    def test_import_images_in_gallery(self):
        self.client.force_login(self.profile1.user)

        with (settings.BASE_DIR / "fixtures" / "archive-gallery.zip").open("rb") as fp:
            response = self.client.post(
                reverse("gallery-image-import", args=[self.gallery.pk]), {"file": fp}, follow=False
            )
        self.assertEqual(302, response.status_code)
        img = self.gallery.get_images()[0]
        self.assertEqual(Image.objects.filter(gallery=self.gallery).count(), 1)
        self.assertEqual("jpg", img.get_extension())
        response = self.client.post(
            reverse("gallery-image-delete", kwargs={"pk_gallery": self.gallery.pk}),
            {"delete": "", "image": img.pk},
            follow=True,
        )
        self.assertEqual(200, response.status_code)

    def test_import_images_in_gallery_no_archive(self):
        self.client.force_login(self.profile1.user)

        with (settings.BASE_DIR / "fixtures" / "archive-gallery.zip").open("rb"):
            response = self.client.post(
                reverse("gallery-image-import", args=[self.gallery.pk]),
                {
                    # normally we have
                    # 'file': fp
                    # but here we want to act as if we forgot it
                },
                follow=False,
            )
        self.assertEqual(200, response.status_code)
        self.assertEqual(Image.objects.filter(gallery=self.gallery).count(), 0)

    def test_denies_import_images_in_gallery(self):
        self.client.force_login(self.profile2.user)

        with (settings.BASE_DIR / "fixtures" / "archive-gallery.zip").open("rb") as fp:
            response = self.client.post(
                reverse("gallery-image-import", args=[self.gallery.pk]), {"file": fp}, follow=True
            )
        self.assertEqual(403, response.status_code)
        self.assertEqual(Image.objects.filter(gallery=self.gallery).count(), 0)
Пример #27
0
class ModifyImageTest(TestCase):
    def setUp(self):
        self.profile1 = ProfileFactory()
        self.profile2 = ProfileFactory()
        self.profile3 = ProfileFactory()
        self.gallery1 = GalleryFactory()
        self.gallery2 = GalleryFactory()
        self.image1 = ImageFactory(gallery=self.gallery1)
        self.image2 = ImageFactory(gallery=self.gallery1)
        self.image3 = ImageFactory(gallery=self.gallery2)
        self.user_gallery1 = UserGalleryFactory(user=self.profile1.user, gallery=self.gallery1)
        self.user_gallery2 = UserGalleryFactory(user=self.profile1.user, gallery=self.gallery2)
        self.user_gallery3 = UserGalleryFactory(user=self.profile2.user, gallery=self.gallery1, mode="R")

    def tearDown(self):
        self.image1.delete()
        self.image2.delete()
        self.image3.delete()

    def test_fail_modify_image_with_no_permission(self):
        self.client.force_login(self.profile3.user)

        response = self.client.post(
            reverse("gallery-image-delete", kwargs={"pk_gallery": self.gallery1.pk}),
            {
                "gallery": self.gallery1.pk,
            },
            follow=True,
        )
        self.assertTrue(403, response.status_code)

    def test_delete_image_from_other_user(self):
        """if user try to remove images from another user without permission"""
        profile4 = ProfileFactory()
        gallery4 = GalleryFactory()
        image4 = ImageFactory(gallery=gallery4)
        UserGalleryFactory(user=profile4.user, gallery=gallery4)
        self.assertEqual(1, Image.objects.filter(pk=image4.pk).count())

        self.client.force_login(self.profile1.user)

        self.client.post(
            reverse("gallery-image-delete", kwargs={"pk_gallery": self.gallery1.pk}),
            {"gallery": self.gallery1.pk, "delete": "", "image": image4.pk},
            follow=True,
        )

        self.assertEqual(1, Image.objects.filter(pk=image4.pk).count())
        image4.delete()

    def test_success_delete_image_write_permission(self):
        self.client.force_login(self.profile1.user)
        nb_files = len(os.listdir(self.gallery1.get_gallery_path()))

        response = self.client.post(
            reverse("gallery-image-delete", kwargs={"pk_gallery": self.gallery1.pk}),
            {"gallery": self.gallery1.pk, "delete": "", "image": self.image1.pk},
            follow=True,
        )
        self.assertEqual(200, response.status_code)

        self.assertEqual(0, Image.objects.filter(pk=self.image1.pk).count())

        # picture AND thumbnails should be gone
        self.assertEqual(nb_files, len(os.listdir(self.gallery1.get_gallery_path())))

    def test_success_delete_list_images_write_permission(self):
        self.client.force_login(self.profile1.user)

        response = self.client.post(
            reverse("gallery-image-delete", kwargs={"pk_gallery": self.gallery1.pk}),
            {"gallery": self.gallery1.pk, "delete_multi": "", "g_items": [self.image1.pk, self.image2.pk]},
            follow=True,
        )
        self.assertEqual(200, response.status_code)

        self.assertEqual(0, Image.objects.filter(pk=self.image1.pk).count())
        self.assertEqual(0, Image.objects.filter(pk=self.image2.pk).count())

    def test_fail_delete_image_read_permission(self):
        self.client.force_login(self.profile2.user)

        response = self.client.post(
            reverse("gallery-image-delete", kwargs={"pk_gallery": self.gallery1.pk}),
            {"gallery": self.gallery1.pk, "delete": "", "image": self.image1.pk},
            follow=True,
        )
        self.assertEqual(403, response.status_code)

        self.assertEqual(1, Image.objects.filter(pk=self.image1.pk).count())
Пример #28
0
    def test_filters(self):
        # create topic and content and toggle request
        author = ProfileFactory().user
        category = ForumCategoryFactory(position=1)
        forum = ForumFactory(category=category, position_in_category=1)
        topic = TopicFactory(forum=forum, author=author)

        FeaturedRequested.objects.toogle_request(topic, author)

        tutorial = PublishedContentFactory(author_list=[author])
        gallery = GalleryFactory()
        image = ImageFactory(gallery=gallery)
        tutorial.image = image
        tutorial.save()

        FeaturedRequested.objects.toogle_request(tutorial, author)

        # without filter
        staff = StaffProfileFactory()
        self.client.force_login(staff.user)

        response = self.client.get(reverse("featured-resource-requests"))
        self.assertEqual(200, response.status_code)

        self.assertEqual(len(response.context["featured_request_list"]), 2)
        self.assertTrue(any(r.content_object == topic for r in response.context["featured_request_list"]))
        self.assertTrue(any(r.content_object == tutorial for r in response.context["featured_request_list"]))

        # filter topic
        response = self.client.get(reverse("featured-resource-requests") + "?type=topic")
        self.assertEqual(200, response.status_code)

        self.assertEqual(len(response.context["featured_request_list"]), 1)
        self.assertTrue(any(r.content_object == topic for r in response.context["featured_request_list"]))
        self.assertFalse(any(r.content_object == tutorial for r in response.context["featured_request_list"]))

        # filter tuto
        response = self.client.get(reverse("featured-resource-requests") + "?type=content")
        self.assertEqual(200, response.status_code)

        self.assertEqual(len(response.context["featured_request_list"]), 1)
        self.assertFalse(any(r.content_object == topic for r in response.context["featured_request_list"]))
        self.assertTrue(any(r.content_object == tutorial for r in response.context["featured_request_list"]))

        # reject topic
        content_type = ContentType.objects.get_for_model(topic)
        q = FeaturedRequested.objects.get(object_id=topic.pk, content_type__pk=content_type.pk)
        q.rejected = True
        q.save()

        response = self.client.get(reverse("featured-resource-requests") + "?type=topic")
        self.assertEqual(200, response.status_code)

        self.assertEqual(len(response.context["featured_request_list"]), 0)

        # filter ignored
        response = self.client.get(reverse("featured-resource-requests") + "?type=ignored")
        self.assertEqual(200, response.status_code)

        self.assertEqual(len(response.context["featured_request_list"]), 1)
        self.assertTrue(any(r.content_object == topic for r in response.context["featured_request_list"]))

        # put back vote count to 0 for tutorial
        FeaturedRequested.objects.toogle_request(tutorial, author)
        response = self.client.get(reverse("featured-resource-requests") + "?type=content")
        self.assertEqual(200, response.status_code)

        self.assertEqual(len(response.context["featured_request_list"]), 0)  # does not appear with no votes

        # upvote topic
        other = ProfileFactory().user
        FeaturedRequested.objects.toogle_request(topic, other)

        response = self.client.get(reverse("featured-resource-requests") + "?type=topic")
        self.assertEqual(200, response.status_code)

        self.assertEqual(len(response.context["featured_request_list"]), 1)  # it is back!
Пример #29
0
    def test_toggle(self):
        author = ProfileFactory()
        self.client.force_login(author.user)

        # create topic and toggle request
        category = ForumCategoryFactory(position=1)
        forum = ForumFactory(category=category, position_in_category=1)
        topic = TopicFactory(forum=forum, author=author.user)

        response = self.client.post(
            reverse("topic-edit") + f"?topic={topic.pk}",
            {"request_featured": 1},
            HTTP_X_REQUESTED_WITH="XMLHttpRequest",
        )
        self.assertEqual(200, response.status_code)

        self.assertEqual(FeaturedRequested.objects.count(), 1)
        r = FeaturedRequested.objects.last()
        self.assertEqual(r.content_object, topic)
        self.assertIn(author.user, r.users_voted.all())

        # lock topic: cannot vote anymore
        topic.is_locked = True
        topic.save()

        response = self.client.post(
            reverse("topic-edit") + f"?topic={topic.pk}",
            {"request_featured": 1},
            HTTP_X_REQUESTED_WITH="XMLHttpRequest",
        )
        self.assertEqual(403, response.status_code)
        self.assertEqual(FeaturedRequested.objects.count(), 1)

        # create tutorial and toggle request
        tutorial = PublishedContentFactory(author_list=[author.user])
        gallery = GalleryFactory()
        image = ImageFactory(gallery=gallery)
        tutorial.image = image
        tutorial.save()

        response = self.client.post(
            reverse("content:request-featured", kwargs={"pk": tutorial.pk}),
            {"request_featured": 1},
            HTTP_X_REQUESTED_WITH="XMLHttpRequest",
        )
        self.assertEqual(200, response.status_code)

        self.assertEqual(FeaturedRequested.objects.count(), 2)
        r = FeaturedRequested.objects.last()
        self.assertEqual(r.content_object, tutorial)
        self.assertIn(author.user, r.users_voted.all())

        # create opinion: cannot toggle request!
        opinion = PublishedContentFactory(type="OPINION", author_list=[author.user])
        gallery = GalleryFactory()
        image = ImageFactory(gallery=gallery)
        opinion.image = image
        opinion.save()

        response = self.client.post(
            reverse("content:request-featured", kwargs={"pk": opinion.pk}),
            {"request_featured": 1},
            HTTP_X_REQUESTED_WITH="XMLHttpRequest",
        )
        self.assertEqual(403, response.status_code)
        self.assertEqual(FeaturedRequested.objects.count(), 2)

        # set tutorial as obsolete: cannot toggle
        tutorial.is_obsolete = True
        tutorial.save()

        response = self.client.post(
            reverse("content:request-featured", kwargs={"pk": tutorial.pk}),
            {"request_featured": 1},
            HTTP_X_REQUESTED_WITH="XMLHttpRequest",
        )
        self.assertEqual(403, response.status_code)

        r = FeaturedRequested.objects.get(pk=r.pk)
        self.assertEqual(r.content_object, tutorial)
        self.assertIn(author.user, r.users_voted.all())

        # reject tutorial proposition
        tutorial.is_obsolete = False  # can vote again
        tutorial.save()

        r = FeaturedRequested.objects.get(pk=r.pk)
        r.rejected = True
        r.save()

        # upvote with other user
        other = ProfileFactory()
        self.client.force_login(other.user)

        response = self.client.post(
            reverse("content:request-featured", kwargs={"pk": tutorial.pk}),
            {"request_featured": 1},
            HTTP_X_REQUESTED_WITH="XMLHttpRequest",
        )
        self.assertEqual(200, response.status_code)

        r = FeaturedRequested.objects.get(pk=r.pk)
        self.assertIn(other.user, r.users_voted.all())
        self.assertFalse(r.rejected)  # not rejected anymore

        # reject for good, cannot vote anymore!
        r.rejected_for_good = True
        r.save()

        response = self.client.post(
            reverse("content:request-featured", kwargs={"pk": tutorial.pk}),
            {"request_featured": 1},
            HTTP_X_REQUESTED_WITH="XMLHttpRequest",
        )
        self.assertEqual(403, response.status_code)

        r = FeaturedRequested.objects.get(pk=r.pk)
        self.assertIn(other.user, r.users_voted.all())
Пример #30
0
    def test_unregister(self):
        """
        To test that unregistering user is working.
        """

        # test not logged user can't unregister.
        self.client.logout()
        result = self.client.post(reverse("member-unregister"), follow=False)
        self.assertEqual(result.status_code, 302)

        # test logged user can unregister.
        user = ProfileFactory()
        self.client.force_login(user.user)
        result = self.client.post(reverse("member-unregister"), follow=False)
        self.assertEqual(result.status_code, 302)
        self.assertEqual(User.objects.filter(username=user.user.username).count(), 0)

        # Attach a user at tutorials, articles, topics and private topics. After that,
        # unregister this user and check that he is well removed in all contents.
        user = ProfileFactory()
        user2 = ProfileFactory()
        alone_gallery = GalleryFactory()
        UserGalleryFactory(gallery=alone_gallery, user=user.user)
        shared_gallery = GalleryFactory()
        UserGalleryFactory(gallery=shared_gallery, user=user.user)
        UserGalleryFactory(gallery=shared_gallery, user=user2.user)
        # first case : a published tutorial with only one author
        published_tutorial_alone = PublishedContentFactory(type="TUTORIAL")
        published_tutorial_alone.authors.add(user.user)
        published_tutorial_alone.save()
        # second case : a published tutorial with two authors
        published_tutorial_2 = PublishedContentFactory(type="TUTORIAL")
        published_tutorial_2.authors.add(user.user)
        published_tutorial_2.authors.add(user2.user)
        published_tutorial_2.save()
        # third case : a private tutorial with only one author
        writing_tutorial_alone = PublishableContentFactory(type="TUTORIAL")
        writing_tutorial_alone.authors.add(user.user)
        writing_tutorial_alone.save()
        writing_tutorial_alone_galler_path = writing_tutorial_alone.gallery.get_gallery_path()
        # fourth case : a private tutorial with at least two authors
        writing_tutorial_2 = PublishableContentFactory(type="TUTORIAL")
        writing_tutorial_2.authors.add(user.user)
        writing_tutorial_2.authors.add(user2.user)
        writing_tutorial_2.save()
        self.client.force_login(self.staff)
        # same thing for articles
        published_article_alone = PublishedContentFactory(type="ARTICLE")
        published_article_alone.authors.add(user.user)
        published_article_alone.save()
        published_article_2 = PublishedContentFactory(type="ARTICLE")
        published_article_2.authors.add(user.user)
        published_article_2.authors.add(user2.user)
        published_article_2.save()
        writing_article_alone = PublishableContentFactory(type="ARTICLE")
        writing_article_alone.authors.add(user.user)
        writing_article_alone.save()
        writing_article_2 = PublishableContentFactory(type="ARTICLE")
        writing_article_2.authors.add(user.user)
        writing_article_2.authors.add(user2.user)
        writing_article_2.save()
        # beta content
        beta_forum = ForumFactory(category=ForumCategoryFactory())
        beta_content = BetaContentFactory(author_list=[user.user], forum=beta_forum)
        beta_content_2 = BetaContentFactory(author_list=[user.user, user2.user], forum=beta_forum)
        # about posts and topics
        authored_topic = TopicFactory(author=user.user, forum=self.forum11, solved_by=user.user)
        answered_topic = TopicFactory(author=user2.user, forum=self.forum11)
        PostFactory(topic=answered_topic, author=user.user, position=2)
        edited_answer = PostFactory(topic=answered_topic, author=user.user, position=3)
        edited_answer.editor = user.user
        edited_answer.save()

        upvoted_answer = PostFactory(topic=answered_topic, author=user2.user, position=4)
        upvoted_answer.like += 1
        upvoted_answer.save()
        CommentVote.objects.create(user=user.user, comment=upvoted_answer, positive=True)

        private_topic = PrivateTopicFactory(author=user.user)
        private_topic.participants.add(user2.user)
        private_topic.save()
        PrivatePostFactory(author=user.user, privatetopic=private_topic, position_in_topic=1)

        # add API key
        self.assertEqual(Application.objects.count(), 0)
        self.assertEqual(AccessToken.objects.count(), 0)
        api_application = Application()
        api_application.client_id = "foobar"
        api_application.user = user.user
        api_application.client_type = "confidential"
        api_application.authorization_grant_type = "password"
        api_application.client_secret = "42"
        api_application.save()
        token = AccessToken()
        token.user = user.user
        token.token = "r@d0m"
        token.application = api_application
        token.expires = datetime.now()
        token.save()
        self.assertEqual(Application.objects.count(), 1)
        self.assertEqual(AccessToken.objects.count(), 1)

        # add a karma note and a sanction with this user
        note = KarmaNote(moderator=user.user, user=user2.user, note="Good!", karma=5)
        note.save()
        ban = Ban(moderator=user.user, user=user2.user, type="Ban définitif", note="Test")
        ban.save()

        # login and unregister:
        self.client.force_login(user.user)
        result = self.client.post(reverse("member-unregister"), follow=False)
        self.assertEqual(result.status_code, 302)

        # check that the bot have taken authorship of tutorial:
        self.assertEqual(published_tutorial_alone.authors.count(), 1)
        self.assertEqual(
            published_tutorial_alone.authors.first().username, settings.ZDS_APP["member"]["external_account"]
        )
        self.assertFalse(os.path.exists(writing_tutorial_alone_galler_path))
        self.assertEqual(published_tutorial_2.authors.count(), 1)
        self.assertEqual(
            published_tutorial_2.authors.filter(username=settings.ZDS_APP["member"]["external_account"]).count(), 0
        )

        # check that published tutorials remain published and accessible
        self.assertIsNotNone(published_tutorial_2.public_version.get_prod_path())
        self.assertTrue(os.path.exists(published_tutorial_2.public_version.get_prod_path()))
        self.assertIsNotNone(published_tutorial_alone.public_version.get_prod_path())
        self.assertTrue(os.path.exists(published_tutorial_alone.public_version.get_prod_path()))
        self.assertEqual(
            self.client.get(
                reverse("tutorial:view", args=[published_tutorial_alone.pk, published_tutorial_alone.slug]),
                follow=False,
            ).status_code,
            200,
        )
        self.assertEqual(
            self.client.get(
                reverse("tutorial:view", args=[published_tutorial_2.pk, published_tutorial_2.slug]), follow=False
            ).status_code,
            200,
        )

        # test that published articles remain accessible
        self.assertTrue(os.path.exists(published_article_alone.public_version.get_prod_path()))
        self.assertEqual(
            self.client.get(
                reverse("article:view", args=[published_article_alone.pk, published_article_alone.slug]), follow=True
            ).status_code,
            200,
        )
        self.assertEqual(
            self.client.get(
                reverse("article:view", args=[published_article_2.pk, published_article_2.slug]), follow=True
            ).status_code,
            200,
        )

        # check that the tutorial for which the author was alone does not exists anymore
        self.assertEqual(PublishableContent.objects.filter(pk=writing_tutorial_alone.pk).count(), 0)
        self.assertFalse(os.path.exists(writing_tutorial_alone.get_repo_path()))

        # check that bot haven't take the authorship of the tuto with more than one author
        self.assertEqual(writing_tutorial_2.authors.count(), 1)
        self.assertEqual(
            writing_tutorial_2.authors.filter(username=settings.ZDS_APP["member"]["external_account"]).count(), 0
        )

        # authorship for the article for which user was the only author
        self.assertEqual(published_article_alone.authors.count(), 1)
        self.assertEqual(
            published_article_alone.authors.first().username, settings.ZDS_APP["member"]["external_account"]
        )
        self.assertEqual(published_article_2.authors.count(), 1)

        self.assertEqual(PublishableContent.objects.filter(pk=writing_article_alone.pk).count(), 0)
        self.assertFalse(os.path.exists(writing_article_alone.get_repo_path()))

        # not bot if another author:
        self.assertEqual(
            published_article_2.authors.filter(username=settings.ZDS_APP["member"]["external_account"]).count(), 0
        )
        self.assertEqual(writing_article_2.authors.count(), 1)
        self.assertEqual(
            writing_article_2.authors.filter(username=settings.ZDS_APP["member"]["external_account"]).count(), 0
        )

        # topics, gallery and PMs:
        self.assertEqual(Topic.objects.filter(author__username=user.user.username).count(), 0)
        self.assertEqual(Topic.objects.filter(solved_by=user.user).count(), 0)
        self.assertEqual(Topic.objects.filter(solved_by=self.anonymous).count(), 1)
        self.assertEqual(Post.objects.filter(author__username=user.user.username).count(), 0)
        self.assertEqual(Post.objects.filter(editor__username=user.user.username).count(), 0)
        self.assertEqual(PrivatePost.objects.filter(author__username=user.user.username).count(), 0)
        self.assertEqual(PrivateTopic.objects.filter(author__username=user.user.username).count(), 0)

        self.assertIsNotNone(Topic.objects.get(pk=authored_topic.pk))
        self.assertIsNotNone(PrivateTopic.objects.get(pk=private_topic.pk))
        self.assertIsNotNone(Gallery.objects.get(pk=alone_gallery.pk))
        self.assertEqual(alone_gallery.get_linked_users().count(), 1)
        self.assertEqual(shared_gallery.get_linked_users().count(), 1)
        self.assertEqual(UserGallery.objects.filter(user=user.user).count(), 0)
        self.assertEqual(CommentVote.objects.filter(user=user.user, positive=True).count(), 0)
        self.assertEqual(Post.objects.filter(pk=upvoted_answer.id).first().like, 0)

        # zep 12, published contents and beta
        self.assertIsNotNone(PublishedContent.objects.filter(content__pk=published_tutorial_alone.pk).first())
        self.assertIsNotNone(PublishedContent.objects.filter(content__pk=published_tutorial_2.pk).first())
        self.assertTrue(Topic.objects.get(pk=beta_content.beta_topic.pk).is_locked)
        self.assertFalse(Topic.objects.get(pk=beta_content_2.beta_topic.pk).is_locked)

        # check API
        self.assertEqual(Application.objects.count(), 0)
        self.assertEqual(AccessToken.objects.count(), 0)

        # check that the karma note and the sanction were kept
        self.assertTrue(KarmaNote.objects.filter(pk=note.pk).exists())
        self.assertTrue(Ban.objects.filter(pk=ban.pk).exists())