Debian Codegraph @

tests/test_escape.py

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