Esempio n. 1
0
    def mark_complete(cls,
                      name,
                      chapter,
                      current_roles=None,
                      user=None,
                      obj=None):
        extra = {}
        if current_roles:
            extra = {"owner__in": current_roles}
        task = Task.objects.filter(name=name, **extra).first()
        if not task:
            return
        next_date = task.incomplete_dates_for_task_chapter(chapter).first()
        if not next_date:
            return
        task_obj = TaskChapter(task=next_date,
                               chapter=chapter,
                               date=timezone.now())
        if obj:
            from submissions.models import Submission

            extra_info = None
            create_submission = True
            submit_obj = obj
            if name == "Audit":
                score_type = ScoreType.objects.filter(slug="audit").first()
                file = f"forms:audit_complete {obj.pk}"
                submit_name = f"Audit by {task.owner}"
            elif name == "Pledge Program":
                score_type = ScoreType.objects.filter(
                    slug="pledge-program").first()
                file = "forms:pledge_program"
                submit_name = "Pledge program"
                extra_info = {"unmodified": obj.manual != "other"}
            elif name == "Outstanding Student Member":
                score_type = ScoreType.objects.filter(slug="osm").first()
                file = "osmform"
                submit_name = "Outstanding Student Member"
            else:
                # Chapter Report, Credentials, Premature Alumnus, Risk Management Form
                # Gear Article, Lock-in, Newsletter for Alumni, Initiation Report,
                # Member Updates
                create_submission = False
            if create_submission:
                submit_obj = Submission(
                    user=user,
                    file=file,
                    name=submit_name,
                    type=score_type,
                    chapter=chapter,
                )
                submit_obj.save(extra_info=extra_info)
            task_obj.submission_object = submit_obj
        task_obj.save()
    def test_can_see(self):
        # Everyone can see submissions
        exhibition = Exhibition(title='New Exhibition', description='description goes here', released_at=timezone.now())
        student_artwork = Artwork(title='New Artwork', code='// code goes here', author=self.user)
        staff_artwork = Artwork(title='New Artwork', code='// code goes here', author=self.staff_user)
        submission = Submission(exhibition=exhibition, artwork=student_artwork)

        self.assertTrue(submission.can_see())
        self.assertTrue(submission.can_see(self.user))
        self.assertTrue(submission.can_see(self.staff_user))
        self.assertTrue(submission.can_see(self.super_user))
def get_submission(
    given_name,
    description,
    technique,
    quality_control,
    replicate_series,
    date_replicate,
    note,
    publishable,
    user,
    experiment,
    publication_list,
):
    # check if submission exist, if so return, if not create new
    try:
        year_later = datetime.now() + timedelta(days=(1 * 365))
        # Get generated id and unique name
        generated_id = return_unique_generated_id(Submission.objects.all().count())
        name = return_unique_submission_name(generated_id, given_name)

        submission = Submission(
            generated_id=generated_id,
            name=name,
            given_name=given_name,
            description=description,
            publishable=publishable,
            date_created=datetime.now(),
            date_embargo=year_later,
            technique=technique,
            quality_control=quality_control,
            replicate_series=replicate_series,
            date_replicate=date_replicate,
            note=note,
        )
        submission.validate_unique()
        submission.save()

        submission.experiments.add(experiment)
        for publication in publication_list:
            submission.publications.add(publication)

        # Establish User to Submission relationships
        submission_contributor = SubmissionContributor.submission_contributor_objects.create_submission_as_superuser(
            submission, user
        )
        submission_contributor.validate_unique()
        submission_contributor.save()

    except ValidationError as e:
        print e
        submission = Submission.objects.get(given_name=given_name)

    return submission
Esempio n. 4
0
    def setUp(self):
        self.teacher = User.objects.create(email="*****@*****.**")
        self.ta = User.objects.create(email="*****@*****.**")
        self.student = User.objects.create(email="*****@*****.**")

        self.course = Course.objects.create(
            title="Test course",
            description="Test description",
        )
        self.course.add_member(self.teacher, Membership.TEACHER)
        self.course.add_member(self.ta, Membership.TA)
        self.course.add_member(self.student, Membership.STUDENT)

        self.teacher_access_token = AccessToken.for_user(self.teacher)
        self.ta_access_token = AccessToken.for_user(self.ta)
        self.student_access_token = AccessToken.for_user(self.student)

        self.environment = Environment.objects.create(
            course=self.course,
            title="Test environment",
            dockerfile_content=
            "FROM python:3.7\nRUN mkdir /src\nWORKDIR /src\n",
            tag="test_image",
        )
        self.assignment = Assignment.objects.create(
            course=self.course,
            environment=self.environment,
            title="Test assignment",
            description="Test assignment description",
        )
        self.rule = Rule.objects.create(
            title="Test rule",
            description="Test rule description",
            order=1,
            command="python caesar.py",
            timeout=None,
            continue_on_fail=True,
            assignment=self.assignment,
        )
        self.submission = Submission(assignment=self.assignment,
                                     user=self.teacher,
                                     repo_url='github.com/terdenan/test-educi',
                                     branch='master')
        self.submission.save(download_type=Submission.STRATEGY_REPOSITORY)

        self.submission_list_url = reverse('courses:submissions:list',
                                           args=(self.course.id, ))
        self.submission_detail_url = reverse('courses:submissions:detail',
                                             args=(
                                                 self.course.id,
                                                 self.submission.id,
                                             ))
Esempio n. 5
0
def work(job_id):
    lines = {}
    usernames = []
    submissions = Submission.latest_from_each_user()
    major_set = set()
    for username in submissions.keys():
        sub = submissions[username]
        lines[username] = readdata(sub.uploaded_file.path)
        for m in list(lines[username].keys()):
            major_set.add(m)
        usernames.append(username)

    majors = sorted(list(major_set))

    create_out_dir(job_id)
    for m in majors:
        user_results = {}
        for u in usernames:
            if m in lines[u]:
                user_results[u] = lines[u][m]
            else:
                user_results[u] = []
            
        res = compare(usernames, user_results)
        if len(res) != 0:
            output_compare_result(job_id, m, usernames, res)
Esempio n. 6
0
    def create(self, validated_data):
        download_type = validated_data['type']

        assignment = validated_data['assignment']
        user = validated_data['user']

        repo_url = validated_data.get('repo_url', "")
        branch = validated_data.get('branch', "")
        source = validated_data.get('source', None)

        submission = Submission(assignment=assignment,
                                user=user,
                                repo_url=repo_url,
                                branch=branch,
                                source=source)
        submission.save(download_type=download_type)

        return submission
    def test_save_unique(self):

        exhibition = Exhibition(
            title='New Exhibition',
            description='description goes here',
            released_at=timezone.now(),
            author=self.user)
        exhibition.save()
        artwork = Artwork(title='New Artwork', code='// code goes here', author=self.user)
        artwork.save()
        submission1 = Submission(exhibition=exhibition, artwork=artwork, submitted_by=self.user)
        submission2 = Submission(exhibition=exhibition, artwork=artwork, submitted_by=self.user)

        # submissions must be unique
        self.assertEqual(submission1.save(), None)
        self.assertRaisesRegexp(
            IntegrityError,
            'columns exhibition_id, artwork_id are not unique',
            submission2.save)
    def test_str(self):
        
        exhibition = Exhibition(title='New Exhibition', description='description goes here')
        artwork = Artwork(title='New Artwork', code='// code goes here')

        submission = Submission(exhibition=exhibition, artwork=artwork)

        self.assertEquals(
            str(submission),
            'New Exhibition :: New Artwork'
        )
    def get_queryset(self):
        '''Show submissions to the given exhibition.'''
        qs = Submission.can_see_queryset(user=self.request.user,
                                         exhibition=self._get_exhibition_id())

        # Show most recently submitted first
        order = self._get_order_by()
        if order == 'score':
            qs = qs.order_by('-score')
        else:
            qs = qs.order_by('-created_at')
        return qs
Esempio n. 10
0
 def from_data(cls, festhome_data):
     submission = Submission(
         title=festhome_data.title,
         title_en=festhome_data.title_en,
         country=COUNTRIES_DICT.get(festhome_data.country, "ZZ"),
         section=SECTION_DICT.get(festhome_data.section, 1),
         synopsis=festhome_data.synopsis,
         length=festhome_data.length,
         aspect_ratio=" ",
         year=datetime.strptime(festhome_data.date, "%Y-%m-%d").year,
         premiere=2,  # no
         budget=" ",
         attend=0,
         allow_tv=2,
         allow_noncommercial=2,
         allow_network=2,
         backlink=12,  # other
         applicant="%s %s" % (festhome_data.applicant_name, festhome_data.applicant_lastname),
         applicant_email=festhome_data.applicant_email,
         applicant_phone="(%s) %s" % (festhome_data.applicant_code, festhome_data.applicant_phone),
         applicant_address="%s, %s, %s, %s"
         % (
             festhome_data.applicant_street,
             festhome_data.applicant_city,
             festhome_data.applicant_state,
             festhome_data.applicant_country,
         ),
         director="%s %s" % (festhome_data.applicant_name, festhome_data.applicant_lastname),
         director_email=festhome_data.applicant_email,
         director_address="%s, %s, %s, %s"
         % (
             festhome_data.applicant_street,
             festhome_data.applicant_city,
             festhome_data.applicant_state,
             festhome_data.applicant_country,
         ),
         comment="Import from Festhome",
     )
     submission.save()
     return cls(submission=submission, festhome_id=festhome_data.festhome_id)
    def test_can_save_released_exhibition(self):

        exhibition = Exhibition(title='New Exhibition', description='description goes here', released_at=timezone.now())
        self.assertTrue(exhibition.released_yet)

        student_artwork = Artwork(title='New Artwork', code='// code goes here', author=self.user)
        staff_artwork = Artwork(title='New Artwork', code='// code goes here', author=self.staff_user)

        # only authors can submit artwork
        submission = Submission(exhibition=exhibition, artwork=student_artwork)
        self.assertTrue(submission.can_save(self.user))
        self.assertFalse(submission.can_save(self.staff_user))
        self.assertFalse(submission.can_save(self.super_user))

        submission = Submission(exhibition=exhibition, artwork=staff_artwork)
        self.assertFalse(submission.can_save(self.user))
        self.assertTrue(submission.can_save(self.staff_user))
        self.assertFalse(submission.can_save(self.super_user))
Esempio n. 12
0
    def get_queryset(self):
        '''Show submissions to the given exhibition.'''
        qs = Submission.can_see_queryset(
                user=self.request.user, 
                exhibition=self._get_exhibition_id())

        # Show most recently submitted first
        order = self._get_order_by()
        if order == 'score':
            qs = qs.order_by('-score')
        else:
            qs = qs.order_by('-created_at')
        return qs
    def test_can_save_unreleased_exhibition(self):

        exhibition = Exhibition(
            title='New Exhibition', 
            description='description goes here', 
            released_at=timezone.now() + timedelta(hours=24))
        self.assertFalse(exhibition.released_yet)

        student_artwork = Artwork(title='New Artwork', code='// code goes here', author=self.user)
        staff_artwork = Artwork(title='New Artwork', code='// code goes here', author=self.staff_user)

        # students cannot submit to unreleased exhibitions
        submission = Submission(exhibition=exhibition, artwork=student_artwork)
        self.assertFalse(submission.can_save(self.user))
        self.assertFalse(submission.can_save(self.staff_user))
        self.assertFalse(submission.can_save(self.super_user))

        # but staff can
        submission = Submission(exhibition=exhibition, artwork=staff_artwork)
        self.assertFalse(submission.can_save(self.user))
        self.assertTrue(submission.can_save(self.staff_user))
        self.assertFalse(submission.can_save(self.super_user))
Esempio n. 14
0
def _get_submission_model(uuid, read_replica=False):
    """
    Helper to retrieve a given Submission object from the database. Helper is needed to centralize logic that fixes
    EDUCATOR-1090, because uuids are stored both with and without hyphens.
    """
    submission_qs = Submission.objects
    if read_replica:
        submission_qs = _use_read_replica(submission_qs)
    try:
        submission = submission_qs.get(uuid=uuid)
    except Submission.DoesNotExist:
        try:
            hyphenated_value = str(UUID(uuid))
            query = """
                SELECT
                    `submissions_submission`.`id`,
                    `submissions_submission`.`uuid`,
                    `submissions_submission`.`student_item_id`,
                    `submissions_submission`.`attempt_number`,
                    `submissions_submission`.`submitted_at`,
                    `submissions_submission`.`created_at`,
                    `submissions_submission`.`raw_answer`,
                    `submissions_submission`.`status`
                FROM
                    `submissions_submission`
                WHERE (
                    NOT (`submissions_submission`.`status` = 'D')
                    AND `submissions_submission`.`uuid` = '{}'
                )
            """
            query = query.replace("{}", hyphenated_value)

            # We can use Submission.objects instead of the SoftDeletedManager, we'll include that logic manually
            submission = Submission.objects.raw(query)[0]
        except IndexError as error:
            raise Submission.DoesNotExist() from error
        # Avoid the extra hit next time
        submission.save(update_fields=['uuid'])
    return submission
Esempio n. 15
0
def profile(request):
    if request.method == "POST":
        data = dict(request.POST)
        data = data["data"][0]
        data = json.loads(data)
        # print type(data)
        # if isinstance(data, dict):
        # 	print True

        # print data.keys()

        s = Submission()
        s.name = data['name']
        s.submitted_data = json.dumps(data["json"])
        s.total_score = data['total_score']
        s.save()

    q = Question.objects.all().order_by('order')
    print len(q)
    template = "base.html"
    context = {"questions": q}  #"form": form, "image_form": image_form
    return render(request, template, context)
    def test_can_see_queryset(self):

        # Everyone can see submissions
        exhibition1 = Exhibition.objects.create(
            title='Exhibition One', 
            description='description goes here',
            author=self.user)
        artwork1 = Artwork.objects.create(
            title='New Artwork', 
            code='// code goes here', 
            author=self.user)
        submission1 = Submission.objects.create(
            exhibition=exhibition1, 
            artwork=artwork1, 
            submitted_by=self.user)

        exhibition2 = Exhibition.objects.create(
            title='Exhibition Two', 
            description='description goes here',
            author=self.user)
        artwork2 = Artwork.objects.create(
            title='New Artwork', 
            code='// code goes here', 
            author=self.user)
        submission2 = Submission.objects.create(
            exhibition=exhibition2, 
            artwork=artwork2, 
            submitted_by=self.user)

        # By default, all submissions are included in the can_see queryset
        submissions = Submission.can_see_queryset().all()
        self.assertEqual(len(submissions), 2)
        self.assertEqual(submissions[0], submission1)
        self.assertEqual(submissions[1], submission2)

        # Same for all users
        submissions = Submission.can_see_queryset(user=self.user).all()
        self.assertEqual(len(submissions), 2)
        self.assertEqual(submissions[0], submission1)
        self.assertEqual(submissions[1], submission2)

        submissions = Submission.can_see_queryset(user=self.staff_user).all()
        self.assertEqual(len(submissions), 2)
        self.assertEqual(submissions[0], submission1)
        self.assertEqual(submissions[1], submission2)

        # Unless you filter by exhibition
        submissions = Submission.can_see_queryset(exhibition=exhibition1).all()
        self.assertEqual(len(submissions), 1)
        self.assertEqual(submissions[0], submission1)

        submissions = Submission.can_see_queryset(exhibition=exhibition1.id).all()
        self.assertEqual(len(submissions), 1)
        self.assertEqual(submissions[0], submission1)

        submissions = Submission.can_see_queryset(exhibition=exhibition2).all()
        self.assertEqual(len(submissions), 1)
        self.assertEqual(submissions[0], submission2)

        submissions = Submission.can_see_queryset(exhibition=exhibition2.id).all()
        self.assertEqual(len(submissions), 1)
        self.assertEqual(submissions[0], submission2)
Esempio n. 17
0
    def post(self, request, pid):
        global lang
        problem = get_object_or_404(Problem, pk=pid)
        if 'lang_select' in request.POST:
            form2 = self.form_class2(request.POST)
            if form2.is_valid():
                lang = form2.cleaned_lang()
                form1 = self.form_class1(lang, None)
                form2 = self.form_class2(None)
                return render(
                    request, self.template_name, {
                        'problem': problem,
                        'form1': form1,
                        'form2': form2,
                        'lang': lang
                    })
            else:
                form1 = self.form_class1(lang, None)
                form2 = self.form_class2(None)
                return render(
                    request, self.template_name, {
                        'problem': problem,
                        'form1': form1,
                        'form2': form2,
                        'lang': lang
                    })
        else:
            form1 = self.form_class1(data=request.POST, lang=lang)
            if not form1.is_valid():
                form1 = self.form_class1(lang, None)
                form2 = self.form_class2(None)
                return render(request, self.template_name, {
                    'form1': form1,
                    'form2': form2,
                    'lang': lang
                })

            content = ContentFile(request.POST['code'])
            submission = Submission(user=request.user,
                                    lang=lang,
                                    problem=problem)
            submission.code.save('x' + self.lang_map[lang],
                                 content,
                                 save=False)
            r = submission.compile()

            # Compilation error
            if r != 200:
                submission.code.delete(save=False)
                form2 = self.form_class2(None)
                return render(request, self.template_name, {
                    'form1': form1,
                    'form2': form2,
                    'lang': lang,
                    'errors': r
                })
            submission.save()
            result = problem.test(submission)
            result.status = status[result.status]
            result.toe = '{:.2f}'.format(result.toe)
            form2 = self.form_class2(None)
            return render(
                request, self.template_name, {
                    'problem': problem,
                    'form1': form1,
                    'form2': form2,
                    'lang': lang,
                    'result': result
                })
Esempio n. 18
0
def upload_submission(request, learner, trigger, no_thumbnail=True):
    """
    Handles the upload of the user's submission.
    """
    base_dir_for_file_uploads = settings.MEDIA_ROOT
    thumbnail_file_name_django = ''
    entry_point = trigger.entry_point

    files = request.FILES.getlist('file_upload', None)
    if files is None:
        return None

    # Is the storage space reachable?
    deepest_dir = base_dir_for_file_uploads + 'uploads/{0}/tmp/'.format(
        entry_point.id)

    try:
        os.makedirs(deepest_dir)
    except OSError:
        if not os.path.isdir(deepest_dir):
            logger.error(
                'Cannot create directory for upload: {0}'.format(deepest_dir))
            raise

    if len(files) == 1:
        filename = files[0].name
        extension = filename.split('.')[-1].lower()
        submitted_file_name_django = 'uploads/{0}/{1}'.format(
            entry_point.id,
            generate_random_token(token_length=16) + '.' + extension)
        full_path = base_dir_for_file_uploads + submitted_file_name_django
        with open(full_path, 'wb+') as dst:
            for chunk in files[0].chunks():
                dst.write(chunk)

        f_size = os.path.getsize(full_path)
        if f_size > trigger.max_file_upload_size_MB * 1024 * 1024:
            logger.warning(
                'File too large {0}'.format(submitted_file_name_django))
            return None, ('File too large ({0} MB); it must be less than '
                          '{1} MB.'.format(
                              round(float(f_size / 1024.0 / 1024.0), 1),
                              trigger.max_file_upload_size_MB))

    else:  #if trigger.allow_multiple_files: this is removed for now
        filename = ''
        extension = ''
        submitted_file_name_django = ''
        full_path = ''

    # Check that the file format is PDF, if that is required.
    strike1 = False
    if 'pdf' in trigger.accepted_file_types_comma_separated.lower() and \
       extension in ('pdf',):
        try:
            mime = magic.from_file(full_path, mime=True)
            if not (isinstance(mime, str)):
                mime = mime.decode('utf-8')
        except Exception as exp:
            logger.error('Could not determine MIME type: ' + str(exp))
            mime = ''
            strike1 = True

        if 'application/pdf' not in mime.lower():
            strike1 = True

        if strike1:
            logger.debug('Invalid PDF upload: {0} [{1}]'.format(
                mime, full_path))
            #return None, 'Invalid file uploaded. Uploaded file must be a PDF.'

        doc = PdfFileReader(full_path)
        if doc.isEncrypted:
            logger.debug('Encrypted PDF upload: {0}'.format(full_path))
            return None, ('An encrypted PDF cannot be uploaded. Please remove '
                          'the encryption and try again.')

    strike1 = False
    if (('jpeg' in trigger.accepted_file_types_comma_separated.lower()) or \
       ('jpg' in trigger.accepted_file_types_comma_separated.lower())) and \
       extension in ('jpg', 'jpeg'):

        try:
            mime = magic.from_file(full_path, mime=True)
            if not (isinstance(mime, str)):
                mime = mime.decode('utf-8')
        except Exception as exp:
            logger.error('Could not determine MIME type: ' + str(exp))
            mime = ''
            strike1 = True

        if 'image/jpeg' not in mime.lower():
            strike1 = True

        if strike1:
            logger.debug('Invalid JPG upload: {0} [{1}]'.format(
                mime, full_path))
            return None, ('Invalid file. Uploaded image should be a valid '
                          'and readable JPEG file.')

    strike1 = False
    if ('png' in trigger.accepted_file_types_comma_separated.lower()) and \
       extension in ('png',):

        try:
            mime = magic.from_file(full_path, mime=True)
            if not (isinstance(mime, str)):
                mime = mime.decode('utf-8')
        except Exception as exp:
            logger.error('Could not determine MIME type: ' + str(exp))
            mime = ''
            strike1 = True

        if 'image/png' not in mime.lower():
            strike1 = True

        if strike1:
            logger.debug('Invalid PNG upload: {0} [{1}]'.format(
                mime, full_path))
            return None, ('Invalid file. Uploaded image should be a valid '
                          'and readable PNG file.')

    strike2 = False
    if extension.lower() not in \
                            trigger.accepted_file_types_comma_separated.lower():
        logger.debug('Invalid file type upload: received ".{0}"; [{1}]'.format(\
                                                    extension, full_path))
        return None, ('Invalid file uploaded. Uploaded file must be: {}'.format(\
                                 trigger.accepted_file_types_comma_separated))

    if trigger == entry_point:
        # In some instances we don't use triggers, just entry_points
        prior = Submission.objects.filter(status='S',
                                          submitted_by=learner,
                                          entry_point=entry_point,
                                          is_valid=True)
    else:
        prior_indiv = Q(status='S',
                        submitted_by=learner,
                        entry_point=entry_point,
                        trigger=trigger,
                        is_valid=True)

        # We need this here, but also for the code later in the next
        # if (trigger==entry_point) part

        # Default returned by this function is ``None`` if the user is not
        # enrolled in a group, or if this course simply does not use groups.
        group_submitted = is_group_submission(learner, entry_point)
        if is_group_submission(learner, entry_point):
            group_submitted = group_submitted.group

            prior_group = Q(status='S',
                            group_submitted=group_submitted,
                            entry_point=entry_point,
                            trigger=trigger,
                            is_valid=True)
        else:
            prior_group = Q()

        prior = Submission.objects.filter(prior_indiv | prior_group)

    for item in prior:
        logger.debug(('Setting prior submission to False: {0} and name '
                      '"{1}"'.format(str(item), item.submitted_file_name)))
        item.is_valid = False
        item.save()

    if trigger == entry_point:
        # In some instances we don't use triggers, just entry_points
        sub = Submission(
            submitted_by=learner,
            group_submitted=None,
            status='S',
            entry_point=entry_point,
            is_valid=True,
            file_upload=submitted_file_name_django,
            thumbnail=thumbnail_file_name_django,
            submitted_file_name=filename,
            ip_address=get_IP_address(request),
        )
        sub.save()
    else:

        sub = Submission(
            submitted_by=learner,
            group_submitted=group_submitted,
            status='S',
            entry_point=entry_point,
            trigger=trigger,
            is_valid=True,
            file_upload=submitted_file_name_django,
            thumbnail=thumbnail_file_name_django,
            submitted_file_name=filename,
            ip_address=get_IP_address(request),
        )
        sub.save()

    if 'pdf' in trigger.accepted_file_types_comma_separated.lower() and \
                                                         extension in ('pdf',):
        clean_PDF(sub)

    return sub
Esempio n. 19
0
def get_submission(submission_uuid, read_replica=False):
    """Retrieves a single submission by uuid.

    Args:
        submission_uuid (str): Identifier for the submission.

    Kwargs:
        read_replica (bool): If true, attempt to use the read replica database.
            If no read replica is available, use the default database.

    Raises:
        SubmissionNotFoundError: Raised if the submission does not exist.
        SubmissionRequestError: Raised if the search parameter is not a string.
        SubmissionInternalError: Raised for unknown errors.

    Examples:
        >>> get_submission("20b78e0f32df805d21064fc912f40e9ae5ab260d")
        {
            'student_item': 2,
            'attempt_number': 1,
            'submitted_at': datetime.datetime(2014, 1, 29, 23, 14, 52, 649284, tzinfo=<UTC>),
            'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>),
            'answer': u'The answer is 42.'
        }

    """
    if not isinstance(submission_uuid, six.string_types):
        if isinstance(submission_uuid, UUID):
            submission_uuid = six.text_type(submission_uuid)
        else:
            raise SubmissionRequestError(
                msg="submission_uuid ({!r}) must be serializable".format(submission_uuid)
            )

    cache_key = Submission.get_cache_key(submission_uuid)
    try:
        cached_submission_data = cache.get(cache_key)
    except Exception:
        # The cache backend could raise an exception
        # (for example, memcache keys that contain spaces)
        logger.exception("Error occurred while retrieving submission from the cache")
        cached_submission_data = None

    if cached_submission_data:
        logger.info("Get submission {} (cached)".format(submission_uuid))
        return cached_submission_data

    try:
        submission = _get_submission_model(submission_uuid, read_replica)
        submission_data = SubmissionSerializer(submission).data
        cache.set(cache_key, submission_data)
    except Submission.DoesNotExist:
        logger.error("Submission {} not found.".format(submission_uuid))
        raise SubmissionNotFoundError(
            u"No submission matching uuid {}".format(submission_uuid)
        )
    except Exception as exc:
        # Something very unexpected has just happened (like DB misconfig)
        err_msg = "Could not get submission due to error: {}".format(exc)
        logger.exception(err_msg)
        raise SubmissionInternalError(err_msg)

    logger.info("Get submission {}".format(submission_uuid))
    return submission_data
Esempio n. 20
0
def valid_submission(valid_submission_data):
    return Submission(**valid_submission_data)
Esempio n. 21
0
def reset_score(student_id, course_id, item_id, clear_state=False, emit_signal=True):
    """
    Reset scores for a specific student on a specific problem.

    Note: this does *not* delete `Score` models from the database,
    since these are immutable.  It simply creates a new score with
    the "reset" flag set to True.

    Args:
        student_id (unicode): The ID of the student for whom to reset scores.
        course_id (unicode): The ID of the course containing the item to reset.
        item_id (unicode): The ID of the item for which to reset scores.
        clear_state (bool): If True, will appear to delete any submissions associated with the specified StudentItem

    Returns:
        None

    Raises:
        SubmissionInternalError: An unexpected error occurred while resetting scores.

    """
    # Retrieve the student item
    try:
        student_item = StudentItem.objects.get(
            student_id=student_id, course_id=course_id, item_id=item_id
        )
    except StudentItem.DoesNotExist:
        # If there is no student item, then there is no score to reset,
        # so we can return immediately.
        return

    # Create a "reset" score
    try:
        score = Score.create_reset_score(student_item)
        if emit_signal:
            # Send a signal out to any listeners who are waiting for scoring events.
            score_reset.send(
                sender=None,
                anonymous_user_id=student_id,
                course_id=course_id,
                item_id=item_id,
                created_at=score.created_at,
            )

        if clear_state:
            for sub in student_item.submission_set.all():
                # soft-delete the Submission
                sub.status = Submission.DELETED
                sub.save(update_fields=["status"])

                # Also clear out cached values
                cache_key = Submission.get_cache_key(sub.uuid)
                cache.delete(cache_key)

    except DatabaseError:
        msg = (
            u"Error occurred while reseting scores for"
            u" item {item_id} in course {course_id} for student {student_id}"
        ).format(item_id=item_id, course_id=course_id, student_id=student_id)
        logger.exception(msg)
        raise SubmissionInternalError(msg)
    else:
        msg = u"Score reset for item {item_id} in course {course_id} for student {student_id}".format(
            item_id=item_id, course_id=course_id, student_id=student_id
        )
        logger.info(msg)
Esempio n. 22
0
class TestCreate(APITestCase):
    """
    tests for create
    """
    def setUp(self):
        self.token = get_auth_token()
        self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + str(self.token))
        self.create_initial_data()

    def create_initial_data(self):
        """
        create initials data
        :return:
        :rtype:
        """
        description = """Apply remote sensing principles and methods to analyze
                        data and solve problems in areas such as natural resource management,
                        urban planning, or homeland security. May develop new sensor systems,
                        analytical techniques, or new applications for existing systems."""

        self.industry, _ = Industry.objects.get_or_create(
            naics_code="313110", industry_type="Fiber, Yarn, and Thread Mills")

        self._test_category, _ = JobCategory.objects.get_or_create(
            o_net_soc_code="199999999",
            category_name="Remote Sensing Scientists and Technologistss")
        self._test_category.description = description
        self._test_category.save()

        self.test_catalog, _ = JobCatalog.objects.get_or_create(
            naics_code=self.industry, category=self._test_category)

        self.test_job_tag, _ = JobTag.objects.get_or_create(
            tag="machine learning")

        # self.test_program_id = uuid.uuid4()
        self.test_program_id = 'f1a9413d-1ef5-44d6-ac4b-90e4952890be'

        self.test_job_title, _ = JobTitle.objects.get_or_create(
            program_id=self.test_program_id,
            category=self._test_category,
            title="software developer555",
            level="3",
            status=True,
            created_by="jai",
            modified_by="jai")

        self.test_job_config, _ = JobConfiguration.objects.get_or_create(
            program_id=self.test_program_id,
            config_json={'option': 'unKnown'},
            version='test')

        self.test_foundation_data, _ = FoundationData.objects.get_or_create(
            program_id=self.test_program_id)

        current_date = datetime.date.today()

        self.test_job, _ = Job.objects.get_or_create(
            program_id=self.test_program_id,
            config_id=self.test_job_config,
            category=self._test_category,
            title=self.test_job_title,
            no_of_openings=8,
            salary_min_range=20000,
            salary_max_range=30000,
            start_date=current_date,
            end_date=current_date + datetime.timedelta(days=1),
            foundational=self.test_foundation_data)

        self.current_user_id = uuid.uuid4()

        self.test_candidate_id = uuid_shuffle(self.current_user_id)

        self.test_submission = Submission(
            job=self.test_job,
            program_id=self.test_program_id,
            organization_id='test_organization_id',
            candidate_id=self.test_candidate_id,
            created_by=self.current_user_id,
            modified_by=self.current_user_id)
        self.test_submission.save()

        self.body = {
            "job_template_id": self.test_job.id,
            "job_category_id": self._test_category.id,
            "job_level": 7,
            "job_title_id": self.test_job_title.id,
            "min_rate_rule": "Cannot Change",
            "max_rate_rule": "Cannot Change",
            "min_rate": 75.0,
            "max_rate": 88.0,
            "currency": "USD",
            "work_location": "UP"
        }

    def test_post_rate_card(self):
        """
        post rate card test
        """

        url = reverse('rate_card:rate_card_get_list_n_post',
                      kwargs={'program_id': self.test_program_id})

        response = self.client.post(url, self.body, format='json')
        data = response.data

        self.assertEqual(response.status_code, 201)
        self.assertEqual(data["program_id"],
                         RATE_CARD_POST_RESPONSE["program_id"])
        self.assertEqual(data["job_level"],
                         RATE_CARD_POST_RESPONSE["job_level"])
        self.assertEqual(data["min_rate_rule"],
                         RATE_CARD_POST_RESPONSE["min_rate_rule"])
        self.assertEqual(data["max_rate_rule"],
                         RATE_CARD_POST_RESPONSE["max_rate_rule"])
        self.assertEqual(data["min_rate"], RATE_CARD_POST_RESPONSE["min_rate"])
        self.assertEqual(data["max_rate"], RATE_CARD_POST_RESPONSE["max_rate"])
        self.assertEqual(data["currency"], RATE_CARD_POST_RESPONSE["currency"])
        self.assertEqual(data["work_location"],
                         RATE_CARD_POST_RESPONSE["work_location"])

    def test_get_rate_card_list(self):
        """
        get rate_card_list
        :return:
        :rtype:
        """

        url = reverse('rate_card:rate_card_get_list_n_post',
                      kwargs={'program_id': self.test_program_id})

        post_response = self.client.post(url, self.body, format='json').data
        get_list_response = self.client.get(url,
                                            format='json').data["results"][0]
        self.assertEqual(post_response["program_id"],
                         get_list_response["program_id"])
        self.assertEqual(post_response["job_template"]["id"],
                         get_list_response["job_template"]["id"])
        self.assertEqual(post_response["job_category"]["id"],
                         get_list_response["job_category"]["id"])
        self.assertEqual(post_response["job_title"]["id"],
                         get_list_response["job_title"]["id"])
        self.assertEqual(post_response["job_level"],
                         get_list_response["job_level"])
        self.assertEqual(post_response["min_rate_rule"],
                         get_list_response["min_rate_rule"])
        self.assertEqual(post_response["max_rate_rule"],
                         get_list_response["max_rate_rule"])
        self.assertEqual(post_response["min_rate"],
                         get_list_response["min_rate"])
        self.assertEqual(post_response["max_rate"],
                         get_list_response["max_rate"])
        self.assertEqual(post_response["currency"],
                         get_list_response["currency"])
        self.assertEqual(post_response["work_location"],
                         get_list_response["work_location"])

    def test_get_single_rate_card(self):
        """
        get single rate_card
        :return:
        :rtype:
        """

        url = reverse('rate_card:rate_card_get_list_n_post',
                      kwargs={'program_id': self.test_program_id})

        post_response = self.client.post(url, self.body, format='json').data

        url = reverse('rate_card:rate_card_get_put_del',
                      kwargs={
                          'program_id': self.test_program_id,
                          'pk': post_response["id"]
                      })

        get_single_response = self.client.get(url, format='json').data
        self.assertEqual(post_response["program_id"],
                         get_single_response["program_id"])
        self.assertEqual(post_response["job_template"]["id"],
                         get_single_response["job_template"]["id"])
        self.assertEqual(post_response["job_category"]["id"],
                         get_single_response["job_category"]["id"])
        self.assertEqual(post_response["job_title"]["id"],
                         get_single_response["job_title"]["id"])
        self.assertEqual(post_response["job_level"],
                         get_single_response["job_level"])
        self.assertEqual(post_response["min_rate_rule"],
                         get_single_response["min_rate_rule"])
        self.assertEqual(post_response["max_rate_rule"],
                         get_single_response["max_rate_rule"])
        self.assertEqual(post_response["min_rate"],
                         get_single_response["min_rate"])
        self.assertEqual(post_response["max_rate"],
                         get_single_response["max_rate"])
        self.assertEqual(post_response["currency"],
                         get_single_response["currency"])
        self.assertEqual(post_response["work_location"],
                         get_single_response["work_location"])

    def test_update_single_rate_card(self):
        """
        update single rate_card
        :return:
        :rtype:
        """

        url = reverse('rate_card:rate_card_get_list_n_post',
                      kwargs={'program_id': self.test_program_id})

        post_response = self.client.post(url, self.body, format='json').data

        url = reverse('rate_card:rate_card_get_put_del',
                      kwargs={
                          'program_id': self.test_program_id,
                          'pk': post_response["id"]
                      })

        work_location = self.body["work_location"]
        self.body["work_location"] = "New Delhi"

        get_single_response = self.client.put(url, self.body,
                                              format='json').data
        self.body["work_location"] = work_location
        self.assertEqual(post_response["program_id"],
                         get_single_response["program_id"])
        self.assertEqual(post_response["job_template"]["id"],
                         get_single_response["job_template"]["id"])
        self.assertEqual(post_response["job_category"]["id"],
                         get_single_response["job_category"]["id"])
        self.assertEqual(post_response["job_title"]["id"],
                         get_single_response["job_title"]["id"])
        self.assertEqual(post_response["job_level"],
                         get_single_response["job_level"])
        self.assertEqual(post_response["min_rate_rule"],
                         get_single_response["min_rate_rule"])
        self.assertEqual(post_response["max_rate_rule"],
                         get_single_response["max_rate_rule"])
        self.assertEqual(post_response["min_rate"],
                         get_single_response["min_rate"])
        self.assertEqual(post_response["max_rate"],
                         get_single_response["max_rate"])
        self.assertEqual(post_response["currency"],
                         get_single_response["currency"])
        self.assertEqual(get_single_response["work_location"], "New Delhi")

    def test_filter_rate_card(self):
        """
        filter rate_card
        :return:
        :rtype:
        """

        url = reverse('rate_card:rate_card_get_list_n_post',
                      kwargs={'program_id': self.test_program_id})

        post_response = self.client.post(url, self.body, format='json').data

        query_string = {
            "job_template_id": self.test_job.id,
            "job_category_id": self._test_category.id,
            "job_level": 7,
            "job_title_id": self.test_job_title.id,
            "min_rate_rule": "Cannot Change",
            "max_rate_rule": "Cannot Change",
            "min_rate": 75.0,
            "max_rate": 88.0,
            "currency": "USD",
            "work_location": "UP"
        }
        query_string_v2 = "&".join(
            ["{}={}".format(key, val) for key, val in query_string.items()])

        get_list_response = self.client.get(url,
                                            QUERY_STRING=query_string_v2,
                                            format='json')
        get_list_response = get_list_response.data["results"][0]
        self.assertEqual(post_response["program_id"],
                         get_list_response["program_id"])
        self.assertEqual(post_response["job_template"]["id"],
                         get_list_response["job_template"]["id"])
        self.assertEqual(post_response["job_category"]["id"],
                         get_list_response["job_category"]["id"])
        self.assertEqual(post_response["job_title"]["id"],
                         get_list_response["job_title"]["id"])
        self.assertEqual(post_response["job_level"],
                         get_list_response["job_level"])
        self.assertEqual(post_response["min_rate_rule"],
                         get_list_response["min_rate_rule"])
        self.assertEqual(post_response["max_rate_rule"],
                         get_list_response["max_rate_rule"])
        self.assertEqual(post_response["min_rate"],
                         get_list_response["min_rate"])
        self.assertEqual(post_response["max_rate"],
                         get_list_response["max_rate"])
        self.assertEqual(post_response["currency"],
                         get_list_response["currency"])
        self.assertEqual(post_response["work_location"],
                         get_list_response["work_location"])

    def test_negative_filter_rate_card(self):
        """
        negative filter rate_card
        :return:
        :rtype:
        """

        url = reverse('rate_card:rate_card_get_list_n_post',
                      kwargs={'program_id': self.test_program_id})

        post_response = self.client.post(url, self.body, format='json').data

        query_string = {
            "job_template_id": self.test_job.id,
            "job_category_id": self._test_category.id,
            "job_level": 7,
            "job_title_id": self.test_job_title.id,
            "min_rate_rule": "Cannot Change",
            "max_rate_rule": "Cannot Change",
            "min_rate": 75.0,
            "max_rate": 88.0,
            "currency": "USD",
            "work_location": "Delhi"
        }
        query_string_v2 = "&".join(
            ["{}={}".format(key, val) for key, val in query_string.items()])

        get_list_response = self.client.get(url,
                                            QUERY_STRING=query_string_v2,
                                            format='json')
        get_list_response = get_list_response.data["results"]
        self.assertEqual(get_list_response.__len__(), 0)
Esempio n. 23
0
    def create_initial_data(self):
        """
        create initials data
        :return:
        :rtype:
        """
        description = """Apply remote sensing principles and methods to analyze
                        data and solve problems in areas such as natural resource management,
                        urban planning, or homeland security. May develop new sensor systems,
                        analytical techniques, or new applications for existing systems."""

        self.industry, _ = Industry.objects.get_or_create(
            naics_code="313110", industry_type="Fiber, Yarn, and Thread Mills")

        self._test_category, _ = JobCategory.objects.get_or_create(
            o_net_soc_code="199999999",
            category_name="Remote Sensing Scientists and Technologistss")
        self._test_category.description = description
        self._test_category.save()

        self.test_catalog, _ = JobCatalog.objects.get_or_create(
            naics_code=self.industry, category=self._test_category)

        self.test_job_tag, _ = JobTag.objects.get_or_create(
            tag="machine learning")

        # self.test_program_id = uuid.uuid4()
        self.test_program_id = 'f1a9413d-1ef5-44d6-ac4b-90e4952890be'

        self.test_job_title, _ = JobTitle.objects.get_or_create(
            program_id=self.test_program_id,
            category=self._test_category,
            title="software developer555",
            level="3",
            status=True,
            created_by="jai",
            modified_by="jai")

        self.test_job_config, _ = JobConfiguration.objects.get_or_create(
            program_id=self.test_program_id,
            config_json={'option': 'unKnown'},
            version='test')

        self.test_foundation_data, _ = FoundationData.objects.get_or_create(
            program_id=self.test_program_id)

        current_date = datetime.date.today()

        self.test_job, _ = Job.objects.get_or_create(
            program_id=self.test_program_id,
            config_id=self.test_job_config,
            category=self._test_category,
            title=self.test_job_title,
            no_of_openings=8,
            salary_min_range=20000,
            salary_max_range=30000,
            start_date=current_date,
            end_date=current_date + datetime.timedelta(days=1),
            foundational=self.test_foundation_data)

        self.current_user_id = uuid.uuid4()

        self.test_candidate_id = uuid_shuffle(self.current_user_id)

        self.test_submission = Submission(
            job=self.test_job,
            program_id=self.test_program_id,
            organization_id='test_organization_id',
            candidate_id=self.test_candidate_id,
            created_by=self.current_user_id,
            modified_by=self.current_user_id)
        self.test_submission.save()

        self.body = {
            "job_template_id": self.test_job.id,
            "job_category_id": self._test_category.id,
            "job_level": 7,
            "job_title_id": self.test_job_title.id,
            "min_rate_rule": "Cannot Change",
            "max_rate_rule": "Cannot Change",
            "min_rate": 75.0,
            "max_rate": 88.0,
            "currency": "USD",
            "work_location": "UP"
        }
    def test_can_see_queryset(self):

        exhibition0 = Exhibition.objects.create(
            title='Exhibition No Cohort', 
            description='description goes here',
            cohort=None,
            author=self.user)
        artwork0 = Artwork.objects.create(
            title='New Artwork', 
            code='// code goes here', 
            author=self.user)
        submission0 = Submission.objects.create(
            exhibition=exhibition0, 
            artwork=artwork0, 
            submitted_by=self.user)

        exhibition1 = Exhibition.objects.create(
            title='Exhibition One', 
            description='description goes here',
            cohort=self.cohort1,
            author=self.user)
        artwork1 = Artwork.objects.create(
            title='New Artwork', 
            code='// code goes here', 
            author=self.user)
        submission1 = Submission.objects.create(
            exhibition=exhibition1, 
            artwork=artwork1, 
            submitted_by=self.user)

        exhibition2 = Exhibition.objects.create(
            title='Exhibition Two', 
            description='description goes here',
            cohort=self.cohort2,
            author=self.user)
        artwork2 = Artwork.objects.create(
            title='New Artwork', 
            code='// code goes here', 
            author=self.user)
        submission2 = Submission.objects.create(
            exhibition=exhibition2, 
            artwork=artwork2, 
            submitted_by=self.user)


        # Everyone sees submissions in no-cohort and default exhibitions
        submissions = Submission.can_see_queryset().all()
        self.assertEqual(len(submissions), 2)
        self.assertEqual(submissions[0], submission0)
        self.assertEqual(submissions[1], submission1)

        # Users see no-cohort and exhibitions in their own cohort
        submissions = Submission.can_see_queryset(user=self.no_cohort_user).all()
        self.assertEqual(len(submissions), 2)
        self.assertEqual(submissions[0], submission0)
        self.assertEqual(submissions[1], submission1)

        submissions = Submission.can_see_queryset(user=self.cohort1_user).all()
        self.assertEqual(len(submissions), 2)
        self.assertEqual(submissions[0], submission0)
        self.assertEqual(submissions[1], submission1)

        submissions = Submission.can_see_queryset(user=self.cohort2_user).all()
        self.assertEqual(len(submissions), 2)
        self.assertEqual(submissions[0], submission0)
        self.assertEqual(submissions[1], submission2)

        # Unless you filter by exhibition
        submissions = Submission.can_see_queryset(exhibition=exhibition1).all()
        self.assertEqual(len(submissions), 1)
        self.assertEqual(submissions[0], submission1)

        submissions = Submission.can_see_queryset(exhibition=exhibition1.id).all()
        self.assertEqual(len(submissions), 1)
        self.assertEqual(submissions[0], submission1)

        submissions = Submission.can_see_queryset(exhibition=exhibition2).all()
        self.assertEqual(len(submissions), 1)
        self.assertEqual(submissions[0], submission2)

        submissions = Submission.can_see_queryset(exhibition=exhibition2.id).all()
        self.assertEqual(len(submissions), 1)
        self.assertEqual(submissions[0], submission2)

        # Test user+exhibition permutations
        submissions = Submission.can_see_queryset(user=self.no_cohort_user, exhibition=exhibition1).all()
        self.assertEqual(len(submissions), 1)
        self.assertEqual(submissions[0], submission1)

        submissions = Submission.can_see_queryset(user=self.cohort1_user, exhibition=exhibition1).all()
        self.assertEqual(len(submissions), 1)
        self.assertEqual(submissions[0], submission1)

        submissions = Submission.can_see_queryset(user=self.cohort2_user, exhibition=exhibition1).all()
        self.assertEqual(len(submissions), 1)
        self.assertEqual(submissions[0], submission1)

        submissions = Submission.can_see_queryset(user=self.no_cohort_user, exhibition=exhibition2).all()
        self.assertEqual(len(submissions), 1)
        self.assertEqual(submissions[0], submission2)

        submissions = Submission.can_see_queryset(user=self.cohort1_user, exhibition=exhibition2).all()
        self.assertEqual(len(submissions), 1)
        self.assertEqual(submissions[0], submission2)

        submissions = Submission.can_see_queryset(user=self.cohort2_user, exhibition=exhibition2).all()
        self.assertEqual(len(submissions), 1)
        self.assertEqual(submissions[0], submission2)
Esempio n. 25
0
def get_submission(submission_uuid, read_replica=False):
    """Retrieves a single submission by uuid.

    Args:
        submission_uuid (str): Identifier for the submission.

    Kwargs:
        read_replica (bool): If true, attempt to use the read replica database.
            If no read replica is available, use the default database.

    Raises:
        SubmissionNotFoundError: Raised if the submission does not exist.
        SubmissionRequestError: Raised if the search parameter is not a string.
        SubmissionInternalError: Raised for unknown errors.

    Examples:
        >>> get_submission("20b78e0f32df805d21064fc912f40e9ae5ab260d")
        {
            'student_item': 2,
            'attempt_number': 1,
            'submitted_at': datetime.datetime(2014, 1, 29, 23, 14, 52, 649284, tzinfo=<UTC>),
            'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>),
            'answer': u'The answer is 42.'
        }

    """
    if not isinstance(submission_uuid, str):
        if isinstance(submission_uuid, UUID):
            submission_uuid = str(submission_uuid)
        else:
            raise SubmissionRequestError(
                msg=
                f"submission_uuid ({submission_uuid!r}) must be serializable")

    cache_key = Submission.get_cache_key(submission_uuid)
    try:
        cached_submission_data = cache.get(cache_key)
    except Exception:  # pylint: disable=broad-except
        # The cache backend could raise an exception
        # (for example, memcache keys that contain spaces)
        logger.exception(
            "Error occurred while retrieving submission from the cache")
        cached_submission_data = None

    if cached_submission_data:
        logger.info("Get submission %s (cached)", submission_uuid)
        return cached_submission_data

    try:
        submission = _get_submission_model(submission_uuid, read_replica)
        submission_data = SubmissionSerializer(submission).data
        cache.set(cache_key, submission_data)
    except Submission.DoesNotExist as error:
        logger.error("Submission %s not found.", submission_uuid)
        raise SubmissionNotFoundError(
            f"No submission matching uuid {submission_uuid}") from error
    except Exception as exc:
        # Something very unexpected has just happened (like DB misconfig)
        err_msg = f"Could not get submission due to error: {exc}"
        logger.exception(err_msg)
        raise SubmissionInternalError(err_msg) from exc

    logger.info("Get submission %s", submission_uuid)
    return submission_data
Esempio n. 26
0
class SubmissionAPIViewTest(APITestCase):
    def setUp(self):
        self.teacher = User.objects.create(email="*****@*****.**")
        self.ta = User.objects.create(email="*****@*****.**")
        self.student = User.objects.create(email="*****@*****.**")

        self.course = Course.objects.create(
            title="Test course",
            description="Test description",
        )
        self.course.add_member(self.teacher, Membership.TEACHER)
        self.course.add_member(self.ta, Membership.TA)
        self.course.add_member(self.student, Membership.STUDENT)

        self.teacher_access_token = AccessToken.for_user(self.teacher)
        self.ta_access_token = AccessToken.for_user(self.ta)
        self.student_access_token = AccessToken.for_user(self.student)

        self.environment = Environment.objects.create(
            course=self.course,
            title="Test environment",
            dockerfile_content=
            "FROM python:3.7\nRUN mkdir /src\nWORKDIR /src\n",
            tag="test_image",
        )
        self.assignment = Assignment.objects.create(
            course=self.course,
            environment=self.environment,
            title="Test assignment",
            description="Test assignment description",
        )
        self.rule = Rule.objects.create(
            title="Test rule",
            description="Test rule description",
            order=1,
            command="python caesar.py",
            timeout=None,
            continue_on_fail=True,
            assignment=self.assignment,
        )
        self.submission = Submission(assignment=self.assignment,
                                     user=self.teacher,
                                     repo_url='github.com/terdenan/test-educi',
                                     branch='master')
        self.submission.save(download_type=Submission.STRATEGY_REPOSITORY)

        self.submission_list_url = reverse('courses:submissions:list',
                                           args=(self.course.id, ))
        self.submission_detail_url = reverse('courses:submissions:detail',
                                             args=(
                                                 self.course.id,
                                                 self.submission.id,
                                             ))

    def test_can_get_list_of_submissions(self):
        self.client.credentials(
            HTTP_AUTHORIZATION=f"Bearer {self.teacher_access_token}")
        response = self.client.get(self.submission_list_url)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.data), 1)
        self.assertEqual(response.data[0]['user'], self.teacher.id)

    def test_can_get_submission(self):
        self.client.credentials(
            HTTP_AUTHORIZATION=f"Bearer {self.teacher_access_token}")
        response = self.client.get(self.submission_detail_url)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['user'], self.teacher.id)

    def test_can_create_submission(self):
        self.client.credentials(
            HTTP_AUTHORIZATION=f"Bearer {self.teacher_access_token}")
        test_submission = {
            'assignment': self.assignment.id,
            'repo_url': 'github.com/terdenan/test-educi',
            'branch': 'master',
            'type': Submission.STRATEGY_REPOSITORY
        }
        response = self.client.post(self.submission_list_url, test_submission)

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(response.data['user'], self.teacher.id)
        self.assertEqual(response.data['status'], Submission.PROCESSING)

        response = self.client.get(
            reverse('courses:submissions:detail',
                    args=(self.course.id, response.data['id'])))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['status'], Submission.PERFORMED)
Esempio n. 27
0
def reset_score(student_id,
                course_id,
                item_id,
                clear_state=False,
                emit_signal=True):
    """
    Reset scores for a specific student on a specific problem.

    Note: this does *not* delete `Score` models from the database,
    since these are immutable.  It simply creates a new score with
    the "reset" flag set to True.

    Args:
        student_id (unicode): The ID of the student for whom to reset scores.
        course_id (unicode): The ID of the course containing the item to reset.
        item_id (unicode): The ID of the item for which to reset scores.
        clear_state (bool): If True, will appear to delete any submissions associated with the specified StudentItem

    Returns:
        None

    Raises:
        SubmissionInternalError: An unexpected error occurred while resetting scores.

    """
    # Retrieve the student item
    try:
        student_item = StudentItem.objects.get(student_id=student_id,
                                               course_id=course_id,
                                               item_id=item_id)
    except StudentItem.DoesNotExist:
        # If there is no student item, then there is no score to reset,
        # so we can return immediately.
        return

    # Create a "reset" score
    try:
        score = Score.create_reset_score(student_item)
        if emit_signal:
            # Send a signal out to any listeners who are waiting for scoring events.
            score_reset.send(
                sender=None,
                anonymous_user_id=student_id,
                course_id=course_id,
                item_id=item_id,
                created_at=score.created_at,
            )

        if clear_state:
            for sub in student_item.submission_set.all():
                # soft-delete the Submission
                sub.status = DELETED
                sub.save(update_fields=["status"])

                # Also clear out cached values
                cache_key = Submission.get_cache_key(sub.uuid)
                cache.delete(cache_key)

    except DatabaseError as error:
        msg = ("Error occurred while reseting scores for"
               " item {item_id} in course {course_id} for student {student_id}"
               ).format(item_id=item_id,
                        course_id=course_id,
                        student_id=student_id)
        logger.exception(msg)
        raise SubmissionInternalError(msg) from error
    else:
        msg = "Score reset for item {item_id} in course {course_id} for student {student_id}".format(
            item_id=item_id, course_id=course_id, student_id=student_id)
        logger.info(msg)
Esempio n. 28
0
def problemstmt(request, _id):
    # posted the problem
    if request.method == 'POST':
        # post request
        problem = Problem.objects.filter(id=_id)
        if not problem.exists():
            return HttpResponseNotFound()
        if request.user.is_authenticated:
            # authentic user
            # evaluate the submission
            remark = compiler.compilation(request.user.id,
                                          request.POST['lang'],
                                          request.POST['code'], _id)
            # messages.success(
            #     request, 'Submission successful')
            userid = request.user.id
            lang = request.POST['lang']
            code = request.POST['code']
            status = remark
            # check the previous successful submission
            prevsub = Submission.objects.filter(userid=request.user.id).filter(
                problemid=_id).filter(status='0')
            submission = Submission(userid=userid,
                                    lang=lang,
                                    code=code,
                                    status=status,
                                    problemid=_id)
            # submission.save()
            problem = problem[0]
            problem.attempts = problem.attempts + 1
            if status == 0:
                # increase problem solves count
                problem.successes = problem.successes + 1
                # if no previous success
                print('got this far-----------------------------')
                print('{} has length of solves: {}'.format(
                    request.user.username, len(prevsub)))
                if len(prevsub) == 0:
                    profile = Profile.objects.filter(user_id=request.user.id)
                    if profile.exists():
                        # update the score with correct score
                        profile = profile[0]
                        profile.score = profile.score + problem.score
                        profile.save()
            # update the problemsets
            # increase the score if success
            problem.save()
            submission.save()
            if remark == 0:
                messages.success(request, details[remark])
            else:
                messages.warning(request, details[remark])
        else:
            messages.warning(request, 'Required login to submit')
        return redirect('/submissions/{}/'.format(submission.id))
        # return render(request, 'submissions/submissiondetails.html', {'submission': res})
    else:
        # get request
        # with open('io/problem{}.html'.format(_id), 'r') as rf:
        #     stmt = rf.read()
        problem = Problem.objects.filter(id=_id)
        if not problem.exists():
            return HttpResponseNotFound()
        else:
            problem = problem[0]
        return render(request, 'problemsets/problemstmt.html',
                      {'problem': problem})