def create_question():
    try:
        json = request.get_json()

        errors = []

        username = json.get('user', '')
        text = json.get('text', '')

        if not username:
            errors.append({'field': 'user', 'message': 'User is required.'})

        if not text:
            errors.append({'field': 'text', 'message': 'Text is required.'})

        if errors:
            return jsonify({'errors': errors}), 422

        question = Question.create(username=username, text=text)
        question.save()

        return jsonify({'question': question.to_json()}), 201
    except BadRequest as e:
        return jsonify({
            'errors':
            'Something went wrong! Maybe your JSON is malformed. Please, fix it and try again.'
        }), 400
 def test_question_follows(self):
     u1 = User.create(email='*****@*****.**', password='******')
     u2 = User.create(email='*****@*****.**', password='******')
     q1 = Question.create(title='你见过的最漂亮的人', author=u2)
     db.session.add_all([u1, u2, q1])
     db.session.commit()
     self.assertFalse(u1.is_following_question(q1))
     self.assertFalse(q1.is_followed_by(u1))
     timestamp_before = datetime.datetime.utcnow()
     u1.follow(q1)
     db.session.add(u1)
     db.session.commit()
     timestamp_after = datetime.datetime.utcnow()
     self.assertTrue(u1.is_following_question(q1))
     self.assertTrue(q1.is_followed_by(u1))
     self.assertTrue(q1.followers.count() == 1)
     self.assertTrue(u1.followed_questions.count() == 1)
     f = u1.followed_questions.all()[0]
     self.assertTrue(f.followed == q1)
     self.assertTrue(timestamp_before <= f.timestamp <= timestamp_after)
     s = q1.followers.all()[0]
     self.assertTrue(s.follower == u1)
     u1.unfollow(q1)
     db.session.add(u1)
     db.session.commit()
     self.assertFalse(u1.is_following_question(q1))
     self.assertFalse(q1.is_followed_by(u1))
     self.assertTrue(u1.followed_questions.count() == 0)
     self.assertTrue(q1.followers.count() == 0)
     self.assertTrue(FollowQuestion.query.count() == 0)
    def test_question_comment(self):
        """
        测试评论添加删除
        以及回复添加删除
        :return:
        """
        u = User.create(username='******', password='******')
        u1 = User.create(username='******', password='******')
        question = Question.create(author=u, description='dwdwdgg?')
        self.assertTrue(question.undelete_comments.count() == 0)
        self.assertTrue(question.comments.count() == 0)
        c = Comment.create(author=u1,
                           question=question,
                           topic_type='question',
                           body='fdjhfjdj')
        c1 = Comment.create(author=u1,
                            question=question,
                            topic_type='question',
                            body='lgkjgfdjhfjdj')
        self.assertTrue(question.comments.count() == 2)
        self.assertTrue(question.undelete_comments.count() == 2)
        r = Reply.create(comment=c, author=u, body='kllfdd')
        r1 = Reply.create(comment=c, author=u1, user=u, body='ldkkkfg')
        self.assertTrue(c.replies.count() == 2)

        u.delete_comment(c)  # 先删除评论
        self.assertTrue(c.replies.count() == 2)  # 不会影响回复
        self.assertTrue(question.comments.count() == 2)
        self.assertTrue(question.undelete_comments.count() == 1)

        u.delete_reply(r)  # 删除一条回复
        self.assertTrue(c.replies.count() == 1)
        u.delete_reply(r1)  #删除最后一条回复
        self.assertNotIn(c, question.comments.all())  #c不应该在所有评论里面
Esempio n. 4
0
    def test_insert(self):
        print('')
        print('Creating an admin user...')
        role = Role.get_by_name('admin')
        self.assertTrue(role is not None)
        user = User(username='******', role=role, password='******')
        print('Admin user successfully created.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')
        print('Adding and committing an admin user into the database...')
        db.session.add(user)
        db.session.commit()
        self.assertTrue(
            User.query.filter_by(username='******').first() is not None)
        print('Admin user successfully added and committed into the database.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')

        print('Creating a course...')
        c = Course(course_code='TEST')
        print('Course successfully created.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')
        print('Trying to add and commit course into database...')
        db.session.add(c)
        db.session.commit()
        self.assertTrue(
            Course.query.filter_by(course_code='TEST').first() is not None)
        print('Course successfully added and committed into database.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')

        print('Creating a survey...')
        survey = Survey.create(description='blah test',
                               times=['1', '2'],
                               owner_id=user.id,
                               course=c.course_code)
        self.assertTrue(
            Survey.query.filter_by(
                description='blah test').first() is not None)
        print('Survey successfully created.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')
        print('Creating a question for the survey...')
        question = Question.create(description="a test question",
                                   owner_id=user.id,
                                   optional=False,
                                   q_type=1)
        self.assertTrue(question is not None)
        print('Question successfully created.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')
        print('Assigning question to survey...')
        survey.set_questions([question.id])
        self.assertTrue(survey.questions.all() is not None)
        print('Question successfully assigned.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')
        print('')
 def test_add_remove_question(self):
     topic = Topic.create(title='摄影')
     question = Question.create(title='好吗?')
     questions = [i.question for i in topic.questions.all()]
     self.assertListEqual(questions, [])
     self.assertTrue(topic.questions.count() == 0)
     topic.add_question(question)
     questions = [i.question for i in topic.questions.all()]
     self.assertListEqual(questions, [question])
     self.assertTrue(topic.questions.count() == 1)
     topic.remove_question(question)
     self.assertFalse(topic.is_in_topic(question))
     self.assertTrue(topic.questions.count() == 0)
    def test_collect_question(self):
        q = Question.create(title='wdffd')
        f = Favorite.create(title='数学')

        self.assertListEqual(f.questions.all(), [])
        self.assertTrue(f.questions.count() == 0)
        self.assertTrue(q.favorites.count() == 0)
        f.collect(q)
        self.assertListEqual([i.question for i in f.questions.all()], [q])
        self.assertTrue(f.questions.count() == 1)
        self.assertTrue(q.favorites.count() == 1)
        self.assertTrue(f.has_collect_question(q))
        f.uncollect(q)
        self.assertTrue(f.questions.count() == 0)
        self.assertTrue(q.favorites.count() == 0)
        self.assertFalse(f.has_collect_question(q))
    def test_collect_answer(self):
        q = Question.create(title='dwwf')
        a = Answer.create(body='dwwdf', question=q)
        f = Favorite.create(title='数学')

        self.assertListEqual(f.answers.all(), [])
        self.assertTrue(f.answers.count() == 0)
        self.assertTrue(a.favorites.count() == 0)
        f.collect(a)
        self.assertListEqual([i.answer for i in f.answers.all()], [a])
        self.assertTrue(f.answers.count() == 1)
        self.assertTrue(a.favorites.count() == 1)
        self.assertTrue(f.has_collect_answer(a))
        f.uncollect(a)
        self.assertTrue(f.answers.count() == 0)
        self.assertTrue(a.favorites.count() == 0)
        self.assertFalse(f.has_collect_answer(a))
Esempio n. 8
0
def pose_question():
    """
    提出问题
    :return:
    """
    s = search()
    if s:
        return s
    form = QuestionForm()
    if form.validate_on_submit():

        question = Question.create(author=current_user._get_current_object(), title=form.title.data,
                                   description=form.description.data, anonymous=form.anonymous.data)

        for each in form.topic.data:
            topic = Topic.query.get(each)
            if topic.add_question(question):
                flash('添加到话题:{}'.format(topic.title), 'success')

        flash('提问成功')
        return redirect(url_for('.index'))
    return render_template('question/pose_question.html', form=form)
Esempio n. 9
0
def seed_all():
    for item in questions_list:
        num = random.randint(0, len(users_list) - 1)
        question = Question.create(
            text=item['text'], username=users_list[num]['email'])
        print(f'Seeding question `{question.text}`')
        question.save()

        max_answers = random.randint(0, 20)

        for i in range(max_answers):
            a_num = random.randint(0, len(answers_list) - 1)
            num = random.randint(0, len(users_list) - 1)
            answer = Answer.create(
                text=answers_list[a_num]['text'],
                username=users_list[num]['email'],
                question=question
            )
            print(
                f'Seeding answer `{answer.text}` to question `{question.text}`')
            answer.save()

    print('Finished seeding.')
    def test_core_database_functionality(self):
        # admin_create_survey
        print('')
        print('Creating an administrator user...')
        role = Role.get_by_name('admin')
        self.assertTrue(role is not None)
        user = User(username='******', role=role, password='******')
        print('Adding and commiting data to database...')
        db.session.add(user)
        db.session.commit()
        self.assertTrue(User.query.filter_by(
            username='******').first() is not None)
        print('Successfully added and committed data to database.')
        print('Administrator user successfully created.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')

        print('Creating course...')
        c = Course(course_code='TEST')
        print('Adding and commiting data to database...')
        db.session.add(c)
        db.session.commit()
        self.assertTrue(Course.query.filter_by(
            course_code='TEST').first() is not None)
        print('Successfully added and committed data to database.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')

        print('Creating a survey with the course code...')
        survey = Survey.create(description='blah test', times=['1', '2'],
                               owner_id=user.id, course=c.course_code)
        self.assertTrue(Survey.query.filter_by(description='blah test')
                        .first() is not None)
        self.assertTrue(Survey.query.filter_by(description='blah test')
                        .first().status == 'review')
        print('Survey successfully created with the course code.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')
        print('Creating questions for survey...')
        question1 = Question.create(
            description="a test question1", owner_id=user.id, optional=False, q_type=2)
        question2 = Question.create(
            description="a test question2", owner_id=user.id, optional=True, q_type=2)
        self.assertTrue(question1 is not None)
        self.assertTrue(question2 is not None)
        print('Successfully created questions.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')
        print('Setting questions to survey...')
        survey.set_questions([question1.id, question2.id])
        self.assertTrue(survey.questions.all() is not None)
        print('Successfully assigned questions to survey.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')

        # staff_review_survey
        print('Creating staff user...')
        role = Role.get_by_name('staff')
        self.assertTrue(role is not None)
        user = User(username='******', role=role, password='******')
        print('Adding and commiting data to database...')
        db.session.add(user)
        db.session.commit()
        self.assertTrue(User.query.filter_by(username='******')
                        .first() is not None)
        survey = Survey.query.filter_by(description='blah test').first()
        self.assertTrue(survey is not None)
        self.assertTrue(survey.status == 'review')
        print('Successfully added and committed data to database.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')
        print('Setting survey phase to open...')
        survey.status = 'open'
        self.assertTrue(survey.status == 'open')
        db.session.add(survey)
        db.session.commit()
        print('Successfully set survey phase to open and made changes to database.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')

        # student_answer_survey
        print('Creating a student user...')
        role = Role.get_by_name('student')
        self.assertTrue(role is not None)
        user = User(username='******', role=role, password='******')
        db.session.add(user)
        db.session.commit()
        print('Successfully created student user.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')
        print('Creating a survey...')
        survey = Survey.query.filter_by(description='blah test').first()
        self.assertTrue(survey is not None)
        self.assertTrue(survey.status == 'open')
        print('Successfully created a survey.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')
        print('Creating answers for the survey...')
        a = Answer.create(survey_id=survey.id, owner_id=user.id)
        self.assertTrue(a is not None)
        self.assertTrue(a.survey_id == survey.id)
        self.assertTrue(a.owner_id == user.id)
        for question in survey.questions.all():
            ae = AnswerEntity.create(answer_id=a.id,
                                     question_id=question.id,
                                     answer_content='blah'
                                     )
            self.assertTrue(ae is not None)
            self.assertTrue(ae.question_id == question.id)
            self.assertTrue(ae.answer_id == a.id)
        print('Successfully created answers for the survey.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')

        # admin_close_survey
        print('Creating an administrator user...')
        user = User.query.filter_by(username='******').first()
        self.assertTrue(user is not None)
        print('Administrator user successfully created.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')
        print('Creating a survey...')
        survey = Survey.query.filter_by(description='blah test').first()
        self.assertTrue(survey is not None)
        print('Survey successfully created.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')
        print('Setting survey phase to closed...')
        survey.status = 'closed'
        db.session.add(survey)
        db.session.commit()
        self.assertTrue(survey.status == 'closed')
        print('Successfully set survey to closed.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')
        print('')