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
Ejemplo n.º 2
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)
Ejemplo n.º 3
0
    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)
Ejemplo n.º 4
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)
Ejemplo n.º 5
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
Ejemplo n.º 6
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
                })
Ejemplo n.º 7
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)
Ejemplo n.º 8
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})