def setUp(self): self.staff = StaffProfileFactory().user settings.EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend" self.mas = ProfileFactory().user self.overridden_zds_app["member"]["bot_account"] = self.mas.username self.licence = LicenceFactory() self.subcategory = SubCategoryFactory() self.user_author = ProfileFactory().user self.user_staff = StaffProfileFactory().user self.user_guest = ProfileFactory().user self.tuto = PublishableContentFactory(type="TUTORIAL") self.tuto.authors.add(self.user_author) UserGalleryFactory(gallery=self.tuto.gallery, user=self.user_author, mode="W") self.tuto.licence = self.licence self.tuto.subcategory.add(self.subcategory) self.tuto.save() self.beta_forum = ForumFactory( pk=self.overridden_zds_app["forum"]["beta_forum_id"], category=ForumCategoryFactory(position=1), position_in_category=1, ) # ensure that the forum, for the beta versions, is created self.tuto_draft = self.tuto.load_version() self.part1 = ContainerFactory(parent=self.tuto_draft, db_object=self.tuto) self.chapter1 = ContainerFactory(parent=self.part1, db_object=self.tuto) self.extract1 = ExtractFactory(container=self.chapter1, db_object=self.tuto) bot = Group(name=self.overridden_zds_app["member"]["bot_group"]) bot.save() self.external = UserFactory( username=self.overridden_zds_app["member"]["external_account"], password="******")
def test_private_lists(self): tutorial = PublishedContentFactory(author_list=[self.user_author]) tutorial_unpublished = PublishableContentFactory( author_list=[self.user_author]) article = PublishedContentFactory(author_list=[self.user_author], type="ARTICLE") article_unpublished = PublishableContentFactory( author_list=[self.user_author], type="ARTICLE") self.client.force_login(self.user_author) resp = self.client.get( reverse("tutorial:find-tutorial", args=[self.user_author.username])) self.assertContains(resp, tutorial.title) self.assertContains(resp, tutorial_unpublished.title) self.assertContains(resp, "content-illu") resp = self.client.get( reverse("article:find-article", args=[self.user_author.username])) self.assertContains(resp, article.title) self.assertContains(resp, article_unpublished.title) self.assertContains(resp, "content-illu")
def setUp(self): # Create users self.author = ProfileFactory().user self.staff = StaffProfileFactory().user self.outsider = ProfileFactory().user # Create contents and suggestion self.content = PublishableContentFactory(author_list=[self.author]) self.suggestable_content = PublishedContentFactory() # Get information to be reused in tests self.form_url = reverse("content:add-suggestion", kwargs={"pk": self.content.pk}) self.login_url = reverse("member-login") + "?next=" + self.form_url self.content_url = reverse("content:view", kwargs={ "pk": self.content.pk, "slug": self.content.slug }) self.form_data = {"options": self.suggestable_content.pk}
def setUp(self): # Create users self.staff = StaffProfileFactory().user self.author = ProfileFactory().user # Create a content self.content = PublishableContentFactory(author_list=[self.author]) self.suggested_content_1 = PublishableContentFactory() self.suggested_content_2 = PublishableContentFactory() self.suggestion_1 = ContentSuggestion(publication=self.content, suggestion=self.suggested_content_1) self.suggestion_1.save() self.suggestion_2 = ContentSuggestion(publication=self.content, suggestion=self.suggested_content_2) self.suggestion_2.save() # Get information to be reused in tests self.form_url = reverse("content:remove-suggestion", kwargs={"pk": self.content.pk}) self.success_message_fragment = _("Vous avez enlevé") self.error_messages = RemoveSuggestionForm.declared_fields["pk_suggestion"].error_messages # Log in with an authorized user to perform the tests self.client.force_login(self.staff)
def test_permanently_unpublish_opinion(self): opinion = PublishableContentFactory(type="OPINION") opinion.authors.add(self.user_author) UserGalleryFactory(gallery=opinion.gallery, user=self.user_author, mode="W") opinion.licence = self.licence opinion.save() opinion_draft = opinion.load_version() ExtractFactory(container=opinion_draft, db_object=opinion) ExtractFactory(container=opinion_draft, db_object=opinion) self.client.force_login(self.user_author) # publish result = self.client.post( reverse("validation:publish-opinion", kwargs={"pk": opinion.pk, "slug": opinion.slug}), {"source": "", "version": opinion_draft.current_version}, follow=False, ) self.assertEqual(result.status_code, 302) # login as staff self.client.force_login(self.user_staff) # unpublish opinion result = self.client.post( reverse("validation:ignore-opinion", kwargs={"pk": opinion.pk, "slug": opinion.slug}), { "operation": "REMOVE_PUB", }, follow=False, ) self.assertEqual(result.status_code, 200) # refresh opinion = PublishableContent.objects.get(pk=opinion.pk) # check that the opinion is not published self.assertFalse(opinion.in_public()) # check that it's impossible to publish the opinion again result = self.client.get(opinion.get_absolute_url()) self.assertContains(result, _("Billet modéré")) # front result = self.client.post( reverse("validation:publish-opinion", kwargs={"pk": opinion.pk, "slug": opinion.slug}), {"source": "", "version": opinion_draft.current_version}, follow=False, ) self.assertEqual(result.status_code, 403) # back
def test_opinion_publication_staff(self): """ Test the publication of PublishableContent where type is OPINION (with staff). """ text_publication = "Aussi tôt dit, aussi tôt fait !" opinion = PublishableContentFactory(type="OPINION") opinion.authors.add(self.user_author) UserGalleryFactory(gallery=opinion.gallery, user=self.user_author, mode="W") opinion.licence = self.licence opinion.save() opinion_draft = opinion.load_version() ExtractFactory(container=opinion_draft, db_object=opinion) ExtractFactory(container=opinion_draft, db_object=opinion) self.client.force_login(self.user_staff) result = self.client.post( reverse("validation:publish-opinion", kwargs={"pk": opinion.pk, "slug": opinion.slug}), {"text": text_publication, "source": "", "version": opinion_draft.current_version}, follow=False, ) self.assertEqual(result.status_code, 302) self.assertEqual(PublishedContent.objects.count(), 1) opinion = PublishableContent.objects.get(pk=opinion.pk) self.assertIsNotNone(opinion.public_version) self.assertEqual(opinion.public_version.sha_public, opinion_draft.current_version)
def test_collaborative_article_edition_and_editor_persistence(self): selenium = self.selenium find_element = selenium.find_element_by_css_selector author = ProfileFactory() article = PublishableContentFactory(type="ARTICLE", author_list=[author.user]) versioned_article = article.load_version() article.sha_draft = versioned_article.repo_update("article", "", "", update_slug=False) article.save() article_edit_url = reverse("content:edit", args=[article.pk, article.slug]) self.login(author) selenium.execute_script('localStorage.setItem("editor_choice", "new")' ) # we want the new editor selenium.get(self.live_server_url + article_edit_url) intro = find_element("div#div_id_introduction div.CodeMirror") # ActionChains: Support for CodeMirror https://stackoverflow.com/a/48969245/2226755 action_chains = ActionChains(selenium) scrollDriverTo(selenium, 0, 312) action_chains.click(intro).perform() action_chains.send_keys("intro").perform() output = "div#div_id_introduction div.CodeMirror div.CodeMirror-code" self.assertEqual("intro", find_element(output).text) article.sha_draft = versioned_article.repo_update("article", "new intro", "", update_slug=False) article.save() selenium.refresh() self.assertEqual( "new intro", find_element(".md-editor#id_introduction").get_attribute("value"))
def setUp(self): self.licence = LicenceFactory() self.subcategory = SubCategoryFactory() self.author = ProfileFactory() self.user = ProfileFactory() self.staff = StaffProfileFactory() self.tuto = PublishableContentFactory(type="TUTORIAL") self.tuto.authors.add(self.author.user) self.tuto.licence = self.licence self.tuto.subcategory.add(self.subcategory) self.tuto.save() self.validation = Validation( content=self.tuto, version=self.tuto.sha_draft, comment_authors="bla", date_proposition=datetime.now(), ) self.validation.save() self.topic = send_mp(author=self.author.user, users=[], title="Title", text="Testing", subtitle="", leave=False) self.topic.add_participant(self.user.user) send_message_mp(self.user.user, self.topic, "Testing") # humane_delta test periods = ((1, 0), (2, 1), (3, 7), (4, 30), (5, 360)) cont = dict() cont["date_today"] = periods[0][0] cont["date_yesterday"] = periods[1][0] cont["date_last_week"] = periods[2][0] cont["date_last_month"] = periods[3][0] cont["date_last_year"] = periods[4][0] self.context = Context(cont)
def test_content_ordering(self): category_1 = ContentCategoryFactory() category_2 = ContentCategoryFactory() subcategory_1 = SubCategoryFactory(category=category_1) subcategory_1.position = 5 subcategory_1.save() subcategory_2 = SubCategoryFactory(category=category_1) subcategory_2.position = 1 subcategory_2.save() subcategory_3 = SubCategoryFactory(category=category_2) tuto_1 = PublishableContentFactory(type="TUTORIAL") tuto_1.subcategory.add(subcategory_1) tuto_1_draft = tuto_1.load_version() publish_content(tuto_1, tuto_1_draft, is_major_update=True) top_categories_tuto = topbar_publication_categories("TUTORIAL").get( "categories") expected = [(subcategory_1.title, subcategory_1.slug, category_1.slug)] self.assertEqual(top_categories_tuto[category_1.title], expected) tuto_2 = PublishableContentFactory(type="TUTORIAL") tuto_2.subcategory.add(subcategory_2) tuto_2_draft = tuto_2.load_version() publish_content(tuto_2, tuto_2_draft, is_major_update=True) top_categories_tuto = topbar_publication_categories("TUTORIAL").get( "categories") # New subcategory is now first is the list expected.insert( 0, (subcategory_2.title, subcategory_2.slug, category_1.slug)) self.assertEqual(top_categories_tuto[category_1.title], expected) article_1 = PublishableContentFactory(type="TUTORIAL") article_1.subcategory.add(subcategory_3) article_1_draft = tuto_2.load_version() publish_content(article_1, article_1_draft, is_major_update=True) # New article has no impact top_categories_tuto = topbar_publication_categories("TUTORIAL").get( "categories") self.assertEqual(top_categories_tuto[category_1.title], expected) top_categories_contents = topbar_publication_categories( ["TUTORIAL", "ARTICLE"]).get("categories") expected_2 = [(subcategory_3.title, subcategory_3.slug, category_2.slug)] self.assertEqual(top_categories_contents[category_1.title], expected) self.assertEqual(top_categories_contents[category_2.title], expected_2)
def test_publish_content_medium_tuto(self): # 3. Medium-size tutorial midsize_tuto = PublishableContentFactory(type="TUTORIAL") midsize_tuto.authors.add(self.user_author) UserGalleryFactory(gallery=midsize_tuto.gallery, user=self.user_author, mode="W") midsize_tuto.licence = self.licence midsize_tuto.save() # populate with 2 chapters (1 extract each) midsize_tuto_draft = midsize_tuto.load_version() chapter1 = ContainerFactory(parent=midsize_tuto_draft, db_object=midsize_tuto) ExtractFactory(container=chapter1, db_object=midsize_tuto) chapter2 = ContainerFactory(parent=midsize_tuto_draft, db_object=midsize_tuto) ExtractFactory(container=chapter2, db_object=midsize_tuto) # publish it midsize_tuto = PublishableContent.objects.get(pk=midsize_tuto.pk) published = publish_content(midsize_tuto, midsize_tuto_draft) self.assertEqual(published.content, midsize_tuto) self.assertEqual(published.content_pk, midsize_tuto.pk) self.assertEqual(published.content_type, midsize_tuto.type) self.assertEqual(published.content_public_slug, midsize_tuto_draft.slug) self.assertEqual(published.sha_public, midsize_tuto.sha_draft) public = midsize_tuto.load_version(sha=published.sha_public, public=published) self.assertIsNotNone(public) self.assertTrue(public.PUBLIC) # it's a PublicContent object self.assertEqual(public.type, published.content_type) self.assertEqual(public.current_version, published.sha_public) # test creation of files: self.assertTrue(Path(published.get_prod_path()).is_dir()) self.assertTrue( Path(published.get_prod_path(), "manifest.json").is_file()) self.assertTrue( Path(public.get_prod_path(), public.introduction).is_file()) self.assertTrue( Path(public.get_prod_path(), public.conclusion).is_file()) self.assertEqual(len(public.children), 2) for child in public.children: self.assertTrue(os.path.isfile( child.get_prod_path())) # an HTML file for each chapter self.assertIsNone(child.introduction) self.assertIsNone(child.conclusion)
def setUp(self): # Create users self.author = ProfileFactory().user self.staff = StaffProfileFactory().user self.outsider = ProfileFactory().user # Create a content self.content = PublishableContentFactory(author_list=[self.author]) # Get information to be reused in tests self.events_list_url = reverse("content:events", kwargs={"pk": self.content.pk}) self.login_url = reverse( "member-login") + "?next=" + self.events_list_url
def setUp(self): self.user1 = ProfileFactory().user self.user2 = ProfileFactory().user # create a tutorial self.tuto = PublishableContentFactory(type="TUTORIAL") self.tuto.authors.add(self.user1) UserGalleryFactory(gallery=self.tuto.gallery, user=self.user1, mode="W") self.tuto.licence = LicenceFactory() self.tuto.subcategory.add(SubCategoryFactory()) self.tuto.save() tuto_draft = self.tuto.load_version() # then, publish it ! version = tuto_draft.current_version self.published = publish_content(self.tuto, tuto_draft, is_major_update=True) self.tuto.sha_public = version self.tuto.sha_draft = version self.tuto.public_version = self.published self.tuto.save() self.client.force_login(self.user1)
def create_multiple_tags(self, number_of_tags=REST_PAGE_SIZE): tags = [] for tag in range(0, number_of_tags): tags.append("number" + str(tag)) # Prepare content containing all the tags content = PublishableContentFactory(type="TUTORIAL") content.add_tags(tags) content.save() content_draft = content.load_version() # then, publish it ! publish_content(content, content_draft)
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()
def setUp(self): self.mas = ProfileFactory().user self.overridden_zds_app["member"]["bot_account"] = self.mas.username self.licence = LicenceFactory() self.user_author = ProfileFactory().user self.staff = StaffProfileFactory().user self.tuto = PublishableContentFactory(type="TUTORIAL") self.tuto.authors.add(self.user_author) UserGalleryFactory(gallery=self.tuto.gallery, user=self.user_author, mode="W") self.tuto.licence = self.licence self.tuto.save() self.tuto_draft = self.tuto.load_version() self.part1 = ContainerFactory(parent=self.tuto_draft, db_object=self.tuto) self.chapter1 = ContainerFactory(parent=self.part1, db_object=self.tuto) self.old_registry = { key: value for key, value in PublicatorRegistry.get_all_registered() } class TestPdfPublicator(Publicator): def publish(self, md_file_path, base_name, **kwargs): with Path(base_name + ".pdf").open("w") as f: f.write("bla") shutil.copy2( str(Path(base_name + ".pdf")), str(Path(md_file_path.replace("__building", "")).parent)) PublicatorRegistry.registry["pdf"] = TestPdfPublicator()
def test_image_with_non_ascii_chars(self): """seen on #4144""" article = PublishableContentFactory(type="article", author_list=[self.user_author]) image_string = ( "![Portrait de Richard Stallman en 2014. [Source](https://commons.wikimedia.org/wiki/" "File:Richard_Stallman_-_Fête_de_l%27Humanité_2014_-_010.jpg).]" "(/media/galleries/4410/c1016bf1-a1de-48a1-9ef1-144308e8725d.jpg)") article.sha_draft = article.load_version().repo_update( article.title, image_string, "", update_slug=False) article.save() publish_content(article, article.load_version()) self.assertTrue( PublishedContent.objects.filter(content_id=article.pk).exists())
def setUp(self): # Create users self.author = ProfileFactory().user self.staff = StaffProfileFactory().user self.outsider = ProfileFactory().user # Create a content self.content = PublishableContentFactory(author_list=[self.author]) # Get information to be reused in tests self.form_url = reverse("content:edit-tags", kwargs={"pk": self.content.pk}) self.form_data = {"tags": "test2, test2"} self.content_data = {"pk": self.content.pk, "slug": self.content.slug} self.content_url = reverse("content:view", kwargs=self.content_data) self.login_url = reverse("member-login") + "?next=" + self.form_url
def get_small_opinion(self): """ Returns a published opinion without extract. """ opinion = PublishableContentFactory(type="OPINION") opinion.authors.add(self.user_author) UserGalleryFactory(gallery=opinion.gallery, user=self.user_author, mode="W") opinion.licence = LicenceFactory() opinion.save() opinion_draft = opinion.load_version() return publish_content(opinion, opinion_draft)
def setUp(self): # Create a user self.author = ProfileFactory() # Create a content self.content = PublishableContentFactory( author_list=[self.author.user]) # Get information to be reused in tests self.form_url = reverse("content:edit-tags", kwargs={"pk": self.content.pk}) self.error_messages = EditContentTagsForm.declared_fields[ "tags"].error_messages self.success_message = EditContentTags.success_message # Log in with an authorized user (e.g the author of the content) to perform the tests self.client.force_login(self.author.user)
def setUp(self): # Create entities for the test self.author = ProfileFactory().user self.contributor = ProfileFactory().user self.role = create_role("Validateur") self.content = PublishableContentFactory(author_list=[self.author]) self.contribution = create_contribution(self.role, self.contributor, self.content) # Get information to be reused in tests self.form_url = reverse("content:remove-contributor", kwargs={"pk": self.content.pk}) self.success_message_fragment = _("Vous avez enlevé ") self.error_message_fragment = _( "Les contributeurs sélectionnés n'existent pas.") # Log in with an authorized user to perform the tests self.client.force_login(self.author)
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])
def test_char_count_after_publication(self): """Test the ``get_char_count()`` function. Special care should be taken with this function, since: - The username of the author is, by default "Firmxxx" where "xxx" depends on the tests before ; - The titles (!) also contains a number that also depends on the number of tests before ; - The date is ``datetime.now()`` and contains the months, which is never a fixed number of letters. """ author = ProfileFactory().user author.username = "******" author.save() len_date_now = len(date(datetime.now(), "d F Y")) article = PublishedContentFactory(type="ARTICLE", author_list=[author], title="Un titre") published = PublishedContent.objects.filter(content=article).first() self.assertEqual(published.get_char_count(), 160 + len_date_now) tuto = PublishableContentFactory(type="TUTORIAL", author_list=[author], title="Un titre") # add a chapter, so it becomes a middle tutorial tuto_draft = tuto.load_version() chapter1 = ContainerFactory(parent=tuto_draft, db_object=tuto, title="Un chapitre") ExtractFactory(container=chapter1, db_object=tuto, title="Un extrait") published = publish_content(tuto, tuto_draft, is_major_update=True) tuto.sha_public = tuto_draft.current_version tuto.sha_draft = tuto_draft.current_version tuto.public_version = published tuto.save() published = PublishedContent.objects.filter(content=tuto).first() self.assertEqual(published.get_char_count(), 335 + len_date_now)
def test_extract_is_none(self): """Test the case of a null extract""" article = PublishableContentFactory(type="ARTICLE") versioned = article.load_version() given_title = "Peu importe, en fait, ça compte peu" some_text = "Disparaitra aussi vite que possible" # add a new extract with `None` for text version = versioned.repo_add_extract(given_title, None) # check on the model: new_extract = versioned.children[-1] self.assertIsNone(new_extract.text) # it remains when loading the manifest! versioned2 = article.load_version(sha=version) self.assertIsNotNone(versioned2) self.assertIsNone(versioned.children[-1].text) version = new_extract.repo_update(given_title, None) self.assertIsNone(new_extract.text) # it remains versioned2 = article.load_version(sha=version) self.assertIsNotNone(versioned2) self.assertIsNone(versioned.children[-1].text) version = new_extract.repo_update(given_title, some_text) self.assertIsNotNone(new_extract.text) self.assertEqual(some_text, new_extract.get_text()) # now it changes versioned2 = article.load_version(sha=version) self.assertIsNotNone(versioned2) self.assertIsNotNone(versioned.children[-1].text) # ... and lets go back version = new_extract.repo_update(given_title, None) self.assertIsNone(new_extract.text) # it has changed versioned2 = article.load_version(sha=version) self.assertIsNotNone(versioned2) self.assertIsNone(versioned.children[-1].text)
def setUp(self): # Create entities for the test self.author = ProfileFactory().user self.contributor = ProfileFactory().user self.role = create_role("Validateur") self.content = PublishableContentFactory(author_list=[self.author]) settings.ZDS_APP["member"]["bot_account"] = ProfileFactory( ).user.username # Get information to be reused in tests self.form_url = reverse("content:add-contributor", kwargs={"pk": self.content.pk}) self.error_message_author_contributor = _( "Un auteur ne peut pas être désigné comme contributeur") self.error_message_empty_user = _("Veuillez renseigner l'utilisateur") self.comment = "What an mischievious person!" # Log in with an authorized user to perform the tests self.client.force_login(self.author)
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)
def setUp(self): # Create a user self.author = ProfileFactory() # Create a license self.license = LicenceFactory() # Create a content self.content = PublishableContentFactory( author_list=[self.author.user], add_license=False) # Get information to be reused in tests self.form_url = reverse("content:edit-license", kwargs={"pk": self.content.pk}) self.error_messages = EditContentLicenseForm.declared_fields[ "license"].error_messages self.success_message_license = EditContentLicense.success_message_license self.success_message_profile_update = EditContentLicense.success_message_profile_update # Log in with an authorized user (e.g the author of the content) to perform the tests self.client.force_login(self.author.user)
def get_published_content(self, author, user_staff, nb_part=1, nb_chapter=1, nb_extract=1): bigtuto = PublishableContentFactory(type="TUTORIAL") bigtuto.authors.add(author) UserGalleryFactory(gallery=bigtuto.gallery, user=author, mode="W") bigtuto.licence = LicenceFactory() bigtuto.save() # populate the bigtuto bigtuto_draft = bigtuto.load_version() for i in range(nb_part): part = ContainerFactory(parent=bigtuto_draft, db_object=bigtuto) for j in range(nb_chapter): chapter = ContainerFactory(parent=part, db_object=bigtuto) for k in range(nb_extract): ExtractFactory(container=chapter, db_object=bigtuto) # connect with author: self.client.force_login(author) # ask validation self.client.post( reverse("validation:ask", kwargs={"pk": bigtuto.pk, "slug": bigtuto.slug}), {"text": "ask for validation", "source": "", "version": bigtuto_draft.current_version}, follow=False, ) # login with staff and publish self.client.force_login(user_staff) validation = Validation.objects.filter(content=bigtuto).last() self.client.post( reverse("validation:reserve", kwargs={"pk": validation.pk}), {"version": validation.version}, follow=False ) # accept self.client.post( reverse("validation:accept", kwargs={"pk": validation.pk}), {"text": "accept validation", "is_major": True, "source": ""}, follow=False, ) self.client.logout() published = PublishedContent.objects.filter(content=bigtuto).first() self.assertIsNotNone(published) return published
def setUp(self): # Create users self.author = ProfileFactory().user self.staff = StaffProfileFactory().user self.outsider = ProfileFactory().user # Create a license self.licence = LicenceFactory() # Create a content self.content = PublishableContentFactory(author_list=[self.author]) # Get information to be reused in tests self.form_url = reverse("content:edit-license", kwargs={"pk": self.content.pk}) self.form_data = { "license": self.licence.pk, "update_preferred_license": False } self.content_data = {"pk": self.content.pk, "slug": self.content.slug} self.content_url = reverse("content:view", kwargs=self.content_data) self.login_url = reverse("member-login") + "?next=" + self.form_url
def create_content(self): """ Returns a content and its draft used in following tests. """ tuto = PublishableContentFactory(type="TUTORIAL", intro="Intro tuto", conclusion="Conclusion tuto") tuto.authors.add(self.user_author) UserGalleryFactory(gallery=tuto.gallery, user=self.user_author, mode="W") tuto.licence = self.licence tuto.save() tuto_draft = tuto.load_version() return tuto, tuto_draft
class NotificationPublishableContentTest(TestCase): def setUp(self): self.user1 = ProfileFactory().user self.user2 = ProfileFactory().user # create a tutorial self.tuto = PublishableContentFactory(type="TUTORIAL") self.tuto.authors.add(self.user1) UserGalleryFactory(gallery=self.tuto.gallery, user=self.user1, mode="W") self.tuto.licence = LicenceFactory() self.tuto.subcategory.add(SubCategoryFactory()) self.tuto.save() tuto_draft = self.tuto.load_version() # then, publish it ! version = tuto_draft.current_version self.published = publish_content(self.tuto, tuto_draft, is_major_update=True) self.tuto.sha_public = version self.tuto.sha_draft = version self.tuto.public_version = self.published self.tuto.save() self.client.force_login(self.user1) def test_follow_content_at_publication(self): """ When a content is published, authors automatically follow it. """ subscription = ContentReactionAnswerSubscription.objects.get_existing( user=self.user1, content_object=self.tuto) self.assertIsNone(subscription) # Signal call by the view at the publication. signals.content_published.send(sender=self.tuto.__class__, instance=self.tuto, by_email=False) subscription = ContentReactionAnswerSubscription.objects.get_existing( user=self.user1, content_object=self.tuto) self.assertTrue(subscription.is_active) def test_follow_content_from_view(self): """ Allows a user to follow (or not) a content from the view. """ subscription = ContentReactionAnswerSubscription.objects.get_existing( user=self.user1, content_object=self.tuto) self.assertIsNone(subscription) result = self.client.post( reverse("content:follow-reactions", args=[self.tuto.pk]), {"follow": 1}) self.assertEqual(result.status_code, 302) subscription = ContentReactionAnswerSubscription.objects.get_existing( user=self.user1, content_object=self.tuto) self.assertTrue(subscription.is_active) result = self.client.post( reverse("content:follow-reactions", args=[self.tuto.pk]), {"follow": 0}) self.assertEqual(result.status_code, 302) subscription = ContentReactionAnswerSubscription.objects.get_existing( user=self.user1, content_object=self.tuto) self.assertFalse(subscription.is_active) def test_answer_subscription(self): """ When a user posts on a publishable content, the user gets subscribed. """ subscription = ContentReactionAnswerSubscription.objects.get_existing( user=self.user1, content_object=self.tuto) self.assertIsNone(subscription) result = self.client.post( reverse("content:add-reaction") + f"?pk={self.tuto.pk}", { "text": "message", "last_note": "0" }, follow=True, ) self.assertEqual(result.status_code, 200) subscription = ContentReactionAnswerSubscription.objects.get_existing( user=self.user1, content_object=self.tuto) self.assertTrue(subscription.is_active) def test_notification_read(self): """ When the notification is a reaction, it is marked as read when the corresponding content is displayed to the user. """ ContentReactionFactory(related_content=self.tuto, author=self.user1, position=1) last_note = ContentReactionFactory(related_content=self.tuto, author=self.user2, position=2) self.tuto.last_note = last_note self.tuto.save() notification = Notification.objects.get(subscription__user=self.user1) self.assertFalse(notification.is_read) result = self.client.get(reverse("tutorial:view", args=[self.tuto.pk, self.tuto.slug]), follow=False) self.assertEqual(result.status_code, 200) notification = Notification.objects.get(subscription__user=self.user1) self.assertTrue(notification.is_read) def test_subscription_to_new_publications_from_user(self): """ Any user may subscribe to new publications from a user. """ result = self.client.post(reverse("content:follow", args=[self.user1.pk]), follow=False) self.assertEqual(result.status_code, 403) self.client.logout() self.client.force_login(self.user2) result = self.client.post( reverse("content:follow", args=[self.user1.pk]), {"follow": 1}, follow=False, HTTP_X_REQUESTED_WITH="XMLHttpRequest", ) self.assertEqual(result.status_code, 200) subscription = NewPublicationSubscription.objects.get_existing( user=self.user2, content_object=self.user1) self.assertTrue(subscription.is_active) result = self.client.post( reverse("content:follow", args=[self.user1.pk]), {"email": 1}, follow=False, HTTP_X_REQUESTED_WITH="XMLHttpRequest", ) self.assertEqual(result.status_code, 200) subscription = NewPublicationSubscription.objects.get_existing( user=self.user2, content_object=self.user1) self.assertTrue(subscription.is_active) self.assertTrue(subscription.by_email) def test_notification_generated_when_a_tuto_is_published(self): """ When a user subscribe to new publications from a user, a notification is generated when a publication is published. """ subscription = NewPublicationSubscription.objects.toggle_follow( self.user1, self.user2) signals.content_published.send(sender=self.tuto.__class__, instance=self.tuto, by_email=False) notifications = Notification.objects.filter(subscription=subscription, is_read=False).all() self.assertEqual(1, len(notifications)) signals.content_read.send(sender=self.tuto.__class__, instance=self.tuto, user=self.user2, target=ContentReaction) notifications = Notification.objects.filter(subscription=subscription, is_read=False).all() self.assertEqual(1, len(notifications)) signals.content_read.send(sender=self.tuto.__class__, instance=self.tuto, user=self.user2, target=PublishableContent) notifications = Notification.objects.filter(subscription=subscription, is_read=False).all() self.assertEqual(0, len(notifications)) def test_no_error_on_multiple_subscription(self): subscription = NewPublicationSubscription.objects.toggle_follow( self.user1, self.user2) signals.content_published.send(sender=self.tuto.__class__, instance=self.tuto, by_email=False) subscription1 = Notification.objects.filter(subscription=subscription, is_read=False).first() subscription2 = copy.copy(subscription1) subscription2.save() subscription.mark_notification_read(self.tuto) subscription1 = Notification.objects.filter(subscription=subscription, is_read=False).first() self.assertIsNone(subscription1) self.assertEqual( 1, Notification.objects.filter(subscription=subscription, is_read=True).count())