Пример #1
0
    def handle(self, *args, **options):

        Question.objects.all().delete()
        Answer.objects.all().delete()
        print('Deleted existing data')

        answers = []
        with open(settings.BASE_DIR + '/../' + self.csv_file, 'r') as csvfile:
            reader = csv.reader(csvfile, delimiter='|')
            next(reader, None)

            for row in reader:

                if(len(answers) > 80):
                    save_answers(answers)
                    answers = []


                q = Question(question=row[0])
                q.save()

                print('Saved question with id ' + str(q.id));

                answers.append(Answer(question=q, choice=row[1], correct=True))

                for i in row[2].split(','):
                    answers.append(Answer(question=q, choice=i, correct=False))

        save_answers(answers)
Пример #2
0
def gradeQuestion(request):
	questionList = json.loads(request.POST['questions'])
	for question in questionList:
		sentenceText = question['sentence']
		questionText = question['question']
		labelText = question['label']
		gradeVal = question['grade']
		if Sentence.objects.filter(text=sentenceText).exists() :
			sentence = Sentence.objects.get(text=sentenceText)
		else:
			sentence = Sentence(text=sentenceText)
			sentence.save()

		if Question.objects.filter(text=questionText).exists():
			question = Question.objects.get(text=questionText)
		else:
			question = Question(text=questionText)
			question.save()

		if Label.objects.filter(text=labelText).exists():
			label = Label.objects.get(text = labelText)
		else:
			label = Label(text = labelText)
			label.save()
		grade = Grade(sentence=sentence,question=question,label=label,grade=gradeVal)
		grade.save()
	return HttpResponse('200')
Пример #3
0
    def test_cron_updates_counts(self):
        q = question(save=True)
        self.refresh()

        eq_(q.num_votes_past_week, 0)
        # NB: Need to call .values_dict() here and later otherwise we
        # get a Question object which has data from the database and
        # not the index.
        document = (Question.search().values_dict(
            'question_num_votes_past_week').filter(id=q.id))[0]
        eq_(document['question_num_votes_past_week'], 0)

        vote = questionvote(question=q, anonymous_id='abc123')
        vote.save()
        q.num_votes_past_week = 0
        q.save()

        update_weekly_votes()

        q = Question.objects.get(pk=q.pk)
        eq_(1, q.num_votes_past_week)

        document = (Question.search().values_dict(
            'question_num_votes_past_week').filter(id=q.id))[0]
        eq_(document['question_num_votes_past_week'], 1)
Пример #4
0
class NotificationTests(TestCase):
    '''Tests related to the actual Notification functionality.'''
    def setUp(self):
        '''Set up the user infrastructure.'''

        #User creation
        self.user = MyUser.objects.create_test_user(
            username="******",
            email="*****@*****.**",
            password="******",
        )

        #Course Instantiation
        self.course = Course(name="testing course", slug="testing-course")
        self.course.save()

        #Course Section Instantiation
        self.coursesection = CourseSection(name="Section 1",
                                           course=self.course)
        self.coursesection.save()

        #Category Instantiation
        self.category = Category(
            name="Category 1 for testing course",
            slug="cat-1-testing-course",
            section=self.coursesection,
        )
        self.category.save()

        #SubCategory Instantiation
        self.subcategory = SubCategory(
            name="SubCategory 1 for testing course",
            slug="subcategory-1-testing-course",
            category=self.category,
        )
        self.subcategory.save()

        self.question = Question(
            course=self.course,
            section=self.coursesection,
            category=self.category,
            subcategory=self.subcategory,
            question_text="Here is an example question.",
            option_A="Here is option A.",
            option_B="Here is option B.",
            answer_letter="A",
            answer_explanation="Here is an example explanation.",
        )
        self.question.save()

    def test_notification_creation(self):
        '''Test the creation of a notification.'''

        notification = Notification.objects.create(
            text="Notification test",
            recipient=self.user,
            link=self.question.get_absolute_url())

        notification.read = True
        notification.save()
Пример #5
0
    def test_from_url(self):
        """Verify question returned from valid URL."""
        q = question(save=True)

        eq_(q, Question.from_url('/en-US/questions/%s' % q.id))
        eq_(q, Question.from_url('/es/questions/%s' % q.id))
        eq_(q, Question.from_url('/questions/%s' % q.id))
Пример #6
0
def ask(request):
    ask_form = AskQuestion(request.POST or None)
    args = {}
    args['form'] = ask_form
    if request.POST and ask_form.is_valid():
        question = Question(text=ask_form.cleaned_data['text'], title=ask_form.cleaned_data['title'])
        tags = ask_form.cleaned_data['tags']

        g = Tag.objects.all()
        getTag = tags.split(', ')

        for tag in getTag:
            counter = 0
            for l in g:
                if l.tag == tag:
                    counter += 1
            if counter == 0:
                t = Tag(tag=tag)
                t.save()


        user = auth.get_user(request)
        question.author = user

        question.save()
        a = g.filter(tag__in=getTag)
        question.tags.add(*a)
        return redirect('questionGet', question_id=question.id)

    else:
        return render(request, 'ask.html', args)
Пример #7
0
    def test_cron_updates_counts(self):
        q = question(save=True)
        self.refresh()

        eq_(q.num_votes_past_week, 0)
        # NB: Need to call .values_dict() here and later otherwise we
        # get a Question object which has data from the database and
        # not the index.
        document = (Question.search()
                            .values_dict('question_num_votes_past_week')
                            .filter(id=q.id))[0]
        eq_(document['question_num_votes_past_week'], 0)

        vote = questionvote(question=q, anonymous_id='abc123')
        vote.save()
        q.num_votes_past_week = 0
        q.save()

        update_weekly_votes()
        self.refresh()

        q = Question.objects.get(pk=q.pk)
        eq_(1, q.num_votes_past_week)

        document = (Question.search()
                            .values_dict('question_num_votes_past_week')
                            .filter(id=q.id))[0]
        eq_(document['question_num_votes_past_week'], 1)
Пример #8
0
def question_create(request,
                    name,
                    content,
                    author,
                    categories=None,
                    is_archive=None):
    if request.method == 'POST':
        if is_archive is None:
            archive = False
        else:
            archive = is_archive
        category_list = []
        if categories is not None:
            categories = Category.objects.all()
            for category in categories:
                category_list.append(categories.filter(name=category))
        user = User.objects.get(username=author)
        question = Question(name=name,
                            content=content,
                            author=user,
                            is_archive=archive,
                            categories=category_list)
        question.save()
        return {"result": "success"}
    return {"error": "not post"}
Пример #9
0
def submit_question(request):
    # If this is a POST request then process form data
    if request.method == 'POST':
        # Grab the question from the request
        form = SubmitQuestionForm(request.POST)

        # Check if the question is actually valid
        if form.is_valid():
            # If it is, then create a new PrivateQuestion data
            new_question = Question(subject=form.cleaned_data['subject'],
                                    content=form.cleaned_data['content'],
                                    post_date=datetime.date.today())

            # If op choses to give us his email, record it
            if form.data['email']:
                new_question.op_email = form.cleaned_data['email']

            # Query the new question to the database
            new_question.save()

            return HttpResponseRedirect(reverse('submit-success'))

    # If this is a GET request then give out the new form
    else:
        form = SubmitQuestionForm()

    context = {
        'form': form,
    }

    return render(request, 'questions/submit_question.html', context)
Пример #10
0
def board(request, username):
    # TODO: refactor into a class based view
    try:
        profile = Profile.objects.get(user__username=username)
    except Profile.DoesNotExist:
        messages.warning(request, f"No user found with username: {username}")
        return HttpResponse(f"No user found with username: {username}")
    if request.method == 'POST' and request.user.is_authenticated:
        form = PostQuestionForm(request.POST)
        if form.is_valid():
            q = Question(asked_by=request.user if
                         not form.cleaned_data.get('is_anonymous') else None,
                         asked_to=profile.user,
                         content=form.cleaned_data.get('question_text'))
            q.save()
            messages.success(request, 'Question posted successfully!')
    elif request.method == 'POST' and not request.user.is_authenticated:
        messages.warning(request, 'Log in to post a question.')
        return redirect('/login/')
    form = PostQuestionForm()
    questions = profile.user.get_public_questions()
    paginator = Paginator(questions, 5)
    questions_page = paginator.get_page(request.GET.get('page'))
    return render(
        request, 'core/board.html', {
            'question_max_length': 512,
            'profile': profile,
            'questions_page': questions_page,
            'form': form
        })
Пример #11
0
    def setUp(self):
        # create an organisation
        user = User(username='******')
        user.save()
        org = Organisation(name='test_org')
        org.user = user
        org.save()

        # create three questions
        self.q1 = Question(question='What is your name?', organisation=org)
        self.q1.save()

        # create a candidate
        self.candidate = Candidate(name='Terry',
                                   participating=True,
                                   popit_id=1234)
        self.candidate.save()
        # post-save hook on candidate will automatically assign q1

        q2 = Question(question='What is your quest?', organisation=org)
        q2.save()
        q3 = Question(question='What is your favourite colour?',
                      organisation=org)
        q3.save()

        # assign 1 question to the candidate
        self.answer = Answer.objects.get(question=self.q1,
                                         candidate=self.candidate)
Пример #12
0
 def test_get_absolute_url(self):
     question = Question(title='test_title',
                         question='asasdasdas',
                         owner_id=1)
     question.save()
     resp = self.client.get(question.get_absolute_url())
     self.assertEquals(resp.status_code, 200)
Пример #13
0
    def test_form_should_post_proper_data_via_signal(self):
        """ test signal sending message if added a comment """
        mock_handler = MagicMock()

        user = User.objects.create_user(username='******',
                                        email='*****@*****.**',
                                        password='******')
        user.save()
        question = Question(title='test_title',
                            question='asasdasdas',
                            owner_id=1)
        question.save()
        answer = Answer(answer_text='some_text', answers_question=question)
        answer.save()

        signals.post_save.connect(mock_handler, sender=Answer)

        signals.post_save.send(sender=Answer,
                               instance=question,
                               answer=answer.answer_text)

        # handler.assert_called_once_with(
        #                                  signal=signals.post_save.send,
        #                                  sender=Answer,
        #                                  instance=question,
        #                                  answer=answer.answer_text)
        self.assertEquals(mock_handler.call_count, 1)
Пример #14
0
    def handle(self, *args, **options):
        users = list(User.objects.all())

        for i in range(10):
            t = Topic()
            t.name = u'Topic Name {}'.format(i)
            t.description = u'Topic Description {}'.format(i)
            t.save()
        topics = list(Topic.objects.all())

        for j in range(100):
            q = Question()
            q.author = random.choice(users)
            q.title = u'title {}'.format(j)
            q.text = u'text {}'.format(j)
            q.pub_date = datetime.datetime.now()
            q.is_published = True
            q.save()
            q.topics = random.sample(topics, random.randint(1, 6))
        questions = list(Question.objects.all())

        for k in range(100):
            c = Comment()
            c.author = random.choice(users)
            c.question = random.choice(questions)
            c.text = u'text {}'.format(k)
            c.pub_date = datetime.datetime.now()
            c.save()
Пример #15
0
def auto_lock_old_questions():
    """Locks all questions that were created over 180 days ago"""
    # Set up logging so it doesn't send Ricky email.
    logging.basicConfig(level=logging.ERROR)

    # Get a list of ids of questions we're going to go change. We need
    # a list of ids so that we can feed it to the update, but then
    # also know what we need to update in the index.
    days_180 = datetime.now() - timedelta(days=180)
    q_ids = list(
        Question.objects.filter(is_locked=False).filter(
            created__lte=days_180).values_list('id', flat=True))

    if q_ids:
        log.info('Updating %d questions', len(q_ids))

        sql = """
            UPDATE questions_question
            SET is_locked = 1
            WHERE id IN (%s)
            """ % ','.join(map(str, q_ids))

        cursor = connection.cursor()
        cursor.execute(sql)
        transaction.commit_unless_managed()

        if settings.ES_LIVE_INDEXING:
            try:
                es = get_indexing_es()

                # So... the first time this runs, it'll handle 160K
                # questions or so which stresses everything. Thus we
                # do it in chunks because otherwise this won't work.
                #
                # After we've done this for the first time, we can nix
                # the chunking code.

                from search.utils import chunked
                for chunk in chunked(q_ids, 1000):

                    # Fetch all the documents we need to update.
                    es_docs = get_documents(Question, chunk)

                    log.info('Updating %d index documents', len(es_docs))

                    # For each document, update the data and stick it
                    # back in the index.
                    for doc in es_docs:
                        doc[u'question_is_locked'] = True
                        Question.index(doc, bulk=True, es=es)

                    es.flush_bulk(forced=True)
                    es.refresh(WRITE_INDEX, timesleep=0)

            except (ESTimeoutError, ESMaxRetryError, ESException):
                # Something happened with ES, so let's push index updating
                # into an index_task which retries when it fails because
                # of ES issues.
                index_task.delay(Question, q_ids)
Пример #16
0
def auto_lock_old_questions():
    """Locks all questions that were created over 180 days ago"""
    # Set up logging so it doesn't send Ricky email.
    logging.basicConfig(level=logging.ERROR)

    # Get a list of ids of questions we're going to go change. We need
    # a list of ids so that we can feed it to the update, but then
    # also know what we need to update in the index.
    days_180 = datetime.now() - timedelta(days=180)
    q_ids = list(Question.objects.filter(is_locked=False)
                                 .filter(created__lte=days_180)
                                 .values_list('id', flat=True))

    if q_ids:
        log.info('Updating %d questions', len(q_ids))

        sql = """
            UPDATE questions_question
            SET is_locked = 1
            WHERE id IN (%s)
            """ % ','.join(map(str, q_ids))

        cursor = connection.cursor()
        cursor.execute(sql)
        transaction.commit_unless_managed()

        if settings.ES_LIVE_INDEXING:
            try:
                es = get_es()

                # So... the first time this runs, it'll handle 160K
                # questions or so which stresses everything. Thus we
                # do it in chunks because otherwise this won't work.
                #
                # After we've done this for the first time, we can nix
                # the chunking code.

                from search.utils import chunked
                for chunk in chunked(q_ids, 1000):

                    # Fetch all the documents we need to update.
                    es_docs = get_documents(Question, chunk)

                    log.info('Updating %d index documents', len(es_docs))

                    # For each document, update the data and stick it
                    # back in the index.
                    for doc in es_docs:
                        doc[u'question_is_locked'] = True
                        Question.index(doc, bulk=True, es=es)

                    es.flush_bulk(forced=True)
                    es.refresh(WRITE_INDEX, timesleep=0)

            except ES_EXCEPTIONS:
                # Something happened with ES, so let's push index updating
                # into an index_task which retries when it fails because
                # of ES issues.
                index_task.delay(Question, q_ids)
Пример #17
0
	def test_is_recent_with_future_question(self):
		"""
		is_recent() should return False for questions whose
		pub_date is in the future
		"""
		time = timezone.now() + datetime.timedelta(days=30)
		future_question = Question(pub_date=time)
		self.assertEqual(future_question.is_recent(),False)
Пример #18
0
    def test_from_invalid_url(self):
        """Verify question returned from valid URL."""
        q = question(save=True)

        eq_(None, Question.from_url('/en-US/questions/%s/edit' % q.id))
        eq_(None, Question.from_url('/en-US/kb/%s' % q.id))
        eq_(None, Question.from_url('/random/url'))
        eq_(None, Question.from_url('/en-US/questions/stats'))
Пример #19
0
	def test_is_recent_with_recent_question(self):
		"""
		is_recent() should return True for
		questions whose pub_date is within the last day
		"""
		time = timezone.now() - datetime.timedelta(hours=1)
		recent_question = Question(pub_date=time)
		self.assertEqual(recent_question.is_recent(), True)
Пример #20
0
def q_and_a_creation(q_body, a_body):
    length = len(Question.objects.all())
    q_new = Question(body=q_body, address=(length + 1))
    a_new = Answer(body=a_body, address=(length + 1))
    add_new_data_to_db_files(q_new, a_new)
    q_new.save()
    a_new.save()
    return [q_new.address, a_new.address]
Пример #21
0
    def test_notification_created(self):
        """Creating a new question auto-watches it for answers."""

        u = User.objects.get(pk=118533)
        q = Question(creator=u, title='foo', content='bar')
        q.save()

        assert QuestionReplyEvent.is_notifying(u, q)
Пример #22
0
	def test_is_recent_with_old_questions(self):
		"""
		is_recent() should return False for questions 
		whose pub_date is older than 1 day
		"""
		time = timezone.now() - datetime.timedelta(days=30)
		old_question = Question(pub_date=time)
		self.assertEqual(old_question.is_recent(), False)
Пример #23
0
    def test_question_no_answers_deleted(self):
        q = question(title=u'Does this work?', save=True)
        self.refresh()
        eq_(Question.search().query(question_title__text='work').count(), 1)

        q.delete()
        self.refresh()
        eq_(Question.search().query(question_title__text='work').count(), 0)
Пример #24
0
    def test_notification_created(self):
        """Creating a new question auto-watches it."""

        u = User.objects.get(pk=118533)
        q = Question(creator=u, title='foo', content='bar')
        q.save()

        assert check_watch(Question, q.id, u.email, 'reply')
Пример #25
0
    def test_notification_created(self):
        """Creating a new question auto-watches it for answers."""

        u = User.objects.get(pk=118533)
        q = Question(creator=u, title='foo', content='bar')
        q.save()

        assert QuestionReplyEvent.is_notifying(u, q)
Пример #26
0
    def test_question_no_answers_deleted(self):
        q = question(title=u'Does this work?', save=True)
        self.refresh()
        eq_(Question.search().query('work').count(), 1)

        q.delete()
        self.refresh()
        eq_(Question.search().query('work').count(), 0)
Пример #27
0
 def _create_tags_and_questions(self):
     for i in range(len(self.titles)):
         current_question = Question(id=i,
                                     title=self.titles[i],
                                     user_id=0,
                                     details=self.descriptions[i])
         current_question.save()
         tag = Tag(id=i, name=self.tags[i])
         tag.save()
Пример #28
0
 def test_no_inactive_users(self):
     """Ensure that inactive users' questions don't appear in the feed."""
     u = User.objects.get(pk=118533)
     u.is_active = False
     u.save()
     q = Question(title='Test Question', content='Lorem Ipsum Dolor',
                  creator_id=118533)
     q.save()
     assert q.id not in [x.id for x in QuestionsFeed().items()]
Пример #29
0
    def setUp(self):
        super(TestQuestionMetadata, self).setUp()

        # add a new Question to test with
        question = Question(title='Test Question',
                            content='Lorem Ipsum Dolor',
                            creator_id=1)
        question.save()
        self.question = question
Пример #30
0
 def get_queryset(self):
     if 'sort' in self.request.GET.keys():
         if self.request.GET['sort']=='title':
             return Question.get_query_sorted_by_title()
         if self.request.GET['sort']=='date':
             return Question.get_query_sorted_by_publish_date()
         if self.request.GET['sort']=='likes':
             return Question.get_query_sorted_by_likes()
     return Question.objects.all()
Пример #31
0
def update_question_vote_chunk(data):
    """Update num_votes_past_week for a number of questions."""

    # First we recalculate num_votes_past_week in the db.
    log.info('Calculating past week votes for %s questions.' % len(data))

    ids = ','.join(map(str, data))
    sql = """
        UPDATE questions_question q
        SET num_votes_past_week = (
            SELECT COUNT(created)
            FROM questions_questionvote qv
            WHERE qv.question_id = q.id
            AND qv.created >= DATE(SUBDATE(NOW(), 7))
        )
        WHERE q.id IN (%s);
        """ % ids
    cursor = connection.cursor()
    cursor.execute(sql)
    transaction.commit_unless_managed()

    # Next we update our index with the changes we made directly in
    # the db.
    if data and settings.ES_LIVE_INDEXING:
        # Get the data we just updated from the database.
        sql = """
            SELECT id, num_votes_past_week
            FROM questions_question
            WHERE id in (%s);
            """ % ids
        cursor = connection.cursor()
        cursor.execute(sql)

        # Since this returns (id, num_votes_past_week) tuples, we can
        # convert that directly to a dict.
        id_to_num = dict(cursor.fetchall())

        try:
            # Fetch all the documents we need to update.
            from questions.models import Question
            from search import es_utils
            es_docs = es_utils.get_documents(Question, data)

            # For each document, update the data and stick it back in the
            # index.
            for doc in es_docs:
                # Note: Need to keep this in sync with
                # Question.extract_document.
                num = id_to_num[int(doc[u'id'])]
                doc[u'question_num_votes_past_week'] = num

                Question.index(doc)
        except ES_EXCEPTIONS:
            # Something happened with ES, so let's push index updating
            # into an index_task which retries when it fails because
            # of ES issues.
            index_task.delay(Question, id_to_num.keys())
Пример #32
0
    def save(self, user):

        question = Question(
            title=self.cleaned_data['title'],
            text=self.cleaned_data['text'],
            author=Profile.objects.filter(user=user).first(),
        )
        question.save()
        return question._get_pk_val()
Пример #33
0
    def setUp(self):
        super(TestQuestionMetadata, self).setUp()

        # add a new Question to test with
        question = Question(title='Test Question',
                            content='Lorem Ipsum Dolor',
                            creator_id=1)
        question.save()
        self.question = question
Пример #34
0
def create_questions(questions, poll_id):
    for question in questions:
        new_question = Question(title=question.title,
                                poll=Poll.objects.get(pk=poll_id),
                                answer=question.answer)
        new_question.save()

        for choice in question.choices:
            new_choice = Choice(title=choice, question=new_question)
            new_choice.save()
Пример #35
0
 def test_no_inactive_users(self):
     """Ensure that inactive users' questions don't appear in the feed."""
     u = User.objects.get(pk=118533)
     u.is_active = False
     u.save()
     q = Question(title='Test Question',
                  content='Lorem Ipsum Dolor',
                  creator_id=118533)
     q.save()
     assert q.id not in [x.id for x in QuestionsFeed().items()]
Пример #36
0
    def setUp(self):

        self.question_catalogue = QuestionCatalogue(pk=1,
                                                    catalogue_scope='private',
                                                    catalogue_name='tests')
        self.question_catalogue.save()
        question = Question(pk=1,
                            question_text="text",
                            question_catalogue=self.question_catalogue)
        question.save()
Пример #37
0
    def setUp(self):
        '''Set up the test and category infrastructure.'''

        #Course Instantiation
        self.course = Course(name="testing course", slug="testing-course")
        self.course.save()

        #Course Section Instantiation
        self.coursesection = CourseSection(name="Section 1",
                                           course=self.course)
        self.coursesection.save()

        #Category Instantiation
        self.category = Category(
            name="Category 1 for testing course",
            slug="cat-1-testing-course",
            section=self.coursesection,
        )
        self.category.save()

        #SubCategory Instantiation
        self.subcategory = SubCategory(
            name="SubCategory 1 for testing course",
            slug="subcategory-1-testing-course",
            category=self.category,
        )
        self.subcategory.save()

        #User creation
        self.user = MyUser.objects.create_test_user(
            username="******",
            email="*****@*****.**",
            password="******",
        )

        self.user2 = MyUser.objects.create_test_user(
            username="******",
            email="*****@*****.**",
            password="******",
        )

        #Question creation
        self.question = Question(
            course=self.course,
            section=self.coursesection,
            category=self.category,
            subcategory=self.subcategory,
            question_text="Here is an example question.",
            option_A="Here is option A.",
            option_B="Here is option B.",
            answer_letter="A",
            answer_explanation="Here is an example explanation.",
            index=1,
        )
        self.question.save()
Пример #38
0
    def handle(self, *args, **options):
        users = list(User.objects.all())

        for i in range(10):
            t = Topic()
            t.name = u'Topic Name {}'.format(i)
            t.description = u'Topic Description {}'.format(i)
            t.save()
        topics = list(Topic.objects.all())

        for j in range(100):
            q = Question()
            q.author = random.choice(users)
            q.title = u'title {}'.format(j)
            q.text = u'text {}'.format(j)
            q.pub_date = datetime.datetime.now()
            q.is_published = True
            q.save()
            q.topics = random.sample(topics, random.randint(1, 6))
        questions = list(Question.objects.all())

        for k in range(100):
            c = Comment()
            c.author = random.choice(users)
            c.question = random.choice(questions)
            c.text = u'text {}'.format(k)
            c.pub_date = datetime.datetime.now()
            c.save()
Пример #39
0
    def fill_questions(self):
        fake = Factory.create()



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

        for i in range(0, 40):
            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.author = Profile.objects.first()
            q.rating = randint(0, 1500)
            q.id = i
            q.save()
            self.stdout.write('add question [%d]' % (q.id))
Пример #40
0
    def test_question_questionvote(self):
        # Create a question and verify it doesn't show up in a
        # query for num_votes__gt=0.
        q = question(title=u'model makers will inherit the earth', save=True)
        self.refresh()
        eq_(Question.search().filter(num_votes__gt=0).count(), 0)

        # Add a QuestionVote--it should show up now.
        questionvote(question=q, save=True)
        self.refresh()
        eq_(Question.search().filter(num_votes__gt=0).count(), 1)
Пример #41
0
 def handle(self, *args, **options):
     question = Question(
         title=self.text_gen(10) + "?",
         text=self.text_gen(40),
         author=Profile.objects.get(user=User.objects.get(id=1)),
         tag=Tag.objects.get(id=1))
     question.save()
     self.stdout.write(
         self.style.SUCCESS('Successfully created question ' +
                            question.title + ' with text ' + question.text +
                            ' with tag ' + question.tag.name))
Пример #42
0
def post_question(request):
    u = User.objects.get(pk=1)
    title = request.POST['title']
    content = request.POST['content']
    q = Question(title=title,
                 content=content,
                 author=u,
                 pub_date=timezone.now(),
                 votes=0)
    q.save()
    return detail(request, q.id)
Пример #43
0
    def test_question_questionvote(self):
        # Create a question and verify it doesn't show up in a
        # query for num_votes__gt=0.
        q = question(title=u'model makers will inherit the earth', save=True)
        self.refresh()
        eq_(Question.search().filter(question_num_votes__gt=0).count(), 0)

        # Add a QuestionVote--it should show up now.
        questionvote(question=q, save=True)
        self.refresh()
        eq_(Question.search().filter(question_num_votes__gt=0).count(), 1)
Пример #44
0
 def _bootstrap_questions_same_topics(self, author, topics, num_questions):
     for i in range(num_questions):
         q = Question(author=author,
                      content="",
                      explanation="",
                      difficulty=0,
                      quality=0,
                      difficultyCount=0,
                      qualityCount=0)
         q.save()
         q.topics.set(topics)
Пример #45
0
 def create_question(self, name):
     user = UserWithAvatar.objects.order_by("?")[:1][0]
     pub_date = timezone.now()
     title = "Could you help me with " + name + "?"
     text = self.lorem * 10
     tags = Tag.objects.order_by("?")[:5]
     question = Question(author=user, pub_date=pub_date, text=text, title=title)
     question.save()
     for tag in tags:
         question.tags.add(tag)
     question.save()
	def test_questions_increment_votes_down(self):
		"""
		Test voting up a question
		"""
		question_1 = Question(text="Can you help me with Outlook?",
							  votes=-4,
							  created=datetime.datetime.utcnow().replace(tzinfo=utc),
							  status="new")

		question_1.increment_votes(-13)

		self.assertEquals(question_1.votes, -17)
	def test_questions_increment_votes_up(self):
		"""
		Test voting up a question
		"""
		question_1 = Question(text="How can my team get started with testing?",
							  votes=7,
							  created=datetime.datetime.utcnow().replace(tzinfo=utc),
							  status="new")
							
		question_1.increment_votes(4)
		
		self.assertEquals(question_1.votes, 11)
Пример #48
0
def update_question_vote_chunk(data, **kwargs):
    """Update num_votes_past_week for a number of questions."""

    # First we recalculate num_votes_past_week in the db.
    log.info('Calculating past week votes for %s questions.' % len(data))

    ids = ','.join(map(str, data))
    sql = """
        UPDATE questions_question q
        SET num_votes_past_week = (
            SELECT COUNT(created)
            FROM questions_questionvote qv
            WHERE qv.question_id = q.id
            AND qv.created >= DATE(SUBDATE(NOW(), 7))
        )
        WHERE q.id IN (%s);
        """ % ids
    cursor = connection.cursor()
    cursor.execute(sql)
    transaction.commit_unless_managed()

    # Next we update our index with the changes we made directly in
    # the db.
    if data and settings.ES_LIVE_INDEXING:
        # Get the data we just updated from the database.
        sql = """
            SELECT id, num_votes_past_week
            FROM questions_question
            WHERE id in (%s);
            """ % ids
        cursor = connection.cursor()
        cursor.execute(sql)

        # Since this returns (id, num_votes_past_week) tuples, we can
        # convert that directly to a dict.
        id_to_num = dict(cursor.fetchall())

        # Fetch all the documents we need to update.
        from questions.models import Question
        from search import es_utils
        es_docs = es_utils.get_documents(Question, data)

        # For each document, update the data and stick it back in the
        # index.
        for doc in es_docs:
            doc_id = int(doc[u'_id'])
            document = doc[u'_source']
            new_num_votes = id_to_num[doc_id]

            document[u'question_votes'] = new_num_votes

            Question.index(document, refresh=True)
Пример #49
0
 def handle(self, *args, **options):
     for i in range(1, 20):
         u = User.objects.get(id=1)
         t = Tag.objects.get(word='test_tag')
         titlename= 'Test Question ' + str(i)
         exampletext = 'Examples of closed-ended questions are: Are you feeling better today? May I use the bathroom? Is the prime rib a special tonight?'
         q = Question(author = u, title = titlename, text = exampletext, rating = random.randint(-10, 10), date = datetime.now())
         q.save()
         q.tags.add(t)
         exampleanswer = 'Closed-ended questions should not always be thought of as simple questions that anyone can quickly answer merely because they require a yes or no answer. '
         a = Answer(question_id=q.id, author = u, text = exampleanswer, rating = random.randint(-10, 10), date = datetime.now(), correct=False)
         a.save()
         self.stdout.write(self.style.SUCCESS('Successfully added item "%s"' % i))
Пример #50
0
    def test_delete_question_removes_flag(self):
        """Deleting a question also removes the flags on that question."""
        question = Question(title='Test Question',
                            content='Lorem Ipsum Dolor',
                            creator_id=118533)
        question.save()
        FlaggedObject.objects.create(
            status=0, content_object=question,
            reason='language', creator_id=118533)
        eq_(1, FlaggedObject.objects.count())

        question.delete()
        eq_(0, FlaggedObject.objects.count())
Пример #51
0
    def create(self, validated_data):
        """
        Custom create method. Prepare and create nested choices.

        """
        choices_data = validated_data.pop("choices", None)

        question = Question(**validated_data)
        question.save()

        self.create_choices(question, choices_data)

        return question
Пример #52
0
    def mutate(self, info, description, objective, comment, answer,
               level_index):
        user = info.context.user
        level = Level.objects.filter(index=level_index).first()
        question = Question(description=description,
                            objective=objective,
                            comment=comment,
                            answer=answer,
                            level=level,
                            created_by=user.id)
        question.save()

        return CreateQuestion(question=question)
Пример #53
0
def ask(request):
    ask_form = AskQuestion(request.POST or None)
    args = {}
    args['form'] = ask_form
    if request.POST and ask_form.is_valid():
        question = Question(text_question=ask_form.cleaned_data['text'], title=ask_form.cleaned_data['title'])

        user = auth.get_user(request)
        question.user = user

        question.save()
        return render(request, 'question.html', args)
    else:
        return render(request, 'question.html', args)
Пример #54
0
    def test_recent_counts(self):
        """Verify recent_asked_count and recent unanswered count."""
        # create a question for each of past 4 days
        now = datetime.now()
        question(created=now, save=True)
        question(created=now - timedelta(hours=24), save=True, is_locked=True)
        q = question(created=now - timedelta(hours=48), save=True)
        answer(question=q, save=True)
        # 73 hours instead of 72 to avoid random test fails.
        question(created=now - timedelta(hours=73), save=True)

        # Only 3 are recent from last 72 hours, 1 has an answer.
        eq_(3, Question.recent_asked_count())
        eq_(1, Question.recent_unanswered_count())
	def test_vote_on_question(self):
		"""
		Test that a hitting a URL will incrememt a question's vote count
		"""
		question_1 = Question(text="How can my team get started with testing?",
							  votes=3,
							  created=datetime.datetime.utcnow().replace(tzinfo=utc),
							  status="new")
		question_1.save()
		
		response = self.client.get('/vote/1/up/')
		self.assertRedirects(response, '/')
		
		question_1_after_vote = Question.objects.get(id=1)
		self.assertEqual(question_1_after_vote.votes, 4)
Пример #56
0
    def setUp(self):
        self.user1 = User.objects.create_superuser(email='*****@*****.**', password='', username='******')
        self.user1.set_password('admin')
        self.user1.save()
        # self.user2 = User.objects.create_superuser(email='*****@*****.**', password='', username='******')
        # self.user2.set_password('qwerty')
        # self.user2.save()
        # self.questions1 = QuestionFactory.create_batch(2, author=self.user1 )
        # self.questions2 = QuestionFactory.create_batch(3, author=self.user1 )

        self.question1 = Question.objects.create(author=self.user1, question_title='description',
                                                 question_text='How many more time ?')
        self.question1.pub_date = timezone.make_aware(datetime.datetime(2009, 12, 29, 10, 0, 0), timezone.get_default_timezone())
        self.question1.save()
        print 'pub_date' + str(self.question1.pub_date)

        # self.question1 = self.questions1[0] #QuestionFactory(author=self.user1)
        #self.question2 =  self.questions2[0]   #QuestionFactory(author=self.user2)
        self.question2 = Question(author=self.user1, question_title='qtitle', question_text='qtext')
        self.question2.save()

        self.comments1 = QuestionCommentFactory.create_batch(3, question=self.question1)
        self.comments2 = QuestionCommentFactory.create_batch(5, question=self.question2)
        #
        # self.comments1[0].author = self.user1
        # self.comments1[0].comment_text = 'commentarium'
        # self.comments1[0].pub_date = self.question1.pub_date

        self.comment1 = QuestionComment(author=self.user1, question=self.question1, comment_text='commentarium',
                                        pub_date=self.question1.pub_date)
        self.comment2 = QuestionComment(author=self.user1, question=self.question1, comment_text='another comment')
Пример #57
0
    def test_questions_tags(self):
        """Make sure that adding tags to a Question causes it to
        refresh the index.

        """
        tag = u'hiphop'
        eq_(Question.search().filter(tag=tag).count(), 0)
        q = question(save=True)
        self.refresh()
        eq_(Question.search().filter(tag=tag).count(), 0)
        q.tags.add(tag)
        self.refresh()
        eq_(Question.search().filter(tag=tag).count(), 1)
        q.tags.remove(tag)
        self.refresh()
        eq_(Question.search().filter(tag=tag).count(), 0)