Example #1
0
    def test_tags(self):
        q = Question.create(
            author_id=self.user._id,
            title='How to patch KDE on FreeBSD?',
            body="subjxxxxxx",
            tags=["kde", "freebsd", "anime"],
        )
        q.save()
        self.run_tasks()

        cnt = 0
        for tag in Tag.find():
            cnt += 1
            self.assertEqual(tag.questions_count, 1)
        self.assertEqual(cnt, len(q.tags))

        q2 = Question.create(
            author_id=self.user._id,
            title='TCPDump on FreeBSD',
            body="Does FreeBSD has a linux-like tcpdump or it's been as usual",
            tags=["freebsd", "tcpdump"],
        )
        q2.save()
        self.run_tasks()

        t = Tag.get("freebsd")
        self.assertEqual(t.questions_count, 2)

        q2.destroy()
        q.destroy()
        self.run_tasks()
        self.assertEqual(Tag.find().count(),
                         4)  # tags are not deleted automatically anymore
Example #2
0
	def handle(self, *args, **options):
		user = User.objects.get(email='*****@*****.**')
		list_tags = ["Perl", "Python", "TechnoPark", "MySQL", "Django", "Mailru", "Voloshin", "Firefox", "black-jack", "bender"]
		Question.objects.all().delete()
		Answer.objects.all().delete()
		Tag.objects.all().delete()
		for i in range(0, 100):
			q=Question(
				author=user,
				body='body ' + str(i),
				title = 'title ' + str(i),
			)
			q.save()
			for j in range(1, 3):
				a=Answer(
					text='answer ' + str(i) + ' ' + str(j),
					author=user,
					question=q,
				)
				a.save()
			tmp = i%10
			t=Tag(
				name = list_tags[tmp],
				rating = tmp,
			)
			t.save()
			t.question.add(q)
Example #3
0
    def test_mention_event(self):
        user = User({"username": "******", "ext_id": "test"})
        user.save()
        other_user = User({"username": "******", "ext_id": "other"})
        other_user.save()

        p = Question({
            "title": "test title",
            "body": "test body, @test is mentioned",
            "tags": ["test-tag"],
            "author_id": user._id
        })
        p.save()
        self.run_tasks()
        events = user.get_new_events()
        self.assertEqual(events.count(), 0)

        a = p.create_answer({
            "author_id": other_user._id,
            "body": "this @test mention should create an event"
        })
        a.save()
        self.run_tasks()

        events = user.get_new_events()
        self.assertEqual(events.count(), 2)  # new comment event and mention event

        found_mention_event = False
        for event in events:
            if isinstance(event, MentionEvent):
                found_mention_event = True
                self.assertEqual(event.author_id, other_user._id)
                self.assertEqual(event.post_id, a._id)
        self.assertTrue(found_mention_event)
Example #4
0
def create():
    user: User = get_user_from_app_context()
    attrs = request.json
    attrs["author_id"] = user._id
    q = Question(attrs)
    q.save()
    return json_response({"data": q.api_dict(fields=QUESTION_FIELDS)})
    def fill_db(self):
        for i in range(0, 30):
            usr = User(username='******' + str(i),
                       password='******' + str(i),
                       first_name='User')
            usr.save()
            prof = Profile(avatar='avatar.jpeg', user=usr)
            prof.save()
            try:
                tbag = Tag.objects.get(name='Bucket' + str(i % 20))
                tbag.popularity += 1
            except Exception:
                tbag = Tag(name='Bucket' + str(i % 20), popularity=1)
            tbag.save()

            quest = Question(title=str(i) + 'bucket',
                             text='see my bucket, I have a' + str(10000 - i) +
                             ' bucket remains',
                             author=prof,
                             votes=i)
            quest.save()
            quest.liked.add(prof)
            quest.tag.add(tbag)

            for j in range(0, 20):
                ans = Answer(text='Test answer' + str(i),
                             author=prof,
                             question=quest)
                ans.votes = int(((i + j) * 6) % 40)
                ans.save()
                ans.voted.add(prof)
Example #6
0
    def handle(self, *args, **options):
        fake = Factory.create()

        number = int(options['number'])

        users = User.objects.all()[1:]

        starts = ('How do I Sort a Multidimensional', 'What is Vlad?',
                  'SQL Server')

        for i in range(0, number):
            q = Question()

            q.title = fake.sentence(nb_words=randint(2, 4),
                                    variable_nb_words=True)
            q.text = u"%s %s %s" % (
                choice(starts),
                os.linesep,
                fake.paragraph(nb_sentences=randint(1, 4),
                               variable_nb_sentences=True),
            )
            q.user = choice(users)
            q.rating = randint(0, 1500)
            q.is_published = True
            q.id = i
            q.save()
            self.stdout.write('add question [%d]' % (q.id))
    def handle(self, *args, **options):
		u = User.objects.get(id=1)
		q = Question(title = u'Проверка',
					 text = u'Проверка работоспособности',
					 author = u,
					 rating = 79
					 )
		q.save()
Example #8
0
	def handle(self, *args, **options):
		n = int(args[0])
		for i in range(1, n):
			title = self.fake.text(random.randint(10, 40))
			content = self.fake.text(random.randint(500, 1500))
			topic = Topic.objects.get(id = int(random.randint(1, Topic.objects.count())))
			user = User.objects.get(id = int(random.randint(1, User.objects.count())))
			date = self.fake.rdate()
			q = Question(title = title, content = content, topic = topic, user = user, date = date)
			q.save()
Example #9
0
 def drop(self):
     fx_users = User.find({"username": re.compile(r"^fx_test_user")})
     user_ids = [u._id for u in fx_users]
     ctx.log.info("dropping fixture comments")
     Comment.destroy_many({"author_id": {"$in": user_ids}})
     ctx.log.info("dropping fixture answers")
     Answer.destroy_many({"author_id": {"$in": user_ids}})
     ctx.log.info("dropping fixture questions")
     Question.destroy_many({"author_id": {"$in": user_ids}})
     ctx.log.info("dropping fixture users")
     User.destroy_many({"username": re.compile(r"^fx_test_user")})
Example #10
0
 def handle(self, *args, **options):
     for i in range(10):
         question = Question(
             title=self.text_gen(),
             text=self.text_gen(20) + " " + self.text_gen(20) + " " +
             self.text_gen(20) + "?",
             author=User.objects.get(id=random.randint(1, 10)))
         question.save()
         self.stdout.write(
             self.style.SUCCESS('Successfully created question ' +
                                question.title + ' with text ' +
                                question.text))
Example #11
0
    def handle(self, *args, **options):
        createdQuestions = 0
        createdRelations_q_t = 0
        (amount,) = args
        count = int(amount)
        countOfUsers = User.objects.count()
        countOfTags = Tag.objects.count()
        if count < 1:
            raise ValueError('incorrect parameter')
        if countOfUsers < 2:
            raise ValueError('table of users is empty. You must add users!')
        if countOfTags < 1:
            raise ValueError('table of tags is empty. You must add tags!')

        firstUser = User.objects.first().id
        lastUser = User.objects.last().id

        #generate questions
        for i in range(count):
            while True:
                try:
                    u = User.objects.get(id=random.randint(firstUser + 1, lastUser)) #without admin user
                    # print('user was founded : ' + str(u.id))
                    break
                except ObjectDoesNotExist:
                    continue

            title = randomText(random.randint(1, 4)) + '?'
            text = randomText(random.randint(5, 30)) + '?'
            q = Question(title=title, text=text, user=u, rating=0)
            firstTagID = Tag.objects.first().id
            lastTagID = Tag.objects.last().id
            amountTags = random.randint(1,5)
            q.save()
            for i in range(amountTags):
                while True:
                     try:
                         t = Tag.objects.get(id=random.randint(firstTagID, lastTagID))
                         #print('question was founded : ' + str(q.id))
                         break
                     except ObjectDoesNotExist:
                         #print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!incorrect question was generated')
                         continue
                q.tags.add(t)
                createdRelations_q_t+=1
                q.save()
            createdQuestions+=1
            print('was created : ' + str(createdQuestions) + ' questions')
        print('==============================================')
        print('was created : ' + str(createdQuestions) + ' questions')
        print('was created : ' + str(createdRelations_q_t) + ' relations question_tag')
Example #12
0
def restore_answer_comment(question_id, answer_id, comment_id):
    c: Optional[Comment] = Comment.get(comment_id, "comment not found")
    a: Optional[Answer] = Answer.get(answer_id, "comment not found")
    q: Optional[Question] = Question.get(question_id, "comment not found")
    if a.parent_id != q._id or c.parent_id != a._id:
        raise NotFound("comment not found")
    restore_post(c)
    return json_response({"data": c.api_dict(COMMENT_FIELDS)})
Example #13
0
    def handle(self, *args, **options):
        fake = Factory.create()

        number = int(options['number'])

        users = Profile.objects.all()

        starts = (
                u'Help! Nothing happens!',
                u'I tried all, help',
                u'I do not find any solutions on the Internet, save',
                u'Following problem:',
                u'I think that someone of you faced with the question',
                u'Sorry, but I am a novice in this matters',
                u'Hi! Dates burn, need advice',
                )

        for i in range(0, number):
            q = Question()

            q.title = fake.sentence(nb_words=randint(4, 6), variable_nb_words=True)[:40]
            q.text = u"%s %s %s" % (
                    choice(starts),
                    os.linesep,
                    fake.paragraph(nb_sentences=randint(4, 17), variable_nb_sentences=True),
                    )
            q.owner = choice(users)
            q.save()
            tag_cnt = randint(1,5)
            for i in range(0, tag_cnt):
                tq = Tag.objects.filter(id=randint(1, tag_cnt))[0]
                q.tags.add(tq)
            self.stdout.write('added question [%d]' % (q.id))
Example #14
0
    def handle(self, *args, **options):
        try:
            user = Profile.objects.get(user_id=options['author_id'])
        except Profile.DoesNotExist:
            raise CommandError("User %s doesn't exist" % options['author_id'])

        title = options['title']
        text = options['text']

        question = Question(title=title, text=text, author=user)
        question.save()

        for tag in options['tags'].split():
            try:
                question.tags.add(Tag.objects.get(name=tag))
            except Tag.DoesNotExist:
                raise CommandError('Tag "%s" does not exist' % tag)
        question.save()
Example #15
0
def question_ask(request):
    question_form = QuestionForm(request.POST)
    if question_form.is_valid():

        title = question_form.cleaned_data["title"]
        contents = question_form.cleaned_data["contents"]

        question = Question(title=title, contents=contents, author=request.user, date_created=timezone.now())
        question.save()

        return HttpResponse('{"question_id": ' + str(question.id) + '}')
    else:
        error = ""

        for field in question_form:
            if field.errors:
                error += field.label_tag + ": " + field.errors + "<br>"

        return HttpResponse('{"error": "' + error + '"}')
Example #16
0
def accept_answer(question_id, answer_id):
    u: User = get_user_from_app_context()
    q: Optional[Question] = Question.get(question_id, "answer not found")
    a: Optional[Answer] = Answer.get(answer_id, "answer not found")
    if a.parent_id != q._id:
        raise NotFound("answer not found")
    if q.author_id != u._id:
        raise Forbidden("only question's author can accept answers")
    q.set_accepted_answer(a)
    return json_response({"data": a.api_dict(ANSWER_FIELDS)})
Example #17
0
    def test_hrid(self):
        q = Question.create(
            author_id=self.user._id,
            title='How to patch KDE on FreeBSD?',
            body="subjxxxxxx",
            tags=["kde", "freebsd", "anime"],
        )
        q.save()
        self.run_tasks()
        self.assertEqual(q.human_readable_id, "how-to-patch-kde-on-freebsd")

        q = Question.create(
            author_id=self.user._id,
            title='How to patch KDE on FreeBSD?',
            body="subjxxxxxx",
            tags=["kde", "freebsd", "anime"],
        )
        q.save()
        self.run_tasks()
        self.assertEqual(q.human_readable_id, "how-to-patch-kde-on-freebsd_1")
Example #18
0
def create_comment(question_id):
    q = Question.get(question_id, "question not found")
    user: User = get_user_from_app_context()
    attrs = request.json

    if "body" not in attrs:
        raise ApiError("body is missing")

    c = q.create_comment({"body": attrs["body"], "author_id": user._id})
    c.save()
    return json_response({"data": c.api_dict(COMMENT_FIELDS)})
Example #19
0
def newquestion(request):
    if (request.method == "POST"):
        form = NewQuestionForm(request.POST)
        if (form.is_valid):
            if (Question.objects.filter(
                    header=request.POST["header"]).count() == 0):
                uscontent = request.POST["content"]
                usheader = request.POST["header"]
                ususer = User.objects.get(username=request.user.username)
                quest = Question(header=usheader,
                                 content=uscontent,
                                 author=ususer)
                quest.save()
                if ((request.POST.has_key("tag1")) and
                    (Tag.objects.filter(name=request.POST["tag1"]).count() !=
                     0)):
                    tag = Tag.objects.get(name=request.POST["tag1"])
                    quest.tag.add(tag)
                return redirect('/user/')
                if ((request.POST.has_key("tag2")) and
                    (Tag.objects.filter(name=request.POST["tag2"]).count() !=
                     0)):
                    tag = Tag.objects.get(name=request.POST["tag2"])
                    quest.tag.add(tag)
                return redirect('/user/')
                if ((request.POST.has_key("tag3")) and
                    (Tag.objects.filter(name=request.POST["tag3"]).count() !=
                     0)):
                    tag = Tag.objects.get(name=request.POST["tag3"])
                    quest.tag.add(tag)
                return redirect('/user/')
            else:
                newDict = defaultDict
                newDict["status"] = "alreadyEx"
                newDict["curUser"] = request.user
                return render(request, "newquestion.html", newDict)
    else:
        newDict = defaultDict
        newDict["status"] = "newPage"
        newDict["curUser"] = request.user
        return render(request, "newquestion.html", newDict)
Example #20
0
def create_answer(question_id):
    q: Optional[Question] = Question.get(question_id, "question not found")
    user: User = get_user_from_app_context()
    attrs = request.json

    if "body" not in attrs:
        raise ApiError("body is missing")

    a = q.create_answer({"author_id": user._id, "body": attrs["body"]})
    a.save()

    return json_response({"data": a.api_dict()})
Example #21
0
def newquestion(request):
    if request.user.is_authenticated():
        u = request.user
        user = u.customuser
        question_form = QuestionForm(request.POST)  # A form bound to the POST data
        if question_form.is_valid():  # All validation rules pass
            question = Question(
                title=question_form.cleaned_data["title"],
                question_text=question_form.cleaned_data["question_text"],
                customuser=user,
                pub_data=timezone.now(),
            )
            question.save()
            request.session["message"] = "Your answer was successfully added!!"
            request.session["flag"] = 1
        else:
            request.session["message"] = "Error!!"
            request.session["flag"] = 1
    else:
        request.session["message"] = "You must be logged in"
        request.session["flag"] = 0
    return HttpResponseRedirect(reverse("questions"))  # Redirect after POST
Example #22
0
def revoke_answer(question_id, answer_id):
    u: User = get_user_from_app_context()
    q: Optional[Question] = Question.get(question_id, "answer not found")
    a: Optional[Answer] = Answer.get(answer_id, "answer not found")
    if a.parent_id != q._id:
        raise NotFound("answer not found")
    if q.author_id != u._id:
        raise Forbidden("only question's author can revoke answers")
    if not a.accepted:
        raise NotAccepted("answer is not accepted so can't be revoked")
    q.set_accepted_answer(None)
    a.reload()
    return json_response({"data": a.api_dict(ANSWER_FIELDS)})
Example #23
0
def addask(req):
	if req.method == "POST":
		if "title" in req.POST and "topic" in req.POST and "content" in req.POST:
			if "name" in req.session:
				title = req.POST["title"]
				topic_id = int(req.POST["topic"])
				content = req.POST["content"]
				try:
					u = User.objects.get(id=int(req.session["name"]))
					u.raiting = u.raiting + 1
					topic = Topic.objects.get(id = topic_id)
					u.save()
				except (Topic.DoesNotExist, User.DoesNotExist):
					return HttpResponse("Error")
				af = AskForm({"title" : title, "content" : content, "topic": topic_id})
				if af.is_valid():
					q = Question(title = title, topic = topic, content = content, user = u, date = datetime.datetime.now(), raiting = 0)
					q.save()
					return HttpResponseRedirect("../../qstadd/?qst_id={0}".format(q.id))
				else:
					return HttpResponse("Error Valid")
	return HttpResponse("")
Example #24
0
def post_query(request):
    if request.method == "POST":
        query = Question()
        query.question = request.POST.get('question-area')
        query.asked_by = Profile.objects.get(user = request.user)
        query.save()
        messages.success(request,"Your Question was posted!")
    return redirect("askCommunity:home")
Example #25
0
def vote_question(question_id):
    q: Optional[Question] = Question.get(question_id, "question not found")
    u: User = get_user_from_app_context()
    if q.author_id == u._id:
        raise Forbidden("you can't vote for your own question")

    attrs = request.json

    if "value" not in attrs:
        raise ApiError("value field is mandatory")

    Vote.vote(q._id, u._id, attrs["value"])
    q.reload()
    return json_response({"data": q.api_dict(fields=QUESTION_FIELDS)})
Example #26
0
def ask(request):
    form = questionform()
    if request.method == "POST":
        form = questionform(request.POST)
        if form.is_valid():
            q = Question(title=form.cleaned_data['title'],
                         text=form.cleaned_data['text'],
                         author=get_object_or_404(Author, user=request.user),
                         pub_date=timezone.now(),
                         rating=0)
            q.save()
            for tg in form.cleaned_data['tag']:
                Tag.objects.get_or_create(name=tg)
                q.tags.add(Tag.objects.get(name=tg))
                qid = q.id
            return HttpResponseRedirect(
                reverse('ask:question', kwargs={'question_id': qid}))
    return render(
        request, 'ask/question_create.html', {
            'form': form,
            'users': Author.objects.all(),
            'tags': Tag.objects.besters(),
        })
Example #27
0
def ask(request):
	form = NewQuestion()
	
	if request.POST:
		title = request.POST.get('title')
		text = request.POST.get('text')
		tags = request.POST.get('tags')

		form.fields['title'].initial = title
		form.fields['text'].initial = text
		form.fields['tags'].initial = tags
		
		is_empty_fields = False
		if isEmptyQuestionFields(title, text, tags):
			is_empty_fields = True
		
		if is_empty_fields:
			context = {
				'is_empty_fields': is_empty_fields,
				'form': form			
			}
			return render(request, 'ask.html', context)
		else:
			#tags.encode('utf-8')
			#connectTags(q, tags)
			#t = Tag(text = tags)
			#t.save()
			q = Question(title = title, text = text, author = request.user, rating = 0)
			q.save()
			connectTags(q, tags)
			#q.tags.add(t)
			q.save()
			id_question = q.id
			#return render(request, 'answer.html/' + str(id_question) + '/')
			#return HttpResponseRedirect('/answer/' + str(id_question) + '/')
			return redirect('/answer/' + str(id_question) + '/')
	return render(request, 'ask.html', {'form': form})
	def AskUser(self,request):
		user = request.user
		if form.is_valid():
			theme = form.cleaned_data.get('theme')
			quest = form.cleaned_data.get('question')
			c = CustomUser.objects.get(user = user)
			
			q = Question(user=c,title=theme,text=quest)
			q.save()
			tags = form.cleaned_data.get('tags').split(',')
			for tag in tags:
				if ' ' in tag:
					tag = tag.replace(' ', '_')
				try:
					t = Tag.objects.get(name=tag)
				except Tag.DoesNotExist:
					t = Tag.objects.create(name=tag)
					t.save()

				q.tags.add(t)
			redirect_to= '/question/'+str(q.id)+'/'
			return True
		else:
			return False
Example #29
0
def ask(request):
	errors = []
	if not request.user.is_authenticated():
		errors.append("you need to login !!")
		return erquestion(request, errors)
	else:
		if request.method == 'POST':
			form = AskForm(request.POST)
			if form.is_valid():
				cd = form.cleaned_data
				u = request.user
				he = cd['header']
				b = cd['body']
				q = Question(header = he, body = b, user = u, ask_date = timezone.now(), rating = 0)
				q.save()
				send_email('Nice, your question was published, %s' % (u.username), '%s \n %s' %(he, b), [u.email])
				u = User.objects.all().order_by('-date_joined')[:10]
				return HttpResponseRedirect("/")
			else:
				errors.append("All feilds in ask form are required")
				return erquestion(request, errors)
	latest_question = Question.objects.all().order_by('-ask_date')[:20]
	ask_form = AskForm()
	return render(request, 'ask/question.html', { 'errors':errors , 'latest_question':latest_question , 'AskForm':ask_form, 'last_users':u })
Example #30
0
 def handle(self, *args, **options):
     User.objects.all().delete()
     user = User.objects.create_user("nuf", "*****@*****.**", "nuf")
     user.save()
     tagmas = [
         'ActionScript', 'Ada', 'Bash', '(Visual) Basic', 'Bourne Shell',
         'Bro', 'C', 'C Shell', 'C#', 'C++', 'Curl', 'Fortran', 'Go',
         'Haskell', 'Java', 'JavaScript', 'Lisp', 'Maple', 'Mathematica',
         'MATLAB', 'MOO', 'Objective-C', 'Pascal', 'Perl', 'PHP', 'Python',
         'Ruby', 'Simulink', 'Verilog', 'VHDL'
     ]
     Question.objects.all().delete()
     Tags.objects.all().delete()
     for i in range(1, 10):
         q = Question(
             author=user,
             text=
             'In eget neque in turpis suscipit tristique vitae nec mauris. Vestibulum auctor, turpis non lobortis gravida, nisi est vulputate lectus, ut dictum erat augue ut erat.',
             title='title' + str(i),
             question_id=i,
         )
         q.save()
         t1 = Tags(name=tagmas[(i - 1) * 2])
         t2 = Tags(name=tagmas[(i - 1) * 2 + 1])
         t1.save()
         t2.save()
         t1.question.add(q)
         t2.question.add(q)
         for j in range(1, 10):
             a = Answer(
                 text=
                 'In eget neque in turpis suscipit tristique vitae nec mauris. Vestibulum auctor, turpis non lobortis gravida, nisi est vulputate lectus, ut dictum erat augue ut erat. In fringilla tincidunt dolor, at pulvinar lacus cursus nec. Pellentesque ultrices eget odio ac ullamcorper. Duis turpis orci, tempor vel massa id, posuere condimentum purus. Sed rutrum magna non nisi posuere interdum. Vivamus eget diam dictum mi malesuada accumsan.',
                 author=user,
                 question=q,
             )
             a.save()
Example #31
0
    def handle(self, *args, **options):
        fake = Factory.create()

        number = int(options['number'])

        users = User.objects.all()[1:]
        for i in range(0, number):
            q = Question()

            q.title = fake.sentence(nb_words=randint(2, 4),
                                    variable_nb_words=True)
            q.text = fake.paragraph(nb_sentences=randint(4, 17),
                                    variable_nb_sentences=True)
            q.auth = choice(users)
            q.save()
Example #32
0
def vote_answer_comment(question_id, answer_id, comment_id):
    c: Optional[Comment] = Comment.get(comment_id, "comment not found")
    a: Optional[Answer] = Answer.get(answer_id, "comment not found")
    q: Optional[Question] = Question.get(question_id, "comment not found")
    if a.parent_id != q._id or c.parent_id != a._id:
        raise NotFound("comment not found")
    u: User = get_user_from_app_context()
    if c.author_id == u._id:
        raise Forbidden("you can't vote for your own comments")

    attrs = request.json

    if "value" not in attrs:
        raise ApiError("value field is mandatory")

    Vote.vote(c._id, u._id, attrs["value"])
    c.reload()
    return json_response({"data": c.api_dict(fields=COMMENT_FIELDS)})
Example #33
0
    def test_substitutions(self):
        ctx.cfg["substitutions"] = (
            (r"\b([A-Z]+-\d+)\b",
             r"[\1](https://jira.example.com/browse/\1)"), )

        q = Question.create(
            author_id=self.user._id,
            title='How to patch KDE on FreeBSD?',
            body="Is that exactly what is meant in MYPROJ-338?",
            tags=["kde", "freebsd", "anime"],
        )

        q.save()
        self.run_tasks()

        self.assertEqual(
            q.body, "Is that exactly what is meant in "
            "[MYPROJ-338](https://jira.example.com/browse/MYPROJ-338)?")

        a = q.create_answer({
            "author_id": self.user._id,
            "body": "No, it's not. It's actually MYPROJ-42"
        })
        a.save()
        self.run_tasks()

        self.assertEqual(
            a.body, "No, it's not. It's actually "
            "[MYPROJ-42](https://jira.example.com/browse/MYPROJ-42)")
        a.save()

        c = a.create_comment({
            "author_id":
            self.user._id,
            "body":
            "MYPROJ-338 looks more promising. Well, MYPROJ-42 is OK too.",
        })

        c.save()
        self.run_tasks()

        self.assertEqual(
            c.body,
            "MYPROJ-338 looks more promising. Well, MYPROJ-42 is OK too.")
Example #34
0
def setup():
    f = Faker()
    tags = f.words(nb=20)
    for i in tags:
        a = Tag(tag=i)
        a.save()

    for i in range(100):
        tt = f.text(50)
        te = f.text()
        a = Question(title=tt, text=te, author_id=randint(2, 4))
        a.save()
        a.tags.add(randint(1, 20), randint(1, 20), randint(1, 20))

    for i in range(300):
        te = f.text()
        an = Answer(text=te,
                    author_id=randint(2, 4),
                    question_id=randint(1, 100))
        an.save()
Example #35
0
def index():
    u: User = get_user_from_app_context()

    if "_sort" in request.values:
        srt = request.values["_sort"]
    else:
        srt = "rating"

    sortExpr = SORT_MAP.get(srt)
    if sortExpr is None:
        raise ApiError(f"unknown sort operator \"{srt}\"")

    if get_boolean_request_param("_mine"):
        if u:
            # only mine posts
            query = {"author_id": u._id}
        else:
            # nothing to show, user is not logged in
            query = {"_id": NilObjectId}
    else:
        # otherwise show all not deleted posts
        query = {
            "$or": [
                {
                    "deleted": False
                },
            ]
        }
        if u:
            # if user is logged in, he can view his own deleted posts
            query["$or"].append({"author_id": u._id})

    questions = Question.find(query).sort(sortExpr)
    results = paginated(
        questions, transform=default_transform(fields=QUESTION_LIST_FIELDS))
    author_ids = set()
    for q in results["data"]:
        author_ids.add(resolve_id(q["author_id"]))
    authors = User.find({"_id": {"$in": list(author_ids)}})
    return json_response({"questions": results, "authors": {"data": authors}})
Example #36
0
    def test_tag_new_post_event(self):
        u = User({"username": "******", "ext_id": "test"})
        u.save()
        u.subscribe_to_tag("test-tag")
        u.subscribe_to_tag("test-tag2")
        u.subscribe_to_tag("test-tag3")

        p = Question({
            "title": "test title",
            "body": "test body, needs to be long",
            "tags": ["test-tag", "test-tag2"],
            "author_id": u._id
        })
        p.save()
        self.run_tasks()

        events = u.get_new_events()
        self.assertEqual(events.count(), 0)

        other_user = User({"username": "******", "ext_id": "other"})
        other_user.save()

        p = Question({
            "title": "test title",
            "body": "test body, needs to be long",
            "tags": ["test-tag", "test-tag2"],
            "author_id": other_user._id
        })
        p.save()
        self.run_tasks()
        events = u.get_new_events()
        self.assertEqual(events.count(), 1)
        event: TagNewQuestionEvent = events[0]

        # only subscribed tags are listed in event
        self.assertCountEqual(event.tags, ["test-tag", "test-tag2"])
        self.assertEqual(event.question_id, p._id)
Example #37
0
    def save(self, owner):
        data = self.cleaned_data
        title = data.get('title')
        text = data.get('text')
        tags_list = data.get('tags')
        if tags_list:
            tags_list = [tag.replace(' ', '') for tag in tags_list]
            tags_list = [tag.replace('-', '_') for tag in tags_list]

        q = Question()
        q.title = title
        q.text = text
        q.owner = Profile.objects.get(user_id=owner.id)
        q.save()

        for tag in tags_list:
            tag_obj = Tag.objects.get_or_create(tag)
            q.tags.add(tag_obj)

        return q
Example #38
0
def add_question(request):
    u = get_object_or_404(User, pk=12)
    for i in range(5000, 10000):
        question = Question(title=int(i), question_text="Question", customuser=u.customuser, pub_data=timezone.now())
        question.save()
    return HttpResponseRedirect(reverse("questions"))
def create_qusetion_answer_and_connect_user(how_many):
	does_NOT_exist_users = ''
	for j in range(how_many):
		### User get random
		user_id = random.randint(1, 10362)
		try:
			u = User.objects.get(id=user_id)
		except:
			does_NOT_exist_users = does_NOT_exist_users + str(user_id) + ' '
			user_id = random.randint(1, 10362)
			try:
				u = User.objects.get(id=user_id)
			except:
				does_NOT_exist_users = does_NOT_exist_users + str(user_id) + ' '
				user_id = random.randint(1, 10362)
				u = User.objects.get(id=user_id)
		### End User get random
		
		### Tag create
		start_tag_lenght = 3
		end_tag_lenght = 6
		t_text = randomword(start_tag_lenght, end_tag_lenght)
		
		t = Tag(text = t_text)
		
		t.save()
		### End Tag create
		
		### Question create
		question_length_low = 8
		question_length_high = 15
		q_title = randomword(question_length_low, question_length_high)
		for i in range(random.randint(0, 2)):
			q_title = q_title + ' ' + randomword(question_length_low, question_length_high)
		q_title = q_title  + '?'
		q_text = randomword(question_length_low, question_length_high)
		for i in range(random.randint(3, 20)):
			q_text = q_text + ' ' + randomword(question_length_low, question_length_high)
		q_rating = random.randint(-10, 150)
		
		q = Question(title = q_title,
					 text = q_text,
					 author = u,
					 rating = q_rating
					 )
					 
		q.save()
		q.tags.add(t)
		q.save()
		### End Question create
		
		### User get random
		ser_id = random.randint(1, 10362)
		try:
			u = User.objects.get(id=user_id)
		except:
			does_NOT_exist_users = does_NOT_exist_users + str(user_id) + ' '
			user_id = random.randint(1, 10362)
			try:
				u = User.objects.get(id=user_id)
			except:
				does_NOT_exist_users = does_NOT_exist_users + str(user_id) + ' '
				user_id = random.randint(1, 10362)
				u = User.objects.get(id=user_id)
		### End User get random
		
		### Answer create
		answer_length_low = 8
		answer_length_high = 15
		a_text = randomword(answer_length_low, answer_length_high)
		for i in range(random.randint(7, 25)):
			a_text = a_text + ' ' + randomword(answer_length_low, answer_length_high)
		a_right_answer = True
		
		a = Answer(question = q,
				   text = a_text, 
				   right_answer = a_right_answer, 
				   author = u
				   )
		a.save()
		### End asnwer create
		print('Create: ' + str(j))
	print('Create: ' + str(how_many))
	print(does_NOT_exist_users)
def create_questions(users):
  for i in range(0, 100000):
    uid = random.randint(0, len(users) - 1)
    
    question = Question(title="Doctor, where am i?", contents="With Black Jack and ladies of course", author=users[uid], date_created=timezone.now())
    question.save()