Esempio n. 1
0
 def put(self, id, answer_id):
     '''Accept an answer and update an answer'''
     question = Question.get_by_id(id=id)
     logged_in_user = get_jwt_identity()
     answer_to_update = Answer.get_by_id(answer_id)
     print(answer_to_update)
     if question:
         if answer_to_update:
             if answer_to_update['user_id'] == logged_in_user:
                 parser = reqparse.RequestParser()
                 parser.add_argument('body',
                                     help='The body field cannot be blank',
                                     required=True, type=str)
                 parser.parse_args()
                 answer_to_update = Answer.update(id=answer_id,
                                                  body=request.json['body'],
                                                  user_id=get_jwt_identity(),
                                                  accept=False)
                 return {"message": "You have successfully updated the answer",
                         "data": answer_to_update}, 201
             if question['user']["id"] == logged_in_user and answer_to_update['question_id'] == question["id"]:
                 if Validate.check_answer_accepted(question_id=question["id"]):
                     return {"message": "The question has an already acceped answer"}, 405
                 Answer.accept(id=answer_id)
                 return {"message": "You have successfully accepted the answer"}, 201
             else:
                 return {"message": "You are not authorized to modify the answer"}, 401
         return {"message": "Answer not found"}, 404
     return {"message": "No question found with that answer"}, 404
Esempio n. 2
0
    def get(self, id):
        '''Get a question by id'''

        question = Question.get_by_id(id)

        if question == None:
            return {"status": "No question found with that id"}, 404

        return {"message": "Success", "data": question}, 200
Esempio n. 3
0
 def delete(self, id):
     '''Delete a question'''
     question_to_delete = Question.get_by_id(id)
     logged_in_user = get_jwt_identity()
     if question_to_delete:
         if question_to_delete['user']["id"] == logged_in_user:
             Question.delete_question(id)
             return {"message": "Successfully deleted"}, 200
         return {"message": "You are not authorized to delete this question"}, 401
     return {"message": "No question found"}, 404
Esempio n. 4
0
    def post(self, id):
        '''Post an answer to a question'''
        parser = reqparse.RequestParser()
        parser.add_argument('body', help='The body field cannot be blank',
                            required=True, type=str)
        data = parser.parse_args()
        if len(data['body']) < 15:
            return {'message': 'Ops!,the answer is too short,kindly provide an answer of more than 15 characters'}, 400
        question_to_answer = Question.get_by_id(id)
        if question_to_answer == None:
            return {'message': 'The question with that id was not found'}, 404
        answer = Answer.save(self, body=request.json['body'], question_id=id,
                             user_id=get_jwt_identity(),
                             date_created=datetime.now(),
                             date_modified=datetime.now(), accept=False)

        return {"message": "The answer was posted successfully",
                "data": answer}, 201
    def test_core_api_functionality(self):
        print('')
        print('Trying to create users...')
        # insert admin staff guest student and a course
        role_student = Role.get_by_name('student')
        self.assertTrue(role_student is not None)
        role_admin = Role.get_by_name('admin')
        self.assertTrue(role_admin is not None)
        role_staff = Role.get_by_name('staff')
        self.assertTrue(role_staff is not None)
        role_guest = Role.get_by_name('guest')
        self.assertTrue(role_guest is not None)
        print('Creating student...')
        student = User(username='******', role=role_student, password='******')
        self.assertTrue(student is not None)
        print('Student successfully created.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')
        print('Creating administrator...')
        admin = User(username='******', role=role_admin, password='******')
        self.assertTrue(admin is not None)
        print('Administrator successfully created.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')
        print('Creating staff member...')
        staff = User(username='******', role=role_staff, password='******')
        self.assertTrue(staff is not None)
        print('Staff member successfully created.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')
        print('Creating guest user...')
        guest = User(username='******', role=role_guest,
                     password='******', verified=True)
        self.assertTrue(guest is not None)
        print('Guest user successfully created.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')
        print('Assigning courses to users...')
        course = Course(course_code='COMP2511 17s2')
        db.session.add(course)
        db.session.commit()
        code = course.course_code
        admin.add_course(code)
        student.add_course(code)
        staff.add_course(code)
        guest.add_course(code)
        self.assertTrue(course is not None)
        print('Courses successfully assigned.')
        print('Users successfully created.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')

        print('Trying to login as an administrator...')
        # login admin and get token
        response = self.client.get(
            url_for('api.get_token'),
            headers=self.get_api_headers('admin', 'cat'),
            data=self.get_api_data('admin', 'cat')
        )

        self.assertTrue(response.status_code == 200)
        json_response = json.loads(response.data.decode('utf-8'))
        self.assertIsNotNone(json_response.get('token'))
        admin_token = json_response['token']
        print('Successfully logged in as an administrator.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')

        print('Trying to create a mandatory question as an administrator...')
        # admin create mandatory question
        response = self.client.get(
            url_for('api.create_question'),
            headers=self.get_api_headers('admin', 'cat'),
            data=json.dumps({
                'qType': 2,
                'title': 'test question',
                'optional': False
            })
        )

        q1 = Question.query.filter_by(description='test question').first()
        self.assertTrue(q1 is not None)
        print('Successfully created a mandatory question as an administrator.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')

        print('Trying to create an optional question as an administrator...')
        # admin create optional question
        response = self.client.get(
            url_for('api.create_question'),
            headers=self.get_api_headers('admin', 'cat'),
            data=json.dumps({
                'qType': 2,
                'title': 'test optional question',
                'optional': True
            })
        )
        q2 = Question.query.filter_by(
            description='test optional question').first()
        self.assertTrue(q2 is not None)
        print('Successfully created an optional question as an administrator.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')

        print('Trying to create a survey as an administrator...')
        # admin create survey
        response = self.client.post(
            url_for('api.create_survey'),
            headers=self.get_api_headers(admin_token, ''),
            data=json.dumps({
                'start': '2017-10-23T03:17:55.000Z',
                'end': '2017-11-29T03:17:55.000Z',
                'title': 'test',
                'course': 'COMP2511 17s2',
                'questions_opt': [{'id': q2.id}],
                'questions_man': [{'id': q1.id}],
            })
        )
        self.assertTrue(response.status_code == 200)
        json_response = json.loads(response.data.decode('utf-8'))
        self.assertTrue(json_response['success'] is True)
        survey = Survey.query.all()[0]
        self.assertTrue(survey is not None)
        self.assertTrue(survey.status == 'review')
        print('Successfully created a survey as an administrator.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')

        print('Trying to review a survey as a staff member...')
        # staff review survey
        # login staff and get token
        response = self.client.get(
            url_for('api.get_token'),
            headers=self.get_api_headers('staff', 'cat'),
            data=self.get_api_data('staff', 'cat')
        )
        self.assertTrue(response.status_code == 200)
        json_response = json.loads(response.data.decode('utf-8'))
        self.assertIsNotNone(json_response.get('token'))
        staff_token = json_response['token']

        # send modify survey request
        response = self.client.post(
            url_for('api.modify_survey'),
            headers=self.get_api_headers(staff_token, ''),
            data=json.dumps({
                'id': survey.id,
                'start': survey.start_date,
                'end': survey.end_date,
                'title': 'test',
                'purpose': 'review',
                'course': 'COMP2511 17s2',
                'status': 'open',
                'questions_opt': [],
                'questions_man': [],
            })
        )

        self.assertTrue(response.status_code == 200)
        json_response = json.loads(response.data.decode('utf-8'))
        self.assertTrue(json_response['success'] is True)
        survey = Survey.query.all()[0]
        self.assertTrue(survey is not None)
        self.assertTrue(survey.status == 'open')
        print('Successfully reviewed a survey as a staff member.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')

        print('Trying to answer a survey as a student...')
        # student answer survey
        # login student and get token
        response = self.client.get(
            url_for('api.get_token'),
            headers=self.get_api_headers('student', 'cat'),
            data=self.get_api_data('student', 'cat')
        )
        self.assertTrue(response.status_code == 200)
        json_response = json.loads(response.data.decode('utf-8'))
        self.assertIsNotNone(json_response.get('token'))
        student_token = json_response['token']

        # send answer survey form
        response = self.client.post(
            url_for('main.answer', hash_str=survey.id_hash) +
            '?token=' + student_token,
            headers=self.get_api_headers(student_token, ''),
            data=json.dumps({
                str(q1.id): 'q1',
                str(q1.id): 'q2'
            })
        )
        self.assertTrue(response.status_code == 302)
        self.assertTrue(Answer.query.all() is not None)
        self.assertTrue(b'thank' in response.data)
        print('Successfully answered a survey as a student.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')

        print('Trying to login as a guest...')
        response = self.client.get(
            url_for('api.get_token'),
            headers=self.get_api_headers('guest', 'cat'),
            data=self.get_api_data('guest', 'cat')
        )
        self.assertTrue(response.status_code == 200)
        json_response = json.loads(response.data.decode('utf-8'))
        self.assertIsNotNone(json_response.get('token'))
        guest_token = json_response['token']
        self.assertTrue(guest_token is not None)
        print('Successfully logged in as a guest.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')

        print('Trying to answer a survey as a guest...')
        response = self.client.post(
            url_for('main.answer', hash_str=survey.id_hash) +
            '?token=' + guest_token,
            headers=self.get_api_headers(student_token, ''),
            data=json.dumps({
                str(q1.id): 'q1',
                str(q1.id): 'q2'
            })
        )
        self.assertTrue(response.status_code == 302)
        self.assertTrue(Answer.query.all() is not None)
        self.assertTrue(b'thank' in response.data)
        print('Successfully answered survey as a guest.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')

        print('Trying to close a survey as an administrator...')
        # admin close the survey
        response = self.client.post(
            url_for('api.modify_survey'),
            headers=self.get_api_headers(admin_token, ''),
            data=json.dumps({
                'id': survey.id,
                'start': survey.start_date,
                'end': survey.end_date,
                'title': 'test',
                'purpose': 'update_status',
                'course': 'COMP2511 17s2',
                'status': 'closed',
                'questions_opt': [],
                'questions_man': [],
            })
        )

        survey = Survey.query.all()[0]
        self.assertTrue(response.status_code == 200)
        json_response = json.loads(response.data.decode('utf-8'))
        self.assertTrue(json_response['success'] is True)
        survey = Survey.query.all()[0]
        self.assertTrue(survey is not None)
        self.assertTrue(survey.status == 'closed')
        print('Successfully closed a survey as an administrator.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')

        print('Trying to answer a closed survey as a student...')
        # student answer after closed
        response = self.client.post(
            url_for('main.answer', hash_str=survey.id_hash) +
            '?token=' + student_token,
            headers=self.get_api_headers(student_token, '')
        )
        self.assertTrue(response.status_code == 302)
        self.assertTrue(b'not' in response.data)
        print('Student was shown the appropriate error message.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')

        print('Trying to generate a pie chart as a student...')
        # student get survey result
        response = self.client.post(
            url_for('api.fetch_pie_chart'),
            headers=self.get_api_headers(student_token, ''),
            data=json.dumps({
                'survey': survey.id,
                'question': q1.id
            })
        )
        self.assertTrue(response.status_code == 200)
        print('Successfully generated a pie chart as a student.')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')

        print('Trying to delete a question as an administrator...')
        # admin delete question
        response = self.client.get(
            url_for('api.delete_question'),
            headers=self.get_api_headers('admin', 'cat'),
            data=json.dumps({'id': q2.id})
        )
        q2 = Question.get_by_id(q2.id)
        self.assertTrue(q2.deleted is True)
        print('Successfully deleted a question as an administrator.')
        print('')
        print('\x1b[0;32;40m' + 'pass' + '\x1b[0m')