def reports(): """Generate reports.""" from app import mail from flask_mail import Message from app.models import User, Survey user = User() survey = Survey() msg = Message("MS-Registry Reports", recipients=app.config['MAIL_RECIPIENTS']) user_report_filename = user.getCSVReportInformedConsent() with app.open_resource( os.path.join(app.config['REPORTS_DIR'], user_report_filename)) as fp: msg.attach(user_report_filename, "text/csv", fp.read()) survey_report_filename = survey.getCSVReportTagsAndOngoing() with app.open_resource( os.path.join(app.config['REPORTS_DIR'], survey_report_filename)) as fp: msg.attach(survey_report_filename, "text/csv", fp.read()) mail.send(msg)
def test_import_export(self): u = User(nickname = 'john', email = '*****@*****.**', role = ROLE_RESEARCHER) db.session.add(u) survey = Survey(title = "test",researcher = u) db.session.add(survey) consent = Consent(text="a", survey=survey) db.session.add(consent) s1 = Section (title = "1",description = "a", sequence = 1, percent = 1, survey = survey) db.session.add(s1) s11 = Section (title = "11", description = "a", sequence = 1, percent = 0.5, parent = s1) db.session.add(s11) s12 = Section (title = "12", description = "a", sequence = 1, percent = 0.5, parent = s1) db.session.add(s12) s111 = Section (title = "111", description = "a", sequence = 1, parent = s11) db.session.add(s111) s112 = Section (title = "112", description = "a", sequence = 2, parent = s11) db.session.add(s112) q1 = QuestionText(text="q1",section=s1) db.session.add(q1) q2 = QuestionChoice(text="q2",section=s11,range_min=1,range_max=10) db.session.add(q2) l=["thing1","thing2","thing3"] q3 = QuestionChoice(text="q3",section=s11,choices =l) db.session.add(q3) condition=Condition(operation="==",value="0") db.session.add(condition) q4 = QuestionYN(text="q4", section=s11, condition=condition, parent = q3) db.session.add(q4) q5 = QuestionLikertScale(text="q5",minLikert =1,maxLikert=7, labelMin="min",labelMax="max", section=s112) db.session.add(q5) db.session.commit() xml = survey.to_xml() tf = tempfile.NamedTemporaryFile() xml.write(tf.name,encoding="ISO-8859-1", method="xml") msg,s = Survey.from_xml(tf.name,u) self.assertTrue(s.title == survey.title) self.assertTrue(s.consents.first().text == survey.consents.first().text) j = Section.query.filter(Section.title=="1",Section.root==s).first() self.assertTrue(j.percent==s1.percent) j = Section.query.filter(Section.title=="112",Section.root==s).first() self.assertTrue(j.sequence==s112.sequence) q = Question.query.filter(Question.text=="q3", Question.section_id==Section.id,Section.root==s).first() self.assertTrue(len(q.choices)==3) q = Question.query.filter(Question.text=="q4", Question.section_id==Section.id,Section.root==s).first() self.assertTrue(q.isSubquestion) self.assertFalse(q.isExpectedAnswer()) self.assertTrue(q.section.title==q4.section.title)
def add_survey(): form = SurveyForm() form.event.query_factory = event_query if form.validate_on_submit(): value_average = (form.value_1.data + form.value_2.data + form.value_3.data + form.value_4.data + form.value_5.data) / 5 speaker_average = (form.speaker_1.data + form.speaker_2.data + form.speaker_3.data) / 3 content_average = (form.content_1.data + form.content_2.data) / 2 facility_average = (form.facility_1.data + form.facility_2.data) / 2 overall_average = (value_average + speaker_average + content_average + facility_average) / 4 survey = Survey(value_1=form.value_1.data, value_2=form.value_2.data, value_3=form.value_3.data, value_4=form.value_4.data, value_5=form.value_5.data, value_average=value_average, speaker_1=form.speaker_1.data, speaker_2=form.speaker_2.data, speaker_3=form.speaker_3.data, speaker_average=speaker_average, content_1=form.content_1.data, content_2=form.content_2.data, content_average=content_average, facility_1=form.facility_1.data, facility_2=form.facility_2.data, facility_average=facility_average, response_1=form.response_1.data, response_2=form.response_2.data, response_3=form.response_3.data, response_4=form.response_4.data, name=form.name.data, email=form.email.data, overall_average=overall_average ) db.session.add(survey) db.session.commit() survey.event = form.event.data db.session.commit() for speaker in survey.event.speakers: update_speaker(speaker) update_event(survey.event) flash("Survey Saved.") return redirect(url_for('index')) return render_template('add_survey.html', title='Add Survey', form=form)
def addSurvey(): form = addSurveyForm() if form.validate_on_submit(): survey = Survey( title=form.title.data, description=form.describe.data, content_origin=form.content.data, dimension=form.dimension.data, uptime=datetime.now(), author=current_user ) if current_user.is_administrator(): survey.status = SurveyStatus.PUB survey_origin = SurveyMeta( meta_key='survey_origin', meta_value=form.content.data, author_id=current_user.id, survey=survey ) db.session.add(survey) db.session.add(survey_origin) db.session.add(Distribute(owner=current_user, survey=survey, type=OwnerType.OWNER)) db.session.commit() flash(u'操作成功') return redirect(url_for('manage.listSurvey')) return render_template('manage/add_survey.html', form=form, pagetitle=u'添加问卷', surveyManage='active' )
def get_all_users(): """ Get all users """ from app.models import User, Survey user = User() survey = Survey() all_users = user.getAll() all_surveys = survey.getAll() print("Found {0} users".format(len(all_users))) print("Found {0} surveys".format(len(all_surveys)))
def test_addByUniqueID(self): u = User() self.assertTrue(u.createIfNotExistsByUniqueID(self.uniqueID)) s = Survey() self.assertTrue( s.addByUniqueID(self.uniqueID, { 'survey': { 'value': 'any' }, 'tags': ['tag'], 'ongoing': True }))
def create_survey(): req_data = request.get_json() new_survey = Survey(title=req_data['title']) db.session.add(new_survey) for question_data in req_data.get('questions', []): question = Question(survey=new_survey, text=question_data['text']) db.session.add(question) db.session.commit() return jsonify(new_survey.as_dict())
def test_find_questions(self): u = User(nickname="john", email="*****@*****.**", role=ROLE_RESEARCHER) db.session.add(u) db.session.commit() base = os.path.abspath(os.path.dirname(__file__)) name = "como_son_nuestros_voluntarios_only_games.xml" msg, s = Survey.from_xml(os.path.join(base, name), u) game = Games(s.id) self.assertIsNotNone(game.select_game["part2", True]) self.assertIsNotNone(game.select_game["part2", False]) self.assertIsNotNone(game.select_game["decision1_v1", True]) self.assertIsNotNone(game.select_game["decision1_v1", False]) self.assertIsNotNone(game.select_game["decision2", True]) self.assertIsNotNone(game.select_game["decision2", False]) self.assertIsNotNone(game.select_game["decision3", True]) self.assertIsNotNone(game.select_game["decision3", False]) self.assertIsNotNone(game.select_game["decision4", True]) self.assertIsNotNone(game.select_game["decision4", False]) self.assertIsNotNone(game.select_game["decision5", True]) self.assertIsNotNone(game.select_game["decision5", False]) self.assertIsNotNone(game.select_game["decision6", True]) self.assertIsNotNone(game.select_game["decision6", False]) qs = Question.query.filter(Question.decision == "decision_two") for q in qs: db.session.delete(q) db.session.commit() game = Games(s.id) self.assertIsNone(game.select_game["decision2", True]) self.assertIsNone(game.select_game["decision2", False])
def new(): form = SurveyForm() if form.validate_on_submit(): # file = request.files['file'] # if file: filename = secure_filename(form.surveyXml.data.filename) if filename: tf = tempfile.NamedTemporaryFile() form.surveyXml.data.save(tf.name) msg, survey = Survey.from_xml(tf.name, g.user) tf.close() for m in msg: flash(m) return redirect(url_for('researcher.index')) else: survey = Survey( title = form.title.data, description = form.description.data, endDate = form.endDate.data, startDate = None, maxNumberRespondents = form.maxNumberRespondents.data, duration = form.duration.data, researcher = g.user) db.session.add(survey) db.session.commit() flash('Your survey have been saved.') return redirect(url_for('researcher.editSurvey',id_survey = survey.id)) return render_template('/researcher/new.html', title = 'New survey', form = form)
def InsertData(request): if request.method == 'POST': Survey( #rnum = len(list(Survey.objects.all().values())) + 1, #자동증가 칼럼이 아닌 경우 gender=request.POST.get('gender'), age=request.POST.get('age'), co_survey=request.POST.get('co_survey'), ).save()
def add_survey(data): form = AddSurveyForm() if form.validate_on_submit(): try: s = Survey(name=form.name.data, survey_id=form.survey_id.data) db.session.add(s) db.session.commit() except IntegrityError: flash('Survey already registered') return redirect(url_for('survey'))
def test_delete_user(test_client, test_db): admin_user = User.query.filter_by(username='******').first() user_to_delete = User.query.filter_by(username='******').first() user_to_delete_id = user_to_delete.id # add a survey survey = Survey(name='test survey', structure={}, created_by=user_to_delete, updated_by=user_to_delete) test_db.session.add(survey) test_db.session.commit() # posts some responses survey_response = SurveyResponse(survey_id=survey.id, structure={}, created_by=user_to_delete, updated_by=user_to_delete) test_db.session.add(survey_response) survey_response2 = SurveyResponse(survey_id=survey.id, structure={}, created_by=user_to_delete, updated_by=user_to_delete) test_db.session.add(survey_response2) test_db.session.commit() # add a case definition case_definition = CaseDefinition(name="Test Case Definition", key='TCD', created_by=user_to_delete, updated_by=user_to_delete) test_db.session.add(case_definition) test_db.session.commit() access_token = create_access_token(identity=admin_user.id) response = test_client.delete(f"/users/{user_to_delete.id}", headers={ 'Content-Type': 'application/json', 'Authorization': f"Bearer {access_token}" }) assert response.status_code == 200 # assert all references to user are now admin assert survey.created_by.id == admin_user.id assert survey.updated_by.id == admin_user.id assert survey_response.created_by.id == admin_user.id assert survey_response.updated_by.id == admin_user.id assert survey_response2.created_by.id == admin_user.id assert survey_response2.updated_by.id == admin_user.id assert case_definition.created_by.id == admin_user.id assert case_definition.updated_by.id == admin_user.id # assert user is deleted assert len(User.query.filter_by(username='******').all()) == 0
def reports(): """Generate reports.""" from app import mail from flask_mail import Message from app.models import User, Survey user = User() survey = Survey() msg = Message("MS-Registry Reports", recipients=app.config['MAIL_RECIPIENTS']) user_report_filename = user.getCSVReportInformedConsent() with app.open_resource(os.path.join(app.config['REPORTS_DIR'] , user_report_filename)) as fp: msg.attach(user_report_filename, "text/csv", fp.read()) survey_report_filename = survey.getCSVReportTagsAndOngoing() with app.open_resource(os.path.join(app.config['REPORTS_DIR'] , survey_report_filename)) as fp: msg.attach(survey_report_filename, "text/csv", fp.read()) mail.send(msg)
def test_insert(self): print('') print('Creating an admin user...') role = Role.get_by_name('admin') self.assertTrue(role is not None) user = User(username='******', role=role, password='******') print('Admin user successfully created.') print('\x1b[0;32;40m' + 'pass' + '\x1b[0m') print('Adding and committing an admin user into the database...') db.session.add(user) db.session.commit() self.assertTrue( User.query.filter_by(username='******').first() is not None) print('Admin user successfully added and committed into the database.') print('\x1b[0;32;40m' + 'pass' + '\x1b[0m') print('Creating a course...') c = Course(course_code='TEST') print('Course successfully created.') print('\x1b[0;32;40m' + 'pass' + '\x1b[0m') print('Trying to add and commit course into database...') db.session.add(c) db.session.commit() self.assertTrue( Course.query.filter_by(course_code='TEST').first() is not None) print('Course successfully added and committed into database.') print('\x1b[0;32;40m' + 'pass' + '\x1b[0m') print('Creating a survey...') survey = Survey.create(description='blah test', times=['1', '2'], owner_id=user.id, course=c.course_code) self.assertTrue( Survey.query.filter_by( description='blah test').first() is not None) print('Survey successfully created.') print('\x1b[0;32;40m' + 'pass' + '\x1b[0m') print('Creating a question for the survey...') question = Question.create(description="a test question", owner_id=user.id, optional=False, q_type=1) self.assertTrue(question is not None) print('Question successfully created.') print('\x1b[0;32;40m' + 'pass' + '\x1b[0m') print('Assigning question to survey...') survey.set_questions([question.id]) self.assertTrue(survey.questions.all() is not None) print('Question successfully assigned.') print('\x1b[0;32;40m' + 'pass' + '\x1b[0m') print('')
def survey(): visit = User.query.filter_by(username=current_user.username).first() visit.surveyVisted = 1 form = SurveyForm() if form.validate_on_submit(): option = Survey(major=form.major.data, outdoor=form.outdoor.data, indoor=form.indoor.data, question = form.question.data, answer = form.answer.data, user_id=current_user.id) db.session.add(option) db.session.commit() return redirect(url_for('user', username=current_user.username)) return render_template('Survey.html', form=form, title="Survey")
def test_matching(self): import utiles u = User(nickname="john", email="*****@*****.**", role=ROLE_RESEARCHER) db.session.add(u) db.session.commit() base = os.path.abspath(os.path.dirname(__file__)) name = "como_son_nuestros_voluntarios_only_games.xml" msg, s = Survey.from_xml(os.path.join(base, name), u) game = Games(s.id) s.endDate = s.endDate + datetime.timedelta(1, 0) db.session.add(s) db.session.commit() n1 = 40 utiles.generate_answers_fake(s.id, n1) game.match() users = StateSurvey.query.filter( StateSurvey.survey_id == s.id, StateSurvey.status.op("&")(StateSurvey.FINISH_OK), StateSurvey.status.op("&")(StateSurvey.PART2_MONEY) == 0, StateSurvey.status.op("&")(StateSurvey.PART2_NO_MONEY) == 0, ) for u in users: game.part2(u.user) game.raffle(u.user) self.assertEqual(n1, len(GameImpatience.query.all())) n2 = 1 utiles.generate_answers_fake(s.id, n2) game.match() users = StateSurvey.query.filter( StateSurvey.survey_id == s.id, StateSurvey.status.op("&")(StateSurvey.FINISH_OK), StateSurvey.status.op("&")(StateSurvey.PART2_MONEY) == 0, StateSurvey.status.op("&")(StateSurvey.PART2_NO_MONEY) == 0, ) for u in users: game.part2(u.user) game.raffle(u.user) self.assertEqual(n1 + n2, len(GameImpatience.query.all()))
def test_new_survey(): survey = Survey(name='hiren raj') assert survey.name == 'hiren raj'
def test_post_valid_case_definition(test_client, test_db): num_definitions_before = test_db.session.query(CaseDefinition).count() user = User.query.filter_by(username='******').first() survey = Survey(name='Test Survey', reporting_table_name='test_survey', structure={ "pages": [{ "name": "page1", "elements": [{ "type": "text", "name": "question1" }] }], "title": "Test Survey" }, created_by=user, updated_by=user) test_db.session.add(survey) test_db.session.commit() survey_id = survey.id case_definition = { "name": "Test Case Definition 6", "key": "TCD1", "description": "This is a description of the test case definition 6", "surveys": [survey_id], "documents": [{ "name": "Birth Certificate", "description": "blash blah", "is_required": True }, { "name": "Document 2", "description": "blash blah", "is_required": False }], "custom_fields": [{ "name": "Household Long Text", "field_type": "textarea", "selections": None, "validation_rules": None, "custom_section_id": None, "help_text": "This is for longer answers", "sort_order": 1 }, { "name": "Household Selection Field", "field_type": "select", "selections": [{ "id": "1", "value": "Household Selection Option A" }, { "id": "2", "value": "Household Selection Option B" }, { "id": "3", "value": "Household Selection Option C" }], "validation_rules": None, "custom_section_id": None, "help_text": "This is for a single selection among many", "sort_order": 2 }] } access_token = create_access_token(identity=user.id) response = test_client.post("/case_definitions/", data=json.dumps(case_definition), headers={ 'Content-Type': 'application/json', 'Authorization': f"Bearer {access_token}" }) assert response.status_code == 200 assert (num_definitions_before + 1) == test_db.session.query(CaseDefinition).count() json_data = response.get_json() assert json_data['id'] assert len(json_data['surveys']) == 1 assert len(json_data['documents']) == 2 assert len(json_data['custom_fields']) == 2 cd = CaseDefinition.query.get(json_data['id']) assert cd assert len(cd.surveys.all()) == 1 assert len(cd.documents) == 2 assert len(cd.custom_fields) == 2
def test_survey_can_delete(): survey = Survey(name='Hiren Raj') with pytest.raises(Exception): survey.can_delete()
def survey(survey_id=None): return Survey.get_delete_put_post(survey_id)
def test_survey_verify(): survey = Survey(name='') with pytest.raises(Exception): survey.verify(survey)
def test_survey_repr(): survey = repr(Survey(name='Test')) assert survey == '<name : Test>'
def test_core_database_functionality(self): # admin_create_survey print('') print('Creating an administrator user...') role = Role.get_by_name('admin') self.assertTrue(role is not None) user = User(username='******', role=role, password='******') print('Adding and commiting data to database...') db.session.add(user) db.session.commit() self.assertTrue(User.query.filter_by( username='******').first() is not None) print('Successfully added and committed data to database.') print('Administrator user successfully created.') print('\x1b[0;32;40m' + 'pass' + '\x1b[0m') print('Creating course...') c = Course(course_code='TEST') print('Adding and commiting data to database...') db.session.add(c) db.session.commit() self.assertTrue(Course.query.filter_by( course_code='TEST').first() is not None) print('Successfully added and committed data to database.') print('\x1b[0;32;40m' + 'pass' + '\x1b[0m') print('Creating a survey with the course code...') survey = Survey.create(description='blah test', times=['1', '2'], owner_id=user.id, course=c.course_code) self.assertTrue(Survey.query.filter_by(description='blah test') .first() is not None) self.assertTrue(Survey.query.filter_by(description='blah test') .first().status == 'review') print('Survey successfully created with the course code.') print('\x1b[0;32;40m' + 'pass' + '\x1b[0m') print('Creating questions for survey...') question1 = Question.create( description="a test question1", owner_id=user.id, optional=False, q_type=2) question2 = Question.create( description="a test question2", owner_id=user.id, optional=True, q_type=2) self.assertTrue(question1 is not None) self.assertTrue(question2 is not None) print('Successfully created questions.') print('\x1b[0;32;40m' + 'pass' + '\x1b[0m') print('Setting questions to survey...') survey.set_questions([question1.id, question2.id]) self.assertTrue(survey.questions.all() is not None) print('Successfully assigned questions to survey.') print('\x1b[0;32;40m' + 'pass' + '\x1b[0m') # staff_review_survey print('Creating staff user...') role = Role.get_by_name('staff') self.assertTrue(role is not None) user = User(username='******', role=role, password='******') print('Adding and commiting data to database...') db.session.add(user) db.session.commit() self.assertTrue(User.query.filter_by(username='******') .first() is not None) survey = Survey.query.filter_by(description='blah test').first() self.assertTrue(survey is not None) self.assertTrue(survey.status == 'review') print('Successfully added and committed data to database.') print('\x1b[0;32;40m' + 'pass' + '\x1b[0m') print('Setting survey phase to open...') survey.status = 'open' self.assertTrue(survey.status == 'open') db.session.add(survey) db.session.commit() print('Successfully set survey phase to open and made changes to database.') print('\x1b[0;32;40m' + 'pass' + '\x1b[0m') # student_answer_survey print('Creating a student user...') role = Role.get_by_name('student') self.assertTrue(role is not None) user = User(username='******', role=role, password='******') db.session.add(user) db.session.commit() print('Successfully created student user.') print('\x1b[0;32;40m' + 'pass' + '\x1b[0m') print('Creating a survey...') survey = Survey.query.filter_by(description='blah test').first() self.assertTrue(survey is not None) self.assertTrue(survey.status == 'open') print('Successfully created a survey.') print('\x1b[0;32;40m' + 'pass' + '\x1b[0m') print('Creating answers for the survey...') a = Answer.create(survey_id=survey.id, owner_id=user.id) self.assertTrue(a is not None) self.assertTrue(a.survey_id == survey.id) self.assertTrue(a.owner_id == user.id) for question in survey.questions.all(): ae = AnswerEntity.create(answer_id=a.id, question_id=question.id, answer_content='blah' ) self.assertTrue(ae is not None) self.assertTrue(ae.question_id == question.id) self.assertTrue(ae.answer_id == a.id) print('Successfully created answers for the survey.') print('\x1b[0;32;40m' + 'pass' + '\x1b[0m') # admin_close_survey print('Creating an administrator user...') user = User.query.filter_by(username='******').first() self.assertTrue(user is not None) print('Administrator user successfully created.') print('\x1b[0;32;40m' + 'pass' + '\x1b[0m') print('Creating a survey...') survey = Survey.query.filter_by(description='blah test').first() self.assertTrue(survey is not None) print('Survey successfully created.') print('\x1b[0;32;40m' + 'pass' + '\x1b[0m') print('Setting survey phase to closed...') survey.status = 'closed' db.session.add(survey) db.session.commit() self.assertTrue(survey.status == 'closed') print('Successfully set survey to closed.') print('\x1b[0;32;40m' + 'pass' + '\x1b[0m') print('')
def test_addByUniqueID(self): u = User() self.assertTrue(u.createIfNotExistsByUniqueID(self.uniqueID)) s = Survey() self.assertTrue(s.addByUniqueID(self.uniqueID, {'survey': {'value': 'any'}, 'tags': ['tag'], 'ongoing': True}))