test_escape.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from __future__ import annotations
  2. import typing as t
  3. import pytest
  4. from markupsafe import escape
  5. from markupsafe import Markup
  6. @pytest.mark.parametrize(
  7. ("value", "expect"),
  8. (
  9. # empty
  10. ("", ""),
  11. # ascii
  12. ("abcd&><'\"efgh", "abcd&amp;&gt;&lt;&#39;&#34;efgh"),
  13. ("&><'\"efgh", "&amp;&gt;&lt;&#39;&#34;efgh"),
  14. ("abcd&><'\"", "abcd&amp;&gt;&lt;&#39;&#34;"),
  15. # 2 byte
  16. ("こんにちは&><'\"こんばんは", "こんにちは&amp;&gt;&lt;&#39;&#34;こんばんは"),
  17. ("&><'\"こんばんは", "&amp;&gt;&lt;&#39;&#34;こんばんは"),
  18. ("こんにちは&><'\"", "こんにちは&amp;&gt;&lt;&#39;&#34;"),
  19. # 4 byte
  20. (
  21. "\U0001f363\U0001f362&><'\"\U0001f37a xyz",
  22. "\U0001f363\U0001f362&amp;&gt;&lt;&#39;&#34;\U0001f37a xyz",
  23. ),
  24. ("&><'\"\U0001f37a xyz", "&amp;&gt;&lt;&#39;&#34;\U0001f37a xyz"),
  25. ("\U0001f363\U0001f362&><'\"", "\U0001f363\U0001f362&amp;&gt;&lt;&#39;&#34;"),
  26. ),
  27. )
  28. def test_escape(value: str, expect: str) -> None:
  29. assert escape(value) == Markup(expect)
  30. class Proxy:
  31. def __init__(self, value: t.Any) -> None:
  32. self.__value = value
  33. @property # type: ignore[misc]
  34. def __class__(self) -> type[t.Any]:
  35. # Make o.__class__ and isinstance(o, str) see the proxied object.
  36. return self.__value.__class__ # type: ignore[no-any-return]
  37. def __str__(self) -> str:
  38. return str(self.__value)
  39. def test_proxy() -> None:
  40. """Handle a proxy object that pretends its __class__ is str."""
  41. p = Proxy("test")
  42. assert p.__class__ is str
  43. assert isinstance(p, str)
  44. assert escape(p) == Markup("test")
  45. class ReferenceStr(str):
  46. def __str__(self) -> str:
  47. # This should return a str, but it returns the subclass instead.
  48. return self
  49. def test_subclass() -> None:
  50. """Handle if str(o) does not return a plain str."""
  51. s = ReferenceStr("test")
  52. assert isinstance(s, str)
  53. assert escape(s) == Markup("test")