How to use shared_gallery method in lisa

Best Python code snippet using lisa_python

tests_views.py

Source:tests_views.py Github

copy

Full Screen

1# coding: utf-82from datetime import datetime3import os4import shutil5from oauth2_provider.models import AccessToken, Application6from django.conf import settings7from django.contrib.auth.models import User, Group8from django.core import mail9from django.core.urlresolvers import reverse10from django.test import TestCase11from django.test.utils import override_settings12from django.utils.translation import ugettext_lazy as _13from zds.settings import BASE_DIR14from zds.notification.models import TopicAnswerSubscription15from zds.member.factories import ProfileFactory, StaffProfileFactory, NonAsciiProfileFactory, UserFactory, \16 DevProfileFactory17from zds.mp.factories import PrivateTopicFactory, PrivatePostFactory18from zds.member.models import Profile, KarmaNote, TokenForgotPassword19from zds.mp.models import PrivatePost, PrivateTopic20from zds.member.models import TokenRegister, Ban21from zds.tutorialv2.factories import PublishableContentFactory, PublishedContentFactory, BetaContentFactory22from zds.tutorialv2.models.models_database import PublishableContent, PublishedContent23from zds.forum.factories import CategoryFactory, ForumFactory, TopicFactory, PostFactory24from zds.forum.models import Topic, Post25from zds.gallery.factories import GalleryFactory, UserGalleryFactory26from zds.gallery.models import Gallery, UserGallery27from zds.utils.models import CommentVote28overrided_zds_app = settings.ZDS_APP29overrided_zds_app['content']['repo_private_path'] = os.path.join(BASE_DIR, 'contents-private-test')30overrided_zds_app['content']['repo_public_path'] = os.path.join(BASE_DIR, 'contents-public-test')31@override_settings(MEDIA_ROOT=os.path.join(BASE_DIR, 'media-test'))32@override_settings(ZDS_APP=overrided_zds_app)33class MemberTests(TestCase):34 def setUp(self):35 settings.EMAIL_BACKEND = \36 'django.core.mail.backends.locmem.EmailBackend'37 self.mas = ProfileFactory()38 settings.ZDS_APP['member']['bot_account'] = self.mas.user.username39 self.anonymous = UserFactory(40 username=settings.ZDS_APP['member']['anonymous_account'],41 password='anything')42 self.external = UserFactory(43 username=settings.ZDS_APP['member']['external_account'],44 password='anything')45 self.category1 = CategoryFactory(position=1)46 self.forum11 = ForumFactory(47 category=self.category1,48 position_in_category=1)49 self.staff = StaffProfileFactory().user50 self.bot = Group(name=settings.ZDS_APP['member']['bot_group'])51 self.bot.save()52 def test_karma(self):53 user = ProfileFactory()54 other_user = ProfileFactory()55 self.client.login(56 username=other_user.user.username,57 password='hostel77'58 )59 r = self.client.post(reverse('member-modify-karma'), {60 'profile_pk': user.pk,61 'karma': 42,62 'note': 'warn'63 })64 self.assertEqual(403, r.status_code)65 self.client.logout()66 self.client.login(67 username=self.staff.username,68 password='hostel77'69 )70 # bad id71 r = self.client.post(reverse('member-modify-karma'), {72 'profile_pk': 'blah',73 'karma': 42,74 'note': 'warn'75 }, follow=True)76 self.assertEqual(404, r.status_code)77 # good karma78 r = self.client.post(reverse('member-modify-karma'), {79 'profile_pk': user.pk,80 'karma': 42,81 'note': 'warn'82 }, follow=True)83 self.assertEqual(200, r.status_code)84 self.assertIn('{} : 42'.format(_('Modification du karma')), r.content.decode('utf-8'))85 # more than 100 karma must unvalidate the karma86 r = self.client.post(reverse('member-modify-karma'), {87 'profile_pk': user.pk,88 'karma': 420,89 'note': 'warn'90 }, follow=True)91 self.assertEqual(200, r.status_code)92 self.assertNotIn('{} : 420'.format(_('Modification du karma')), r.content.decode('utf-8'))93 # empty warning must unvalidate the karma94 r = self.client.post(reverse('member-modify-karma'), {95 'profile_pk': user.pk,96 'karma': 41,97 'note': ''98 }, follow=True)99 self.assertEqual(200, r.status_code)100 self.assertNotIn('{} : 41'.format(_('Modification du karma')), r.content.decode('utf-8'))101 def test_list_members(self):102 """103 To test the listing of the members with and without page parameter.104 """105 # create strange member106 weird = ProfileFactory()107 weird.user.username = u'ïtrema718'108 weird.user.email = u'foo@\xfbgmail.com'109 weird.user.save()110 # list of members.111 result = self.client.get(112 reverse('member-list'),113 follow=False114 )115 self.assertEqual(result.status_code, 200)116 nb_users = len(result.context['members'])117 # Test that inactive user don't show up118 unactive_user = ProfileFactory()119 unactive_user.user.is_active = False120 unactive_user.user.save()121 result = self.client.get(122 reverse('member-list'),123 follow=False124 )125 self.assertEqual(result.status_code, 200)126 self.assertEqual(nb_users, len(result.context['members']))127 # Add a Bot and check that list didn't change128 bot_profile = ProfileFactory()129 bot_profile.user.groups.add(self.bot)130 bot_profile.user.save()131 result = self.client.get(132 reverse('member-list'),133 follow=False134 )135 self.assertEqual(result.status_code, 200)136 self.assertEqual(nb_users, len(result.context['members']))137 # list of members with page parameter.138 result = self.client.get(139 reverse('member-list') + u'?page=1',140 follow=False141 )142 self.assertEqual(result.status_code, 200)143 # page which doesn't exist.144 result = self.client.get(145 reverse('member-list') +146 u'?page=1534',147 follow=False148 )149 self.assertEqual(result.status_code, 404)150 # page parameter isn't an integer.151 result = self.client.get(152 reverse('member-list') +153 u'?page=abcd',154 follow=False155 )156 self.assertEqual(result.status_code, 404)157 def test_details_member(self):158 """159 To test details of a member given.160 """161 # details of a staff user.162 result = self.client.get(163 reverse('member-detail', args=[self.staff.username]),164 follow=False165 )166 self.assertEqual(result.status_code, 200)167 # details of an unknown user.168 result = self.client.get(169 reverse('member-detail', args=['unknown_user']),170 follow=False171 )172 self.assertEqual(result.status_code, 404)173 def test_moderation_history(self):174 user = ProfileFactory().user175 ban = Ban(176 user=user,177 moderator=self.staff,178 type='Lecture Seule Temporaire',179 note='Test de LS',180 pubdate=datetime.now(),181 )182 ban.save()183 note = KarmaNote(184 user=user,185 moderator=self.staff,186 karma=5,187 note='Test de karma',188 pubdate=datetime.now(),189 )190 note.save()191 # staff rights are required to view the history, check that192 self.client.logout()193 self.client.login(username=user.username, password='hostel77')194 result = self.client.get(195 user.profile.get_absolute_url(),196 follow=False197 )198 self.assertNotContains(result, 'Historique de modération')199 self.client.logout()200 self.client.login(username=self.staff.username, password='hostel77')201 result = self.client.get(202 user.profile.get_absolute_url(),203 follow=False204 )205 self.assertContains(result, 'Historique de modération')206 # check that the note and the sanction are in the context207 self.assertIn(ban, result.context['actions'])208 self.assertIn(note, result.context['actions'])209 # and are displayed210 self.assertContains(result, 'Test de LS')211 self.assertContains(result, 'Test de karma')212 def test_profile_page_of_weird_member_username(self):213 # create some user with weird username214 user_1 = ProfileFactory()215 user_2 = ProfileFactory()216 user_3 = ProfileFactory()217 user_1.user.username = u'ïtrema'218 user_1.user.save()219 user_2.user.username = u'&#34;a'220 user_2.user.save()221 user_3.user.username = u'_`_`_`_'222 user_3.user.save()223 # profile pages of weird users.224 result = self.client.get(225 reverse('member-detail', args=[user_1.user.username]),226 follow=True227 )228 self.assertEqual(result.status_code, 200)229 result = self.client.get(230 reverse('member-detail', args=[user_2.user.username]),231 follow=True232 )233 self.assertEqual(result.status_code, 200)234 result = self.client.get(235 reverse('member-detail', args=[user_3.user.username]),236 follow=True237 )238 self.assertEqual(result.status_code, 200)239 def test_modify_member(self):240 user = ProfileFactory().user241 # we need staff right for update other profile, so a member who is not staff can't access to the page242 self.client.logout()243 self.client.login(username=user.username, password='hostel77')244 result = self.client.get(245 reverse('member-settings-mini-profile', args=['xkcd']),246 follow=False247 )248 self.assertEqual(result.status_code, 403)249 self.client.logout()250 self.client.login(username=self.staff.username, password='hostel77')251 # an inexistant member return 404252 result = self.client.get(253 reverse('member-settings-mini-profile', args=['xkcd']),254 follow=False255 )256 self.assertEqual(result.status_code, 404)257 # an existant member return 200258 result = self.client.get(259 reverse('member-settings-mini-profile', args=[self.mas.user.username]),260 follow=False261 )262 self.assertEqual(result.status_code, 200)263 def test_success_preview_biography(self):264 member = ProfileFactory()265 self.client.login(266 username=member.user.username,267 password='hostel77'268 )269 response = self.client.post(270 reverse('update-member'),271 {272 'text': 'It is **my** life',273 'preview': '',274 }, HTTP_X_REQUESTED_WITH='XMLHttpRequest')275 result_string = ''.join(response.streaming_content)276 self.assertIn('<strong>my</strong>', result_string, 'We need the biography to be properly formatted')277 def test_login(self):278 """279 To test user login.280 """281 user = ProfileFactory()282 # login a user. Good password then redirection to the homepage.283 result = self.client.post(284 reverse('member-login'),285 {'username': user.user.username,286 'password': 'hostel77',287 'remember': 'remember'},288 follow=False)289 self.assertRedirects(result, reverse('homepage'))290 # login failed with bad password then no redirection291 # (status_code equals 200 and not 302).292 result = self.client.post(293 reverse('member-login'),294 {'username': user.user.username,295 'password': 'hostel',296 'remember': 'remember'},297 follow=False)298 self.assertEqual(result.status_code, 200)299 # login a user. Good password and next parameter then300 # redirection to the "next" page.301 result = self.client.post(302 reverse('member-login') +303 '?next=' + reverse('gallery-list'),304 {'username': user.user.username,305 'password': 'hostel77',306 'remember': 'remember'},307 follow=False)308 self.assertRedirects(result, reverse('gallery-list'))309 # check if the login form will redirect if there is310 # a next parameter.311 self.client.logout()312 result = self.client.get(313 reverse('member-login') +314 '?next=' + reverse('gallery-list'))315 self.assertContains(result,316 reverse('member-login') +317 '?next=' + reverse('gallery-list'),318 count=1)319 def test_register(self):320 """321 To test user registration.322 """323 # register a new user.324 result = self.client.post(325 reverse('register-member'),326 {327 'username': 'firm1',328 'password': 'flavour',329 'password_confirm': 'flavour',330 'email': 'firm1@zestedesavoir.com'},331 follow=False)332 self.assertEqual(result.status_code, 200)333 # check email has been sent.334 self.assertEquals(len(mail.outbox), 1)335 # check if the new user is well inactive.336 user = User.objects.get(username='firm1')337 self.assertFalse(user.is_active)338 # make a request on the link which has been sent in mail to339 # confirm the registration.340 token = TokenRegister.objects.get(user=user)341 result = self.client.get(342 settings.ZDS_APP['site']['url'] + token.get_absolute_url(),343 follow=False)344 self.assertEqual(result.status_code, 200)345 # check a new email hasn't been sent at the new user.346 self.assertEquals(len(mail.outbox), 1)347 # check if the new user is active.348 self.assertTrue(User.objects.get(username='firm1').is_active)349 def test_unregister(self):350 """351 To test that unregistering user is working.352 """353 # test not logged user can't unregister.354 self.client.logout()355 result = self.client.post(356 reverse('member-unregister'),357 follow=False)358 self.assertEqual(result.status_code, 302)359 # test logged user can register.360 user = ProfileFactory()361 login_check = self.client.login(362 username=user.user.username,363 password='hostel77')364 self.assertEqual(login_check, True)365 result = self.client.post(366 reverse('member-unregister'),367 follow=False)368 self.assertEqual(result.status_code, 302)369 self.assertEqual(User.objects.filter(username=user.user.username).count(), 0)370 # Attach a user at tutorials, articles, topics and private topics. After that,371 # unregister this user and check that he is well removed in all contents.372 user = ProfileFactory()373 user2 = ProfileFactory()374 alone_gallery = GalleryFactory()375 UserGalleryFactory(gallery=alone_gallery, user=user.user)376 shared_gallery = GalleryFactory()377 UserGalleryFactory(gallery=shared_gallery, user=user.user)378 UserGalleryFactory(gallery=shared_gallery, user=user2.user)379 # first case : a published tutorial with only one author380 published_tutorial_alone = PublishedContentFactory(type='TUTORIAL')381 published_tutorial_alone.authors.add(user.user)382 published_tutorial_alone.save()383 # second case : a published tutorial with two authors384 published_tutorial_2 = PublishedContentFactory(type='TUTORIAL')385 published_tutorial_2.authors.add(user.user)386 published_tutorial_2.authors.add(user2.user)387 published_tutorial_2.save()388 # third case : a private tutorial with only one author389 writing_tutorial_alone = PublishableContentFactory(type='TUTORIAL')390 writing_tutorial_alone.authors.add(user.user)391 writing_tutorial_alone.save()392 writing_tutorial_alone_galler_path = writing_tutorial_alone.gallery.get_gallery_path()393 # fourth case : a private tutorial with at least two authors394 writing_tutorial_2 = PublishableContentFactory(type='TUTORIAL')395 writing_tutorial_2.authors.add(user.user)396 writing_tutorial_2.authors.add(user2.user)397 writing_tutorial_2.save()398 self.client.login(username=self.staff.username, password='hostel77')399 # same thing for articles400 published_article_alone = PublishedContentFactory(type='ARTICLE')401 published_article_alone.authors.add(user.user)402 published_article_alone.save()403 published_article_2 = PublishedContentFactory(type='ARTICLE')404 published_article_2.authors.add(user.user)405 published_article_2.authors.add(user2.user)406 published_article_2.save()407 writing_article_alone = PublishableContentFactory(type='ARTICLE')408 writing_article_alone.authors.add(user.user)409 writing_article_alone.save()410 writing_article_2 = PublishableContentFactory(type='ARTICLE')411 writing_article_2.authors.add(user.user)412 writing_article_2.authors.add(user2.user)413 writing_article_2.save()414 # beta content415 beta_forum = ForumFactory(category=CategoryFactory())416 beta_content = BetaContentFactory(author_list=[user.user], forum=beta_forum)417 beta_content_2 = BetaContentFactory(author_list=[user.user, user2.user], forum=beta_forum)418 # about posts and topics419 authored_topic = TopicFactory(author=user.user, forum=self.forum11)420 answered_topic = TopicFactory(author=user2.user, forum=self.forum11)421 PostFactory(topic=answered_topic, author=user.user, position=2)422 edited_answer = PostFactory(topic=answered_topic, author=user.user, position=3)423 edited_answer.editor = user.user424 edited_answer.save()425 upvoted_answer = PostFactory(topic=answered_topic, author=user2.user, position=4)426 upvoted_answer.like += 1427 upvoted_answer.save()428 CommentVote.objects.create(user=user.user, comment=upvoted_answer, positive=True)429 private_topic = PrivateTopicFactory(author=user.user)430 private_topic.participants.add(user2.user)431 private_topic.save()432 PrivatePostFactory(author=user.user, privatetopic=private_topic, position_in_topic=1)433 # add API key434 self.assertEqual(Application.objects.count(), 0)435 self.assertEqual(AccessToken.objects.count(), 0)436 api_application = Application()437 api_application.client_id = 'foobar'438 api_application.user = user.user439 api_application.client_type = 'confidential'440 api_application.authorization_grant_type = 'password'441 api_application.client_secret = '42'442 api_application.save()443 token = AccessToken()444 token.user = user.user445 token.token = 'r@d0m'446 token.application = api_application447 token.expires = datetime.now()448 token.save()449 self.assertEqual(Application.objects.count(), 1)450 self.assertEqual(AccessToken.objects.count(), 1)451 # add a karma note and a sanction with this user452 note = KarmaNote(moderator=user.user, user=user2.user, note='Good!', karma=5)453 note.save()454 ban = Ban(moderator=user.user, user=user2.user, type='Ban définitif', note='Test')455 ban.save()456 # login and unregister:457 login_check = self.client.login(458 username=user.user.username,459 password='hostel77')460 self.assertEqual(login_check, True)461 result = self.client.post(462 reverse('member-unregister'),463 follow=False)464 self.assertEqual(result.status_code, 302)465 # check that the bot have taken authorship of tutorial:466 self.assertEqual(published_tutorial_alone.authors.count(), 1)467 self.assertEqual(published_tutorial_alone.authors.first().username,468 settings.ZDS_APP['member']['external_account'])469 self.assertFalse(os.path.exists(writing_tutorial_alone_galler_path))470 self.assertEqual(published_tutorial_2.authors.count(), 1)471 self.assertEqual(published_tutorial_2.authors472 .filter(username=settings.ZDS_APP['member']['external_account'])473 .count(), 0)474 # check that published tutorials remain published and accessible475 self.assertIsNotNone(published_tutorial_2.public_version.get_prod_path())476 self.assertTrue(os.path.exists(published_tutorial_2.public_version.get_prod_path()))477 self.assertIsNotNone(published_tutorial_alone.public_version.get_prod_path())478 self.assertTrue(os.path.exists(published_tutorial_alone.public_version.get_prod_path()))479 self.assertEqual(self.client.get(480 reverse('tutorial:view', args=[481 published_tutorial_alone.pk,482 published_tutorial_alone.slug]), follow=False).status_code, 200)483 self.assertEqual(self.client.get(484 reverse('tutorial:view', args=[485 published_tutorial_2.pk,486 published_tutorial_2.slug]), follow=False).status_code, 200)487 # test that published articles remain accessible488 self.assertTrue(os.path.exists(published_article_alone.public_version.get_prod_path()))489 self.assertEqual(self.client.get(490 reverse(491 'article:view',492 args=[493 published_article_alone.pk,494 published_article_alone.slug]),495 follow=True).status_code, 200)496 self.assertEqual(self.client.get(497 reverse(498 'article:view',499 args=[500 published_article_2.pk,501 published_article_2.slug]),502 follow=True).status_code, 200)503 # check that the tutorial for which the author was alone does not exists anymore504 self.assertEqual(PublishableContent.objects.filter(pk=writing_tutorial_alone.pk).count(), 0)505 self.assertFalse(os.path.exists(writing_tutorial_alone.get_repo_path()))506 # check that bot haven't take the authorship of the tuto with more than one author507 self.assertEqual(writing_tutorial_2.authors.count(), 1)508 self.assertEqual(writing_tutorial_2.authors509 .filter(username=settings.ZDS_APP['member']['external_account'])510 .count(), 0)511 # authorship for the article for which user was the only author512 self.assertEqual(published_article_alone.authors.count(), 1)513 self.assertEqual(published_article_alone.authors514 .first().username, settings.ZDS_APP['member']['external_account'])515 self.assertEqual(published_article_2.authors.count(), 1)516 self.assertEqual(PublishableContent.objects.filter(pk=writing_article_alone.pk).count(), 0)517 self.assertFalse(os.path.exists(writing_article_alone.get_repo_path()))518 # not bot if another author:519 self.assertEqual(published_article_2.authors520 .filter(username=settings.ZDS_APP['member']['external_account']).count(), 0)521 self.assertEqual(writing_article_2.authors.count(), 1)522 self.assertEqual(writing_article_2.authors523 .filter(username=settings.ZDS_APP['member']['external_account']).count(), 0)524 # topics, gallery and PMs:525 self.assertEqual(Topic.objects.filter(author__username=user.user.username).count(), 0)526 self.assertEqual(Post.objects.filter(author__username=user.user.username).count(), 0)527 self.assertEqual(Post.objects.filter(editor__username=user.user.username).count(), 0)528 self.assertEqual(PrivatePost.objects.filter(author__username=user.user.username).count(), 0)529 self.assertEqual(PrivateTopic.objects.filter(author__username=user.user.username).count(), 0)530 self.assertIsNotNone(Topic.objects.get(pk=authored_topic.pk))531 self.assertIsNotNone(PrivateTopic.objects.get(pk=private_topic.pk))532 self.assertIsNotNone(Gallery.objects.get(pk=alone_gallery.pk))533 self.assertEquals(alone_gallery.get_linked_users().count(), 1)534 self.assertEquals(shared_gallery.get_linked_users().count(), 1)535 self.assertEquals(UserGallery.objects.filter(user=user.user).count(), 0)536 self.assertEquals(CommentVote.objects.filter(user=user.user, positive=True).count(), 0)537 self.assertEquals(Post.objects.filter(pk=upvoted_answer.id).first().like, 0)538 # zep 12, published contents and beta539 self.assertIsNotNone(PublishedContent.objects.filter(content__pk=published_tutorial_alone.pk).first())540 self.assertIsNotNone(PublishedContent.objects.filter(content__pk=published_tutorial_2.pk).first())541 self.assertTrue(Topic.objects.get(pk=beta_content.beta_topic.pk).is_locked)542 self.assertFalse(Topic.objects.get(pk=beta_content_2.beta_topic.pk).is_locked)543 # check API544 self.assertEqual(Application.objects.count(), 0)545 self.assertEqual(AccessToken.objects.count(), 0)546 # check that the karma note and the sanction were kept547 self.assertTrue(KarmaNote.objects.filter(pk=note.pk).exists())548 self.assertTrue(Ban.objects.filter(pk=ban.pk).exists())549 def test_forgot_password(self):550 """To test nominal scenario of a lost password."""551 # Empty the test outbox552 mail.outbox = []553 result = self.client.post(554 reverse('member-forgot-password'),555 {556 'username': self.mas.user.username,557 'email': '',558 },559 follow=False)560 self.assertEqual(result.status_code, 200)561 # check email has been sent562 self.assertEquals(len(mail.outbox), 1)563 # clic on the link which has been sent in mail564 user = User.objects.get(username=self.mas.user.username)565 token = TokenForgotPassword.objects.get(user=user)566 result = self.client.get(567 settings.ZDS_APP['site']['url'] + token.get_absolute_url(),568 follow=False)569 self.assertEqual(result.status_code, 200)570 def test_sanctions(self):571 """572 Test various sanctions.573 """574 staff = StaffProfileFactory()575 login_check = self.client.login(576 username=staff.user.username,577 password='hostel77')578 self.assertEqual(login_check, True)579 # list of members.580 result = self.client.get(reverse('member-list'), follow=False)581 self.assertEqual(result.status_code, 200)582 nb_users = len(result.context['members'])583 # Test: LS584 user_ls = ProfileFactory()585 result = self.client.post(586 reverse(587 'member-modify-profile', kwargs={588 'user_pk': user_ls.user.id}), {589 'ls': '', 'ls-text': 'Texte de test pour LS'}, follow=False)590 user = Profile.objects.get(id=user_ls.id) # Refresh profile from DB591 self.assertEqual(result.status_code, 302)592 self.assertFalse(user.can_write)593 self.assertTrue(user.can_read)594 self.assertIsNone(user.end_ban_write)595 self.assertIsNone(user.end_ban_read)596 ban = Ban.objects.filter(user__id=user.user.id).order_by('-pubdate')[0]597 self.assertEqual(ban.type, 'Lecture Seule')598 self.assertEqual(ban.note, 'Texte de test pour LS')599 self.assertEquals(len(mail.outbox), 1)600 result = self.client.get(reverse('member-list'), follow=False)601 self.assertEqual(result.status_code, 200)602 self.assertEquals(nb_users + 1, len(result.context['members'])) # LS guy still shows up, good603 # Test: Un-LS604 result = self.client.post(605 reverse(606 'member-modify-profile', kwargs={607 'user_pk': user_ls.user.id}), {608 'un-ls': '', 'unls-text': 'Texte de test pour un-LS'},609 follow=False)610 user = Profile.objects.get(id=user_ls.id) # Refresh profile from DB611 self.assertEqual(result.status_code, 302)612 self.assertTrue(user.can_write)613 self.assertTrue(user.can_read)614 self.assertIsNone(user.end_ban_write)615 self.assertIsNone(user.end_ban_read)616 ban = Ban.objects.filter(user__id=user.user.id).order_by('-id')[0]617 self.assertEqual(ban.type, u'Autorisation d\'écrire')618 self.assertEqual(ban.note, 'Texte de test pour un-LS')619 self.assertEquals(len(mail.outbox), 2)620 result = self.client.get(reverse('member-list'), follow=False)621 self.assertEqual(result.status_code, 200)622 self.assertEquals(nb_users + 1, len(result.context['members'])) # LS guy still shows up, good623 # Test: LS temp624 user_ls_temp = ProfileFactory()625 result = self.client.post(626 reverse(627 'member-modify-profile', kwargs={628 'user_pk': user_ls_temp.user.id}), {629 'ls-temp': '', 'ls-jrs': 10,630 'ls-text': u'Texte de test pour LS TEMP'},631 follow=False)632 user = Profile.objects.get(id=user_ls_temp.id) # Refresh profile from DB633 self.assertEqual(result.status_code, 302)634 self.assertFalse(user.can_write)635 self.assertTrue(user.can_read)636 self.assertIsNotNone(user.end_ban_write)637 self.assertIsNone(user.end_ban_read)638 ban = Ban.objects.filter(user__id=user.user.id).order_by('-id')[0]639 self.assertEqual(ban.type, u'Lecture Seule Temporaire')640 self.assertEqual(ban.note, u'Texte de test pour LS TEMP')641 self.assertEquals(len(mail.outbox), 3)642 # reset nb_users643 result = self.client.get(reverse('member-list'), follow=False)644 self.assertEqual(result.status_code, 200)645 nb_users = len(result.context['members'])646 # Test: BAN647 user_ban = ProfileFactory()648 result = self.client.post(649 reverse(650 'member-modify-profile', kwargs={651 'user_pk': user_ban.user.id}), {652 'ban': '', 'ban-text': u'Texte de test pour BAN'}, follow=False)653 user = Profile.objects.get(id=user_ban.id) # Refresh profile from DB654 self.assertEqual(result.status_code, 302)655 self.assertTrue(user.can_write)656 self.assertFalse(user.can_read)657 self.assertIsNone(user.end_ban_write)658 self.assertIsNone(user.end_ban_read)659 ban = Ban.objects.filter(user__id=user.user.id).order_by('-id')[0]660 self.assertEqual(ban.type, u'Ban définitif')661 self.assertEqual(ban.note, u'Texte de test pour BAN')662 self.assertEquals(len(mail.outbox), 4)663 result = self.client.get(reverse('member-list'), follow=False)664 self.assertEqual(result.status_code, 200)665 self.assertEquals(nb_users, len(result.context['members'])) # Banned guy doesn't show up, good666 # Test: un-BAN667 result = self.client.post(668 reverse(669 'member-modify-profile', kwargs={670 'user_pk': user_ban.user.id}),671 {'un-ban': '',672 'unban-text': u'Texte de test pour BAN'},673 follow=False)674 user = Profile.objects.get(id=user_ban.id) # Refresh profile from DB675 self.assertEqual(result.status_code, 302)676 self.assertTrue(user.can_write)677 self.assertTrue(user.can_read)678 self.assertIsNone(user.end_ban_write)679 self.assertIsNone(user.end_ban_read)680 ban = Ban.objects.filter(user__id=user.user.id).order_by('-id')[0]681 self.assertEqual(ban.type, u'Autorisation de se connecter')682 self.assertEqual(ban.note, u'Texte de test pour BAN')683 self.assertEquals(len(mail.outbox), 5)684 result = self.client.get(reverse('member-list'), follow=False)685 self.assertEqual(result.status_code, 200)686 self.assertEquals(nb_users + 1, len(result.context['members'])) # UnBanned guy shows up, good687 # Test: BAN temp688 user_ban_temp = ProfileFactory()689 result = self.client.post(690 reverse('member-modify-profile',691 kwargs={'user_pk': user_ban_temp.user.id}),692 {'ban-temp': '', 'ban-jrs': 10,693 'ban-text': u'Texte de test pour BAN TEMP'},694 follow=False)695 user = Profile.objects.get(696 id=user_ban_temp.id) # Refresh profile from DB697 self.assertEqual(result.status_code, 302)698 self.assertTrue(user.can_write)699 self.assertFalse(user.can_read)700 self.assertIsNone(user.end_ban_write)701 self.assertIsNotNone(user.end_ban_read)702 ban = Ban.objects.filter(user__id=user.user.id).order_by('-id')[0]703 self.assertEqual(ban.type, u'Ban Temporaire')704 self.assertEqual(ban.note, u'Texte de test pour BAN TEMP')705 self.assertEquals(len(mail.outbox), 6)706 def test_sanctions_with_not_staff_user(self):707 user = ProfileFactory().user708 # we need staff right for update the sanction of an user, so a member who is not staff can't access to the page709 self.client.logout()710 self.client.login(username=user.username, password='hostel77')711 # Test: LS712 result = self.client.post(713 reverse(714 'member-modify-profile', kwargs={715 'user_pk': self.staff.id}), {716 'ls': '', 'ls-text': 'Texte de test pour LS'}, follow=False)717 self.assertEqual(result.status_code, 403)718 # if the user is staff, he can update the sanction of an user719 self.client.logout()720 self.client.login(username=self.staff.username, password='hostel77')721 # Test: LS722 result = self.client.post(723 reverse(724 'member-modify-profile', kwargs={725 'user_pk': user.id}), {726 'ls': '', 'ls-text': 'Texte de test pour LS'}, follow=False)727 self.assertEqual(result.status_code, 302)728 def test_failed_bot_sanctions(self):729 staff = StaffProfileFactory()730 login_check = self.client.login(731 username=staff.user.username,732 password='hostel77')733 self.assertEqual(login_check, True)734 bot_profile = ProfileFactory()735 bot_profile.user.groups.add(self.bot)736 bot_profile.user.save()737 # Test: LS738 result = self.client.post(739 reverse(740 'member-modify-profile', kwargs={741 'user_pk': bot_profile.user.id}), {742 'ls': '', 'ls-text': 'Texte de test pour LS'}, follow=False)743 user = Profile.objects.get(id=bot_profile.id) # Refresh profile from DB744 self.assertEqual(result.status_code, 403)745 self.assertTrue(user.can_write)746 self.assertTrue(user.can_read)747 self.assertIsNone(user.end_ban_write)748 self.assertIsNone(user.end_ban_read)749 def test_nonascii(self):750 user = NonAsciiProfileFactory()751 result = self.client.get(reverse('member-login') + '?next=' +752 reverse('member-detail', args=[user.user.username]),753 follow=False)754 self.assertEqual(result.status_code, 200)755 def test_promote_interface(self):756 """757 Test promotion interface.758 """759 # create users (one regular, one staff and one superuser)760 tester = ProfileFactory()761 staff = StaffProfileFactory()762 tester.user.is_active = False763 tester.user.save()764 staff.user.is_superuser = True765 staff.user.save()766 # create groups767 group = Group.objects.create(name='DummyGroup_1')768 groupbis = Group.objects.create(name='DummyGroup_2')769 # create Forums, Posts and subscribe member to them.770 category1 = CategoryFactory(position=1)771 forum1 = ForumFactory(772 category=category1,773 position_in_category=1)774 forum1.groups.add(group)775 forum1.save()776 forum2 = ForumFactory(777 category=category1,778 position_in_category=2)779 forum2.groups.add(groupbis)780 forum2.save()781 forum3 = ForumFactory(782 category=category1,783 position_in_category=3)784 topic1 = TopicFactory(forum=forum1, author=staff.user)785 topic2 = TopicFactory(forum=forum2, author=staff.user)786 topic3 = TopicFactory(forum=forum3, author=staff.user)787 # LET THE TEST BEGIN !788 # tester shouldn't be able to connect789 login_check = self.client.login(790 username=tester.user.username,791 password='hostel77')792 self.assertEqual(login_check, False)793 # connect as staff (superuser)794 login_check = self.client.login(795 username=staff.user.username,796 password='hostel77')797 self.assertEqual(login_check, True)798 # check that we can go through the page799 result = self.client.get(800 reverse('member-settings-promote',801 kwargs={'user_pk': tester.user.id}), follow=False)802 self.assertEqual(result.status_code, 200)803 # give groups thanks to staff (but account still not activated)804 result = self.client.post(805 reverse('member-settings-promote',806 kwargs={'user_pk': tester.user.id}),807 {808 'groups': [group.id, groupbis.id],809 }, follow=False)810 self.assertEqual(result.status_code, 302)811 tester = Profile.objects.get(id=tester.id) # refresh812 self.assertEqual(len(tester.user.groups.all()), 2)813 self.assertFalse(tester.user.is_active)814 # Now our tester is going to follow one post in every forum (3)815 TopicAnswerSubscription.objects.toggle_follow(topic1, tester.user)816 TopicAnswerSubscription.objects.toggle_follow(topic2, tester.user)817 TopicAnswerSubscription.objects.toggle_follow(topic3, tester.user)818 self.assertEqual(len(TopicAnswerSubscription.objects.get_objects_followed_by(tester.user)), 3)819 # retract all right, keep one group only and activate account820 result = self.client.post(821 reverse('member-settings-promote',822 kwargs={'user_pk': tester.user.id}),823 {824 'groups': [group.id],825 'activation': 'on'826 }, follow=False)827 self.assertEqual(result.status_code, 302)828 tester = Profile.objects.get(id=tester.id) # refresh829 self.assertEqual(len(tester.user.groups.all()), 1)830 self.assertTrue(tester.user.is_active)831 self.assertEqual(len(TopicAnswerSubscription.objects.get_objects_followed_by(tester.user)), 2)832 # no groups specified833 result = self.client.post(834 reverse('member-settings-promote',835 kwargs={'user_pk': tester.user.id}),836 {837 'activation': 'on'838 }, follow=False)839 self.assertEqual(result.status_code, 302)840 tester = Profile.objects.get(id=tester.id) # refresh841 self.assertEqual(len(TopicAnswerSubscription.objects.get_objects_followed_by(tester.user)), 1)842 # Finally, check that user can connect and can not access the interface843 login_check = self.client.login(844 username=tester.user.username,845 password='hostel77')846 self.assertEqual(login_check, True)847 result = self.client.post(848 reverse('member-settings-promote',849 kwargs={'user_pk': staff.user.id}),850 {851 'activation': 'on'852 }, follow=False)853 self.assertEqual(result.status_code, 403) # forbidden !854 def test_filter_member_ip(self):855 """856 Test filter member by ip.857 """858 # create users (one regular and one staff and superuser)859 tester = ProfileFactory()860 staff = StaffProfileFactory()861 # test login normal user862 result = self.client.post(863 reverse('member-login'),864 {'username': tester.user.username,865 'password': 'hostel77',866 'remember': 'remember'},867 follow=False)868 # good password then redirection869 self.assertEqual(result.status_code, 302)870 # Check that the filter can't be access from normal user871 result = self.client.post(872 reverse('member-from-ip',873 kwargs={'ip_address': tester.last_ip_address}),874 {}, follow=False)875 self.assertEqual(result.status_code, 403)876 # log the staff user877 result = self.client.post(878 reverse('member-login'),879 {'username': staff.user.username,880 'password': 'hostel77',881 'remember': 'remember'},882 follow=False)883 # good password then redirection884 self.assertEqual(result.status_code, 302)885 # test that we retrieve correctly the 2 members (staff + user) from this ip886 result = self.client.post(887 reverse('member-from-ip',888 kwargs={'ip_address': staff.last_ip_address}),889 {}, follow=False)890 self.assertEqual(result.status_code, 200)891 self.assertEqual(len(result.context['members']), 2)892 def test_modify_user_karma(self):893 """894 To test karma of a user modified by a staff user.895 """896 tester = ProfileFactory()897 staff = StaffProfileFactory()898 # login as user899 result = self.client.post(900 reverse('member-login'),901 {'username': tester.user.username,902 'password': 'hostel77'},903 follow=False)904 self.assertEqual(result.status_code, 302)905 # check that user can't use this feature906 result = self.client.post(reverse('member-modify-karma'), follow=False)907 self.assertEqual(result.status_code, 403)908 # login as staff909 result = self.client.post(910 reverse('member-login'),911 {'username': staff.user.username,912 'password': 'hostel77'},913 follow=False)914 self.assertEqual(result.status_code, 302)915 # try to give a few bad points to the tester916 result = self.client.post(917 reverse('member-modify-karma'),918 {'profile_pk': tester.pk,919 'note': 'Bad tester is bad !',920 'karma': '-50'},921 follow=False)922 self.assertEqual(result.status_code, 302)923 tester = Profile.objects.get(pk=tester.pk)924 self.assertEqual(tester.karma, -50)925 self.assertEqual(KarmaNote.objects.filter(user=tester.user).count(), 1)926 # Now give a few good points927 result = self.client.post(928 reverse('member-modify-karma'),929 {'profile_pk': tester.pk,930 'note': 'Good tester is good !',931 'karma': '10'},932 follow=False)933 self.assertEqual(result.status_code, 302)934 tester = Profile.objects.get(pk=tester.pk)935 self.assertEqual(tester.karma, -40)936 self.assertEqual(KarmaNote.objects.filter(user=tester.user).count(), 2)937 # Now access some unknow user938 result = self.client.post(939 reverse('member-modify-karma'),940 {'profile_pk': 9999,941 'note': 'Good tester is good !',942 'karma': '10'},943 follow=False)944 self.assertEqual(result.status_code, 404)945 # Now give unknow point946 result = self.client.post(947 reverse('member-modify-karma'),948 {'profile_pk': tester.pk,949 'note': 'Good tester is good !',950 'karma': ''},951 follow=False)952 self.assertEqual(result.status_code, 302)953 tester = Profile.objects.get(pk=tester.pk)954 self.assertEqual(tester.karma, -40)955 self.assertEqual(KarmaNote.objects.filter(user=tester.user).count(), 3)956 # Now give no point at all957 result = self.client.post(958 reverse('member-modify-karma'),959 {'profile_pk': tester.pk,960 'note': 'Good tester is good !'},961 follow=False)962 self.assertEqual(result.status_code, 302)963 tester = Profile.objects.get(pk=tester.pk)964 self.assertEqual(tester.karma, -40)965 self.assertEqual(KarmaNote.objects.filter(user=tester.user).count(), 4)966 # Now access without post967 result = self.client.get(reverse('member-modify-karma'), follow=False)968 self.assertEqual(result.status_code, 405)969 def test_karma_and_pseudo_change(self):970 """971 To test that a karma note is added when a member change its pseudo972 """973 tester = ProfileFactory()974 old_pseudo = tester.user.username975 self.client.login(username=tester.user.username, password='hostel77')976 data = {977 'username': 'dummy',978 'email': tester.user.email979 }980 result = self.client.post(reverse('update-username-email-member'), data, follow=False)981 self.assertEqual(result.status_code, 302)982 notes = KarmaNote.objects.filter(user=tester.user).all()983 self.assertEqual(len(notes), 1)984 self.assertTrue(old_pseudo in notes[0].note and 'dummy' in notes[0].note)985 def test_ban_member_is_not_contactable(self):986 """987 When a member is ban, we hide the button to send a PM.988 """989 user_ban = ProfileFactory()990 user_ban.can_read = False991 user_ban.can_write = False992 user_ban.save()993 user_1 = ProfileFactory()994 user_2 = ProfileFactory()995 phrase = 'Envoyer un message privé'996 result = self.client.get(reverse('member-detail', args=[user_1.user.username]), follow=False)997 self.assertNotContains(result, phrase)998 result = self.client.get(reverse('member-detail', args=[user_ban.user.username]), follow=False)999 self.assertNotContains(result, phrase)1000 self.assertTrue(self.client.login(username=user_2.user.username, password='hostel77'))1001 result = self.client.get(reverse('member-detail', args=[user_1.user.username]), follow=False)1002 self.client.logout()1003 self.assertContains(result, phrase)1004 self.assertTrue(self.client.login(username=user_2.user.username, password='hostel77'))1005 result = self.client.get(reverse('member-detail', args=[user_ban.user.username]), follow=False)1006 self.client.logout()1007 self.assertNotContains(result, phrase)1008 self.assertTrue(self.client.login(username=user_1.user.username, password='hostel77'))1009 result = self.client.get(reverse('member-detail', args=[user_1.user.username]), follow=False)1010 self.client.logout()1011 self.assertNotContains(result, phrase)1012 def test_github_token(self):1013 user = ProfileFactory()1014 dev = DevProfileFactory()1015 # test that github settings are only availables for dev1016 self.client.login(username=user.user.username, password='hostel77')1017 result = self.client.get(reverse('update-github'), follow=False)1018 self.assertEqual(result.status_code, 403)1019 result = self.client.post(reverse('remove-github'), follow=False)1020 self.assertEqual(result.status_code, 403)1021 self.client.logout()1022 # now, test the form1023 self.client.login(username=dev.user.username, password='hostel77')1024 result = self.client.get(reverse('update-github'), follow=False)1025 self.assertEqual(result.status_code, 200)1026 result = self.client.post(reverse('update-github'), {1027 'github_token': 'test',1028 }, follow=False)1029 self.assertEqual(result.status_code, 302)1030 # refresh1031 dev = Profile.objects.get(pk=dev.pk)1032 self.assertEqual(dev.github_token, 'test')1033 # test the option to remove the token1034 result = self.client.post(reverse('remove-github'), follow=False)1035 self.assertEqual(result.status_code, 302)1036 # refresh1037 dev = Profile.objects.get(pk=dev.pk)1038 self.assertEqual(dev.github_token, '')1039 def tearDown(self):1040 if os.path.isdir(settings.ZDS_APP['content']['repo_private_path']):1041 shutil.rmtree(settings.ZDS_APP['content']['repo_private_path'])1042 if os.path.isdir(settings.ZDS_APP['content']['repo_public_path']):1043 shutil.rmtree(settings.ZDS_APP['content']['repo_public_path'])1044 if os.path.isdir(settings.MEDIA_ROOT):...

Full Screen

Full Screen

common.py

Source:common.py Github

copy

Full Screen

...198 self.marketplace_raw = None199 else:200 self.marketplace_raw = value.to_dict() # type: ignore201 @property202 def shared_gallery(self) -> Optional[SharedImageGallerySchema]:203 # this is a safe guard and prevent mypy error on typing204 if not hasattr(self, "_shared_gallery"):205 self._shared_gallery: Optional[SharedImageGallerySchema] = None206 shared_gallery: Optional[SharedImageGallerySchema] = self._shared_gallery207 if shared_gallery:208 return shared_gallery209 if isinstance(self.shared_gallery_raw, dict):210 # Users decide the cases of image names,211 # the inconsistent cases cause the mismatched error in notifiers.212 # The lower() normalizes the image names,213 # it has no impact on deployment.214 self.shared_gallery_raw = dict(215 (k, v.lower()) for k, v in self.shared_gallery_raw.items()216 )217 shared_gallery = schema.load_by_type(218 SharedImageGallerySchema, self.shared_gallery_raw219 )220 if not shared_gallery.subscription_id:221 shared_gallery.subscription_id = self.subscription_id222 # this step makes shared_gallery_raw is validated, and223 # filter out any unwanted content.224 self.shared_gallery_raw = shared_gallery.to_dict() # type: ignore225 elif self.shared_gallery_raw:226 assert isinstance(227 self.shared_gallery_raw, str228 ), f"actual: {type(self.shared_gallery_raw)}"229 # Users decide the cases of image names,230 # the inconsistent cases cause the mismatched error in notifiers.231 # The lower() normalizes the image names,232 # it has no impact on deployment.233 shared_gallery_strings = re.split(234 r"[/]+", self.shared_gallery_raw.strip().lower()235 )236 if len(shared_gallery_strings) == 5:237 shared_gallery = SharedImageGallerySchema(*shared_gallery_strings)238 # shared_gallery_raw is used239 self.shared_gallery_raw = shared_gallery.to_dict() # type: ignore240 elif len(shared_gallery_strings) == 3:241 shared_gallery = SharedImageGallerySchema(242 self.subscription_id, None, *shared_gallery_strings243 )244 # shared_gallery_raw is used245 self.shared_gallery_raw = shared_gallery.to_dict() # type: ignore246 else:247 raise LisaException(248 f"Invalid value for the provided shared gallery "249 f"parameter: '{self.shared_gallery_raw}'."250 f"The shared gallery parameter should be in the format: "251 f"'<subscription_id>/<resource_group_name>/<image_gallery>/"252 f"<image_definition>/<image_version>' or '<image_gallery>/"253 f"<image_definition>/<image_version>'"254 )255 self._shared_gallery = shared_gallery256 return shared_gallery257 @shared_gallery.setter258 def shared_gallery(self, value: Optional[SharedImageGallerySchema]) -> None:259 self._shared_gallery = value260 if value is None:261 self.shared_gallery_raw = None262 else:263 self.shared_gallery_raw = value.to_dict() # type: ignore264 def get_image_name(self) -> str:265 result = ""266 if self.vhd:267 result = self.vhd268 elif self.shared_gallery:269 assert isinstance(270 self.shared_gallery_raw, dict271 ), f"actual type: {type(self.shared_gallery_raw)}"272 if self.shared_gallery.resource_group_name:...

Full Screen

Full Screen

tests_register.py

Source:tests_register.py Github

copy

Full Screen

1import os2from datetime import datetime3from smtplib import SMTPException4from unittest.mock import Mock5from oauth2_provider.models import AccessToken, Application6from django.conf import settings7from django.contrib.auth.models import User, Group8from django.core import mail9from django.core.mail.backends.base import BaseEmailBackend10from django.urls import reverse11from django.utils.html import escape12from django.test import TestCase, override_settings13from zds.member.tests.factories import ProfileFactory, UserFactory, StaffProfileFactory14from zds.mp.tests.factories import PrivateTopicFactory, PrivatePostFactory15from zds.member.models import KarmaNote, NewEmailProvider16from zds.mp.models import PrivatePost, PrivateTopic17from zds.member.models import TokenRegister, Ban18from zds.tutorialv2.tests.factories import PublishableContentFactory, PublishedContentFactory, BetaContentFactory19from zds.tutorialv2.models.database import PublishableContent, PublishedContent20from zds.tutorialv2.tests import TutorialTestMixin, override_for_contents21from zds.forum.tests.factories import ForumCategoryFactory, ForumFactory, TopicFactory, PostFactory22from zds.forum.models import Topic, Post23from zds.gallery.tests.factories import GalleryFactory, UserGalleryFactory24from zds.gallery.models import Gallery, UserGallery25from zds.utils.models import CommentVote26@override_for_contents()27class TestRegister(TutorialTestMixin, TestCase):28 def setUp(self):29 settings.EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"30 self.mas = ProfileFactory()31 settings.ZDS_APP["member"]["bot_account"] = self.mas.user.username32 self.anonymous = UserFactory(username=settings.ZDS_APP["member"]["anonymous_account"], password="anything")33 self.external = UserFactory(username=settings.ZDS_APP["member"]["external_account"], password="anything")34 self.category1 = ForumCategoryFactory(position=1)35 self.forum11 = ForumFactory(category=self.category1, position_in_category=1)36 self.staff = StaffProfileFactory().user37 self.bot = Group(name=settings.ZDS_APP["member"]["bot_group"])38 self.bot.save()39 def test_register(self):40 """41 To test user registration.42 """43 # register a new user.44 result = self.client.post(45 reverse("register-member"),46 {47 "username": "firm1",48 "password": "flavour",49 "password_confirm": "flavour",50 "email": "firm1@zestedesavoir.com",51 },52 follow=False,53 )54 self.assertEqual(result.status_code, 200)55 # check email has been sent.56 self.assertEqual(len(mail.outbox), 1)57 # check if the new user is well inactive.58 user = User.objects.get(username="firm1")59 self.assertFalse(user.is_active)60 # make a request on the link which has been sent in mail to61 # confirm the registration.62 token = TokenRegister.objects.get(user=user)63 result = self.client.get(settings.ZDS_APP["site"]["url"] + token.get_absolute_url(), follow=False)64 self.assertEqual(result.status_code, 200)65 # check a new email hasn't been sent at the new user.66 self.assertEqual(len(mail.outbox), 1)67 # check if the new user is active.68 self.assertTrue(User.objects.get(username="firm1").is_active)69 def test_unregister(self):70 """71 To test that unregistering user is working.72 """73 # test not logged user can't unregister.74 self.client.logout()75 result = self.client.post(reverse("member-unregister"), {"password": "hostel77"}, follow=False)76 self.assertEqual(result.status_code, 302)77 # test logged user can unregister.78 user = ProfileFactory()79 self.client.force_login(user.user)80 result = self.client.post(reverse("member-unregister"), {"password": "hostel77"}, follow=False)81 self.assertEqual(result.status_code, 302)82 self.assertEqual(User.objects.filter(username=user.user.username).count(), 0)83 # Attach a user at tutorials, articles, topics and private topics. After that,84 # unregister this user and check that he is well removed in all contents.85 user = ProfileFactory()86 user2 = ProfileFactory()87 alone_gallery = GalleryFactory()88 UserGalleryFactory(gallery=alone_gallery, user=user.user)89 shared_gallery = GalleryFactory()90 UserGalleryFactory(gallery=shared_gallery, user=user.user)91 UserGalleryFactory(gallery=shared_gallery, user=user2.user)92 # first case : a published tutorial with only one author93 published_tutorial_alone = PublishedContentFactory(type="TUTORIAL")94 published_tutorial_alone.authors.add(user.user)95 published_tutorial_alone.save()96 # second case : a published tutorial with two authors97 published_tutorial_2 = PublishedContentFactory(type="TUTORIAL")98 published_tutorial_2.authors.add(user.user)99 published_tutorial_2.authors.add(user2.user)100 published_tutorial_2.save()101 # third case : a private tutorial with only one author102 writing_tutorial_alone = PublishableContentFactory(type="TUTORIAL")103 writing_tutorial_alone.authors.add(user.user)104 writing_tutorial_alone.save()105 writing_tutorial_alone_galler_path = writing_tutorial_alone.gallery.get_gallery_path()106 # fourth case : a private tutorial with at least two authors107 writing_tutorial_2 = PublishableContentFactory(type="TUTORIAL")108 writing_tutorial_2.authors.add(user.user)109 writing_tutorial_2.authors.add(user2.user)110 writing_tutorial_2.save()111 self.client.force_login(self.staff)112 # same thing for articles113 published_article_alone = PublishedContentFactory(type="ARTICLE")114 published_article_alone.authors.add(user.user)115 published_article_alone.save()116 published_article_2 = PublishedContentFactory(type="ARTICLE")117 published_article_2.authors.add(user.user)118 published_article_2.authors.add(user2.user)119 published_article_2.save()120 writing_article_alone = PublishableContentFactory(type="ARTICLE")121 writing_article_alone.authors.add(user.user)122 writing_article_alone.save()123 writing_article_2 = PublishableContentFactory(type="ARTICLE")124 writing_article_2.authors.add(user.user)125 writing_article_2.authors.add(user2.user)126 writing_article_2.save()127 # beta content128 beta_forum = ForumFactory(category=ForumCategoryFactory())129 beta_content = BetaContentFactory(author_list=[user.user], forum=beta_forum)130 beta_content_2 = BetaContentFactory(author_list=[user.user, user2.user], forum=beta_forum)131 # about posts and topics132 authored_topic = TopicFactory(author=user.user, forum=self.forum11, solved_by=user.user)133 answered_topic = TopicFactory(author=user2.user, forum=self.forum11)134 PostFactory(topic=answered_topic, author=user.user, position=2)135 edited_answer = PostFactory(topic=answered_topic, author=user.user, position=3)136 edited_answer.editor = user.user137 edited_answer.save()138 upvoted_answer = PostFactory(topic=answered_topic, author=user2.user, position=4)139 upvoted_answer.like += 1140 upvoted_answer.save()141 CommentVote.objects.create(user=user.user, comment=upvoted_answer, positive=True)142 private_topic = PrivateTopicFactory(author=user.user)143 private_topic.participants.add(user2.user)144 private_topic.save()145 PrivatePostFactory(author=user.user, privatetopic=private_topic, position_in_topic=1)146 # add API key147 self.assertEqual(Application.objects.count(), 0)148 self.assertEqual(AccessToken.objects.count(), 0)149 api_application = Application()150 api_application.client_id = "foobar"151 api_application.user = user.user152 api_application.client_type = "confidential"153 api_application.authorization_grant_type = "password"154 api_application.client_secret = "42"155 api_application.save()156 token = AccessToken()157 token.user = user.user158 token.token = "r@d0m"159 token.application = api_application160 token.expires = datetime.now()161 token.save()162 self.assertEqual(Application.objects.count(), 1)163 self.assertEqual(AccessToken.objects.count(), 1)164 # add a karma note and a sanction with this user165 note = KarmaNote(moderator=user.user, user=user2.user, note="Good!", karma=5)166 note.save()167 ban = Ban(moderator=user.user, user=user2.user, type="Ban définitif", note="Test")168 ban.save()169 # login and unregister:170 self.client.force_login(user.user)171 result = self.client.post(reverse("member-unregister"), {"password": "hostel77"}, follow=False)172 self.assertEqual(result.status_code, 302)173 # check that the bot have taken authorship of tutorial:174 self.assertEqual(published_tutorial_alone.authors.count(), 1)175 self.assertEqual(176 published_tutorial_alone.authors.first().username, settings.ZDS_APP["member"]["external_account"]177 )178 self.assertFalse(os.path.exists(writing_tutorial_alone_galler_path))179 self.assertEqual(published_tutorial_2.authors.count(), 1)180 self.assertEqual(181 published_tutorial_2.authors.filter(username=settings.ZDS_APP["member"]["external_account"]).count(), 0182 )183 # check that published tutorials remain published and accessible184 self.assertIsNotNone(published_tutorial_2.public_version.get_prod_path())185 self.assertTrue(os.path.exists(published_tutorial_2.public_version.get_prod_path()))186 self.assertIsNotNone(published_tutorial_alone.public_version.get_prod_path())187 self.assertTrue(os.path.exists(published_tutorial_alone.public_version.get_prod_path()))188 self.assertEqual(189 self.client.get(190 reverse("tutorial:view", args=[published_tutorial_alone.pk, published_tutorial_alone.slug]),191 follow=False,192 ).status_code,193 200,194 )195 self.assertEqual(196 self.client.get(197 reverse("tutorial:view", args=[published_tutorial_2.pk, published_tutorial_2.slug]), follow=False198 ).status_code,199 200,200 )201 # test that published articles remain accessible202 self.assertTrue(os.path.exists(published_article_alone.public_version.get_prod_path()))203 self.assertEqual(204 self.client.get(205 reverse("article:view", args=[published_article_alone.pk, published_article_alone.slug]), follow=True206 ).status_code,207 200,208 )209 self.assertEqual(210 self.client.get(211 reverse("article:view", args=[published_article_2.pk, published_article_2.slug]), follow=True212 ).status_code,213 200,214 )215 # check that the tutorial for which the author was alone does not exists anymore216 self.assertEqual(PublishableContent.objects.filter(pk=writing_tutorial_alone.pk).count(), 0)217 self.assertFalse(os.path.exists(writing_tutorial_alone.get_repo_path()))218 # check that bot haven't take the authorship of the tuto with more than one author219 self.assertEqual(writing_tutorial_2.authors.count(), 1)220 self.assertEqual(221 writing_tutorial_2.authors.filter(username=settings.ZDS_APP["member"]["external_account"]).count(), 0222 )223 # authorship for the article for which user was the only author224 self.assertEqual(published_article_alone.authors.count(), 1)225 self.assertEqual(226 published_article_alone.authors.first().username, settings.ZDS_APP["member"]["external_account"]227 )228 self.assertEqual(published_article_2.authors.count(), 1)229 self.assertEqual(PublishableContent.objects.filter(pk=writing_article_alone.pk).count(), 0)230 self.assertFalse(os.path.exists(writing_article_alone.get_repo_path()))231 # not bot if another author:232 self.assertEqual(233 published_article_2.authors.filter(username=settings.ZDS_APP["member"]["external_account"]).count(), 0234 )235 self.assertEqual(writing_article_2.authors.count(), 1)236 self.assertEqual(237 writing_article_2.authors.filter(username=settings.ZDS_APP["member"]["external_account"]).count(), 0238 )239 # topics, gallery and PMs:240 self.assertEqual(Topic.objects.filter(author__username=user.user.username).count(), 0)241 self.assertEqual(Topic.objects.filter(solved_by=user.user).count(), 0)242 self.assertEqual(Topic.objects.filter(solved_by=self.anonymous).count(), 1)243 self.assertEqual(Post.objects.filter(author__username=user.user.username).count(), 0)244 self.assertEqual(Post.objects.filter(editor__username=user.user.username).count(), 0)245 self.assertEqual(PrivatePost.objects.filter(author__username=user.user.username).count(), 0)246 self.assertEqual(PrivateTopic.objects.filter(author__username=user.user.username).count(), 0)247 self.assertIsNotNone(Topic.objects.get(pk=authored_topic.pk))248 self.assertIsNotNone(PrivateTopic.objects.get(pk=private_topic.pk))249 self.assertIsNotNone(Gallery.objects.get(pk=alone_gallery.pk))250 self.assertEqual(alone_gallery.get_linked_users().count(), 1)251 self.assertEqual(shared_gallery.get_linked_users().count(), 1)252 self.assertEqual(UserGallery.objects.filter(user=user.user).count(), 0)253 self.assertEqual(CommentVote.objects.filter(user=user.user, positive=True).count(), 0)254 self.assertEqual(Post.objects.filter(pk=upvoted_answer.id).first().like, 0)255 # zep 12, published contents and beta256 self.assertIsNotNone(PublishedContent.objects.filter(content__pk=published_tutorial_alone.pk).first())257 self.assertIsNotNone(PublishedContent.objects.filter(content__pk=published_tutorial_2.pk).first())258 self.assertTrue(Topic.objects.get(pk=beta_content.beta_topic.pk).is_locked)259 self.assertFalse(Topic.objects.get(pk=beta_content_2.beta_topic.pk).is_locked)260 # check API261 self.assertEqual(Application.objects.count(), 0)262 self.assertEqual(AccessToken.objects.count(), 0)263 # check that the karma note and the sanction were kept264 self.assertTrue(KarmaNote.objects.filter(pk=note.pk).exists())265 self.assertTrue(Ban.objects.filter(pk=ban.pk).exists())266 def test_register_with_not_allowed_chars(self):267 """268 Test register account with not allowed chars269 :return:270 """271 users = [272 # empty username273 {"username": "", "password": "flavour", "password_confirm": "flavour", "email": "firm1@zestedesavoir.com"},274 # space after username275 {276 "username": "firm1 ",277 "password": "flavour",278 "password_confirm": "flavour",279 "email": "firm1@zestedesavoir.com",280 },281 # space before username282 {283 "username": " firm1",284 "password": "flavour",285 "password_confirm": "flavour",286 "email": "firm1@zestedesavoir.com",287 },288 # username with utf8mb4 chars289 {290 "username": " firm1",291 "password": "flavour",292 "password_confirm": "flavour",293 "email": "firm1@zestedesavoir.com",294 },295 ]296 for user in users:297 result = self.client.post(reverse("register-member"), user, follow=False)298 self.assertEqual(result.status_code, 200)299 # check any email has been sent.300 self.assertEqual(len(mail.outbox), 0)301 # user doesn't exist302 self.assertEqual(User.objects.filter(username=user["username"]).count(), 0)303 def test_new_provider_with_new_account(self):304 new_providers_count = NewEmailProvider.objects.count()305 # register a new user306 self.client.post(307 reverse("register-member"),308 {309 "username": "new",310 "password": "hostel77",311 "password_confirm": "hostel77",312 "email": "test@unknown-provider-register.com",313 },314 follow=False,315 )316 user = User.objects.get(username="new")317 token = TokenRegister.objects.get(user=user)318 self.client.get(token.get_absolute_url(), follow=False)319 # A new provider object should have been created320 self.assertEqual(new_providers_count + 1, NewEmailProvider.objects.count())321mail_backend = Mock()322class FakeBackend(BaseEmailBackend):323 def send_messages(self, email_messages):324 return mail_backend.send_messages(email_messages)325@override_settings(EMAIL_BACKEND="zds.member.tests.views.tests_register.FakeBackend")326class RegisterTest(TestCase):327 def test_exception_on_mail(self):328 def send_messages(messages):329 print("message sent")330 raise SMTPException(messages)331 mail_backend.send_messages = send_messages332 result = self.client.post(333 reverse("register-member"),334 {335 "username": "firm1",336 "password": "flavour",337 "password_confirm": "flavour",338 "email": "firm1@zestedesavoir.com",339 },340 follow=False,341 )342 self.assertEqual(result.status_code, 200)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run lisa automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful