Exemple #1
0
    def on_get(self, req, resp, *args, **kwargs):
        super(ResourceCheckCorrectAnswer, self).on_get(req, resp, *args,
                                                       **kwargs)

        # Recivimos un JSON del usuario con 2 parámetros
        # "question" : EL texto de la pregunta
        # "answer" : la respuesta que el usuario ha dado a la pregunta

        aux_question = Question()
        aux_question.question = req.media["question"]

        # Filtraremos la pregunta para tener su id
        real_question = self.db_session.query(Question).filter \
            (aux_question.question == Question.question).one()

        aux_answer = Answer()
        aux_answer.answer = req.media["answer"]

        # Filtraremos la respuesta para tener su id
        real_answer = self.db_session.query(Answer).filter \
            (aux_answer.answer == Answer.answer).one()

        # Finalmente filtraremos en la Asociacion para comprovar si es correcta
        query = self.db_session.query(AnswerQuestionAssiation).filter\
            (real_question.id == AnswerQuestionAssiation.id_question,
             real_answer.id == AnswerQuestionAssiation.id_answer).one()

        print(query.is_correct)

        if query.is_correct:
            resp.media = "La Respuesta es Correcta"
        else:
            resp.media = "La Respuesta no es Correcta"

        resp.status = falcon.HTTP_200
def get_questions_from_db():
    engine = sqlalchemy.create_engine(DATABASE_URL_DOCKER)
    engine.connect()
    Session = sessionmaker(bind=engine)
    session = Session()
    is_exist = bool(session.query(Quiz) \
                    .filter(Quiz.name == 'First quiz') \
                    .first())
    print(is_exist)
    if is_exist is False:
        questions = get_questions_from_yml('data.yml')
        quiz = Quiz(name='First quiz')
        session.add(quiz)
        for question in questions:
            new_question = Question(name=question['name'], quiz=quiz)
            session.add(new_question)
            for answer in question['answers']:
                if 'is_correct' in answer:
                    new_answer = Answer(name=answer['name'],
                                        is_correct=answer['is_correct'],
                                        question=new_question)
                else:
                    new_answer = Answer(name=answer['name'],
                                        is_correct=False,
                                        question=new_question)
                session.add(new_answer)
        session.commit()

    questions = session.query(Question.name,
                              Question.id) \
        .filter(Question.quiz_id == 1) \
        .all()

    answers = session.query(Answer.name,
                            Answer.is_correct,
                            Answer.question_id) \
        .join(Question) \
        .filter(Question.quiz_id == 1) \
        .all()

    answers = [i._asdict() for i in answers]
    questions = [i._asdict() for i in questions]

    print(answers)
    print(len(answers))
    print(type(answers))

    print(questions)
    print(len(questions))
    print(type(questions))

    for question in questions:
        question['answers'] = []
        for answer in answers:
            if question['id'] == answer['question_id']:
                question['answers'].append(answer)

    print(questions)
    session.close()
    return questions
Exemple #3
0
 def setUp(self):
     self.app = create_app(TestingConfig)
     self.client = self.app.test_client
     # seed data
     self.role = Role('general')
     self.role.insert()
     self.user = User('Ahmed', 'Hamed', '*****@*****.**',
                      'ahmedhrayyan', 'secret', self.role.id)
     self.user.insert()
     self.question = Question(self.user.id, 'Is sal the best QA engine')
     self.question.insert()
     self.answer = Answer(self.user.id, self.question.id, 'Yes it is')
     self.answer.insert()
     self.token = gen_token(self.app.config['SECRET_KEY'], self.user)
Exemple #4
0
    def on_post(self, req, resp, *args, **kwargs):
        super(ResourceAddQuestion, self).on_get(req, resp, *args, **kwargs)

        q = Question()

        try:
            try:
                q.question = req.media["question"]
                category = req.media["category"]

                if category not in [
                        i.value for i in CategoryEnum.__members__.values()
                ]:
                    raise falcon.HTTPInvalidParam(
                        messages.event_status_invalid, "category")
                q.category = category
                answers = req.media["answers"]
                self.db_session.add(q)
                for answer in answers:
                    a = Answer()
                    a.answer = answer["answer"]
                    self.db_session.add(a)
                    self.db_session.commit()
                    s = AnswerQuestionAssiation()
                    s.id_question = q.id
                    s.id_answer = a.id

                    if answer["is_correct"]:
                        s.is_correct = True
                    else:
                        s.is_correct = False

                    self.db_session.add(s)
                    self.db_session.commit()

            except IntegrityError:
                raise falcon.HTTPBadRequest(description=messages.user_exists)

        except KeyError:
            raise falcon.HTTPBadRequest(
                description=messages.parameters_invalid)

        resp.status = falcon.HTTP_200
Exemple #5
0
def fill_db(op):
    session = Session(bind=op.get_bind())
    is_exist = bool(session.query(Quiz) \
                    .filter(Quiz.name == 'First quiz') \
                    .first())
    print(is_exist)
    if is_exist is False:
        questions = get_questions_from_yml('data.yml')
        quiz = Quiz(name='First quiz')
        session.add(quiz)
        for question in questions:
            new_question = Question(name=question['name'], quiz=quiz)
            session.add(new_question)
            for answer in question['answers']:
                if 'is_correct' in answer:
                    new_answer = Answer(name=answer['name'], is_correct=answer['is_correct'], question=new_question)
                else:
                    new_answer = Answer(name=answer['name'], is_correct=False, question=new_question)
                session.add(new_answer)
        session.commit()

    questions = session.query(Question.name,
                              Question.id) \
        .filter(Question.quiz_id == 1) \
        .all()

    answers = session.query(Answer.name,
                            Answer.is_correct,
                            Answer.question_id) \
        .join(Question) \
        .filter(Question.quiz_id == 1) \
        .all()

    answers = [i._asdict() for i in answers]
    questions = [i._asdict() for i in questions]

    for question in questions:
        question['answers'] = []
        for answer in answers:
            if question['id'] == answer['question_id']:
                question['answers'].append(answer)

    session.close()
Exemple #6
0
 def post_answer():
     data = request.get_json() or []
     if 'content' not in data:
         abort(400, 'content expected in request body')
     if 'question_id' not in data:
         abort(400, 'question_id expected in request body')
     question = Question.query.get(data['question_id'])
     if question == None:
         abort(404, 'question not found')
     # sanitize input
     content = bleach.clean(data['content'])
     # supporting markdown
     content = markdown(content)
     # retrive user_id using username (which is stored in the stack by requires_auth decorator)
     username = _request_ctx_stack.top.curr_user['sub']
     user_id = User.query.filter_by(username=username).with_entities(
         User.id).one().id
     new_answer = Answer(user_id, question.id, content)
     try:
         new_answer.insert()
     except Exception:
         abort(422)
     return jsonify({'success': True, 'data': new_answer.format()})
Exemple #7
0
def get_answers_and_agree(question_id, selector):
    try:
        answer_list = selector.xpath('//div[@class="aw-item"]')
        answers = []
        for a in answer_list:
            answer = Answer()
            answer.question_id = question_id
            answer.answer_id = a.xpath('@id')[0].split('_')[2]
            answer.answer_type = 1
            answer.people_id = a.xpath('a/@data-id')[0]
            task_filter('people', answer.people_id)
            answer.content = "".join(a.xpath('div/div/div[1]/div/text()'))
            post_time_str = a.xpath('div/div/div[2]/span/text()')[0]
            answer.post_time = str2datetime(post_time_str)
            answers.append(answer)
            answer_count_str = a.xpath('div/div/div[2]/a/text()')[0]
            answer_count = re.search('(\d+)', answer_count_str)
            if answer_count:
                app.send_task('tasks.question.do_answer_comment',
                              args=(answer.answer_id, ),
                              queue='answer_comment_queue',
                              routing_key='answer_comment')
            agrees = []
            agree_list = a.xpath('div/div/div[1]/p[2]/a/@data-id')
            for p in agree_list:
                task_filter('people', p)
                agree = Agree()
                agree.question_id = question_id
                agree.answer_id = answer.answer_id
                agree.people_id = p
                agrees.append(agree)
            CommonOper.add_all(agrees)
        CommonOper.add_all(answers)
    except Exception as e:
        jsl_log.warning(
            "get answer_list error,question_id:{},here are details {}".format(
                question_id, e))
Exemple #8
0
        line = fp.readline()
        cnt = 1
        q = None

        while line:
            l = line.split(":")
            if l[0] == "C":
                q = Question()
                q.category = str.strip(l[1])
            elif l[0] == "Q":
                q.question = str.strip(l[1])
            elif l[0] == "AF" or l[0] == "AT":
                q.owner_id = int(random.uniform(1, 20))
                db_session.add(q)
                db_session.commit()
                a = Answer()
                a.answer = str.strip(l[1])
                db_session.add(a)
                db_session.commit()

                s = AnswerQuestionAssiation()
                s.id_question = q.id
                s.id_answer = a.id
                if l[0] == "AT":
                    s.is_correct = True
                else:
                    s.is_correct = False
                db_session.add(s)
                db_session.commit()

            cnt += 1
Exemple #9
0
class SalTestCase(unittest.TestCase):
    def setUp(self):
        self.app = create_app(TestingConfig)
        self.client = self.app.test_client
        # seed data
        self.role = Role('general')
        self.role.insert()
        self.user = User('Ahmed', 'Hamed', '*****@*****.**',
                         'ahmedhrayyan', 'secret', self.role.id)
        self.user.insert()
        self.question = Question(self.user.id, 'Is sal the best QA engine')
        self.question.insert()
        self.answer = Answer(self.user.id, self.question.id, 'Yes it is')
        self.answer.insert()
        self.token = gen_token(self.app.config['SECRET_KEY'], self.user)

    def tearDown(self):
        db.drop_all()

    def test_422_upload(self):
        res = self.client().post('api/upload',
                                 headers={
                                     'Authorization': 'Bearer %s' % self.token
                                 },
                                 data={'file': (BytesIO(b'IMAGE DATA'), 'file.jpg')}) # fake data
        json_data = res.get_json()
        self.assertEqual(res.status_code, 422)
        self.assertFalse(json_data['success'])
        self.assertTrue(json_data['message'])

    def test_404_view_uploaded(self):
        res = self.client().get('/uploads/x')
        self.assertEqual(res.status_code, 404)

    def test_422_register(self):
        res = self.client().post('/api/register',
                                 json={
                                     'first_name': 'ahmed',
                                     'last_name': 'hamed',
                                     'email': '*****@*****.**',
                                     'username': self.user.username,  # username already exists
                                     'password': '******'
                                 })
        res_data = res.get_json()
        self.assertEqual(res.status_code, 422)
        self.assertFalse(res_data['success'])
        self.assertTrue(res_data['message'])

    def test_register(self):
        res = self.client().post('/api/register',
                                 json={
                                     'first_name': 'ahmed',
                                     'last_name': 'hamed',
                                     'email': '*****@*****.**',
                                     'username': '******',
                                     'password': '******'
                                 })
        res_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(res_data['success'])
        self.assertEqual(res_data['data']['username'], 'test')

    def test_patch_user(self):
        res = self.client().patch('/api/user',
                                  headers={
                                      'Authorization': 'Bearer %s' % self.token
                                  },
                                  json={
                                      'job': 'test',
                                  })
        res_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(res_data['success'])
        self.assertEqual(res_data['data']['job'], 'test')

    def test_422_login(self):
        res = self.client().post('/api/login',
                                 json={
                                     'username': '******',
                                     'password': '******'
                                 })
        res_data = res.get_json()
        self.assertEqual(res.status_code, 422)
        self.assertFalse(res_data['success'])
        self.assertTrue(res_data['message'])

    def test_login(self):
        res = self.client().post('/api/login',
                                 json={
                                     'username': '******',
                                     'password': '******'
                                 })
        res_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(res_data['success'])
        self.assertEqual(res_data['data']['username'], 'ahmedhrayyan')

    def test_get_notifications(self):
        res = self.client().get('/api/notifications',
                                headers={
                                    'Authorization': 'Bearer %s' % self.token
                                })
        res_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(res_data['success'])
        self.assertGreaterEqual(res_data['unread_count'], 0)

    def test_get_questions(self):
        res = self.client().get('/api/questions')
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])

    def test_404_show_question(self):
        res = self.client().get('/api/questions/232482')
        json_data = res.get_json()
        self.assertEqual(res.status_code, 404)
        self.assertFalse(json_data['success'])
        self.assertTrue(json_data['message'])

    def test_show_question(self):
        res = self.client().get('/api/questions/%i' % self.question.id)
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])
        self.assertEqual(self.question.id, json_data['data']['id'])

    def test_400_post_question(self):
        res = self.client().post('/api/questions',
                                 headers={
                                     'Authorization': 'Bearer %s' % self.token
                                 })
        json_data = res.get_json()
        self.assertEqual(res.status_code, 400)
        self.assertFalse(json_data['success'])
        self.assertTrue(json_data['message'])

    def test_post_question(self):
        content = 'Is this great or what'
        res = self.client().post('/api/questions',
                                 headers={
                                     'Authorization': 'Bearer %s' % self.token
                                 },
                                 json={
                                     'user_id': self.user.id,
                                     'content': content
                                 })
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])
        self.assertIn(content, json_data['data']['content'])

    def test_patch_question(self):
        res = self.client().patch('/api/questions/%i' % self.question.id,
                                  headers={
                                      'Authorization': 'Bearer %s' % self.token
                                  },
                                  json={
                                      'accepted_answer': self.answer.id
                                  })
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])
        self.assertEqual(self.answer.id, json_data['data']['accepted_answer'])

    def test_404_delete_question(self):
        res = self.client().delete('/api/questions/10000',
                                   headers={
                                       'Authorization': 'Bearer %s' % self.token
                                   },
                                   )
        json_data = res.get_json()
        self.assertEqual(res.status_code, 404)
        self.assertFalse(json_data['success'])
        self.assertTrue(json_data['message'])

    def test_delete_question(self):
        res = self.client().delete('/api/questions/%i' % self.question.id,
                                   headers={
                                       'Authorization': 'Bearer %s' % self.token
                                   },
                                   )
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])
        self.assertEqual(self.question.id, json_data['deleted_id'])

    def test_404_show_answer(self):
        res = self.client().get('/api/answers/10420')
        json_data = res.get_json()
        self.assertEqual(res.status_code, 404)
        self.assertFalse(json_data['success'])
        self.assertTrue(json_data['message'])

    def test_show_answer(self):
        res = self.client().get('/api/answers/%i' % self.answer.id)
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])
        self.assertEqual(self.answer.id, json_data['data']['id'])

    def test_400_post_answer(self):
        res = self.client().post('/api/answers',
                                 headers={
                                     'Authorization': 'Bearer %s' % self.token
                                 },
                                 content_type='application/json')
        json_data = res.get_json()
        self.assertEqual(res.status_code, 400)
        self.assertFalse(json_data['success'])
        self.assertTrue(json_data['message'])

    def test_post_answer(self):
        content = 'answer'
        res = self.client().post('/api/answers',
                                 headers={
                                     'Authorization': 'Bearer %s' % self.token
                                 },
                                 json={
                                     'user_id': self.user.id,
                                     'question_id': self.question.id,
                                     'content': content
                                 })
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])
        self.assertIn(content, json_data['data']['content'])

    def test_patch_answer(self):
        content = 'new answer'
        res = self.client().patch('/api/answers/%i' % self.answer.id,
                                  headers={
                                      'Authorization': 'Bearer %s' % self.token
                                  },
                                  json={
                                      'content': content
                                  })
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])
        self.assertIn(content, json_data['data']['content'])

    def test_404_delete_answer(self):
        res = self.client().delete('/api/answers/10000',
                                   headers={
                                       'Authorization': 'Bearer %s' % self.token
                                   },
                                   )
        json_data = res.get_json()
        self.assertEqual(res.status_code, 404)
        self.assertFalse(json_data['success'])
        self.assertTrue(json_data['message'])

    def test_delete_answer(self):
        res = self.client().delete('/api/answers/%i' % self.answer.id,
                                   headers={
                                       'Authorization': 'Bearer %s' % self.token
                                   },
                                   )
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])
        self.assertEqual(self.answer.id, json_data['deleted_id'])

    def test_404_show_user(self):
        res = self.client().get('/api/users/x')
        json_data = res.get_json()
        self.assertEqual(res.status_code, 404)
        self.assertFalse(json_data['success'])
        self.assertTrue(json_data['message'])

    def test_show_user(self):
        res = self.client().get('/api/users/%s' % self.user.username)
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])
        self.assertEqual(json_data['data']['username'], self.user.username)

    def test_404_get_user_questions(self):
        res = self.client().get('/api/users/x/questions')
        json_data = res.get_json()
        self.assertEqual(res.status_code, 404)
        self.assertFalse(json_data['success'])
        self.assertTrue(json_data['message'])

    def test_get_user_questions(self):
        res = self.client().get('/api/users/%s/questions' % self.user.username)
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])

    def test_report_question(self):
        res = self.client().post('/api/report/question',
                                 headers={
                                     'Authorization': 'Bearer %s' % self.token
                                 },
                                 json={
                                     'question_id': self.question.id
                                 })
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])

    def test_report_answer(self):
        res = self.client().post('/api/report/answer',
                                 headers={
                                     'Authorization': 'Bearer %s' % self.token
                                 },
                                 json={
                                     'answer_id': self.answer.id
                                 })
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])