コード例 #1
0
    def setUp(self):
        self.app = create_app()
        self.client = self.app.test_client
        setup_db(self.app, 'trivia_test')

        db.drop_all()
        db.create_all()

        self.temp_categories = [
            Category('Science'),
            Category('Art'),
            Category('Geography'),
            Category('History'),
            Category('Entertainment'),
            Category('Sports')
        ]

        self.temp_questions = [
            Question('Whose autobiography is entitled \'I Know Why the Caged Bird Sings\'?', 'Maya Angelou', 2, 4),
            Question('What boxer\'s original name is Cassius Clay?', 'Muhammad Ali', 1, 4),
            Question('The Taj Mahal is located in which Indian city?', 'Agra', 2, 3),
            Question('Which Dutch graphic artist–initials M C was a creator of optical illusions?', 'Escher', 1, 2),
            Question('What is the heaviest organ in the human body?', 'The Liver', 4, 1)
        ]

        db.session.add_all(self.temp_categories)
        db.session.add_all(self.temp_questions)
        db.session.commit()
コード例 #2
0
ファイル: views.py プロジェクト: DustinFischer/udacity-fsnd
def create_question():
    data = request.get_json()

    fields = {
        'question': data.get('question') or None,  # Force none if empty string
        'answer': data.get('answer') or None,  # Force none if empty string
        'difficulty': data.get('difficulty', None),
        'category': data.get('category', None),
    }

    # Check required fields are populated
    validate_required_fields(fields)

    # Validate specific fields
    errors = []
    if fields['difficulty'] <= 0 or fields['difficulty'] > 5:
        errors.append(
            {'difficulty': 'Difficulty must be an integer between 1 and 5'})

    category = Category.query.get(int(fields['category']))
    if not category:
        errors.append({'category': 'Category is not supported'})

    if errors:
        abort(400, errors)

    # Create the question
    try:
        with db_session():
            question = Question(**fields)
            question.insert()
            return jsonify(question.format())
            # TODO: Test side effect return 422
    except:
        abort(422)
コード例 #3
0
 def add_questions():
     resposta = request.get_json()
     print(resposta)
     cat = int(resposta['category'])
     print(cat)
     question = Question(question=resposta['question'],
                         answer=resposta['answer'],
                         category=cat + 1,
                         difficulty=resposta['difficulty'])
     Question.insert(question)
     return jsonify({'success': True})
コード例 #4
0
ファイル: __init__.py プロジェクト: Onyimatics/trivia
    def create_question():
        try:
            body = request.get_json()
            search_term = body.get('search', None)

            if body == {}:
                abort(422)

            # question search
            if search_term is not None:
                search = "{}".format(search_term.lower())

                search_results = Question.query.filter(
                    Question.question.ilike('%' + search + '%')).all()

                formatted_search_results = [
                    question.format for question in search_results
                ]
                paginated_results = paginate_questions(request, search_results)

                return jsonify({
                    'success': True,
                    'questions': paginated_results,
                    'total_questions': len(search_results)
                })
            # question add
            else:
                question = body.get('question', None)
                answer = body.get('answer', None)
                category = body.get('category', None)
                difficulty = body.get('difficulty', None)

                if question is None or answer is None or category is None or difficulty is None:
                    abort(422)

                new_question = Question(question=question,
                                        answer=answer,
                                        category=category,
                                        difficulty=difficulty)
                new_question.insert()

                selection = Question.query.order_by('id').all()
                paged_questions = paginate_questions(request, selection)

                return jsonify({
                    'success': True,
                    'created': new_question.id,
                    'questions': paged_questions,
                    'total_questions': len(selection)
                }), 201

        except ():
            abort(422)
コード例 #5
0
    def test_delete_question_by_id(self):
        question = Question(question='How long is a mile in kilometers?',
                            answer='Answer',
                            category='Math',
                            difficulty=5)
        question.insert()

        res = self.client().delete(f'/questions/{question.id}')

        assert res.status_code == 200
        data = json.loads(res.data)
        assert data == {'success': True, 'deleted': question.id}
コード例 #6
0
def create_questions(db, count=12):
    some_category = Category(type='Some Category')
    some_category.insert()

    questions = []
    for index in range(count):
        question = Question(question=f'The question? {index}',
                            answer='The answer',
                            category=some_category.id,
                            difficulty=5)
        question.insert()
        questions.append(question)
    return questions, some_category
コード例 #7
0
    def test_delete_question(self):
        question = Question(question='new question',
                            answer='new answer',
                            difficulty=1,
                            category=1)
        question.insert()
        record_id = question.id
        res = self.client().delete(f'/questions/{record_id}/')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertEqual(data['deleted'], record_id)
コード例 #8
0
    def setUp(self):
        super().setUp()

        # Add some categories
        self.science = Category('Science')
        self.geography = Category('Geography')
        db.session.add(self.science)
        db.session.add(self.geography)
        db.session.commit()

        # Add some questions
        self.science_question = Question('What is science?', 'Nobody knows', self.science.id, 5)
        self.geog_question = Question('Is geography real?', 'Probably not', self.geography.id, 5)
        self.science_question.insert()
        self.geog_question.insert()
コード例 #9
0
ファイル: test_flaskr.py プロジェクト: richien/trivia_api
    def test_get_quiz_question_with_previous_questions(self):
        # add an additional question so that there is
        # more than one question in the database
        with self.app.app_context():
            category = Category.query.first()
            new_question = Question(question='Where is England?',
                                    answer='In Europe',
                                    category=category.id,
                                    difficulty=1)
            self.db.session.add(new_question)
            self.db.session.commit()
        question = Question.query.first()
        response = self.client().post('/api/v1/quizzes',
                                      content_type='application/json',
                                      data=json.dumps({
                                          'previous_questions': [question.id],
                                          'quiz_category': {
                                              'id': 0,
                                              'type': 'all'
                                          }
                                      }))

        data = json.loads(response.data)

        self.assertEqual(response.status_code, 200)
        self.assertTrue(data['success'])
        self.assertTrue(data['question'])
        self.assertTrue(data['question']['id'] != question.id)
コード例 #10
0
ファイル: test_flaskr.py プロジェクト: richien/trivia_api
    def setUp(self):
        """Define test variables and initialize app."""
        self.app = create_app()
        self.client = self.app.test_client
        self.database_name = os.getenv('TEST_DATABASE_NAME')
        self.database_user = os.getenv('DATABASE_USER')
        self.database_password = os.getenv('DATABASE_PASSWORD')
        self.database_path = "postgresql://{}:{}@{}/{}".format(
            self.database_user, self.database_password, 'localhost:5432',
            self.database_name)
        setup_db(self.app, self.database_path)

        # binds the app to the current context
        with self.app.app_context():
            self.db = SQLAlchemy()
            self.db.init_app(self.app)
            # create all tables
            self.db.create_all()
            # add a question to a category in the test database
            self.category = Category(type='Asia')
            self.db.session.add(self.category)
            self.db.session.flush()
            self.question = Question(question='Where is China?',
                                     answer='In Asia',
                                     category=self.category.id,
                                     difficulty=2)
            self.db.session.add(self.question)
            self.db.session.commit()
def post_new_question():
    body = request.get_json()
    if not body:
        # posting an envalid json should return a 400 error.
        abort(400)
    if (body.get('question') and body.get('answer') and body.get('difficulty')
            and body.get('category')):
        # posted a new question
        new_question = body.get('question')
        new_answer = body.get('answer')
        new_category = body.get('category')
        new_difficulty = body.get('difficulty')
        # insure that difficulty is only from 1 to 5
        if not 1 <= int(new_difficulty) < 6:
            abort(400)
        try:
            # insert the new question to the database
            question = Question(new_question, new_answer, new_category,
                                new_difficulty)
            question.insert()
            # query the database for all questions
            page = request.args.get('page', 1, type=int)
            selection = Question.query.order_by(Question.id).paginate(
                page, current_app.config['QUESTIONS_PER_PAGE'], True)
            total_questions = selection.total
            if total_questions == 0:
                # no questions were found, return a 404 error.
                abort(404)
            current_questions = [
                question.format() for question in selection.items
            ]
            return jsonify({
                'success': True,
                'id': question.id,
                'question': question.question,
                'questions': current_questions,
                'total_questions': total_questions
            })
        except:
            # creating the question failed, rollback and close the connection
            db.session.rollback()
            abort(422)
    else:
        # anything else posted in the body should return a 400 error
        abort(400)
コード例 #12
0
def create_question():
    body = request.get_json()

    # if the body containts a search term execute the search function
    # otherwise continue with creating a new question
    search_term = body.get("searchTerm")
    if search_term:
        return search_questions(search_term)

    else:
        for key in ["question", "answer", "category", "difficulty"]:
            if body.get(key) is None:
                abort(422)

        new_question = body.get("question", None)
        answer = body.get("answer", None)
        category = body.get("category", None)
        difficulty = body.get("difficulty", None)

        try:
            question = Question(
                question=new_question,
                answer=answer,
                category=category,
                difficulty=difficulty,
            )
            question.insert()

            questions = Question.query.order_by(Question.id).all()
            current_questions = paginate_questions(request, questions)

            return jsonify({
                "success": True,
                "created": question.id,
                "questions": current_questions,
                "total_questions": len(questions),
            })

        except:
            abort(422)
コード例 #13
0
ファイル: routes.py プロジェクト: Osama-Is/Trivia-API
    def create_question():
        try:
            data = request.get_json() if request.is_json else None

            if data is None or len(data) == 0:
                abort(400)
            ''' 
                verify that data does contain (question and answer, category, and difficulty),
                as well as no additional key/value data that is not required,
                and finally verify that data has not empty strings.
                
                Note: I executed it this way so
                 it can dynamically verify needed data from user if i added extra column to Question Model.
                 all i should do when adding a new column to Question is to represent this coulumn as
                 name:type pair in required_question_args
            '''
            required_question_args = {
                'question': str,
                'answer': str,
                'difficulty': int,
                'category': str
            }
            for k in data:
                if len(data) != len(required_question_args) \
                        or k not in required_question_args \
                        or type(data[k]) is not required_question_args[k] \
                        or isinstance(data[k], str) and len(data[k]) == 0:
                    abort(400)

            new_question = Question(**data)
            new_question.insert()

            return jsonify({'success': True, 'created': new_question.id})

        except BadRequest:
            abort(400)
        except:
            abort(500)
コード例 #14
0
    def test_question_list(self):
        """Test that hitting the question list GET endpoint returns a list of question(s), as well as categories"""
        third_question = Question('Why is science?', 'Only Bill Nye knows', self.science.id, 5)
        third_question.insert()

        # Test list with pagination only returns 2 result
        resp = self.client.get('/api/questions')
        assert resp.status_code == 200

        data = json.loads(resp.data)
        assert 'categories' in data
        assert 'questions' in data
        assert 'total_questions' in data

        assert data == {
            'categories': {
                '1': 'Science',
                '2': 'Geography'
            },
            'questions': [
                {
                    'answer': 'Nobody knows',
                    'category': 1,
                    'difficulty': 5,
                    'id': 1,
                    'question': 'What is science?'
                },
                {
                    'answer': 'Probably not',
                    'category': 2,
                    'difficulty': 5,
                    'id': 2, 'question':
                    'Is geography real?'
                }
            ],
            'total_questions': 3
        }
コード例 #15
0
def add_question():
    """
    Adds a question
    :return: Id of the question that has been created
    """
    body = request.get_json()

    if ('question' not in body) or ('answer' not in body) or \
            ('difficulty' not in body) or ('category' not in body):
        abort(422)

    try:
        question = Question(question=body.get('question'),
                            answer=body.get('answer'),
                            difficulty=body.get('difficulty'),
                            category=body.get('category'),
                            )
        question.insert()
        return jsonify({
            'success': True,
            'created': question.id,
        })
    except:
        abort(422)
コード例 #16
0
    def test_questions_search(self):
        question1 = Question(question='How long is a mile in kilometers?',
                             answer='Answer',
                             category='Math',
                             difficulty=5)
        question1.insert()
        question2 = Question(question='How many centimeters is an inch?',
                             answer='Answer',
                             category='Math',
                             difficulty=5)
        question2.insert()

        search_term = 'kilometers'
        res = self.client().post('/questions/search',
                                 json={'searchTerm': search_term})

        assert res.status_code == 200
        data = json.loads(res.data)
        assert len(data['questions']) == 1
        assert data == {
            'questions': [question1.format()],
            'total_questions': 1
        }
コード例 #17
0
    def test_delete_a_question_happypath(self):
        """
        2. Create an endpoint to DELETE question using a question ID.

        ./src/components/QuestionView.js:108:          url: `/questions/${id}`
        """
        self.assertEqual(db.session.query(Question).count(), 19)
        category_id = 5  # entertainment
        new_q = Question(question="test question",
                         answer="answer",
                         category=str(category_id),
                         difficulty=1)
        db.session.add(new_q)
        db.session.commit()
        self.assertEqual(db.session.query(Question).count(), 20)

        response = self.client.delete('/questions/{id}'.format(id=new_q.id))
        self.assertEqual(response.status_code, 204)
        self.assertEqual(db.session.query(Question).count(), 19)
コード例 #18
0
 def delete_questions(id):
     question = Question.query.get(id)
     Question.delete(question)
     return jsonify({'success': True})
コード例 #19
0
class TriviaApiTestCase(BaseTestClass):

    def setUp(self):
        super().setUp()

        # Add some categories
        self.science = Category('Science')
        self.geography = Category('Geography')
        db.session.add(self.science)
        db.session.add(self.geography)
        db.session.commit()

        # Add some questions
        self.science_question = Question('What is science?', 'Nobody knows', self.science.id, 5)
        self.geog_question = Question('Is geography real?', 'Probably not', self.geography.id, 5)
        self.science_question.insert()
        self.geog_question.insert()

    def test_question_list(self):
        """Test that hitting the question list GET endpoint returns a list of question(s), as well as categories"""
        third_question = Question('Why is science?', 'Only Bill Nye knows', self.science.id, 5)
        third_question.insert()

        # Test list with pagination only returns 2 result
        resp = self.client.get('/api/questions')
        assert resp.status_code == 200

        data = json.loads(resp.data)
        assert 'categories' in data
        assert 'questions' in data
        assert 'total_questions' in data

        assert data == {
            'categories': {
                '1': 'Science',
                '2': 'Geography'
            },
            'questions': [
                {
                    'answer': 'Nobody knows',
                    'category': 1,
                    'difficulty': 5,
                    'id': 1,
                    'question': 'What is science?'
                },
                {
                    'answer': 'Probably not',
                    'category': 2,
                    'difficulty': 5,
                    'id': 2, 'question':
                    'Is geography real?'
                }
            ],
            'total_questions': 3
        }

    def test_question_by_category_404(self):
        """Test that a 404 is returned when a category id is not found"""
        resp = self.client.get(f'/api/categories/5000/questions')
        assert resp.status_code == 404

        assert json.loads(resp.data) == {
            'error': '404: Not Found',
            'message': 'Category matching the provided ID was not found'
        }

    def test_question_by_category(self):
        """
        Test that only questions for a given category will be returned when hitting the GET category questions endpoint.
        """
        assert Category.query.count() == 2
        cat = self.science
        resp = self.client.get(f'/api/categories/{cat.id}/questions')
        assert resp.status_code == 200

        data = json.loads(resp.data)

        assert 'current_category' in data
        assert data['current_category'] == cat.id

        assert 'questions' in data
        assert data['questions'][0]['category'] == cat.id

        # Check response shape
        assert data == {
            'current_category': 1,
            'questions': [
                {
                    'answer': 'Nobody knows',
                    'category': 1,
                    'difficulty': 5,
                    'id': 1,
                    'question': 'What is science?'
                }
            ],
            'total_questions': 1
        }

    def test_category_list(self):
        """Test that hitting the categories list GET endpoint returns a dictionary of supported categories"""
        resp = self.client.get('/api/categories')
        assert resp.status_code == 200

        data = json.loads(resp.data)
        assert data == {
            'categories': {
                '1': 'Science',
                '2': 'Geography'
            }
        }

    def test_create_question_fields(self):
        """Test field validations on question create POST endpoint"""
        url = '/api/questions'

        # Test missing fields
        data = {}
        resp = self.client.post(url, json=data)
        assert resp.status_code == 400
        assert json.loads(resp.data) == {
            'error': '400: Bad Request',
            'message': [
                {'question': 'Field is required'},
                {'answer': 'Field is required'},
                {'difficulty': 'Field is required'},
                {'category': 'Field is required'}
            ]
        }

        data = {
            'question': 'Why is science?',
            'answer': 'Only Bill Nye knows',
            'category': 5000,
            'difficulty': 0
        }

        # Test difficulty and cateory validation
        resp = self.client.post(url, json=data)
        assert resp.status_code == 400
        assert json.loads(resp.data) == {
            'error': '400: Bad Request',
            'message': [
                {'difficulty': 'Difficulty must be an integer between 1 and 5'},
                {'category': 'Category is not supported'}
            ]
        }

    @patch('flaskr.api.views.Question.insert')
    def test_create_question_422(self, mock_insert):
        """Test that a 422 error is returned when there is an error raised while processing question creation"""
        # Force raise an exeception while creating question in DB
        mock_insert.side_effect = Exception

        assert Question.query.count() == 2

        data = {
            'question': 'Why is science?',
            'answer': 'Only Bill Nye knows',
            'category': self.science.id,
            'difficulty': 3
        }

        resp = self.client.post('/api/questions', json=data)
        assert resp.status_code == 422
        assert json.loads(resp.data) == {
            'error': '422: Unprocessable Entity',
            'message': 'The request was well-formed but was unable to be followed due to semantic errors.'
        }

        # Ensure changes dont persist
        assert Question.query.count() == 2

    def test_create(self):
        """Test successful creation of a question"""
        assert Question.query.count() == 2

        data = {
            'question': 'Why is science?',
            'answer': 'Only Bill Nye knows',
            'category': self.science.id,
            'difficulty': 3
        }
        resp = self.client.post('/api/questions', json=data)
        assert resp.status_code == 200
        resp_data = json.loads(resp.data)
        assert resp_data == {
            'answer': 'Only Bill Nye knows',
            'category': 1,
            'difficulty': 3,
            'id': 3,
            'question': 'Why is science?'
        }

        # Ensure changes persist in DB
        assert Question.query.count() == 3
        question = Question.query.get(resp_data['id'])
        assert question is not None
        assert question.format() == resp_data

    def test_delete_question_404(self):
        """Test the trying to delete a non-existent question id returns a 404"""
        resp = self.client.delete('/api/questions/5000')
        assert resp.status_code == 404
        assert json.loads(resp.data) == {
            'error': '404: Not Found',
            'message': 'Question matching the provided ID was not found for delete'
        }

    @patch('flaskr.api.views.Question.delete')
    def test_delete_question_500(self, mock_delete):
        """Test that a 500 error is returned when there is an error raised while processing question deletion"""
        # Force raise an exeception while deleting question in DB
        mock_delete.side_effect = Exception

        assert Question.query.count() == 2

        resp = self.client.delete(f'/api/questions/{self.geog_question.id}')
        assert resp.status_code == 500
        assert json.loads(resp.data) == {
            'error': '500: Internal Server Error',
            'message': 'The server encountered an internal error and was unable to complete your request. '
                       'Either the server is overloaded or there is an error in the application.'
        }

        # Ensure delete does not persist in DB
        assert Question.query.count() == 2

    def test_delete_question(self):
        """Test question deletion response and persists in the database"""
        assert Question.query.count() == 2

        resp = self.client.delete(f'/api/questions/{self.geog_question.id}')
        assert resp.status_code == 204

        # Ensure changes persist in DB
        assert Question.query.count() == 1
        assert Question.query.get(self.geog_question.id) is None

    def test_search(self):
        """
        Test that question search can search by:
            - partial category match
            - partial question match
            - partial answer match
            - Specify a category search under
        """
        url = '/api/questions/search'

        search = {
            'searchTerm': 'sci'
        }

        # test category contains
        resp = self.client.post(url, json=search)
        assert resp.status_code == 200
        assert json.loads(resp.data) == {
            'questions': [
                {'answer': 'Nobody knows', 'category': 1, 'difficulty': 5, 'id': 1, 'question': 'What is science?'}
            ],
            'total_questions': 1
        }

        # Test question contains
        search['searchTerm'] = 'what is'
        resp = self.client.post(url, json=search)
        assert resp.status_code == 200
        assert json.loads(resp.data) == {
            'questions': [
                {'answer': 'Nobody knows', 'category': 1, 'difficulty': 5, 'id': 1, 'question': 'What is science?'}
            ],
            'total_questions': 1
        }

        # Test answer contains
        search['searchTerm'] = 'nobody'
        resp = self.client.post(url, json=search)
        assert resp.status_code == 200

        assert json.loads(resp.data) == {
            'questions': [
                {'answer': 'Nobody knows', 'category': 1, 'difficulty': 5, 'id': 1, 'question': 'What is science?'}
            ],
            'total_questions': 1
        }

        # test within category
        new_question = Question('Why is science?', 'Only Bill Nye knows', self.science.id, 5)
        new_question.insert()
        search['categoryId'] = self.science.id
        search['searchTerm'] = 'knows'

        resp = self.client.post(url, json=search)
        assert resp.status_code == 200
        assert json.loads(resp.data) == {
            'questions': [
                {'answer': 'Nobody knows', 'category': 1, 'difficulty': 5, 'id': 1, 'question': 'What is science?'},
                {'answer': 'Only Bill Nye knows', 'category': 1, 'difficulty': 5, 'id': 3, 'question': 'Why is science?'}
            ],
            'total_questions': 2
        }

    def test_quiz_question_categorized(self):
        """Test get random quiz question from specific category"""
        url = '/api/quizzes'
        previous_questions = []

        data = {
            'previous_questions': previous_questions,
            'quiz_category': self.science.id
        }

        # There is only 1 possible question in the science category
        resp = self.client.post(url, json=data)
        assert resp.status_code == 200
        resp_data = json.loads(resp.data)

        assert resp_data == {
            'question': {
                'answer': 'Nobody knows',
                'category': 1,
                'difficulty': 5,
                'id': 1,
                'question': 'What is science?'
            }
        }

        # Get depleted  questions
        previous_questions.append(resp_data['question']['id'])
        data['previous_questions'] = previous_questions

        resp = self.client.post(url, json=data)
        assert resp.status_code == 200

        resp_data = json.loads(resp.data)
        assert resp_data['question'] is None

    def test_quiz_question_uncategorized(self):
        """Test get random quiz question from any category"""
        url = '/api/quizzes'
        previous_questions = []
        data = {'previous_questions': previous_questions}

        resp = self.client.post(url, json=data)
        assert resp.status_code == 200
        resp_data = json.loads(resp.data)

        # Check response for question that was returned
        assert 'question' in resp_data
        assert 'id' in resp_data['question']
        question1 = Question.query.get(resp_data['question']['id'])
        assert question1 is not None
        assert resp_data['question'] == question1.format()

        # Get next question
        previous_questions.append(question1.id)
        data['previous_questions'] = previous_questions

        resp = self.client.post(url, json=data)
        assert resp.status_code == 200

        resp_data = json.loads(resp.data)
        question2 = Question.query.get(resp_data['question']['id'])
        assert question2 is not None
        assert question2.id not in previous_questions

        # Get depleted questions
        previous_questions.append(question2.id)
        data['previous_questions'] = previous_questions

        resp = self.client.post(url, json=data)
        assert resp.status_code == 200

        resp_data = json.loads(resp.data)
        assert resp_data['question'] is None
コード例 #20
0
    def test_search(self):
        """
        Test that question search can search by:
            - partial category match
            - partial question match
            - partial answer match
            - Specify a category search under
        """
        url = '/api/questions/search'

        search = {
            'searchTerm': 'sci'
        }

        # test category contains
        resp = self.client.post(url, json=search)
        assert resp.status_code == 200
        assert json.loads(resp.data) == {
            'questions': [
                {'answer': 'Nobody knows', 'category': 1, 'difficulty': 5, 'id': 1, 'question': 'What is science?'}
            ],
            'total_questions': 1
        }

        # Test question contains
        search['searchTerm'] = 'what is'
        resp = self.client.post(url, json=search)
        assert resp.status_code == 200
        assert json.loads(resp.data) == {
            'questions': [
                {'answer': 'Nobody knows', 'category': 1, 'difficulty': 5, 'id': 1, 'question': 'What is science?'}
            ],
            'total_questions': 1
        }

        # Test answer contains
        search['searchTerm'] = 'nobody'
        resp = self.client.post(url, json=search)
        assert resp.status_code == 200

        assert json.loads(resp.data) == {
            'questions': [
                {'answer': 'Nobody knows', 'category': 1, 'difficulty': 5, 'id': 1, 'question': 'What is science?'}
            ],
            'total_questions': 1
        }

        # test within category
        new_question = Question('Why is science?', 'Only Bill Nye knows', self.science.id, 5)
        new_question.insert()
        search['categoryId'] = self.science.id
        search['searchTerm'] = 'knows'

        resp = self.client.post(url, json=search)
        assert resp.status_code == 200
        assert json.loads(resp.data) == {
            'questions': [
                {'answer': 'Nobody knows', 'category': 1, 'difficulty': 5, 'id': 1, 'question': 'What is science?'},
                {'answer': 'Only Bill Nye knows', 'category': 1, 'difficulty': 5, 'id': 3, 'question': 'Why is science?'}
            ],
            'total_questions': 2
        }
コード例 #21
0
    def post(self):
        errors = []
        good_data = True

        data = json.loads(request.data)

        if data['question'] is None or data['question'].__class__ != str or len(
                data['question'].strip()) < 1:
            good_data = False
            errors.append('Question text cannot be blank, or was not a string')

        if data['answer'] is None or data['answer'].__class__ != str or len(
                data['answer'].strip()) < 1:
            good_data = False
            errors.append('Answer text cannot be blank, or was not a string')

        try:
            if data['difficulty'] is None or data[
                    'difficulty'].__class__ != str or int(
                        data['difficulty']) < 1 or int(data['difficulty']) > 5:
                good_data = False
                errors.append(
                    'Difficulty integer cannot be blank, and must be an integer between 1 and 5'
                )
        except:
            good_data = False
            errors.append(
                'Difficulty integer cannot be blank, and must be an integer between 1 and 5'
            )

        try:
            if data['category'] is None or data[
                    'category'].__class__ != str or db.session.query(
                        Category).filter_by(
                            id=int(data['category'])).one_or_none() is None:
                good_data = False
                errors.append(
                    'Category integer cannot be blank, or is set to an invalid category'
                )
        except:
            good_data = False
            errors.append(
                'Category integer cannot be blank, or is set to an invalid category'
            )

        if good_data:
            q = Question(question=bleach.clean(data['question']),
                         answer=bleach.clean(data['answer']),
                         difficulty=bleach.clean(data['difficulty']),
                         category=bleach.clean(data['category']))
            q.insert()
            payload = {
                'message': 'New question successfully added',
                'question': q.format()
            }
            return payload, 201

        return {
            'success': False,
            'error': 400,
            'message': 'New question was not added, check errors for reasons',
            'errors': errors
        }, 400
コード例 #22
0
def seed_data(db):
    cat_1 = Category(id=1, type='Science')
    db.session.add(cat_1)
    cat_2 = Category(id=2, type='Art')
    db.session.add(cat_2)
    cat_3 = Category(id=3, type='Geography')
    db.session.add(cat_3)
    cat_4 = Category(id=4, type='History')
    db.session.add(cat_4)
    cat_5 = Category(id=5, type='Entertainment')
    db.session.add(cat_5)
    cat_6 = Category(id=6, type='Sports')
    db.session.add(cat_6)
    db.session.execute(
        "SELECT pg_catalog.setval('public.categories_id_seq', 6, true);")
    db.session.commit()

    q_2 = Question(
        id=2,
        question=
        "What movie earned Tom Hanks his third straight Oscar nomination, in 1996?",
        answer="Apollo 13",
        difficulty=4,
        category=5)
    db.session.add(q_2)
    q_4 = Question(
        id=4,
        question=
        "What actor did author Anne Rice first denounce, then praise in the role of her beloved Lestat?",
        answer="Tom Cruise",
        difficulty=4,
        category=5)
    db.session.add(q_4)
    q_5 = Question(
        id=5,
        question=
        "Whose autobiography is entitled 'I Know Why the Caged Bird Sings'?",
        answer="Maya Angelou",
        difficulty=2,
        category=4)
    db.session.add(q_5)
    q_6 = Question(
        id=6,
        question=
        "What was the title of the 1990 fantasy directed by Tim Burton about a young man with multi-bladed appendages?",
        answer="Edward Scissorhands",
        difficulty=3,
        category=5)
    db.session.add(q_6)
    q_9 = Question(id=9,
                   question="What boxer's original name is Cassius Clay?",
                   answer="Muhammad Ali",
                   difficulty=1,
                   category=4)
    db.session.add(q_9)
    q_10 = Question(
        id=10,
        question=
        "Which is the only team to play in every soccer World Cup tournament?",
        answer="Brazil",
        difficulty=3,
        category=6)
    db.session.add(q_10)
    q_11 = Question(
        id=11,
        question="Which country won the first ever soccer World Cup in 1930?",
        answer="Uruguay",
        difficulty=4,
        category=6)
    db.session.add(q_11)
    q_12 = Question(id=12,
                    question="Who invented Peanut Butter?",
                    answer="George Washington Carver",
                    difficulty=2,
                    category=4)
    db.session.add(q_12)
    q_13 = Question(id=13,
                    question="What is the largest lake in Africa?",
                    answer="Lake Victoria",
                    difficulty=2,
                    category=3)
    db.session.add(q_13)
    q_14 = Question(
        id=14,
        question="In which royal palace would you find the Hall of Mirrors?",
        answer="The Palace of Versailles",
        difficulty=3,
        category=3)
    db.session.add(q_14)
    q_15 = Question(id=15,
                    question="The Taj Mahal is located in which Indian city?",
                    answer="Agra",
                    difficulty=2,
                    category=3)
    db.session.add(q_15)
    q_16 = Question(
        id=16,
        question=
        "Which Dutch graphic artist–initials M C was a creator of optical illusions?",
        answer="Escher",
        difficulty=1,
        category=2)
    db.session.add(q_16)
    q_17 = Question(id=17,
                    question="La Giaconda is better known as what?",
                    answer="Mona Lisa",
                    difficulty=3,
                    category=2)
    db.session.add(q_17)
    q_18 = Question(
        id=18,
        question="How many paintings did Van Gogh sell in his lifetime?",
        answer="One",
        difficulty=4,
        category=2)
    db.session.add(q_18)
    q_19 = Question(
        id=19,
        question=
        "Which American artist was a pioneer of Abstract Expressionism, and a leading exponent of action painting?",
        answer="Jackson Pollock",
        difficulty=2,
        category=2)
    db.session.add(q_19)
    q_20 = Question(id=20,
                    question="What is the heaviest organ in the human body?",
                    answer="The Liver",
                    difficulty=4,
                    category=1)
    db.session.add(q_20)
    q_21 = Question(id=21,
                    question="Who discovered penicillin?",
                    answer="Alexander Fleming",
                    difficulty=3,
                    category=1)
    db.session.add(q_21)
    q_22 = Question(
        id=22,
        question=
        "Hematology is a branch of medicine involving the study of what?",
        answer="Blood",
        difficulty=4,
        category=1)
    db.session.add(q_22)
    q_23 = Question(
        id=23,
        question="Which dung beetle was worshipped by the ancient Egyptians?",
        answer="Scarab",
        difficulty=4,
        category=4)
    db.session.add(q_23)
    db.session.execute(
        "SELECT pg_catalog.setval('public.questions_id_seq', 23, true);")

    db.session.commit()