def test_setup(**kwargs): from random import choice from django.contrib.auth.models import User from board.models import Thread, Post, Category from board import sampledata if not settings.DEBUG: return if Thread.objects.all().count() > 0: # return, since there seem to already be threads in the database. return # ask for permission to create the test msg = """ You've installed board with DEBUG=True, do you want to populate the board with random users/threads/posts to test-drive the application? (yes/no): """ populate = raw_input(msg).strip() while not (populate == "yes" or populate == "no"): populate = raw_input("\nPlease type 'yes' or 'no': ").strip() if populate == "no": return # create 10 random users users = ('john', 'sally', 'susan', 'amanda', 'bob', 'tully', 'fran') for u in users: user = User.objects.get_or_create(username=u) # user.is_staff = True cats = ('Random Topics', 'Good Deals', 'Skiing in the Vermont Area', 'The Best Restaurants') for c in cats: cat = Category.objects.get_or_create(label=c) # create up to 30 posts tc = range(1, 50) for i in range(0, 35): print 'thread ', i, 'created' cat= choice(Category.objects.all()) subj = choice(sampledata.objects.split('\n')) thread = Thread(subject=subj, category=cat) thread.save() for j in range(0, choice(tc)): text = '\n\n'.join([sampledata.sample_data() for x in range(0, choice(range(2, 5)))]) # create a post post = Post( user=choice(User.objects.all()), thread=thread, text=text, ip='.'.join([str(choice(range(1,255))) for x in (1,2,3,4)]), ) # allows setting of arbitrary ip post.management_save()
def test_recent_thread(self): # Remove existing threads Thread.objects.all().delete() thread = Thread(title='Test thread', slug='test-thread') thread.save() Message(author=User.objects.get(username='******'), thread=thread, text='foo').save() response = self.client.get(reverse('homepage')) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context['thread_list']), 1)
def setUp(self): user = ActiveUser.objects.get(username='******') # Create dummy thread thread = Thread(title='Hello World!') thread.save() self.msg1 = Message(author=user, thread=thread, text='Hello 1') self.msg2 = Message(author=user, thread=thread, text='Hello 2') self.msg1.save() self.msg2.save()
def create_thread(request): if request.method == 'POST': title = request.POST['title'] text = request.POST['text'] if len(text) > 5 and len(text) < 2000: # Check captcha was correct a = request.POST['a'] b = request.POST['b'] value = request.POST['captcha'] if int(a) + int(b) == int(value or 0): date = timezone.now() thread = Thread(thread_title=title, thread_text=text, pub_date=date, thread_count=0) thread.save() return HttpResponseRedirect(reverse('index'))
def create_thread(request): if request.method == 'POST': title = request.POST['title'] text = request.POST['text'] if len(text) > 5 and len(text) < 2000: # Check captcha was correct a = request.POST['a'] b = request.POST['b'] value = request.POST['captcha'] if int(a) + int(b) == int(value or 0): # Was file uploaded and under 3mb and image file image = request.FILES['image'] if image and image.size < 3000000 and check_image_type(image): thread = Thread(thread_title=title, thread_text=text) thread.save() # Use thread id as image name handle_upload(image, thread.id) return HttpResponseRedirect(reverse('index'))
def create(self, request, board_code, post=None): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) if post: open_post = get_object_or_404(Post, id=post) serializer.validated_data['thread_id'] = open_post.thread_id serializer.validated_data['board'] = [open_post.board.get().id] else: thread = Thread() thread.save() serializer.validated_data['thread'] = thread board = get_object_or_404(Board, code=board_code) serializer.validated_data['board'] = [board] serializer.validated_data['op'] = True # Если создается новая тема, то bump не может быть False, да и я проверял, там не нужны скобочки if self.request.data['email'] == 'sage' and post: serializer.validated_data['bump'] = False serializer.save(ip=self.request.META.get('REMOTE_ADDR')) self.perform_create(serializer) return Response(serializer.data, status=status.HTTP_201_CREATED)
def test_can_delete_a_thread(self): Thread.objects.all().delete() thread = Thread(title='Test thread', slug='test-thread') thread.save() Message(author=User.objects.get(username='******'), thread=thread, text='foo').save() self.selenium.refresh() self.selenium.find_element_by_link_text('Test thread').click() self.selenium.find_element_by_css_selector('span.fa.fa-trash-o').click() WebDriverWait(self.selenium, 1).until( EC.visibility_of_element_located((By.ID, 'confirm-action-yes'))) self.selenium.find_element_by_id('confirm-action-yes').click() alert_texts = [] time.sleep(1) for alert in self.selenium.find_elements_by_css_selector('.contrib-messages .alert'): alert_texts.append(alert.text.strip()) close = '×\n' wanted_text = ['%sLe message a été supprimé.' % close, '%sLa discussion étant vide, elle a été supprimée également.'% close] self.assertEqual(alert_texts, wanted_text) with self.assertRaises(NoSuchElementException): self.selenium.find_element_by_link_text('Test thread')
def test_deletemessage(self): # Log as admin self.client.login(username='******', password='******') user1 = ActiveUser.objects.get(username='******') user2 = ActiveUser.objects.get(username='******') # Create dummy thread thread = Thread(title='Hello World!') thread.save() msg1 = Message(author=user1, thread=thread, text='Hello 1') msg2 = Message(author=user1, thread=thread, text='Hello 2') msg1.save() msg2.save() # Add flags Flag.objects.read(user=user1, message=msg1) Flag.objects.read(user=user2, message=msg2) thread.refresh_from_db() self.assertEqual(thread.number, 2) self.assertEqual(thread.last_message, msg2) self.assertEqual(Flag.objects.get(user=user1, thread=thread).message, msg1) self.assertEqual(Flag.objects.get(user=user2, thread=thread).message, msg2) # Remove second message response = self.client.get(reverse('board_message_delete', kwargs={'message': msg2.pk}), follow=True) self.assertEqual(response.status_code, 200) self.assertEqual(Flag.objects.get(user=user1, thread=thread).message, msg1) self.assertEqual(Flag.objects.get(user=user2, thread=thread).message, msg1) thread.refresh_from_db() self.assertEqual(thread.number, 1) self.assertEqual(thread.last_message, msg1) with self.assertRaises(Message.DoesNotExist): Message.objects.get(pk=msg2.pk) # Remove first (and last) message response = self.client.get(reverse('board_message_delete', kwargs={'message': msg1.pk})) self.assertRedirects(response, reverse('board_latests')) with self.assertRaises(Flag.DoesNotExist): Flag.objects.get(user=user1, thread=thread) with self.assertRaises(Flag.DoesNotExist): Flag.objects.get(user=user2, thread=thread) with self.assertRaises(Message.DoesNotExist): Message.objects.get(pk=msg1.pk) with self.assertRaises(Thread.DoesNotExist): Thread.objects.get(pk=thread.pk)
def convert_post(self, wpost, first_post=False): """Converts single post.""" slug = wpost.section_slug if slug in self.bad_sections: raise ConvertError("Section {} does not exist".format(slug)) post = Post() post.data = "" for f in self.fields: setattr(post, f, getattr(wpost, f)) # add video to the post if wpost.video: try: post.message += u" {}".format(wpost.video) except UnicodeEncodeError: raise ConvertError("Cannot add video to the post {}".format( wpost.id)) if first_post: post.is_op_post = True thread = Thread() thread.section_id = self.section_map[slug] for f in ("is_closed", "is_pinned"): setattr(thread, f, getattr(wpost, f)) else: tid = self.thread_map.get((slug, wpost.parent)) try: thread = Thread.objects.get(id=tid) except Thread.DoesNotExist: raise ConvertError("Thread does not exist") thread.bump = wpost.date thread.save(rebuild_cache=False) if first_post: self.thread_map[(slug, wpost.pid)] = thread.id post.thread = thread if wpost.image: to = os.path.join(settings.WAKABA_PATH, slug) extension = wpost.image.split(".").pop() type_id = self.filetype_map.get(extension) if not type_id: raise ConvertError("Type {} does not exist".format(extension)) try: f = DjangoFile(open(os.path.join(to, wpost.image))) except IOError: pass else: file = File(file=f, hash=wpost.image_md5, type_id=type_id, image_width=wpost.image_width, image_height=wpost.image_height) if wpost.thumb: try: thumb = DjangoFile(open(os.path.join(to, wpost.thumb))) except IOError: pass else: file.thumb = thumb if file.file: file.save() post.file = file post.save() thread.save()
def convert_post(self, wpost, first_post=False): """Converts single post.""" slug = wpost.section_slug if slug in self.bad_sections: raise ConvertError("Section {} does not exist".format(slug)) post = Post() post.data = "" for f in self.fields: setattr(post, f, getattr(wpost, f)) # add video to the post if wpost.video: try: post.message += u" {}".format(wpost.video) except UnicodeEncodeError: raise ConvertError("Cannot add video to the post {}".format(wpost.id)) if first_post: post.is_op_post = True thread = Thread() thread.section_id = self.section_map[slug] for f in ("is_closed", "is_pinned"): setattr(thread, f, getattr(wpost, f)) else: tid = self.thread_map.get((slug, wpost.parent)) try: thread = Thread.objects.get(id=tid) except Thread.DoesNotExist: raise ConvertError("Thread does not exist") thread.bump = wpost.date thread.save(rebuild_cache=False) if first_post: self.thread_map[(slug, wpost.pid)] = thread.id post.thread = thread if wpost.image: to = os.path.join(settings.WAKABA_PATH, slug) extension = wpost.image.split(".").pop() type_id = self.filetype_map.get(extension) if not type_id: raise ConvertError("Type {} does not exist".format(extension)) try: f = DjangoFile(open(os.path.join(to, wpost.image))) except IOError: pass else: file = File( file=f, hash=wpost.image_md5, type_id=type_id, image_width=wpost.image_width, image_height=wpost.image_height, ) if wpost.thumb: try: thumb = DjangoFile(open(os.path.join(to, wpost.thumb))) except IOError: pass else: file.thumb = thumb if file.file: file.save() post.file = file post.save() thread.save()