def create_question(): data = request.get_json() question = data.get('question', '') answer = data.get('answer', '') difficulty = data.get('difficulty', 1) category = data.get('category', None) if category is None: abort(400) try: if len(question) < 1 or len(answer) < 1: abort(400) category = Category.query.filter( Category.id == category).one_or_none() if category is None: abort(404) difficulty = int(difficulty) if difficulty < 1 or difficulty > 5: abort(400) question = Question(question=question, answer=answer, difficulty=difficulty, category=category.id) question.insert() return jsonify({'success': True, 'created': question.id}), 201 except Exception as e: if e.code == 400: abort(400) if e.code == 404: abort(404) abort(422)
def add_question(): body = request.get_json() if not all([len(str(value)) > 0 for value in body.values()]): abort(422) question = Question( question=body.get("question"), answer=body["answer"], category=body["category"], difficulty=body["difficulty"], ) try: question.insert() questions = Question.query.all() print("question was added") current_questions = paginate_questions(request, questions) print(len(questions)) return jsonify({ "success": True, "created": question.id, "questions": current_questions, }) except: abort(404)
def add_questions(): body = request.get_json() new_question = body.get("question", None) new_answer = body.get("answer", None) new_category = body.get("category", None) new_difficulty = body.get("difficulty", None) if (new_question is None) or (new_answer is None) or ( new_category is None) or (new_difficulty is None): abort(422) try: add_question = Question(question=new_question, answer=new_answer, category=new_category, difficulty=new_difficulty) add_question.insert() return jsonify( { "success": True, "created": add_question.id, "total_questions": len(Question.query.all()), }, 200) except: abort(500)
def create_question(): try: data = json.loads(request.data) if 'searchTerm' not in data.keys(): question = data['question'] answer = data['answer'] difficulty = data['difficulty'] category = data['category'] if not (question and answer and difficulty and category): abort(400) new_question = Question(question, answer, category, difficulty) new_question.insert() return jsonify({ 'success': True, }) elif 'searchTerm' in data.keys(): search_term = data['searchTerm'] questions = Question.query.filter( Question.question.ilike(f'%{search_term}%')).all() return jsonify({ 'success': True, 'questions': [question.format() for question in questions] }) except: abort(422)
def test_delete_question(self): new_question = Question(question='TestQuestion', answer='TestAnswer', difficulty=1, category=1) new_question.insert() question_id = new_question.id res = self.client().delete('/questions/{}'.format(question_id)) data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertEqual(data['success'], True) self.assertEqual(data['deleted'], question_id)
def add_question(): try: data = request.json to_add = Question(data['question'], data['answer'], data['category'], data['difficulty']) to_add.insert() return jsonify({'success': True}), 200 except Exception as e: abort(422)
def post_question(): question = Question( question=request.json.get("question"), answer=request.json.get("answer"), difficulty=request.json.get("difficulty"), category=request.json.get("category"), ) question.insert() return jsonify( dict( r, message="Successfully added question to database", data=question.format(), ))
def create_questions(): details = request.get_json() # if search term is present if "searchTerm" in details: search_term = details.get('searchTerm') # query the database using search term selection = Question.query.filter( Question.question.ilike(f'%{search_term}%')).all() if len(selection) == 0: abort(404) # paginate the results paginated = paginate_questions(request, selection) # return results return jsonify({ 'success': True, 'questions': paginated, 'total_questions': len(Question.query.all()) }) else: #save data question = details["question"] answer = details["answer"] difficulty = details["difficulty"] category = details["category"] # ensure all fields have data if ((question is None) or (answer is None) or (difficulty is None) or (category is None)): abort(422) try: # create and insert new question question = Question(question=question, answer=answer, difficulty=difficulty, category=category) question.insert() # return data to view return jsonify({'success': True}) except: # abort unprocessable if exception abort(422)
def create_question(): """ Add a question to database. :return: """ question = request.get_json() if not question: abort(StatusCode.HTTP_400_BAD_REQUEST.value) question = Question(**question) question.insert() return jsonify({ 'success': True, 'id': question.id }), StatusCode.HTTP_201_CREATED.value
def test_delete_question_id(self): question = Question(question="question_to_be_deleted", answer="answer", difficulty=2, category=2) question.insert() id = question.id res = self.client().get("/questions/{}".format(id)) data = json.loads(res.data) check_question_in_db = Question.query.get(id) self.assertEqual(res.status_code, 200) self.assertEqual(data["success"], True) self.assertEqual(data["deleted_id"], id) self.assertTrue(check_question_in_db == None)
def test_delete_questions(self): question = Question(question='test', answer='test', difficulty=5, category=13) question.insert() question_id = question.id res = self.client().delete('/questions/{}'.format(question.id)) data = json.loads(res.data) question = Question.query.filter( Question.id == question.id).one_or_none() self.assertEqual(res.status_code, 200) self.assertEqual(data['success'], True) self.assertEqual(question, None) self.assertEqual(data['deleted'], str(question_id))
def addquestion(): form = AddQuestion() if form.validate_on_submit(): question = Question(question = form.question.data , options = form.options.data, answer = form.answer.data, month_id= form.month.data) db.session.add(question) db.session.commit() flash('Question is Added successfully!','success') return redirect(url_for('dashboard')) return render_template('addquestion.html',title = 'Dashboard',form=form)
def add_question(): data = request.get_json() question = data.get('question', None) answer = data.get('answer', None) difficulty = data.get('difficulty', None) category = data.get('category', None) try: question = Question(question=question, answer=answer, difficulty=difficulty, category=category) question.insert() return jsonify({ 'success': True }) except: abort(422)
def post_new_question(): body = request.get_json() new_content = body.get('question', None) new_answer = body.get('answer', None) new_category = body.get('category', None) new_score = body.get('score', None) search_term = body.get('search', None) if search_term is None: try: question = Question(question=new_content, answer=new_answer, category=new_category, difficulty=new_score) question.insert() return jsonify({ 'success': True, 'created': question.id, 'question': question, 'total_questions': len(Question.query.all()) }) except: abort(422) else: questions = Question.query.filter( Question.question.ilike('%' + search_term + '%')).all() if questions is None: abort(404) else: formatted_questions = [ question.format() for question in questions ] return jsonify({ 'success': True, 'questions': formatted_questions })
def generate_question_objects(self, data: list) -> Question: for item in data: if (item.get("question") and item.get("is_true") in [0, 1] and item.get("real_answer")): answer = item["real_answer"] for i in range(3): source = f"sources{i+1 if i != 0 else ''}" answer += f" {item[source]}" if item[source] else "" yield Question(title=item["question"], is_true=item["is_true"], real_answer=answer)
def create_question(): try: body = request.get_json() new_qus = body.get('question', None) new_answer = body.get('answer', None) catog = body.get('rate', None) diff = body.get('difficulty', None) question = Question(question=new_qus, answer=new_answer, category=catog, difficulty=diff) question.insert() except: abort(202) finally: return jsonify({ "successful": True, "total books": len(Question.query.all()), "messege": 'Created', 'created_question_id': question.id })
def add_question(): body = request.get_json() if not ('question' in body and 'answer' in body and 'category' in body and 'difficulty' in body): abort(422) question_val = body.get('question') answer_val = body.get('answer') category_val = body.get('category') difficulty_val = body.get('difficulty') try: question_obj = Question(question_val, answer_val, category_val, difficulty_val) question_obj.insert() questions = Question.query.order_by(Question.id).all() current_questions = paginate_questions(request, questions) return jsonify({ "success": True, "created": question_obj.id, "questions": current_questions, "total_questions": len(questions) }) except: question_obj.rollback() abort(422)
def add_question(): """ @DONE: Create an endpoint to POST a new question, which will require the question and answer text, category, and difficulty score. TEST: When you submit a question on the "Add" tab, the form will clear and the question will appear at the end of the last page of the questions list in the "List" tab. """ data: dict = request.get_json() question = data.get('question') answer = data.get('answer') category = data.get('category') difficulty = int(data.get('difficulty', 0)) # Simple validation all_values_exist = all([question, answer, category, difficulty]) category_exist = db.session.query( Category.query.filter_by(id=category).exists()).scalar() difficulty_in_range = 1 <= difficulty <= 5 if not all([all_values_exist, category_exist, difficulty_in_range]): message = "" if not all_values_exist: message = "There is an empty required field. " if not category_exist: message += "Category doesn't exist. " if not difficulty_in_range: message += "Difficulty range is between 1 to 5." return jsonify({'message': message}), 422 question_model = Question(question=question, answer=answer, category_id=category, difficulty=difficulty) try: db.session.add(question_model) db.session.commit() _id = question_model.id except SQLAlchemyError: db.session.rollback() db.session.close() raise InternalServerError return jsonify({ 'id': _id, }), 201
def create_question(): body = request.get_json() try: question = Question(question=body.get('question', None), answer=body.get('answer', None), category=body.get('category', None), difficulty=body.get('difficulty', None)) question.insert() questions = Question.query.all() paginated_questions = paginate_questions(request, questions) return jsonify({ 'success': True, 'created': question.id, 'questions': paginated_questions, 'total_questions': len(questions) }) except: abort(422)
def test_delete_question(self): """Tests question deletion success""" # create a new question to be deleted question = Question(question=self.new_question['question'], answer=self.new_question['answer'], category=self.new_question['category'], difficulty=self.new_question['difficulty']) question.insert() # get the id of the new question q_id = question.id # get number of questions before delete questions_before = Question.query.all() # delete the question and store response response = self.client().delete('/questions/{}'.format(q_id)) data = json.loads(response.data) # get number of questions after delete questions_after = Question.query.all() # see if the question has been deleted question = Question.query.filter(Question.id == 1).one_or_none() # check status code and success message self.assertEqual(response.status_code, 200) self.assertEqual(data['success'], True) # check if question id matches deleted id self.assertEqual(data['deleted'], q_id) # check if one less question after delete self.assertTrue(len(questions_before) - len(questions_after) == 1) # check if question equals None after delete self.assertEqual(question, None)
def test_delete_question(self): """Delete a question from the database via API, then create an identical question directly with DB.""" result = self.client().get('/questions') response = json.loads(result.data) total_questions_initial = response['total_questions'] question_vals = Question.query.first().format() question_id = question_vals['id'] question_text = question_vals['question'] answer = question_vals['answer'] category = question_vals['category'] difficulty = question_vals['difficulty'] result = self.client().delete(f'/questions/{question_id}') response = json.loads(result.data) self.assertEqual(response, {'success': True}) result = self.client().get('/questions') response = json.loads(result.data) total_questions_after = response['total_questions'] self.assertEqual(total_questions_after, total_questions_initial - 1) # Now add the same question back, but with a different id new_question = Question(question_text, answer, category, difficulty) new_question.insert()
def search_question(): body = request.get_json() search_term = body.get('title', None) qSearch = Question.query.filter( Question.question.ilike("%{}%".format(search_term))).all() # method search_qustion declared in the Question class r = Question.search_qustion(search_term, qSearch) count = len(qSearch) if count is None: abort(202) return jsonify({ "count": count, "question searched": [r for r in qSearch] })
def setUp(self): """Define test variables and initialize app.""" self.app = create_app() self.client = self.app.test_client self.database_name = "trivia_test" self.database_path = "postgres://{}/{}".format('localhost:5432', self.database_name) setup_db(self.app, self.database_path) self.new_question = { 'category': '1', 'question': 'Neil Gaiman', 'answer': 'aaaaaaa', 'difficulty': 5 } self.new_category = { 'id': '1', 'type': 'test_type', } # binds the app to the current context with self.app.app_context(): self.db = SQLAlchemy(self.app) self.db.init_app(self.app) self.db.create_all() # # create all tables # create all tables self.question = Question(difficulty=self.new_question['difficulty'], question=self.new_question['question'], answer=self.new_question['answer'], category=self.new_question['category']) self.question.insert() if Category.query.first() is None: category = Category(type=self.new_category['type']) category.insert()
questions[question['original_id']]['translations'][lang] = {} questions[question['original_id']]['cat_ids'] = [item['original_id'] for item in question["categories"]] print(questions[question['original_id']]['cat_ids']) questions[question['original_id']]['translations'][lang]['question'] = clean_wordpress_content(question['title']['rendered']) questions[question['original_id']]['translations'][lang]['answer'] = clean_wordpress_content(question['content']['rendered']) questions[question['original_id']]['id'] = int(question['original_id']) questions[question['original_id']]['county'] = "00000000" if len(question["countries"]) == 0 else question["countries"][0] questions[question['original_id']]['audiences'] = [] for step in question["steps"]: questions[question['original_id']]['audiences'].append(Audience.objects.get(id=int(step))) entries_to_delete = Question.objects.all() for question_id in questions: entries_to_delete = entries_to_delete.exclude(id=question_id) entries = Question.objects.language('all').filter(id=question_id) if len(entries) == 0: entry = Question(id=question_id) entry.county = questions[question_id]['county'] entry.audiences = [] entry.save() for language in questions[question_id]['translations']: if language in Question.objects.get(id=question_id).get_available_languages(): entry = Question.objects.language(language).get(id=question_id) else: entry = Question.objects.get(id=question_id).translate(language) entry.question = questions[question_id]['translations'][language]['question'] entry.answer = questions[question_id]['translations'][language]['answer'] entry.categories = questions[question_id]['cat_ids'] entry.county = questions[question_id]['county'] entry.audiences = questions[question_id]['audiences'] entry.save()
class TriviaTestCase(unittest.TestCase): """This class represents the trivia test case""" # initialization logic for the test suite declared in the test module # code that is executed before all tests in one test run @classmethod def setUpClass(cls): pass # clean up logic for the test suite declared in the test module # code that is executed after all tests in one test run @classmethod def tearDownClass(cls): pass def setUp(self): """Define test variables and initialize app.""" self.app = create_app() self.client = self.app.test_client self.database_name = "trivia_test" self.database_path = "postgres://{}/{}".format('localhost:5432', self.database_name) setup_db(self.app, self.database_path) self.new_question = { 'category': '1', 'question': 'Neil Gaiman', 'answer': 'aaaaaaa', 'difficulty': 5 } self.new_category = { 'id': '1', 'type': 'test_type', } # binds the app to the current context with self.app.app_context(): self.db = SQLAlchemy(self.app) self.db.init_app(self.app) self.db.create_all() # # create all tables # create all tables self.question = Question(difficulty=self.new_question['difficulty'], question=self.new_question['question'], answer=self.new_question['answer'], category=self.new_question['category']) self.question.insert() if Category.query.first() is None: category = Category(type=self.new_category['type']) category.insert() def tearDown(self): """Executed after reach test""" if self.question is not None: self.question.delete() self.db.drop_all() pass """ TODO Write at least one test for each test for successful operation and for expected errors. """ def test_get_categories(self): """Test _____________ """ res = self.client().get('/categories') data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertEqual(data['success'], True) self.assertEqual(len(data['categories']), 6) def test_get_categories_wrong_method(self): """Test _____________ """ res = self.client().post('/categories') self.assertEqual(res.status_code, 405) def test_get_paginated_questions(self): res = self.client().get('/questions?page=1') data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertEqual(data['success'], True) self.assertTrue(data['total_questions']) self.assertTrue(len(data['questions'])) def test_404_sent_requesting_beyond_valid_page(self): res = self.client().get('/questions?page=1000') data = json.loads(res.data) self.assertEqual(res.status_code, 404) self.assertEqual(data['success'], False) self.assertEqual(data['message'], 'Not found') def test_delete_question(self): question = self.db.session.query(Question).order_by('answer').first() question_id = question.id res = self.client().delete('/questions/' + str(question.id)) data = json.loads(res.data) question = Question.query.filter(Question.id == question_id).one_or_none() self.assertEqual(res.status_code, 200) self.assertEqual(data['success'], True) self.assertEqual(data['deleted'], question_id) self.assertEqual(question, None) def test_404_if_question_does_not_exist(self): res = self.client().delete('/questions/1000') data = json.loads(res.data) self.assertEqual(res.status_code, 422) self.assertEqual(data['success'], False) self.assertEqual(data['message'], 'Unprocessable Entity') def test_create_new_question(self): res = self.client().post('/questions', json=self.new_question) data = json.loads(res.data) self.assertEqual(res.status_code, 200) def test_422_if_question_creation_fails(self): res = self.client().post('/questions', json={}) data = json.loads(res.data) self.assertEqual(res.status_code, 422) def test_search_question_with_results(self): res = self.client().post('/questions', json={'searchTerm': 'Neil'}) data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertTrue(data['success']) self.assertEqual(data['total_questions'], 2) self.assertTrue(data['questions']) def test_search_question_without_results(self): res = self.client().post('/questions', json={'searchTerm': 'hey'}) data = json.loads(res.data) question = Question.query.filter( self.db.func.lower(Question.question).contains(self.db.func.lower('hey'))).first() self.assertEqual(res.status_code, 200) self.assertTrue(data['success']) self.assertEqual(data['total_questions'], 0) self.assertEqual(question, None) def test_get_question_by_category_with_results(self): res = self.client().get('/categories/1/questions') data = json.loads(res.data) category = Category.query.first() self.assertEqual(res.status_code, 200) self.assertTrue(data['success']) self.assertEqual(len(data['questions']), 5) self.assertEqual(data['total_questions'], 5) self.assertEqual(data['currentCategory'], Category.format(category)) def test_get_question_by_category_without_results(self): res = self.client().get('/categories/57/questions') self.assertEqual(res.status_code, 404) def test_get_quizzes_with_results(self): category = Category.query.first() res = self.client().post('/quizzes', json={'previous_questions': [], 'quiz_category': Category.format(category)}) data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertTrue(data['success']) self.assertEqual(len(data['previous_questions']), 1) def test_get_quizzes_with_wrong_category(self): category = Category.query.first() category.id = 12 res = self.client().post('/quizzes', json={'previous_questions': [], 'quiz_category': Category.format(category)}) data = json.loads(res.data) self.assertEqual(res.status_code, 422) self.assertEqual(data['error'], 422) self.assertEqual(data['message'], 'Unprocessable Entity') self.assertEqual(data['success'], False)
question['title']['rendered']) questions[question['original_id']]['translations'][lang][ 'answer'] = clean_wordpress_content( question['content']['rendered']) questions[question['original_id']]['id'] = int( question['original_id']) questions[question['original_id']]['county'] = 5 questions[question['original_id']]['audiences'] = [ Audience.objects.get(id=random.randint(1, 3)) ] entries_to_delete = Question.objects.all() for question_id in questions: entries_to_delete = entries_to_delete.exclude(id=question_id) entries = Question.objects.language('all').filter(id=question_id) if len(entries) == 0: entry = Question(id=question_id) entry.county = questions[question_id]['county'] entry.audiences = [] entry.save() for language in questions[question_id]['translations']: if language in Question.objects.get( id=question_id).get_available_languages(): entry = Question.objects.language(language).get(id=question_id) else: entry = Question.objects.get(id=question_id).translate(language) entry.question = questions[question_id]['translations'][language][ 'question'] entry.answer = questions[question_id]['translations'][language][ 'answer'] entry.categories = questions[question_id]['cat_ids'] entry.county = questions[question_id]['county']
def forwards(apps, schema_editor): if schema_editor.connection.alias != 'default': return user1 = X5gonUser(name='Amal Kumar', country='India', interests='Mechanical Engineering') user1.save() user2 = X5gonUser(name='Thura Aung', country='Myanmar', interests='Engineering') user2.save() user3 = X5gonUser(name='Afi Ababio', country='Ghana', interests='Geotechnical Engineering') user3.save() user4 = X5gonUser(name='Maria José Villegas', country='Guatemala', interests='Chemical Engineering') user4.save() user5 = X5gonUser(name='Aminah Farooqi', country='Pakistan', interests='Electrical Enginering') user5.save() user6 = X5gonUser(name='Lee Choi', country='South Korea', interests='Electrical Engineering') user6.save() ur1 = UserResource(user=user1, resource=X5gonResource.objects.get(x5gon_id='112789'), crown=False, expert_on=False) ur1.save() ur2 = UserResource(user=user1, resource=X5gonResource.objects.get(x5gon_id='30289'), crown=True, expert_on=True) ur2.save() ur3 = UserResource(user=user1, resource=X5gonResource.objects.get(x5gon_id='65303'), crown=False, expert_on=False) ur3.save() ur4 = UserResource(user=user2, resource=X5gonResource.objects.get(x5gon_id='112789'), crown=True, expert_on=True) ur4.save() ur5 = UserResource(user=user2, resource=X5gonResource.objects.get(x5gon_id='30289'), crown=False, expert_on=False) ur5.save() ur6 = UserResource(user=user2, resource=X5gonResource.objects.get(x5gon_id='65303'), crown=True, expert_on=True) ur6.save() ur7 = UserResource(user=user3, resource=X5gonResource.objects.get(x5gon_id='112789'), crown=True, expert_on=True) ur7.save() ur8 = UserResource(user=user3, resource=X5gonResource.objects.get(x5gon_id='30289'), crown=True, expert_on=True) ur8.save() ur9 = UserResource(user=user3, resource=X5gonResource.objects.get(x5gon_id='65303'), crown=False, expert_on=False) ur9.save() ur10 = UserResource(user=user4, resource=X5gonResource.objects.get(x5gon_id='112789'), crown=False, expert_on=False) ur10.save() ur11 = UserResource(user=user4, resource=X5gonResource.objects.get(x5gon_id='30289'), crown=False, expert_on=False) ur11.save() ur12 = UserResource(user=user4, resource=X5gonResource.objects.get(x5gon_id='65303'), crown=False, expert_on=False) ur12.save() ur13 = UserResource(user=user5, resource=X5gonResource.objects.get(x5gon_id='112789'), crown=True, expert_on=True) ur13.save() ur14 = UserResource(user=user5, resource=X5gonResource.objects.get(x5gon_id='30289'), crown=True, expert_on=True) ur14.save() ur15 = UserResource(user=user5, resource=X5gonResource.objects.get(x5gon_id='65303'), crown=True, expert_on=True) ur15.save() ur16 = UserResource(user=user6, resource=X5gonResource.objects.get(x5gon_id='112789'), crown=False, expert_on=False) ur16.save() ur17 = UserResource(user=user6, resource=X5gonResource.objects.get(x5gon_id='30289'), crown=True, expert_on=True) ur17.save() ur18 = UserResource(user=user6, resource=X5gonResource.objects.get(x5gon_id='65303'), crown=False, expert_on=False) ur18.save() quest1 = Question( resource=X5gonResource.objects.get(x5gon_id='112789'), question= 'Please provide the formula for the restoring Force for small angles.', correct_answer='-(mgs)/L') quest1.save() quest2 = Question( resource=X5gonResource.objects.get(x5gon_id='112789'), question='Please provide the formula for the force constant k.', correct_answer='-(mg)/L') quest2.save() quest3 = Question( resource=X5gonResource.objects.get(x5gon_id='112789'), question='By which physical concept can the pendulum be described?', correct_answer='Harmonic Oscillator') quest3.save()
from starlette.responses import JSONResponse from backend import constants from backend.models import Form, FormList, Question from backend.route import Route from backend.validation import api __FEATURES = [ constants.FormFeatures.DISCOVERABLE.value, constants.FormFeatures.OPEN.value, constants.FormFeatures.REQUIRES_LOGIN.value ] __QUESTION = Question( id="description", name="Check your cookies after pressing the button.", type="section", data={"text": "You can find cookies under \"Application\" in dev tools."}, required=False) EMPTY_FORM = Form( id="empty_auth", features=__FEATURES, questions=[__QUESTION], name="Auth form", description="An empty form to help you get a token.", ) class DiscoverableFormsList(Route): """ List all discoverable forms that should be shown on the homepage.