def judge_(self, grade=None, comment=None, corrected_source=None, annotations=None, **kwargs): self._judge_permissions() judgement_annotations = dict() if annotations: keyfunc = lambda d: d['line'] for k, g in groupby(sorted(annotations, key=keyfunc), key=keyfunc): judgement_annotations[k] = ', '.join((d['comment'] for d in g)) judgement_attrs = dict( grade=grade, comment=comment, corrected_source=corrected_source, annotations=judgement_annotations or None, ) if any((True for x in judgement_attrs.itervalues() if x is not None)): # Judgement is not empty judgement = self.submission.judgement or Judgement(submission=self.submission) judgement.tutor = request.user judgement.date = datetime.now() for k in judgement_attrs: setattr(judgement, k, judgement_attrs[k]) else: # Judgement is empty judgement = None self.submission.judgement = judgement try: DBSession.flush() except SQLAlchemyError: DBSession.rollback() log.warn('Submission %d, judgement could not be saved:', self.submission.id, exc_info=True) flash('Error saving judgement', 'error') redirect(self.submission.url + '/judge')
def submit(self, *args, **kwargs): '''Create new submission for this assignment''' if 'manage' not in request.permissions and \ request.user not in set(self.event.members) | set(self.event.tutorsandteachers): abort(403) if (not self.assignment.is_active and not request.allowance(self.assignment)): flash('This assignment is not active, you may not create a submission', 'warning') redirect(url(self.assignment.url)) submission = Submission( assignment=self.assignment, filename=self.assignment.submission_filename or None, source=self.assignment.submission_template or None, language=self.assignment.allowed_languages[0] if self.assignment.allowed_languages else None, user=request.user, created=datetime.now(), modified=datetime.now(), ) DBSession.add(submission) try: DBSession.flush() except SQLAlchemyError: DBSession.rollback() log.warn('Error creating new submission', exc_info=True) flash('Error creating new submission', 'error') redirect(url(self.assignment.url)) else: redirect(url(submission.url + '/edit'))
def submit(self, *args, **kwargs): '''Create new submission for this assignment''' if 'manage' not in request.permissions and \ request.user not in set(self.event.members) | set(self.event.tutorsandteachers): abort(403) if (not self.assignment.is_active and not request.allowance(self.assignment)): flash( 'This assignment is not active, you may not create a submission', 'warning') redirect(url(self.assignment.url)) submission = Submission( assignment=self.assignment, filename=self.assignment.submission_filename or None, source=self.assignment.submission_template or None, language=self.assignment.allowed_languages[0] if self.assignment.allowed_languages else None, user=request.user, created=datetime.now(), modified=datetime.now(), ) DBSession.add(submission) try: DBSession.flush() except SQLAlchemyError: DBSession.rollback() log.warn('Error creating new submission', exc_info=True) flash('Error creating new submission', 'error') redirect(url(self.assignment.url)) else: redirect(url(submission.url + '/edit'))
def edit_(self, language=None, source=None, filename=None, **kwargs): self._edit_permissions() log.info(dict(submission_id=self.submission.id, assignment_id=self.assignment.id, language=language, filename=filename, source=source)) #self.submission.assignment = self.assignment #if request.student: # self.submission.student = request.student if self.submission.language != language: self.submission.language = language if self.submission.source != source: self.submission.source = source if self.submission.filename != filename: self.submission.filename = filename if self.submission in DBSession.dirty: self.submission.modified = datetime.now() DBSession.add(self.submission) try: DBSession.flush() except SQLAlchemyError: DBSession.rollback() log.warn('Submission %d could not be saved', self.submission.id, exc_info=True) flash('Your submission could not be saved!', 'error') redirect(self.submission.url + '/edit') else: redirect(self.submission.url + '/result')
def index(self, *args, **kwargs): try: server = oauth2.Server() server.add_signature_method(oauth2.SignatureMethod_HMAC_SHA1()) req = oauth2.Request.from_request(request.method, request.url, request.headers, request.params, request.query_string) params = server.verify_request( req, oauth2.Consumer(self.key, self.secret), None) except: log.debug('LTI Tool Provider OAuth Error', exc_info=True) flash('LTI Tool Provider OAuth Error', 'error') abort(403) else: log.debug(params) user_name = ( params.get('tool_consumer_info_product_family_code', 'external') + '_' + params.get('tool_consumer_instance_guid', 'external') + '_' + params.get('user_id')) user = User.query.filter_by(user_name=user_name).first() if not user: log.info('New user %s', user_name) user = User( user_name=user_name, display_name=params.get('lis_person_name_full'), email_address=params.get('lis_person_contact_email_primary'), ) DBSession.add(user) submission = Submission.query.filter( Submission.assignment == self.assignment, Submission.user == user).first() if not submission: submission = Submission( assignment=self.assignment, filename=self.assignment.submission_filename or None, source=self.assignment.submission_template or None, language=self.assignment.allowed_languages[0], user=user, created=datetime.now(), modified=datetime.now(), ) DBSession.add(submission) DBSession.flush() session['lti'] = True session['params'] = params session['user'] = user.id session['submission'] = submission.id session.save() redirect('/lti/%d/edit' % self.assignment.id)
def index(self, *args, **kwargs): try: server = oauth2.Server() server.add_signature_method(oauth2.SignatureMethod_HMAC_SHA1()) req = oauth2.Request.from_request( request.method, request.url, request.headers, request.params, request.query_string ) params = server.verify_request(req, oauth2.Consumer(self.key, self.secret), None) except: log.debug("LTI Tool Provider OAuth Error", exc_info=True) flash("LTI Tool Provider OAuth Error", "error") abort(403) else: log.debug(params) user_name = ( params.get("tool_consumer_info_product_family_code", "external") + "_" + params.get("tool_consumer_instance_guid", "external") + "_" + params.get("user_id") ) user = User.query.filter_by(user_name=user_name).first() if not user: log.info("New user %s", user_name) user = User( user_name=user_name, display_name=params.get("lis_person_name_full"), email_address=params.get("lis_person_contact_email_primary"), ) DBSession.add(user) submission = Submission.query.filter(Submission.assignment == self.assignment, Submission.user == user).first() if not submission: submission = Submission( assignment=self.assignment, filename=self.assignment.submission_filename or None, source=self.assignment.submission_template or None, language=self.assignment.allowed_languages[0], user=user, created=datetime.now(), modified=datetime.now(), ) DBSession.add(submission) DBSession.flush() session["lti"] = True session["params"] = params session["user"] = user.id session["submission"] = submission.id session.save() redirect("/lti/%d/edit" % self.assignment.id)
def edit_(self, *args, **kwargs): self._get_session_data() v = SubmissionForm.validate(kwargs) language = v['language'] source = v['source'] filename = v['filename'] self.submission.assignment = self.assignment self.submission.user = self.user if self.submission.language != language: self.submission.language = language if self.submission.source != source: self.submission.source = source if self.submission.filename != filename: self.submission.filename = filename if self.submission in DBSession.dirty: self.submission.modified = datetime.now() DBSession.add(self.submission) try: DBSession.flush() except SQLAlchemyError: DBSession.rollback() log.warn('Submission %r could not be saved', self.submission, exc_info=True) flash('Your submission could not be saved!', 'error') redirect('./edit') else: # redirect(self.submission.url + '/result') pass (compilation, testruns, result) = self.submission.run_tests() testruns = sorted(set(self.submission.testruns), key=lambda s: s.date) result = self.submission.result if result is True: score = 1.0 else: if testruns: score = (float(len([t for t in testruns if t.result])) / float(len(testruns))) else: score = 0.0 send = self._send_result(score, str(result)) log.info(send) return dict(assignment=self.assignment, submission=self.submission, user=self.user, compilation=compilation, testruns=testruns, result=result, score=score)
def edit_(self, *args, **kwargs): self._get_session_data() v = SubmissionForm.validate(kwargs) language = v["language"] source = v["source"] filename = v["filename"] self.submission.assignment = self.assignment self.submission.user = self.user if self.submission.language != language: self.submission.language = language if self.submission.source != source: self.submission.source = source if self.submission.filename != filename: self.submission.filename = filename if self.submission in DBSession.dirty: self.submission.modified = datetime.now() DBSession.add(self.submission) try: DBSession.flush() except SQLAlchemyError: DBSession.rollback() log.warn("Submission %r could not be saved", self.submission, exc_info=True) flash("Your submission could not be saved!", "error") redirect("./edit") else: # redirect(self.submission.url + '/result') pass (compilation, testruns, result) = self.submission.run_tests() testruns = sorted(set(self.submission.testruns), key=lambda s: s.date) result = self.submission.result if result is True: score = 1.0 else: if testruns: score = float(len([t for t in testruns if t.result])) / float(len(testruns)) else: score = 0.0 send = self._send_result(score, str(result)) log.info(send) return dict( assignment=self.assignment, submission=self.submission, user=self.user, compilation=compilation, testruns=testruns, result=result, score=score, )
def run_tests(self): compilation = None testruns = [] result = False # Consistency checks if self.language and self.source and self.assignment: with Runner(self) as r: log.debug('Starting Runner for submission %d' % self.id) # First compile, if needed compilation = r.compile() if compilation: log.debug('Compilation runtime: %f' % compilation.runtime) log.debug('Compilation result: %s' % compilation.result) if not compilation or compilation.result: # Delete old testruns self.testruns = [] #DBSession.flush() # Then run all the tests testruns = [] start = time() for t in r.test(): testruns.append(t) self.testruns.append( Testrun( submission=self, test=t.test, result=t.result, partial=t.partial, runtime=t.runtime, output_data=t.output_data, error_data=t.error_data, )) end = time() test_time = end - start log.debug('Test runs total runtime: %f' % test_time) log.debug('Test runs results: %s' % ', '.join(str(t.result) for t in testruns)) try: DBSession.flush() except: log.exception('Could not save testrun results') raise result = self.result log.debug('Test runs result: %s ' % result) else: log.debug('Test runs not run') return (compilation, testruns, result)
def setUp(self): """Prepare model test fixture.""" try: new_attrs = {} new_attrs.update(self.attrs) new_attrs.update(self.do_get_dependencies()) self.obj = self.klass(**new_attrs) DBSession.add(self.obj) DBSession.flush() return self.obj except: DBSession.rollback() raise
def test_integration_2(self): test = Test( assignment_id=42, output_data=u'42 Bananas\n4711 Strawberrys\n1337 Apples\n', splitlines=True, sort=True, ) DBSession.add(test) DBSession.flush() test = DBSession.merge(test) d = u'#Result:\n4711 Strawberrys\n42 Bananas\n1337 Apples\n' result, _, expected, output, _ = test.validate(d) converted_output = test.unconvert(test.convert(d)) assert result is True, (expected, output, converted_output)
def run_tests(self): compilation = None testruns = [] result = False # Consistency checks if self.language and self.full_source and self.assignment: with Runner(self) as r: log.debug('Starting Runner for submission %r', self) # First compile, if needed compilation = r.compile() if compilation: log.debug('Compilation runtime: %f', compilation.runtime) log.debug('Compilation result: %s', compilation.result) if not compilation or compilation.result: # Delete old testruns self.testruns = [] #DBSession.flush() # Then run all the tests testruns = [] start = time() for t in r.test(): testruns.append(t) self.testruns.append( Testrun( submission=self, test=t.test, result=t.result, partial=t.partial, runtime=t.runtime, output_data=t.output_data, error_data=t.error_data, ) ) end = time() test_time = end - start log.debug('Test runs total runtime: %f', test_time) log.debug('Test runs results: %r', list(str(t.result) for t in testruns)) try: DBSession.flush() except: log.exception('Could not save testrun results') raise result = self.result log.debug('Test runs result: %s ', result) else: log.debug('Test runs not run') return (compilation, testruns, result)
def test_integration_1(self): test = Test( assignment_id=42, output_data=u'1.0,2.0,3.0\n4.0,5.0,6.0\n7.0,8.0,9.0\n', separator=',', split=True, splitlines=True, parse_float=True, float_precision=1, ) DBSession.add(test) DBSession.flush() test = DBSession.merge(test) d = u'#Result:\n1,2,3\n4,5,6\n,7,8,9\n' result, _, expected, output, _ = test.validate(d) converted_output = test.unconvert(test.convert(d)) assert result is True, (expected, output, converted_output)
def _test_attr(args): kwargs, expected_output_data, good_output_data = args[0:3] bad_output_data = args[4:] test = Test(assignment_id=42, output_data=expected_output_data, **kwargs) DBSession.add(test) DBSession.flush() test = DBSession.merge(test) for d in good_output_data: result, _, expected, output, _ = test.validate(d) converted_output = test.unconvert(test.convert(d)) assert result is True, (expected, output, converted_output) for d in bad_output_data: result, _, expected, output, _ = test.validate(d) converted_output = test.unconvert(test.convert(d)) assert result is False, (expected, output, converted_output)
def post(self, *args, **kwargs): '''Process form data into user profile''' if config.features.get('externalauth', False): # pragma: no cover flash( 'Profile changes are not possible because external authentication is used!', 'error') redirect(url('/user/profile')) user = DBSession.merge(request.user) # try: # d = User.query.filter_by(email_address=kwargs['email_address']).one() # except: # pass # else: # if d.user_name != request.user.user_name: # flash('The email address "%s" is already registered!' % (kwargs['email_address']), 'error') # redirect(url('/user/profile')) try: user._display_name = kwargs.get('display_name', '') # user.first_name = kwargs['first_name'] # user.last_name = kwargs['last_name'] user.email_address = kwargs.get('email_address', '') # Only attempt to change password if both values are set if (kwargs.get('password_1', None) and kwargs.get( 'password_1', None) == kwargs.get('password_2', None)): user.password = kwargs.get('password_1', '') DBSession.flush() except SQLAlchemyError: DBSession.rollback() log.warning('Error modifying profile of User %r', user, exc_info=True) flash('Error modifying profile', 'error') except: log.warning('Error modifying profile of User %r', user, exc_info=True) flash('Error modifying profile', 'error') else: flash('Profile modified', 'ok') finally: redirect(url('/user/profile'))
def submit(self): '''Create new submission for this assignment''' if not self.assignment.is_active and \ not request.allowance(self.assignment): flash('This assignment is not active, you may not create a submission', 'warning') redirect(url(self.assignment.url)) submission = Submission(assignment=self.assignment, user=request.user, created=datetime.now()) DBSession.add(submission) try: DBSession.flush() except SQLAlchemyError: DBSession.rollback() log.warn('Error creating new submission', exc_info=True) flash('Error creating new submission', 'error') redirect(url(self.assignment.url)) else: redirect(url(submission.url + '/edit'))
def public(self, target=None, *args, **kwargs): self._edit_permissions() if target is not None: # Set target = asbool(target) else: # Toggle target = not self.submission.public self.submission.public = target _url = getattr(request, 'referer', None) or self.submission.url try: DBSession.flush() except SQLAlchemyError: DBSession.rollback() log.warn('Submission %r, could not change publicity status to %s', self.submission, target, exc_info=True) flash('Error changing publicity status to %s' % ('public' if target else 'private'), 'error') finally: flash('Changed publicity status to %s' % ('public' if target else 'private'), 'ok') redirect(_url)
def clone(self): s = Submission( user=request.user, assignment=self.submission.assignment, filename=self.submission.filename, source=self.submission.source, language=self.submission.language, ) DBSession.add(s) try: DBSession.flush() except SQLAlchemyError: DBSession.rollback() flash('Error cloning submission', 'error') redirect(url(self.submission.url + '/show')) finally: s = DBSession.merge(s) flash('Cloned submission %d from %d' % (s.id, self.submission.id), 'ok') redirect(url(s.url + '/show'))
def judge_(self, grade=None, comment=None, corrected_source=None, annotations=None, public=None, *args, **kwargs): self._judge_permissions() judgement_annotations = None if annotations: key = lambda d: d['line'] judgement_annotations = dict( (k, ', '.join((d['comment'] for d in g if d['comment']))) for k, g in groupby(sorted(annotations, key=key), key=key) ) judgement_attrs = dict( grade=grade, comment=comment, corrected_source=corrected_source, annotations=judgement_annotations or None, public=public, ) if any((True for x in judgement_attrs.itervalues() if x is not None)): # Judgement is not empty judgement = self.submission.judgement or Judgement(submission=self.submission) judgement.tutor = request.user judgement.date = datetime.now() for k in judgement_attrs: setattr(judgement, k, judgement_attrs[k]) else: # Judgement is empty judgement = None self.submission.judgement = judgement try: DBSession.flush() except SQLAlchemyError: DBSession.rollback() log.warn('Submission %r, judgement could not be saved:', self.submission, exc_info=True) flash('Error saving judgement', 'error') redirect(self.submission.url + '/judge')
def clone(self, *args, **kwargs): s = Submission( user=request.user, assignment=self.submission.assignment, filename=self.submission.filename, source=self.submission.source, language=self.submission.language, # TODO: Clone comment or not? ) DBSession.add(s) try: DBSession.flush() except SQLAlchemyError: DBSession.rollback() flash('Error cloning submission', 'error') redirect(url(self.submission.url + '/show')) finally: s = DBSession.merge(s) flash('Cloned submission %d from %d' % (s.id, self.submission.id), 'ok') redirect(url(s.url + '/show'))
def post(self, *args, **kwargs): '''Process form data into user profile''' if config.features.get('externalauth', False): # pragma: no cover flash('Profile changes are not possible because external authentication is used!', 'error') redirect(url('/user/profile')) user = DBSession.merge(request.user) # try: # d = User.query.filter_by(email_address=kwargs['email_address']).one() # except: # pass # else: # if d.user_name != request.user.user_name: # flash('The email address "%s" is already registered!' % (kwargs['email_address']), 'error') # redirect(url('/user/profile')) try: user._display_name = kwargs.get('display_name', '') # user.first_name = kwargs['first_name'] # user.last_name = kwargs['last_name'] user.email_address = kwargs.get('email_address', '') # Only attempt to change password if both values are set if (kwargs.get('password_1', None) and kwargs.get('password_1', None) == kwargs.get('password_2', None)): user.password = kwargs.get('password_1', '') DBSession.flush() except SQLAlchemyError: DBSession.rollback() log.warning('Error modifying profile of User %r', user, exc_info=True) flash('Error modifying profile', 'error') except: log.warning('Error modifying profile of User %r', user, exc_info=True) flash('Error modifying profile', 'error') else: flash('Profile modified', 'ok') finally: redirect(url('/user/profile'))
def submit(self): '''Create new submission for this assignment''' if not self.assignment.is_active and \ not request.allowance(self.assignment): flash( 'This assignment is not active, you may not create a submission', 'warning') redirect(url(self.assignment.url)) submission = Submission(assignment=self.assignment, user=request.user, created=datetime.now()) DBSession.add(submission) try: DBSession.flush() except SQLAlchemyError: DBSession.rollback() log.warn('Error creating new submission', exc_info=True) flash('Error creating new submission', 'error') redirect(url(self.assignment.url)) else: redirect(url(submission.url + '/edit'))
def delete(self, *args, **kwargs): subm_id = self.submission.id subm_url = self.submission.url try: if (getattr(request, 'user', None) == self.submission.user or request.allowance(self.submission)): DBSession.delete(self.submission) DBSession.flush() else: #abort(403) flash('You have no permission to delete this Submission', 'warning') redirect(url(self.submission.url + '/show')) except SQLAlchemyError: DBSession.rollback() log.warn('Submission %r could not be deleted', self.submission, exc_info=True) flash('Submission could not be deleted', 'error') redirect(url(self.submission.url + '/show')) else: flash('Submission %d deleted' % (subm_id), 'ok') if request.referer and not subm_url in request.referer: # Most likely coming from the submission overview page redirect(request.referer) else: redirect(url(self.assignment.url))
def delete(self): subm_id = self.submission.id subm_url = self.submission.url try: if (getattr(request, 'user', None) == self.submission.user or request.allowance(self.submission)): DBSession.delete(self.submission) DBSession.flush() else: #abort(403) flash('You have no permission to delete this Submission', 'warning') redirect(url(self.submission.url + '/show')) except SQLAlchemyError: DBSession.rollback() log.warn('Submission %d could not be deleted', self.submission.id, exc_info=True) flash('Submission could not be deleted', 'error') redirect(url(self.submission.url + '/show')) else: flash('Submission %d deleted' % (subm_id), 'ok') if request.referer and not subm_url in request.referer: # Most likely coming from the submission overview page redirect(request.referer) else: redirect(url(self.assignment.url))
def edit_(self, language=None, source=None, filename=None, comment=None, *args, **kwargs): self._edit_permissions() log.debug(dict(submission_id=self.submission.id, assignment_id=self.assignment.id, language=language, filename=filename, source=source)) #self.submission.assignment = self.assignment #if request.student: # self.submission.student = request.student if self.submission.language != language: self.submission.language = language if self.submission.source != source: self.submission.source = source if self.submission.filename != filename: self.submission.filename = filename # TODO: Only changing the comment should not trigger re-testing, but it does. if self.submission.comment != comment: self.submission.comment = comment if self.submission in DBSession.dirty: self.submission.modified = datetime.now() if self.submission in DBSession.dirty: DBSession.add(self.submission) try: DBSession.flush() except SQLAlchemyError: DBSession.rollback() log.warn('Submission %r could not be saved', self.submission, exc_info=True) flash('Your submission could not be saved!', 'error') redirect(self.submission.url + '/edit') else: redirect(self.submission.url + '/result')
def setup(): """Function called by nose on module load""" setup_db() DBSession.add( User(id=4771, user_name='dummy', email_address='*****@*****.**')) DBSession.flush()
def enroll(self, password=None, lesson=None, team=None, *args, **kwargs): '''Event enrolling page''' params = {} if not self.event.enroll: flash('Enroll not allowed', 'error') return HTTPForbidden() if self.event.password and password != self.event.password: if password: flash('Wrong password', 'error') c.text = u'Please enter the password to enroll for this event:' c.form = PasswordEnrollForm else: if password: params['password'] = password if self.event.enroll == 'event': try: self.event._members.append(request.user) DBSession.flush() except SQLAlchemyError: log.warn('Error while enrolling user %r for event %r:', request.user, self.event, exc_info=True) flash('An error occured', 'error') else: flash('Enrolled for Event "%s"' % self.event.name, 'ok') redirect(self.event.url) if self.event.enroll in ('lesson_team', 'team', 'team_new') and team: if self.event.enroll == 'team_new' and team == '__new__': try: lesson = Lesson.query.get(int(lesson)) except ValueError: lesson = team = None else: # Get unique team name q = Team.query.filter_by(lesson=lesson) i = q.count() + 1 while True: name = 'New Team %d' % i t = q.filter_by(name=name).first() if not t: break i = i + 1 team = Team(lesson=lesson, name=name) DBSession.add(team) else: try: team = Team.query.get(int(team)) except ValueError: team = None if team: try: team.members.append(request.user) DBSession.flush() except SQLAlchemyError: log.warn('Error while enrolling user %r for team %r:', request.user, team, exc_info=True) flash('An error occured', 'error') lesson = lesson.id else: flash('Enrolled for Team "%s" in Lesson "%s" in Event "%s"' % (team.name, team.lesson.name, self.event.name), 'ok') redirect(self.event.url) else: flash('Selected Team does not exist', 'error') if self.event.enroll in ('lesson', 'lesson_team', 'team', 'team_new') and not lesson: c.text = u'Please select the lesson you would like to attend:' c.form = LessonSelectionForm(event=self.event, action=url('', params)) if self.event.enroll == 'lesson' and lesson: try: lesson = Lesson.query.get(int(lesson)) except ValueError: lesson = None if lesson: try: lesson._members.append(request.user) DBSession.flush() except SQLAlchemyError: log.warn('Error while enrolling user %r for lesson %r:', request.user, lesson, exc_info=True) flash('An error occured', 'error') else: flash('Enrolled for Lesson "%s" in Event "%s"' % (lesson.name, self.event.name), 'ok') redirect(self.event.url) else: flash('Selected Lesson does not exist', 'error') if self.event.enroll in ('lesson_team', 'team', 'team_new') and lesson: try: lesson = Lesson.query.get(int(lesson)) except ValueError: lesson = None else: params['lesson'] = lesson.id c.text = u'Please select the team in which you would like to work:' c.form = TeamSelectionForm( lesson=lesson, new=bool(self.event.enroll == 'team_new'), action=url('', params), ) return dict(page='events', heading=u'Enroll for %s' % self.event.name)
def setup(): """Function called by nose on module load""" setup_db() DBSession.add(User(id=4771, user_name='dummy', email_address='*****@*****.**')) DBSession.flush()
def setup(): """Function called by nose on module load""" setup_db() assignment = Assignment(id=42, name='Dummy', assignment_id=42) DBSession.add(assignment) DBSession.flush()