diff --git a/pyproject.toml b/pyproject.toml index 3e9ac359..26ade48a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -45,7 +45,6 @@ dependencies = [ "openedx-calc", "path", "pyparsing", - "pytz", "random2", "requests", "shapely", diff --git a/src/xblock_lti/block.py b/src/xblock_lti/block.py index bc9950df..b2aa1a63 100644 --- a/src/xblock_lti/block.py +++ b/src/xblock_lti/block.py @@ -62,6 +62,7 @@ from unittest import mock from urllib import parse from xml.sax.saxutils import escape +from zoneinfo import ZoneInfo import markupsafe import nh3 @@ -71,7 +72,6 @@ from lxml import etree from oauthlib.oauth1.rfc5849 import signature from opaque_keys.edx.keys import CourseKey -from pytz import UTC from web_fragments.fragment import Fragment from webob import Response from xblock.core import List, Scope, String, XBlock @@ -94,7 +94,7 @@ DOCS_ANCHOR_TAG_OPEN = ( "" + "href='https://docs.openedx.org/en/latest/educators/navigation/components_activities.html#lti-component'>" ) BREAK_TAG = "
" @@ -389,6 +389,7 @@ class LTIBlock( # Indicates that this XBlock has been extracted from edx-platform. is_extracted = True + i18n_js_namespace = "XBlockLTII18N" def max_score(self): return self.weight if self.has_score else None @@ -499,6 +500,18 @@ def get_context(self): # This lets all plaintext through. sanitized_comment = nh3.clean(self.score_comment) + # The score text next to the title, translated with the block's catalog as in the built-in block. + gettext = self.runtime.service(self, "i18n").ugettext + if self.module_score is not None: + # Translators: "points" is the student's achieved score on this LTI unit, and "total_points" is the + # maximum number of points achievable. + score_text = gettext("{points} / {total_points} points").format( + points=self.module_score, total_points=self.weight + ) + else: + # Translators: "total_points" is the maximum number of points achievable on this LTI unit + score_text = gettext("{total_points} points possible").format(total_points=self.weight) + return { "input_fields": self.get_input_fields(), # These parameters do not participate in OAuth signing. @@ -512,6 +525,7 @@ def get_context(self): "has_score": self.has_score, "weight": self.weight, "module_score": self.module_score, + "score_text": score_text, "comment": sanitized_comment, "description": self.description, "ask_to_send_username": self.ask_to_send_username, @@ -520,6 +534,19 @@ def get_context(self): "accept_grades_past_due": self.accept_grades_past_due, } + def _add_i18n_js_catalog(self, fragment): + """ + Add this block's JavaScript translation catalog to the fragment, if the runtime provides one. + + The catalog defines ``window.XBlockLTII18N`` (see ``i18n_js_namespace``). + Add it before the block's own JS. + """ + i18n_service = self.runtime.service(self, "i18n") + url_getter = getattr(i18n_service, "get_javascript_i18n_catalog_url", None) + url = url_getter(self) if url_getter else None + if url: + fragment.add_javascript_url(url) + def student_view(self, _context=None): """ Create primary view of the LTIBlock, shown to students when viewing courses. @@ -532,6 +559,7 @@ def student_view(self, _context=None): ) frag.add_css(resource_loader.load_unicode("static/css/lti.css")) + self._add_i18n_js_catalog(frag) frag.add_javascript(resource_loader.load_unicode("static/js/src/lti.js")) frag.initialize_js("LTIBlock") return frag @@ -1006,7 +1034,7 @@ def is_past_due(self): close_date = due_date + self.graceperiod else: close_date = due_date - return close_date is not None and datetime.datetime.now(UTC) > close_date + return close_date is not None and datetime.datetime.now(ZoneInfo("UTC")) > close_date @classmethod def definition_from_xml(cls, xml_object, system): diff --git a/src/xblock_lti/static/css/lti.css b/src/xblock_lti/static/css/lti.css index 7e9b5761..7cab9d17 100644 --- a/src/xblock_lti/static/css/lti.css +++ b/src/xblock_lti/static/css/lti.css @@ -1,12 +1,14 @@ -/* CSS for LTIBlock */ +/* CSS for LTIBlock. Every rule is scoped to the block's root element (.lti-wrapper in + templates/lti.html) so it can't restyle other blocks on the page, as the built-in block's + .xmodule_display.xmodule_LTIBlock scope did. */ @import url("https://fonts.googleapis.com/css?family=Open+Sans:300,400,400i,600,700"); -h2.problem-header { +.lti-wrapper h2.problem-header { display: inline-block; } -div.problem-progress { +.lti-wrapper div.problem-progress { display: inline-block; padding-left: 5px; color: #666; @@ -14,44 +16,44 @@ div.problem-progress { font-size: 1em; } -div.lti { +.lti-wrapper div.lti { margin: 0 auto; } -div.lti .wrapper-lti-link { +.lti-wrapper div.lti .wrapper-lti-link { font-size: 14px; background-color: #f6f6f6; padding: 20px; } -div.lti .wrapper-lti-link .lti-link { +.lti-wrapper div.lti .wrapper-lti-link .lti-link { margin-bottom: 0; text-align: right; } -div.lti .wrapper-lti-link .lti-link .link_lti_new_window { +.lti-wrapper div.lti .wrapper-lti-link .lti-link .link_lti_new_window { font-size: 13px; line-height: 20.72px; } -div.lti form.ltiLaunchForm { +.lti-wrapper div.lti form.ltiLaunchForm { display: none; } -div.lti iframe.ltiLaunchFrame { +.lti-wrapper div.lti iframe.ltiLaunchFrame { width: 100%; height: 800px; display: block; border: 0px; } -div.lti h4.problem-feedback-label { +.lti-wrapper div.lti h4.problem-feedback-label { font-weight: 100; font-size: 1em; font-family: "Source Sans", "Open Sans", Verdana, Geneva, sans-serif, sans-serif; } -div.lti div.problem-feedback { +.lti-wrapper div.lti div.problem-feedback { margin-top: 5px; margin-bottom: 5px; } diff --git a/src/xblock_lti/static/js/src/lti.js b/src/xblock_lti/static/js/src/lti.js index a9ab1fd1..96fdf3a4 100644 --- a/src/xblock_lti/static/js/src/lti.js +++ b/src/xblock_lti/static/js/src/lti.js @@ -3,6 +3,15 @@ function LTIBlock(runtime, element) { 'use strict'; + /* + Use this block's translation catalog (window.XBlockLTII18N, loaded by the + runtime before this file) when it is available, else the page's global gettext. + */ + function gettext(msgid) { + var catalog = window.XBlockLTII18N || window; + return catalog.gettext ? catalog.gettext(msgid) : msgid; + } + const $lti = $(element).find('.lti'); const askToSendUsername = $lti.data('ask-to-send-username') === 'True'; const askToSendEmail = $lti.data('ask-to-send-email') === 'True'; @@ -11,11 +20,11 @@ function LTIBlock(runtime, element) { // accept or reject sending their information to a third party $(element).on('click', '.link_lti_new_window', function() { if (askToSendUsername && askToSendEmail) { - return confirm('Click OK to have your username and e-mail address sent to a 3rd party application.\n\nClick Cancel to return to this page without sending your information.'); + return confirm(gettext('Click OK to have your username and e-mail address sent to a 3rd party application.\n\nClick Cancel to return to this page without sending your information.')); } else if (askToSendUsername) { - return confirm('Click OK to have your username sent to a 3rd party application.\n\nClick Cancel to return to this page without sending your information.'); + return confirm(gettext('Click OK to have your username sent to a 3rd party application.\n\nClick Cancel to return to this page without sending your information.')); } else if (askToSendEmail) { - return confirm('Click OK to have your e-mail address sent to a 3rd party application.\n\nClick Cancel to return to this page without sending your information.'); + return confirm(gettext('Click OK to have your e-mail address sent to a 3rd party application.\n\nClick Cancel to return to this page without sending your information.')); } else { return true; } diff --git a/src/xblock_lti/templates/lti.html b/src/xblock_lti/templates/lti.html index da153fef..455f9900 100644 --- a/src/xblock_lti/templates/lti.html +++ b/src/xblock_lti/templates/lti.html @@ -7,18 +7,7 @@

{% if has_score and weight %} -
- {% if module_score is not None %} - {# Translators: "points" is the student's achieved score on this LTI unit, and "total_points" is the maximum number of points achievable. #} - {% trans "points" as points_trans %} - {% trans "{points} / {total_points} points" as score_trans %} - ({{ module_score }} / {{ weight }} {{ points_trans }}) - {% else %} - {# Translators: "total_points" is the maximum number of points achievable on this LTI unit #} - {% trans "total_points" as total_points_trans %} - ({{ weight }} {{ total_points_trans }} possible) - {% endif %} -
+
({{ score_text }})
{% endif %}
{% endif %} @@ -57,12 +47,12 @@

{% endif %} {% elif not hide_launch %}

- {{ _('Please provide launch_url. Click "Edit", and fill in the required fields.') }} + {% trans 'Please provide launch_url. Click "Edit", and fill in the required fields.' %}

{% endif %} {% if has_score and comment %} -

${_("Feedback on your work from the grader:")}

+

{% trans "Feedback on your work from the grader:" %}

{# sanitized with nh3 in view #} {{ comment|safe }} diff --git a/src/xblock_lti/tests/test_lti20_unit.py b/src/xblock_lti/tests/test_lti20_unit.py index 59ac12db..2a757c8e 100644 --- a/src/xblock_lti/tests/test_lti20_unit.py +++ b/src/xblock_lti/tests/test_lti20_unit.py @@ -3,10 +3,10 @@ import datetime import textwrap from unittest.mock import Mock +from zoneinfo import ZoneInfo from django.conf import settings from django.test import TestCase, override_settings -from pytz import UTC from xblock.field_data import DictFieldData from xblock_lti.block import LTIBlock @@ -422,7 +422,7 @@ def test_lti20_request_handler_grade_past_due(self): Test that we get a 404 when accept_grades_past_due is False and it is past due """ self.setup_system_xblock_mocks_for_lti20_request_test() - self.xblock.due = datetime.datetime.now(UTC) + self.xblock.due = datetime.datetime.now(ZoneInfo("UTC")) self.xblock.accept_grades_past_due = False mock_request = self.get_signed_lti20_mock_request(self.GOOD_JSON_PUT) response = self.xblock.lti_2_0_result_rest_handler(mock_request, "user/abcd") diff --git a/src/xblock_lti/tests/test_lti_student_view.py b/src/xblock_lti/tests/test_lti_student_view.py new file mode 100644 index 00000000..1076bb0f --- /dev/null +++ b/src/xblock_lti/tests/test_lti_student_view.py @@ -0,0 +1,155 @@ +""" +Tests for the LTI block's student view: rendered strings, translations, JS and CSS. + +These cover the gaps listed in openedx/xblocks-core#359, where the extracted block differed from +the built-in LTI block that openedx/openedx-platform#38747 removes. +""" + +import gettext +import re +from importlib import resources +from unittest.mock import Mock + +from django.test import TestCase, override_settings +from xblock.field_data import DictFieldData + +from xblock_lti import block as lti_block +from xblock_lti.block import LTIBlock + +from .helpers import get_test_system + + +class StubBlockCatalog(gettext.NullTranslations): + """ + A minimal stand-in for the block's i18n service, backed by a fixed catalog. + + It works both for ``ugettext`` calls in Python and for the ``{% trans %}`` tags in the + template, which merge the service's ``_catalog`` into Django's active translation. + """ + + def __init__(self, catalog, js_catalog_url=None): + super().__init__() + self._catalog = dict(catalog) + self._info = {} + self.plural = lambda n: int(n != 1) + self.js_catalog_url = js_catalog_url + + def get_javascript_i18n_catalog_url(self, _block): + """Like the platform's i18n service: the URL of the block's JS catalog, if any.""" + return self.js_catalog_url + + def gettext(self, message): + return self._catalog.get(message, message) + + ugettext = gettext + + +@override_settings(LMS_BASE="edx.org") +class LTIStudentViewTest(TestCase): + """Render ``student_view`` and check what learners see.""" + + def setUp(self): + super().setUp() + self.runtime = get_test_system() + course = Mock(name="course", lti_passports=["lti_id:test_client:test_secret"]) + self.runtime.modulestore = Mock(name="modulestore") + self.runtime.modulestore.get_course.return_value = course + self.xblock = LTIBlock(self.runtime, DictFieldData({}), Mock()) + self.xblock.lti_id = "lti_id" + self.xblock.launch_url = "http://tool.example.org/launch" + self.xblock.has_score = True + self.xblock.weight = 1.0 + + def render(self): + """Return the student view HTML.""" + return self.xblock.student_view().content + + def use_catalog(self, catalog): + """Make the runtime's i18n service return translations from ``catalog``.""" + self.runtime._services["i18n"] = StubBlockCatalog(catalog) # pylint: disable=protected-access + + def test_grader_feedback_label_renders(self): + """The label above grader comments renders as text, not as a literal template expression.""" + self.xblock.score_comment = "Nice work" + html = self.render() + assert "Feedback on your work from the grader:" in html + assert "${" not in html + + def test_points_possible_text(self): + """Without a score, the block shows how many points are possible, as the built-in block did.""" + html = self.render() + assert "(1.0 points possible)" in html + assert "total_points" not in html + + def test_score_text(self): + """With a score, the block shows the learner's points out of the total.""" + self.xblock.module_score = 0.5 + html = self.render() + assert "(0.5 / 1.0 points)" in html + + def test_score_text_uses_block_catalog(self): + """The score strings are translated with the block's catalog.""" + self.use_catalog( + { + "{total_points} points possible": "{total_points} points possibles", + "{points} / {total_points} points": "{points} sur {total_points} points", + } + ) + assert "(1.0 points possibles)" in self.render() + self.xblock.module_score = 0.5 + assert "(0.5 sur 1.0 points)" in self.render() + + def test_new_window_link_uses_block_catalog(self): + """The default "View resource in a new window" link text comes from the block's catalog.""" + self.xblock.open_in_a_new_page = True + self.use_catalog({"View resource in a new window": "Voir la ressource dans une nouvelle fenĂȘtre"}) + assert "Voir la ressource dans une nouvelle fenĂȘtre" in self.render() + + def test_missing_launch_url_message_uses_block_catalog(self): + """The missing-launch_url error comes from the block's catalog.""" + self.xblock.launch_url = "" + message = 'Please provide launch_url. Click "Edit", and fill in the required fields.' + self.use_catalog({message: "Indiquez launch_url."}) + assert "Indiquez launch_url." in self.render() + + def test_student_view_adds_js_catalog_before_block_js(self): + """The block's JS translation catalog, when available, loads before lti.js.""" + self.runtime._services["i18n"] = StubBlockCatalog({}, js_catalog_url="/i18n/lti.js") # pylint: disable=protected-access + resources_list = self.xblock.student_view().resources + urls = [r.data for r in resources_list if r.kind == "url"] + assert urls == ["/i18n/lti.js"] + assert resources_list.index(next(r for r in resources_list if r.kind == "url")) < resources_list.index( + next(r for r in resources_list if r.kind == "text" and r.mimetype == "application/javascript") + ) + + def test_i18n_js_namespace(self): + """The JS catalog namespace matches the one lti.js reads.""" + assert LTIBlock.i18n_js_namespace == "XBlockLTII18N" + + +class LTIStaticAssetsTest(TestCase): + """Checks on the block's static JS and CSS.""" + + @staticmethod + def read(path): + return resources.files("xblock_lti").joinpath(path).read_text(encoding="utf-8") + + def test_confirm_prompts_are_translatable(self): + """Each confirm() prompt goes through gettext(), as in the built-in block.""" + js = self.read("static/js/src/lti.js") + assert js.count("confirm(") == 3 + assert js.count("confirm(gettext(") == 3 + assert "window.XBlockLTII18N" in js + + def test_css_rules_are_scoped_to_the_block(self): + """Every CSS rule is scoped to the block's root element, so it can't restyle other blocks.""" + css = re.sub(r"/\*.*?\*/", "", self.read("static/css/lti.css"), flags=re.S) + selectors = [s.strip() for s in re.findall(r"([^{}@;]+)\{", css)] + assert selectors + for selector in selectors: + assert selector.startswith(".lti-wrapper "), selector + + def test_docs_link(self): + """The Studio help text links to docs.openedx.org (openedx/openedx-platform#36461).""" + assert "https://docs.openedx.org/" in lti_block.DOCS_ANCHOR_TAG_OPEN + assert "readthedocs" not in lti_block.DOCS_ANCHOR_TAG_OPEN diff --git a/src/xblock_lti/tests/test_lti_unit.py b/src/xblock_lti/tests/test_lti_unit.py index 33b797ad..f8bf2d52 100644 --- a/src/xblock_lti/tests/test_lti_unit.py +++ b/src/xblock_lti/tests/test_lti_unit.py @@ -5,6 +5,7 @@ from copy import copy from unittest.mock import Mock, PropertyMock, patch from urllib import parse +from zoneinfo import ZoneInfo import pytest from django.conf import settings @@ -12,7 +13,6 @@ from lxml import etree from opaque_keys.edx.keys import CourseKey from opaque_keys.edx.locator import BlockUsageLocator -from pytz import UTC from webob.request import Request from xblock.field_data import DictFieldData from xblock.fields import ScopeIds @@ -195,7 +195,7 @@ def test_grade_past_due(self): Should fail if we do not accept past due grades, and it is past due. """ self.xblock.accept_grades_past_due = False - self.xblock.due = datetime.datetime.now(UTC) + self.xblock.due = datetime.datetime.now(ZoneInfo("UTC")) self.xblock.graceperiod = Timedelta().from_json("0 seconds") request = Request(self.environ) request.body = self.get_request_body() diff --git a/uv.lock b/uv.lock index c8c71bdd..3320aced 100644 --- a/uv.lock +++ b/uv.lock @@ -2971,7 +2971,6 @@ dependencies = [ { name = "openedx-calc" }, { name = "path" }, { name = "pyparsing" }, - { name = "pytz" }, { name = "random2" }, { name = "requests" }, { name = "shapely" }, @@ -3070,7 +3069,6 @@ requires-dist = [ { name = "openedx-calc" }, { name = "path" }, { name = "pyparsing" }, - { name = "pytz" }, { name = "random2" }, { name = "requests" }, { name = "shapely" },