Files
edx-platform/xmodule/capa/tests/test_customrender.py
2026-01-07 16:39:11 +05:00

88 lines
2.8 KiB
Python

"""Unit tests for custom rendering of capa problem elements, including solutions and math expressions."""
import unittest
from xml.sax import saxutils
from lxml import etree
from xmodule.capa import customrender
from xmodule.capa.tests.helpers import mock_capa_system
# just a handy shortcut
lookup_tag = customrender.registry.get_class_for_tag
def extract_context(xml):
"""
Given an xml element corresponding to the output of test_capa_system.render_template, get back the
original context
"""
return eval(xml.text) # pylint: disable=eval-used
def quote_attr(s):
"""Return a string safe for XML attributes without outer quotes."""
return saxutils.quoteattr(s)[1:-1] # don't want the outer quotes
class HelperTest(unittest.TestCase):
"""
Make sure that our helper function works!
"""
def check(self, d):
"""Check that rendering and extracting context returns the original data."""
xml = etree.XML(mock_capa_system().render_template("blah", d))
assert d == extract_context(xml)
def test_extract_context(self):
"""Test that the context can be extracted correctly from rendered XML."""
self.check({})
self.check({1, 2})
self.check({"id", "an id"})
self.check({'with"quote', 'also"quote'})
class SolutionRenderTest(unittest.TestCase):
"""
Make sure solutions render properly.
"""
def test_rendering(self):
"""Ensure that <solution> elements are rendered correctly with proper IDs."""
solution = "To compute unicorns, count them."
xml_str = f"""<solution id="solution_12">{solution}</solution>"""
element = etree.fromstring(xml_str)
renderer = lookup_tag("solution")(mock_capa_system(), element)
assert renderer.id == "solution_12"
# Our test_capa_system "renders" templates to a div with the repr of the context.
xml = renderer.get_html()
context = extract_context(xml)
assert context == {"id": "solution_12"}
class MathRenderTest(unittest.TestCase):
"""
Make sure math renders properly.
"""
def check_parse(self, latex_in, mathjax_out):
"""Check that LaTeX input is correctly converted to MathJax output."""
xml_str = f"""<math>{latex_in}</math>"""
element = etree.fromstring(xml_str)
renderer = lookup_tag("math")(mock_capa_system(), element)
assert renderer.mathstr == mathjax_out
def test_parsing(self):
"""Verify that LaTeX input is correctly converted to MathJax output."""
self.check_parse("$abc$", "[mathjaxinline]abc[/mathjaxinline]")
self.check_parse("$abc", "$abc")
self.check_parse(r"$\displaystyle 2+2$", "[mathjax] 2+2[/mathjax]")
# NOTE: not testing get_html yet because I don't understand why it's doing what it's doing.