示例#1
0
    def test_render_django_template_translated(self):
        loader = ResourceLoader(__name__)
        s = loader.render_django_template("data/trans_django_template.txt",
                                          context=example_context,
                                          i18n_service=MockI18nService())
        self.assertEqual(s, expected_translated_template)

        # Test that the language changes were reverted
        s = loader.render_django_template("data/trans_django_template.txt",
                                          example_context)
        self.assertEqual(s, expected_not_translated_template)
示例#2
0
 def test_render_django_template_localized(self):
     # Test that default template tags like l10n are loaded
     loader = ResourceLoader(__name__)
     s = loader.render_django_template("data/l10n_django_template.txt",
                                       context=example_context,
                                       i18n_service=MockI18nService())
     self.assertEqual(s, expected_localized_template)
示例#3
0
    def student_view(self, context=None):
        """
        The primary view of the StaffGradedXBlock, shown to students
        when viewing courses.
        """
        frag = Fragment()
        frag.add_css(self.resource_string("static/css/staff_graded.css"))
        loader = ResourceLoader(__name__)
        _ = self.runtime.service(self, "i18n").ugettext

        # Add i18n js
        statici18n_js_url = self._get_statici18n_js_url()
        if statici18n_js_url:
            frag.add_javascript_url(self.runtime.local_resource_url(self, statici18n_js_url))

        frag.add_javascript(self.resource_string("static/js/src/staff_graded.js"))
        frag.initialize_js('StaffGradedXBlock')

        context['id'] = self.location.html_id()
        context['instructions'] = markdown.markdown(self.instructions)
        context['display_name'] = self.display_name
        context['is_staff'] = self.runtime.user_is_staff

        course_id = self.location.course_key
        context['available_cohorts'] = [cohort.name for cohort in get_course_cohorts(course_id=course_id)]
        context['available_tracks'] = [
            (mode.slug, mode.name) for mode in
            modes_for_course(course_id, only_selectable=False)
            ]

        if context['is_staff']:
            from crum import get_current_request
            from django.middleware.csrf import get_token
            context['import_url'] = self.runtime.handler_url(self, "csv_import_handler")
            context['export_url'] = self.runtime.handler_url(self, "csv_export_handler")
            context['poll_url'] = self.runtime.handler_url(self, "get_results_handler")
            context['csrf_token'] = get_token(get_current_request())
            frag.add_javascript(loader.load_unicode('static/js/src/staff_graded.js'))
            frag.initialize_js('StaffGradedProblem',
                               json_args={k: context[k]
                                          for k
                                          in ('csrf_token', 'import_url', 'export_url', 'poll_url', 'id')})

        try:
            score = get_score(self.location, self.runtime.user_id) or {}
            context['grades_available'] = True
        except NoSuchServiceError:
            context['grades_available'] = False
        else:
            if score:
                grade = score['score']
                context['score_string'] = _('{score} / {total} points').format(score=grade, total=self.weight)
            else:
                context['score_string'] = _('{total} points possible').format(total=self.weight)
        frag.add_content(loader.render_django_template('static/html/staff_graded.html', context))
        return frag
示例#4
0
    def test_block_views(self):
        # Create a blockstore content library
        library = self._create_library(slug="testlib1_preview",
                                       title="Test Library 1",
                                       description="Testing XBlocks")
        # Add content to the library
        html_block_id = self._add_block_to_library(
            library["id"], "html", "html_student_preview")["id"]
        self._set_library_block_olx(html_block_id,
                                    '<html>Student Preview Test</html>')

        # Create a modulestore course
        course = CourseFactory.create(modulestore=self.store,
                                      user_id=self.user.id)
        CourseInstructorRole(course.id).add_users(self.user)
        # Add a "Source from Library" block to the course
        source_block = ItemFactory.create(category="library_sourced",
                                          parent=course,
                                          parent_location=course.location,
                                          user_id=self.user.id,
                                          modulestore=self.store)

        # Check if author_view for empty block renders using the editor template
        html = source_block.render(AUTHOR_VIEW).content
        loader = ResourceLoader('xmodule.library_sourced_block')
        expected_html = loader.render_django_template(
            'templates/library-sourced-block-author-view.html',
            {'save_url': handler_url(source_block, 'submit_studio_edits')})
        self.assertEqual(expected_html, html)

        submit_studio_edits_url = '/xblock/{0}/handler/submit_studio_edits'.format(
            source_block.scope_ids.usage_id)
        post_data = {
            "values": {
                "source_block_id": html_block_id
            },
            "defaults": ["display_name"]
        }
        # Import the html block from the library to the course
        self.client.post(submit_studio_edits_url,
                         data=post_data,
                         format='json')

        # Check if author_view for a configured block renders the children correctly
        # Use self.get_block_view for rendering these as mako templates are mocked to return repr of the template
        # instead of the rendered html
        res = self.get_block_view(source_block, AUTHOR_VIEW)
        self.assertNotIn('library-sourced-block-author-view.html', res)
        self.assertIn('studio_render_children_view.html', res)
        self.assertIn('Student Preview Test', res)

        # Check if student_view renders the children correctly
        res = self.get_block_view(source_block, STUDENT_VIEW)
        self.assertIn('Student Preview Test', res)
    def student_view(self, context=None):
        loader = ResourceLoader('colab_xblock')
        notebook_url = self._get_colab_url(self.notebook_url)
        context = dict(
            url=notebook_url,
            button_text=self.button_text,
            instructions=self.instructions,
        )

        template = loader.render_django_template(
            'static/html/student_view.html', context=context)

        # add html and css
        frag = Fragment(template)
        frag.add_css(self.resource_string('static/css/style.css'))
        return frag
示例#6
0
    def test_build_fragment_prompt_html(self):
        """
        Checks that build_fragment allows html in the prompt variable

        if the 'safe' filter is not used then the django
        template pipeline returns html tags like,
            '&lt;p&gt;Please enter your response here&lt;/p&gt;'
        """
        studio_settings_prompt = "<p>Please enter your response here</p>"
        context = {
            'prompt': studio_settings_prompt,
        }
        loader = ResourceLoader('freetextresponse')
        template = loader.render_django_template(
            'templates/freetextresponse_view.html',
            context=Context(context),
        )
        fragment = self.xblock.build_fragment(
            template,
            initialize_js_func='FreeTextResponseView',
            additional_css=[],
            additional_js=[],
        )
        self.assertIn(studio_settings_prompt, fragment.content)
示例#7
0
 def test_render_django_template(self):
     loader = ResourceLoader(__name__)
     s = loader.render_django_template("data/simple_django_template.txt",
                                       example_context)
     self.assertEqual(s, expected_filled_template)
示例#8
0
    def calculate_results(self, submissions):
        score = 0
        results = []
        tips = None

        if not self.hide_results:
            tips = self.get_tips()

        for choice in self.custom_choices:
            choice_completed = True
            choice_tips_html = []
            choice_selected = choice.value in submissions

            if choice.value in self.required_choices:
                if not choice_selected:
                    choice_completed = False
            elif choice_selected and choice.value not in self.ignored_choices:
                choice_completed = False

            if choice_completed:
                score += 1

            choice_result = {
                'value': choice.value,
                'selected': choice_selected,
                'content': choice.content
            }
            # Only include tips/results in returned response if we want to display them
            if not self.hide_results:
                # choice_tips_html list is being set only when 'self.hide_results' is False, to optimize,
                # execute the loop only when 'self.hide_results' is set to False
                for tip in tips:
                    if choice.value in tip.values:
                        choice_tips_html.append(
                            tip.render('mentoring_view').content)
                        break

                loader = ResourceLoader(__name__)
                choice_result['completed'] = choice_completed
                choice_result['tips'] = loader.render_django_template(
                    'templates/html/tip_choice_group.html', {
                        'tips_html': choice_tips_html,
                    })

            results.append(choice_result)

        status = 'incorrect' if score <= 0 else 'correct' if score >= len(
            results) else 'partial'

        if sub_api:
            # Send the answer as a concatenated list to the submissions API
            answer = [
                choice['content'] for choice in results if choice['selected']
            ]
            sub_api.create_submission(self.student_item_key, ', '.join(answer))

        return {
            'submissions': submissions,
            'status': status,
            'choices': results,
            'message': self.message_formatted,
            'weight': self.weight,
            'score': (float(score) / len(results)) if results else 0,
        }
 def test_render_django_template(self):
     loader = ResourceLoader(__name__)
     s = loader.render_django_template("data/simple_django_template.txt", example_context)
     self.assertEquals(s, expected_filled_template)
示例#10
0
def lti_embed(*,
              html_element_id,
              resource_link_id,
              user_id,
              roles,
              context_id,
              context_title,
              context_label,
              result_sourcedid,
              lti_consumer=None,
              lti_launch_url=None,
              oauth_key=None,
              oauth_secret=None,
              person_sourcedid=None,
              person_contact_email_primary=None,
              outcome_service_url=None,
              launch_presentation_locale=None,
              **custom_parameters):
    """
    Returns an HTML template with JavaScript that will launch an LTI embed

    IMPORTANT NOTE: This method uses keyword only arguments as described in PEP 3102.
    Given the large number of arguments for this method, there is a  desire to
    guarantee that developers using this method know which arguments are being set
    to which values.
    See https://www.python.org/dev/peps/pep-3102/

    This method will use the LtiConsumer1p1 class to generate an HTML form and
    JavaScript that will automatically launch the LTI embedding, but it does not
    generate any response to encapsulate this content. The caller of this method
    must render the HTML on their own.

    Note: This method uses xblockutils.resources.ResourceLoader to load the HTML
    template used. The rationale for this is that ResourceLoader is agnostic
    to XBlock code and functionality. It is recommended that this remain in use
    until LTI1.3 support is merged, or a better means of loading the template is
    made available.

    Arguments:
        html_element_id (string):  Value to use as the HTML element id in the HTML form
        resource_link_id (string):  Opaque identifier guaranteed to be unique
            for every placement of the link
        user_id (string):  Unique value identifying the user
        roles (string):  A comma separated list of role values
        context_id (string):  Opaque identifier used to uniquely identify the
            context that contains the link being launched
        context_title (string):  Plain text title of the context
        context_label (string):  Plain text label for the context
        result_sourcedid (string):  Indicates the LIS Result Identifier (if any)
            and uniquely identifies a row and column within the Tool Consumer gradebook
        lti_consumer (LtiConsumer1p1): A pre-configured LtiConsumer1p1 object
            as an alternative to providing the launch url, oauth key and oauth secret
        lti_launch_url (string):  The URL to send the LTI Launch request to
        oauth_key (string):  The OAuth consumer key
        oauth_secret (string):  The OAuth consumer secret
        person_sourcedid (string):  LIS identifier for the user account performing the launch
        person_contact_email_primary (string):  Primary contact email address of the user
        outcome_service_url (string):  URL pointing to the outcome service. This
            is required if the Tool Consumer is accepting outcomes for launches
            associated with the resource_link_id
        launch_presentation_locale (string):  Language, country and variant as
            represented using the IETF Best Practices for Tags for Identifying
            Languages (BCP-47)
        custom_parameters (dict): Contains any other keyword arguments not listed
            above. It will filter out all arguments provided that do not start with
            'custom_' and will submit the remaining arguments on the LTI Launch form

    Returns:
        unicode: HTML template with the form and JavaScript to automatically
            launch the LTI embedding
    """
    if lti_consumer is None:
        lti_consumer = LtiConsumer1p1(lti_launch_url, oauth_key, oauth_secret)
    else:
        lti_launch_url = lti_consumer.lti_launch_url

    # Set LTI parameters from kwargs
    lti_consumer.set_user_data(
        user_id,
        roles,
        result_sourcedid,
        person_sourcedid=person_sourcedid,
        person_contact_email_primary=person_contact_email_primary)
    lti_consumer.set_context_data(context_id, context_title, context_label)

    if outcome_service_url:
        lti_consumer.set_outcome_service_url(outcome_service_url)

    if launch_presentation_locale:
        lti_consumer.set_launch_presentation_locale(launch_presentation_locale)

    lti_consumer.set_custom_parameters({
        key: value
        for key, value in custom_parameters.items()
        if key.startswith('custom_')
    })

    lti_parameters = lti_consumer.generate_launch_request(resource_link_id)

    # Prepare form data
    context = {'launch_url': lti_launch_url, 'element_id': html_element_id}
    context.update({'lti_parameters': lti_parameters})

    # Render the form template and return the template
    loader = ResourceLoader(__name__)
    template = loader.render_django_template(
        '../../templates/html/lti_launch.html', context)
    return template