def post(self): headers.cors(self.response) if not "score" in self.request.params: abort(400, "No score posted") if not "path" in self.request.params: abort(400, "No path supplied") score = self.request.params.get("score") path = self.request.params.get("path") quiz = ndb.Key(Quiz, path).get() if not quiz: quiz = Quiz(id=path, path=path) quiz.put() QuizScore(parent=quiz.key, score=int(score)).put() recalculation_flag = ndb.Key(QuizNeedingRecalculation, path).get() if not recalculation_flag: QuizNeedingRecalculation(id=path, path=path).put() headers.json(self.response) self.response.out.write(json.dumps({"score": score}))
def create_quiz(): ## Create quiz quiz_name = (str)(request.form['quiz_name']) quiz = Quiz(name=quiz_name) ## Pick questions for that quiz question_list = list() question_count = db.session.query(Question).count() for _ in range(0, 10): searching = True while searching: number = random.randint(1, question_count - 1) if number not in question_list: question_list.append(number) searching = False quiz.questions = json.dumps(question_list) seconds_later = 60 if 'seconds' in request.form.keys(): seconds_later = (int)(request.form['seconds']) quiz.start_time = datetime.now() + timedelta(seconds=seconds_later) quiz.end_time = quiz.start_time + timedelta(minutes=10) db.session.add(quiz) db.session.commit() status_dict = dict() status_dict['status'] = 'CREATED' status_dict['quiz_id'] = quiz.id return jsonify(status_dict)
def data(ws): """ws:导入excel中的工作簿""" global count # 全局变量 for row in ws.iter_rows(): count = count + 1 now = datetime.now() intime = str(now - START)[:-7] print('导入{}题,已经用时{}'.format(count, intime), end='\r', flush=True) tag = row[1].value kind = row[2].value txts = row[3].value.split('\n') name = txts[0] items = txts[1:] answer = row[4].value source = row[5].value if not tag: # 如果为空 tag = '' if not kind: # 如果为空 kind = '' # txts不可能为空 # answer不可能为空 if not source: # 如果为空 source = '' memo = row[6].value if not memo: # 如果为空 memo = '' repo = row[7].value if not repo: # 如果为空 repo = '' other = row[8].value if not other: # 如果为空 other = '' with db_session: if Quiz.get(id=count): print('id为{}的题目已存在'.format(count), end='\r', flush=True) continue quiz = Quiz(tag=tag, kind=kind, name=name, answer=answer, source=source, memo=memo, repo=repo, other=other) for i in items: if i: # 如果不是空行 item = Item(name=i, quiz=quiz)
def test_read_all_quizzes(self): self.assertTrue( Quiz().create( int(Category().read().all()[-1]['id']), "In which year did Ghana gained independence?", "1997, 2012, 1957, 666", "1957")) self.assertEqual(len(Quiz().read().all()), 2)
def seed(): reset_db() userlist = [ User(first_name='Max', last_name='HvA'), User(first_name='Menno', last_name='HvA'), User(first_name='Robert', last_name='HvA') ] for user in userlist: user.hash_password('qwerty') quizlist = [ Quiz(name='My first time using JavaScript', user_id=1), Quiz(name='JavaScript functions', user_id=2) ] questionlist = [ Question(name='Printing', description='Print out Hello World!', answer='Hello World!', quiz_id=1), Question( name='Adding up the numbers', description='Use your knowledge to add up the numbers 1 and 2', answer='3', quiz_id=1), Question(name='Multiplying numbers', description='Multiply 5 by 4', answer='20', quiz_id=1) ] answerlist = [ Answer(input='console.log("Hello World!")', user_id=1, question_id=1), Answer(input='1+2', user_id=1, question_id=2), Answer(input='5*4', user_id=1, question_id=3), ] for user in userlist: session.add(user) session.commit() for quiz in quizlist: session.add(quiz) session.commit() for question in questionlist: session.add(question) session.commit() for answer in answerlist: session.add(answer) session.commit()
def setUp(self): print('\r') # drop all tables in the database db.session.remove() db.drop_all() # crete all tables in the database db.create_all() # adding users user_1 = User('*****@*****.**', encrypt('password'), 'student_1') student_1 = Student(user_1, 'U00000000A') db.session.add(student_1) user_2 = User('*****@*****.**', encrypt('password'), 'student_2') student_2 = Student(user_2, 'U00000000B') db.session.add(student_2) user_3 = User('*****@*****.**', encrypt('password'), 'teacher_1') staff_1 = Staff(user_3) db.session.add(staff_1) # adding topics topic = Topic(name='seng') db.session.add(topic) # adding lessons lesson = Lesson(1, 1, 'lesson_1', 'content') db.session.add(lesson) # adding quizzes quiz_1 = Quiz(3, 'quiz_1', True, '2020-03-30', '2020-03-31') db.session.add(quiz_1) quiz_2 = Quiz(3, 'quiz_2', True, '2020-03-30', '2020-03-31') db.session.add(quiz_2) # adding questions question_1 = Question(1, 1, 'question_1') db.session.add(question_1) question_2 = Question(1, 1, 'question_2') db.session.add(question_2) question_3 = Question(1, 1, 'question_3') db.session.add(question_3) question_4 = Question(1, 1, 'question_4') db.session.add(question_4) # adding challenges challenge = Challenge(1, 2, 1) db.session.add(challenge) db.session.commit()
def setUp(self): print('\r') # drop all tables in the database db.session.remove() db.drop_all() # crete all tables in the database db.create_all() # adding topics topic = Topic(name='seng') db.session.add(topic) # adding lessons lesson = Lesson(topic_id=1, id=1, name='se', content='test') db.session.add(lesson) # adding users user = User('*****@*****.**', encrypt('password'), 'staff_name') staff = Staff(user) db.session.add(staff) # adding quizzes quiz = Quiz(1, 'quiz_name', True, '2020-03-21', '2020-03-22') db.session.add(quiz) db.session.commit()
def setUp(self): print('\r') # drop all tables in the database db.session.remove() db.drop_all() # crete all tables in the database db.create_all() # adding users user = User(email='*****@*****.**', encrypted_password=encrypt('password'), name='john_doe') staff = Staff(user) db.session.add(staff) # adding courses course = Course(index='cz3003') db.session.add(course) # adding quizzes quiz = Quiz( staff_id=1, name="Quiz Test", is_fast=True, date_start='2020-03-01', date_end='2020-03-31', ) db.session.add(quiz) db.session.commit()
def setUp(self): print('\r') # drop all tables in the database db.session.remove() db.drop_all() # crete all tables in the database db.create_all() # adding users user = User(email='*****@*****.**', encrypted_password=encrypt('password'), name='staff') staff = Staff(user) db.session.add(staff) user = User(email='*****@*****.**', encrypted_password=encrypt('password'), name='john_doe') student = Student(user, 'U1722') db.session.add(student) # adding quizzes qz = Quiz(1, 'quiz', True, '2020-03-21', '2020-03-22') db.session.add(qz) # adding quizattempts qa = initializeQuizAttempt(2, 1, 100) db.session.add(qa) db.session.commit()
def test_quizCreate(self): # create a new Quiz object quiz = Quiz( staff_id=1, name="Quiz Test", is_fast=True, date_start='2020-03-01', date_end='2020-03-31', ) # add Quiz object to the database quizCreate(quiz) # retrieve all records from the table 'quizzes' quiz_list = Quiz.query.all() # check that the number of record added is correct print('--- check that the number of record added is correct') self.assertEqual(1, len(quiz_list)) # check that the value(s) of the Quiz object added is correct print( '--- check that the value(s) of the Quiz object added is correct') self.assertEqual(quiz_list[0].name, 'Quiz Test')
def test_create_quiz_raise_intergrity_error_for_existing_quiz(self): with self.assertRaises(sqlite3.IntegrityError): Quiz().create( int(Category().read().all()[-1]['id']), "Who is the first Priminister of Ghana?", "Nana Addo, Kwame Nkrumah, Rawlings", "Kwame Nkrumah")
def test_missing_quizzes_quickcheck(self, m): from utils import missing_quizzes m.register_uri( 'GET', '/api/v1/courses/1/quizzes', json=[ {'id': 1, 'title': 'Quiz 1'}, {'id': 2, 'title': 'Quiz 2'}, {'id': 3, 'title': 'Quiz 3'}, ] ) quiz_obj = Quiz( course_id=1, canvas_id=2, title='Quiz 2' ) views.db.session.add(quiz_obj) views.db.session.commit() response = missing_quizzes(1, quickcheck=True) self.assertIsInstance(response, list) self.assertEqual(len(response), 1) self.assertEqual(response[0]['title'], 'Quiz 1')
def test_missing_quizzes_check_false(self, m): m.register_uri( 'GET', '/api/v1/courses/1/quizzes', json=[{'id': 1, 'title': 'Quiz 1'}] ) course_id = 1 course = Course( canvas_id=course_id, course_name='test' ) views.db.session.add(course) quiz = Quiz( canvas_id=1, course_id=course.id ) views.db.session.add(quiz) views.db.session.commit() extension = Extension( course_id=course.id, user_id=5, percent=200 ) views.db.session.add(extension) views.db.session.commit() response = self.client.get('/missing_quizzes/{}/'.format(course_id)) self.assert_200(response) self.assertEqual(response.data, 'false')
def test_get_or_create_already_exists(self, m): from utils import get_or_create quiz_id = 5 quiz_title = "Final Exam" course_id = 1 prebuilt_quiz = Quiz( canvas_id=quiz_id, course_id=course_id, title=quiz_title ) views.db.session.add(prebuilt_quiz) views.db.session.commit() quiz, created = get_or_create( views.db.session, Quiz, canvas_id=quiz_id, course_id=course_id ) self.assertFalse(created) self.assertIsInstance(quiz, Quiz) self.assertEqual(quiz.canvas_id, quiz_id) self.assertEqual(quiz.course_id, course_id) self.assertEqual(quiz.title, quiz_title)
def setUp(self): print('\r') # drop all tables in the database db.session.remove() db.drop_all() # crete all tables in the database db.create_all() # adding courses course = Course(index='cz3003') db.session.add(course) # adding users user = User(email='*****@*****.**', encrypted_password=encrypt('password'), name='staff') staff = Staff(user) db.session.add(staff) # adding quizzes qz = Quiz(1, 'quiz', True, '2020-03-21', '2020-03-22') db.session.add(qz) # adding RsQuizCourseAssign rs = initializeRsQuizCourseAssign(1, 'cz3003') db.session.add(rs) db.session.commit()
def test_create_quiz_returns_true_on_success(self): self.assertTrue( Quiz().create( int(Category().read().all()[-1]['id']), "Which country promises wealth but without health?", "America, Jamaica, China, Russian", "China"))
def admin(): print "Submitting" qform = AqForm(prefix="qform") form = AtForm(prefix="form") if qform.validate_on_submit() and qform.name.data: print "Submitting" quiz = Quiz(name=qform.name.data, question=qform.question.data, answer=qform.answer.data) db.session.add(quiz) db.session.commit() return redirect(url_for('startpage')) if form.validate_on_submit() and form.name.data: tut = Tut(name=form.name.data, content=form.content.data, question=form.question.data, answer=form.answer.data) db.session.add(tut) db.session.commit() return redirect(url_for('startpage')) tutnames = db.session.query(Tut.name).all() tutnames = [tutname for (tutname, ) in tutnames] return render_template('admin.html', form=form, qform=qform, tutnames=tutnames)
def post(self): parsed_args = parser.parse_args() quiz = Quiz(name=parsed_args['name'], user_id=parsed_args['user_id']) session.add(quiz) session.commit() return quiz.name, 201
def setUp(self) -> None: set_up_database_and_tables() Category().create("POLITICS") Quiz().create( int(Category().read().all()[-1]['id']), "Who is the first Priminister of Ghana?", "Nana Addo, Kwame Nkrumah, Rawlings", "Kwame Nkrumah")
def parse_quiz_yaml(path, string): d = yaml.load(string) sugar = make_sugar(path, d) assert d.get('title') and len(d['title']) > 0, "Quiz is missing title" assert d.get('subtitle') and len( d['subtitle']) > 0, "Quiz is missing subtitle" assert d.get('text') and len(d['text']) > 0, "Quiz is missing text body" assert d.get('questions') and len( d['questions']) > 0, "Quiz has no questions" assert d.get('email') and len(d['email']) > 0, "Quiz has no email message" email = d['email'] for k in ['$name', '$url']: assert k in email, "Quiz email is missing parameter %s" % k questions = d['questions'] for i, q in enumerate(questions): assert q.get('text'), "Question #%d has no text" % (i + 1) assert q.get('choices') and len( q['choices']) > 1, "Question #%d needs more than one choice" % (i + 1) assert q.get( 'correct'), "Question #%d is missing a correct answer" % (i + 1) assert q.get('correct') in q[ 'choices'], "Question #%d has a correct answer that is not one of the choices" % ( i + 1) if q.get('type'): assert q['type'] in [t[0] for t in QUESTION_TYPES] quiz = Quiz( title=d['title'], subtitle=d['subtitle'], text=sugar(d['text']), ) quiz.save() for i, q in enumerate(d['questions']): for choice in q['choices']: q['choices'][choice] = sugar(q['choices'][choice]) question = Question(text=sugar(q['text']), choices=json.dumps(q['choices']), correct=q['correct'], explanation=sugar(q.get('explanation') or ''), index=i + 1) if q.get('type'): question.type = q['type'] question.save() quiz.questions.add(question) return md.markdown(email), quiz
def create_quiz(): """ Create a Quiz """ data = request.get_json() new_id = uuid4() new_quiz = Quiz(id=new_id, name=data['name']) db.session.add(new_quiz) db.session.commit() return jsonify({ 'message': 'New Quiz created!', 'id': new_id })
def create_quiz(request, course_slug, page_slug): ''' create_Quiz View This view will create a quiz and take the user to the quiz editor screen. @author John Hartquist ''' #enforcing permissions try: e = Enrollment.objects.get(course__slug = course_slug, user = request.user) except Enrollment.DoesNotExist: return custom_403(request, "User cannot create a quiz in the course because the user is not enrolled in this course") if not e.edit: return custom_403(request, "User cannot create a quiz in the course because the user does not have edit permissions on the course") page_slug = safeSlug(page_slug) if request.method == "POST" and "Create Quiz" in request.POST: course = Course.objects.get(slug=course_slug) name = request.POST['name'] if name == "": return master_rtr(request, 'page/quiz/create-quiz.html', {'message': "You may not enter a blank quiz name"}) #exists = Quiz.objects.get(slug=slugify(name)) try: exists = Quiz.objects.get(slug=slugify(name), course=course) return master_rtr(request, 'page/quiz/create-quiz.html', {'message': "Quiz with this name already exists"}) except: newQuiz = Quiz(course=course, name=name, slug=slugify(name), text=name, upToDate=True) insertLastChildPage(newQuiz, Page.objects.get(slug=page_slug, course=course)) newQuiz = Quiz.objects.get(slug=newQuiz.slug, course=course) workingCopy = Quiz(course=newQuiz.course, name=newQuiz.name, slug=(newQuiz.slug + "_workingCopy"), text=newQuiz.name, left=0, right=0) workingCopy.save() return HttpResponseRedirect(reverse('pages.views.edit_page', args=[course_slug, newQuiz.slug])) else: return master_rtr(request, 'page/quiz/create-quiz.html')
def parse_quiz_yaml(path, string): d = yaml.load(string) sugar = make_sugar(path, d) assert d.get('title') and len(d['title']) > 0, "Quiz is missing title" assert d.get('subtitle') and len(d['subtitle']) > 0, "Quiz is missing subtitle" assert d.get('text') and len(d['text']) > 0, "Quiz is missing text body" assert d.get('questions') and len(d['questions']) > 0, "Quiz has no questions" assert d.get('email') and len(d['email']) > 0, "Quiz has no email message" email = d['email'] for k in ['$name','$url']: assert k in email, "Quiz email is missing parameter %s" % k questions = d['questions'] for i, q in enumerate(questions): assert q.get('text'), "Question #%d has no text" % (i + 1) assert q.get('choices') and len(q['choices']) > 1, "Question #%d needs more than one choice" % (i + 1) assert q.get('correct'), "Question #%d is missing a correct answer" % (i + 1) assert q.get('correct') in q['choices'], "Question #%d has a correct answer that is not one of the choices" % (i + 1) if q.get('type'): assert q['type'] in [t[0] for t in QUESTION_TYPES] quiz = Quiz( title=d['title'], subtitle=d['subtitle'], text=sugar(d['text']), ) quiz.save() for i, q in enumerate(d['questions']): for choice in q['choices']: q['choices'][choice] = sugar(q['choices'][choice]) question = Question( text=sugar(q['text']), choices=json.dumps(q['choices']), correct=q['correct'], explanation=sugar(q.get('explanation') or ''), index=i+1 ) if q.get('type'): question.type = q['type'] question.save() quiz.questions.add(question) return md.markdown(email), quiz
def test_quizUpdate(self): # create a new Quiz object and add it to the database quiz = Quiz( staff_id=1, name="Quiz Test", is_fast=True, date_start='2020-03-01', date_end='2020-03-31', ) db.session.add(quiz) db.session.commit() # update value of Quiz object quiz.name = "Quiz Test 2" quizUpdate() # fetch updated User object from the database quiz = Quiz.query.filter_by(id=1).first() # check if value of Quiz has been updated print('--- check if value of Quiz object has been updated') self.assertEqual('Quiz Test 2', quiz.name)
def post(self): claims = get_jwt_claims() _quiz_parser = reqparse.RequestParser() _quiz_parser.add_argument("kanji", type=str, required=True, help="This field cannot be blank.") _quiz_parser.add_argument("sentence", type=str, required=True, help="This field cannot be blank.") _quiz_parser.add_argument("quiz_name", type=str, required=True, help="This field cannot be blank.") _quiz_parser.add_argument("class_name", type=str, required=True, help="This field cannot be blank.") data = _quiz_parser.parse_args() _class = Lesson.find_by_name(data['class_name']) student_list = [student for student in _class.students] try: if claims['authorized']: for student in student_list: q = Quiz(kanji=data['kanji'], sentence=data['sentence'], quiz_name=data['quiz_name'], username=student) q.save_to_db() except Exception as e: print(e) return {'message': 'Quiz could not be created'}, 500 return {'message': 'quiz created!'}, 201
def test_integration(): teacher = TeacherBuilder.create_teacher() student_one = Student(name='John') class_room = ClassRoom() teacher.add_class_rooms(class_room) class_room.add_students(student_one) quiz = Quiz() one_plus_one = Question(title='1+1', correct_choice=1, choices=['1', '2', '4']) two_plus_two = Question(title='2+2', correct_choice=0, choices=['4', '5']) quiz.add_questions(one_plus_one, two_plus_two) class_room.assign_quiz(quiz, student=student_one) assert class_room.get_grade_for(student=student_one) == {'John': Decimal('0')} class_room.submit_answer(answer=Answer(one_plus_one, 1), student=student_one) assert class_room.get_grade_for(student=student_one) == {'John': Decimal('0.5')} class_room.submit_answer(answer=Answer(two_plus_two, 0), student=student_one) assert class_room.get_grade_for(student=student_one) == {'John': Decimal('1')} student_two = Student(name='Carl') class_room.add_students(student_two) class_room.assign_quiz(quiz, student=student_two) assert class_room.get_grade_for(student=student_two) == {'Carl': Decimal('0')} class_room.submit_answer(answer=Answer(one_plus_one, 1), student=student_two) assert class_room.get_grade_for(student=student_two) == {'Carl': Decimal('0.5')} class_room.submit_answer(answer=Answer(two_plus_two, 0), student=student_two) assert class_room.get_grade_for(student=student_two) == {'Carl': Decimal('1')}
def test_quizRead(self): # create a new Quiz object and add it to the database quiz = Quiz( staff_id=1, name="Quiz Test", is_fast=True, date_start='2020-03-01', date_end='2020-03-31', ) db.session.add(quiz) db.session.commit() # check that the record retrieved is correct print('--- check that the record retrieved is correct') self.assertEqual(quizRead(1).name, 'Quiz Test')
async def post(self, request, current_user): try: req = request.json user = await Users.get_first('email', req['creator']) req['users'] = user.id questions = [int(q) for q in req['questions']] del req['questions'] quiz = Quiz(**req) quiz_id = await quiz.create() for i, question in enumerate(questions): qq = QuizQuestions(quiz=quiz_id, question=question, question_order=i) await qq.create() return json({'success': True}) except: logging.exception('err quiz_manage.post') return json({}, status=500)
def t030_Quiz(self): """Quiz, le domande a risposta multipla""" L.i("QuizTestData load start") c = 0 for el in TestData.listQuiz: L.i(" Dataloaded #{0}".format(c)) c += 1 Quiz( title=el['title'], body=el['body'], dateStart=self.parseDate(el['dateStart']), dateEnd=self.parseDate(el['dateEnd']), answer=[ self.quizAnswerKeys[0] ], # todo -> deve recuperare i dati dal passo precedente user=el['user']) L.i("QuizTestData load ended") return True
def setUp(self): print('\r') # drop all tables in the database db.session.remove() db.drop_all() # crete all tables in the database db.create_all() # adding users user = User(email='*****@*****.**', encrypted_password=encrypt('password'), name='john_doe') student = Student(user, 'U1722') db.session.add(student) user = User(email='*****@*****.**', encrypted_password=encrypt('password'), name='staff') staff = Staff(user) db.session.add(staff) # adding topics topic = Topic(name='seng') db.session.add(topic) # adding lessons lesson = Lesson(topic_id='1', id='3', name='se', content='test') db.session.add(lesson) # adding questions qn = Question('1', '3', 'easy') db.session.add(qn) # adding quizzes qz = Quiz(2, 'quiz', True, '2020-03-21', '2020-03-22' ) # staff id is 2 here, as it uses the fk of users table db.session.add(qz) # adding courses course = Course(index='cz3003') db.session.add(course) db.session.commit()
def get(self): # Making sure that the user's profile information is fully filled in self.validate() # Normal users are restricted to only viewing published quizzes quizzes_query = Quiz.all() quizzes_query.filter("is_deleting =", False) if not self.is_admin: quizzes_query.filter("is_published =", True) self.values["quizzes"] = quizzes_query.fetch(20) # Any user can see their own scores attempts_query = Attempt.all() attempts_query.filter("user ="******"is_archived =", False) attempts_query.order("-created") self.values["attempts"] = attempts_query.fetch(3) self.output("home.html")
def setUp(self): print('\r') # drop all tables in the database db.session.remove() db.drop_all() # crete all tables in the database db.create_all() # addingusers user = User(email='*****@*****.**', encrypted_password=encrypt('password'), name='john_doe') staff = Staff(user) db.session.add(staff) # adding courses course = Course(index='cz3003') db.session.add(course) # adding quizzes quiz = Quiz( staff_id=1, name="Quiz Test", is_fast=True, date_start='2020-03-01', date_end='2020-03-31', ) db.session.add(quiz) # adding topics topic = Topic(name='seng') db.session.add(topic) # adding lessons lesson = Lesson(topic_id='1', id='3', name='se', content='test') db.session.add(lesson) # adding questions qn = Question('1', '3', 'easy') db.session.add(qn) db.session.commit()
def test_refresh_background_no_missing_quizzes(self, m): from views import refresh_background with self.client.session_transaction() as sess: sess['canvas_user_id'] = 1234 sess['lti_logged_in'] = True sess['is_admin'] = True course_id = 1 m.register_uri('GET', '/api/v1/courses/1', json={ 'id': 1, 'name': 'Example Course' }) m.register_uri('GET', '/api/v1/courses/1/quizzes', json=[{ 'id': 3, 'title': 'Quiz 3' }]) quiz = Quiz(3, course_id) views.db.session.add(quiz) views.db.session.commit() job = self.queue.enqueue_call(func=refresh_background, args=(course_id, )) self.worker.work(burst=True) self.assertTrue(job.is_finished) job_result = job.result meta_keys = ['status', 'status_msg', 'percent', 'error'] self.assertTrue(all(key in job_result for key in meta_keys)) self.assertEqual(job_result['status'], 'complete') self.assertEqual(job_result['status_msg'], 'Complete. No quizzes required updates.') self.assertEqual(job_result['percent'], 100) self.assertFalse(job_result['error'])
def fetch(self, id): from models import Quiz self.values['id'] = id self.quiz_entity = Quiz.get_by_id(int(id)) self.values['quiz'] = self.quiz_entity
def fetch_quiz(self, quiz_id): self.values['quiz_id'] = quiz_id self.quiz_entity = Quiz.get_by_id(int(quiz_id))