|
17 | 17 |
|
18 | 18 | import pytest |
19 | 19 |
|
20 | | -from paasng.utils.text import calculate_percentage, camel_to_snake, remove_suffix, strip_html_tags |
| 20 | +from paasng.utils.text import ( |
| 21 | + BraceOnlyTemplate, |
| 22 | + basic_str_format, |
| 23 | + calculate_percentage, |
| 24 | + camel_to_snake, |
| 25 | + remove_suffix, |
| 26 | + strip_html_tags, |
| 27 | +) |
21 | 28 |
|
22 | 29 |
|
23 | 30 | class TestStripHTMLTags: |
@@ -101,3 +108,43 @@ def test_calculate_percentage(x, y, decimal_places, expected): |
101 | 108 | else: |
102 | 109 | # 否则,应该返回期望值 |
103 | 110 | assert calculate_percentage(x, y, decimal_places) == expected |
| 111 | + |
| 112 | + |
| 113 | +class TestBraceOnlyTemplate: |
| 114 | + @pytest.mark.parametrize( |
| 115 | + ("template_str", "kwargs", "expected"), |
| 116 | + [ |
| 117 | + # Basic substitution |
| 118 | + ("Hello {name}, welcome to {place}!", {"name": "foo", "place": "bar"}, "Hello foo, welcome to bar!"), |
| 119 | + # Variable inside word |
| 120 | + ("prefix_{var}_suffix", {"var": "test"}, "prefix_test_suffix"), |
| 121 | + # Underscore variable |
| 122 | + ("{underscore_var}", {"underscore_var": "value"}, "value"), |
| 123 | + ], |
| 124 | + ) |
| 125 | + def test_various_valid_patterns(self, template_str, kwargs, expected): |
| 126 | + template = BraceOnlyTemplate(template_str) |
| 127 | + assert template.substitute(**kwargs) == expected |
| 128 | + |
| 129 | + def test_escaped_braces(self): |
| 130 | + # Only "{" needs to be escaped |
| 131 | + template = BraceOnlyTemplate("Use {{ to escape braces, like {{name}") |
| 132 | + assert template.substitute(name="foo") == "Use { to escape braces, like {name}" |
| 133 | + |
| 134 | + def test_no_substitution_needed(self): |
| 135 | + template = BraceOnlyTemplate("No variables here!") |
| 136 | + assert template.substitute() == "No variables here!" |
| 137 | + |
| 138 | + def test_missing_variable_raises_error(self): |
| 139 | + template = BraceOnlyTemplate("Hello {name}!") |
| 140 | + with pytest.raises(KeyError): |
| 141 | + template.substitute() |
| 142 | + |
| 143 | + |
| 144 | +class Test__basic_str_format: |
| 145 | + def test_basic(self): |
| 146 | + assert basic_str_format("Hello {name}!", {"name": "foo"}) == "Hello foo!" |
| 147 | + |
| 148 | + def test_index_access_should_fail(self): |
| 149 | + with pytest.raises(ValueError, match="Invalid placeholder .*"): |
| 150 | + basic_str_format("Hello {names[0]}!", {"names": "foobar"}) |
0 commit comments