| 1 |
# BSD 2-Clause License |
| 2 |
# |
| 3 |
# Apprise - Push Notification Library. |
| 4 |
# Copyright (c) 2026, Chris Caron <[email protected]> |
| 5 |
# |
| 6 |
# Redistribution and use in source and binary forms, with or without |
| 7 |
# modification, are permitted provided that the following conditions are met: |
| 8 |
# |
| 9 |
# 1. Redistributions of source code must retain the above copyright notice, |
| 10 |
# this list of conditions and the following disclaimer. |
| 11 |
# |
| 12 |
# 2. Redistributions in binary form must reproduce the above copyright notice, |
| 13 |
# this list of conditions and the following disclaimer in the documentation |
| 14 |
# and/or other materials provided with the distribution. |
| 15 |
# |
| 16 |
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| 17 |
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| 18 |
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| 19 |
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE |
| 20 |
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |
| 21 |
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF |
| 22 |
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 23 |
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN |
| 24 |
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
| 25 |
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
| 26 |
# POSSIBILITY OF SUCH DAMAGE. |
| 27 |
"""Tests for the template variable helpers.""" |
| 28 |
|
| 29 |
import time |
| 30 |
from unittest import mock |
| 31 |
|
| 32 |
import pytest |
| 33 |
|
| 34 |
from apprise.exception import AppriseTemplateError |
| 35 |
from apprise.utils.template import ( |
| 36 |
MAX_TEMPLATE_VALUE_LEN, |
| 37 |
TemplatePlaceholderMap, |
| 38 |
TemplateSchema, |
| 39 |
normalize_name, |
| 40 |
resolve_values, |
| 41 |
validate_value, |
| 42 |
) |
| 43 |
|
| 44 |
|
| 45 |
def schema_of(*entries): |
| 46 |
"""Build a schema from the entries given.""" |
| 47 |
return TemplateSchema.parse(list(entries)) |
| 48 |
|
| 49 |
|
| 50 |
def test_declaration_accepts_a_list(): |
| 51 |
"""A list may mix bare names with names that carry a default.""" |
| 52 |
schema = schema_of("target", {"smtp_host": "smtp.example.com"}) |
| 53 |
assert sorted(schema.names) == ["smtp_host", "target"] |
| 54 |
assert schema.required == ("target",) |
| 55 |
assert schema.variables["smtp_host"].default == "smtp.example.com" |
| 56 |
|
| 57 |
|
| 58 |
def test_declaration_accepts_a_mapping(): |
| 59 |
"""A mapping means the same thing as the list form. |
| 60 |
|
| 61 |
- a value present is the default |
| 62 |
- no value at all makes the variable mandatory |
| 63 |
""" |
| 64 |
schema = TemplateSchema.parse( |
| 65 |
{ |
| 66 |
"smtp_host": "smtp.example.com", |
| 67 |
"target": None, |
| 68 |
} |
| 69 |
) |
| 70 |
assert sorted(schema.names) == ["smtp_host", "target"] |
| 71 |
assert schema.required == ("target",) |
| 72 |
|
| 73 |
|
| 74 |
def test_template_empty_default_is_required(): |
| 75 |
"""``- name:`` reads the same as a bare ``- name``.""" |
| 76 |
assert schema_of({"target": None}).required == ("target",) |
| 77 |
|
| 78 |
|
| 79 |
def test_template_name_case_insensitive(): |
| 80 |
"""TARGET, Target and target all name the same variable.""" |
| 81 |
schema = schema_of("TaRgEt") |
| 82 |
assert schema.names == ("target",) |
| 83 |
assert "TARGET" in schema |
| 84 |
assert normalize_name("TARGET") == "target" |
| 85 |
|
| 86 |
|
| 87 |
def test_template_rejects_duplicate_name(): |
| 88 |
"""The same name twice is refused, even in a different case.""" |
| 89 |
with pytest.raises(AppriseTemplateError): |
| 90 |
schema_of("target", "TARGET") |
| 91 |
|
| 92 |
|
| 93 |
@pytest.mark.parametrize( |
| 94 |
"name", |
| 95 |
["", "a b", "has-dash", "x" * 33, "with.dot", "sym$"], |
| 96 |
) |
| 97 |
def test_template_rejects_invalid_name(name): |
| 98 |
"""Only letters, digits and underscores are allowed.""" |
| 99 |
with pytest.raises(AppriseTemplateError): |
| 100 |
schema_of(name) |
| 101 |
|
| 102 |
|
| 103 |
def test_template_many_declarations(): |
| 104 |
"""There is no cap on how many variables are declared.""" |
| 105 |
schema = schema_of(*[f"v{i}" for i in range(500)]) |
| 106 |
assert len(schema.names) == 500 |
| 107 |
|
| 108 |
|
| 109 |
@pytest.mark.parametrize("entries", ["a string", 42, None]) |
| 110 |
def test_template_rejects_invalid_section(entries): |
| 111 |
"""The section has to be a list or a mapping.""" |
| 112 |
with pytest.raises(AppriseTemplateError): |
| 113 |
TemplateSchema.parse(entries) |
| 114 |
|
| 115 |
|
| 116 |
def test_template_replaces_declared_names_only(): |
| 117 |
"""An undeclared ${...} is left exactly as it was written. |
| 118 |
|
| 119 |
This is what keeps a password holding ``${`` intact. |
| 120 |
""" |
| 121 |
placeholders = TemplatePlaceholderMap(schema_of("target"), "") |
| 122 |
text = "json://user:${NOT_DECLARED}@host/${TARGET}" |
| 123 |
encoded = placeholders.encode(text) |
| 124 |
assert "${NOT_DECLARED}" in encoded |
| 125 |
assert "${TARGET}" not in encoded |
| 126 |
|
| 127 |
|
| 128 |
@pytest.mark.parametrize( |
| 129 |
("text", "expected"), |
| 130 |
[ |
| 131 |
# A "$" in front is ordinary text kept beside the value |
| 132 |
("$${A}", "$real"), |
| 133 |
# ...as is any other text either side of the marker |
| 134 |
("x-$${A}-y", "x-$real-y"), |
| 135 |
# Two of them are simply two |
| 136 |
("$$${A}", "$$real"), |
| 137 |
], |
| 138 |
) |
| 139 |
def test_template_dollar_is_literal(text, expected): |
| 140 |
"""There is no escape syntax; a "$" is just a "$".""" |
| 141 |
placeholders = TemplatePlaceholderMap(schema_of("a"), "") |
| 142 |
encoded = placeholders.encode(text) |
| 143 |
|
| 144 |
assert placeholders.used(encoded) == {"a"} |
| 145 |
assert placeholders.substitute(encoded, {"a": "real"}) == expected |
| 146 |
|
| 147 |
|
| 148 |
def test_template_marker_value_is_not_expanded(): |
| 149 |
"""A value is dropped in as it is, markers and all. |
| 150 |
|
| 151 |
Only the original text is scanned, so a value that happens to contain |
| 152 |
${NAME} is never looked at a second time. |
| 153 |
""" |
| 154 |
placeholders = TemplatePlaceholderMap(schema_of("a", "b"), "") |
| 155 |
encoded = placeholders.encode("${A}") |
| 156 |
|
| 157 |
# The value for 'a' mentions 'b', and stays exactly that text |
| 158 |
result = placeholders.substitute(encoded, {"a": "${B}", "b": "34"}) |
| 159 |
assert result == "${B}" |
| 160 |
|
| 161 |
|
| 162 |
def test_template_default_marker_is_literal(): |
| 163 |
"""One declaration never builds on another.""" |
| 164 |
schema = TemplateSchema.parse([{"value": "34"}, {"key": "${value}"}]) |
| 165 |
|
| 166 |
assert schema.variables["key"].default == "${value}" |
| 167 |
assert resolve_values(schema, None, {}) == { |
| 168 |
"value": "34", |
| 169 |
"key": "${value}", |
| 170 |
} |
| 171 |
|
| 172 |
|
| 173 |
@pytest.mark.parametrize( |
| 174 |
"secret", |
| 175 |
["p${a}ss", "$${x}", "${}", "${toolong" + "g" * 40 + "}", "$", "${"], |
| 176 |
ids=["inline", "double-dollar", "empty", "over-long", "bare", "unclosed"], |
| 177 |
) |
| 178 |
def test_template_preserves_literal_markers(secret): |
| 179 |
"""Nothing is declared, so nothing may be replaced.""" |
| 180 |
placeholders = TemplatePlaceholderMap(TemplateSchema(), "") |
| 181 |
assert placeholders.encode(secret) == secret |
| 182 |
|
| 183 |
|
| 184 |
def test_template_replaces_repeated_name(): |
| 185 |
"""Writing one more than once fills the same value in each time.""" |
| 186 |
placeholders = TemplatePlaceholderMap(schema_of("target"), "") |
| 187 |
encoded = placeholders.encode("${TARGET}/a/${TARGET}?x=${TARGET}") |
| 188 |
result = placeholders.substitute(encoded, {"target": "VALUE"}) |
| 189 |
assert result == "VALUE/a/VALUE?x=VALUE" |
| 190 |
|
| 191 |
|
| 192 |
def test_template_single_pass_substitution(): |
| 193 |
"""A value that looks like a placeholder is left as data.""" |
| 194 |
placeholders = TemplatePlaceholderMap(schema_of("a", "b"), "") |
| 195 |
encoded = placeholders.encode("${A}-${B}") |
| 196 |
# Feed one variable the text of the other's placeholder |
| 197 |
other = placeholders.encode("${B}") |
| 198 |
result = placeholders.substitute(encoded, {"a": other, "b": "second"}) |
| 199 |
assert result == f"{other}-second" |
| 200 |
|
| 201 |
|
| 202 |
def test_template_display_restores_names(): |
| 203 |
"""A placeholder reads as ${NAME} again for display.""" |
| 204 |
placeholders = TemplatePlaceholderMap(schema_of("target"), "") |
| 205 |
encoded = placeholders.encode("json://host/${TARGET}/${TARGET}") |
| 206 |
assert placeholders.display(encoded) == "json://host/${TARGET}/${TARGET}" |
| 207 |
|
| 208 |
|
| 209 |
def test_template_used_names(): |
| 210 |
"""Only declared names count.""" |
| 211 |
placeholders = TemplatePlaceholderMap(schema_of("a", "b"), "") |
| 212 |
encoded = placeholders.encode("${A} ${UNDECLARED}") |
| 213 |
assert placeholders.used(encoded) == {"a"} |
| 214 |
|
| 215 |
|
| 216 |
def test_template_preserves_setting_names(): |
| 217 |
"""A variable fills in a value; it never names a setting.""" |
| 218 |
placeholders = TemplatePlaceholderMap(schema_of("target"), "") |
| 219 |
encoded = placeholders.encode_obj({"${TARGET}": "${TARGET}"}) |
| 220 |
key, value = next(iter(encoded.items())) |
| 221 |
assert key == "${TARGET}" |
| 222 |
assert value != "${TARGET}" |
| 223 |
|
| 224 |
|
| 225 |
def test_template_fills_mapping_name(): |
| 226 |
"""A placeholder sitting in a name is filled in like any other text.""" |
| 227 |
placeholders = TemplatePlaceholderMap(schema_of("target"), "") |
| 228 |
# A parsed URL keeps its query names under "qsd", not at the top |
| 229 |
entry = {"qsd": {placeholders.encode("${TARGET}"): 1}} |
| 230 |
|
| 231 |
assert placeholders.used(entry) == {"target"} |
| 232 |
assert placeholders.substitute(entry, {"target": "real"}) == { |
| 233 |
"qsd": {"real": 1} |
| 234 |
} |
| 235 |
|
| 236 |
|
| 237 |
def test_template_rejects_loop(): |
| 238 |
"""A branch pointing back at itself is not followed.""" |
| 239 |
placeholders = TemplatePlaceholderMap(schema_of("a"), "") |
| 240 |
loop = {} |
| 241 |
loop["self"] = loop |
| 242 |
with pytest.raises(AppriseTemplateError): |
| 243 |
placeholders.encode_obj(loop) |
| 244 |
|
| 245 |
|
| 246 |
def test_template_avoids_placeholder_collision(): |
| 247 |
"""A placeholder cannot collide with the configuration.""" |
| 248 |
placeholders = TemplatePlaceholderMap(schema_of("a"), "") |
| 249 |
assert f"a{placeholders.nonce}" not in "some configuration body" |
| 250 |
|
| 251 |
|
| 252 |
def test_template_call_value_precedence(): |
| 253 |
"""The caller beats the environment and the default.""" |
| 254 |
schema = schema_of({"target": "from-config"}) |
| 255 |
env = {"APPRISE_TEMPLATE_TARGET": "from-env"} |
| 256 |
values = resolve_values(schema, {"target": "from-call"}, env) |
| 257 |
assert values == {"target": "from-call"} |
| 258 |
|
| 259 |
|
| 260 |
def test_template_config_default_beats_the_environment(): |
| 261 |
"""A default in the configuration wins over the server's own value. |
| 262 |
|
| 263 |
The author picked that default for this configuration in particular, |
| 264 |
so it is used ahead of anything the deployment set. |
| 265 |
""" |
| 266 |
schema = schema_of({"target": "from-config"}) |
| 267 |
env = {"APPRISE_TEMPLATE_TARGET": "from-env"} |
| 268 |
assert resolve_values(schema, None, env) == {"target": "from-config"} |
| 269 |
|
| 270 |
|
| 271 |
def test_template_environment_fills_a_name_with_no_default(): |
| 272 |
"""The environment is what a required name falls back to.""" |
| 273 |
schema = schema_of("target") |
| 274 |
env = {"APPRISE_TEMPLATE_TARGET": "from-env"} |
| 275 |
assert resolve_values(schema, None, env) == {"target": "from-env"} |
| 276 |
|
| 277 |
|
| 278 |
def test_template_blank_value_reads_as_nothing_supplied(): |
| 279 |
"""Whitespace is not a value, so the next source is used.""" |
| 280 |
schema = schema_of({"target": "from-config"}) |
| 281 |
for blank in ("", " ", "\t"): |
| 282 |
assert resolve_values(schema, {"target": blank}) == { |
| 283 |
"target": "from-config" |
| 284 |
} |
| 285 |
|
| 286 |
|
| 287 |
def test_template_value_is_trimmed(): |
| 288 |
"""Surrounding whitespace never reaches the URL.""" |
| 289 |
schema = schema_of("target") |
| 290 |
assert resolve_values(schema, {"target": " spaced "}) == { |
| 291 |
"target": "spaced" |
| 292 |
} |
| 293 |
|
| 294 |
|
| 295 |
def test_template_blank_environment_value_is_ignored(): |
| 296 |
"""A blank environment value leaves the name unresolved.""" |
| 297 |
schema = schema_of("target") |
| 298 |
with pytest.raises(AppriseTemplateError): |
| 299 |
resolve_values(schema, None, {"APPRISE_TEMPLATE_TARGET": " "}) |
| 300 |
|
| 301 |
|
| 302 |
def test_template_default_fallback(): |
| 303 |
"""Nothing supplied anywhere falls back to the config.""" |
| 304 |
schema = schema_of({"target": "from-config"}) |
| 305 |
assert resolve_values(schema, None, {}) == {"target": "from-config"} |
| 306 |
|
| 307 |
|
| 308 |
def test_template_required_value(): |
| 309 |
"""A mandatory variable with no value is an error.""" |
| 310 |
with pytest.raises(AppriseTemplateError) as exc: |
| 311 |
resolve_values(schema_of("target"), None, {}) |
| 312 |
|
| 313 |
assert exc.value.variable == "target" |
| 314 |
|
| 315 |
|
| 316 |
def test_template_supplied_name_case_insensitive(): |
| 317 |
"""Callers may use any casing they like.""" |
| 318 |
schema = schema_of("target") |
| 319 |
assert resolve_values(schema, {"TaRgEt": "x"}, {}) == {"target": "x"} |
| 320 |
|
| 321 |
|
| 322 |
def test_template_converts_number_to_text(): |
| 323 |
"""Convert a numeric input to text.""" |
| 324 |
schema = schema_of("target") |
| 325 |
assert resolve_values(schema, {"target": 42}, {}) == {"target": "42"} |
| 326 |
|
| 327 |
|
| 328 |
def test_template_ignores_unrelated_name(): |
| 329 |
"""Each configuration ignores names that it does not use.""" |
| 330 |
schema = schema_of({"target": "a-default"}) |
| 331 |
values = resolve_values(schema, {"target": "x", "elsewhere": "y"}, {}) |
| 332 |
assert values == {"target": "x"} |
| 333 |
|
| 334 |
|
| 335 |
def test_template_checks_the_name_even_when_unused(): |
| 336 |
"""Garbage is still refused, whichever configuration it was for.""" |
| 337 |
with pytest.raises(AppriseTemplateError): |
| 338 |
resolve_values(schema_of({"target": "a"}), {"not a name": "x"}, {}) |
| 339 |
|
| 340 |
|
| 341 |
def test_template_resolves_requested_names_only(): |
| 342 |
"""An entry does not pay for variables it never uses.""" |
| 343 |
schema = schema_of("needed", {"other": "default"}) |
| 344 |
values = resolve_values(schema, {"needed": "x"}, {}, names={"needed"}) |
| 345 |
assert values == {"needed": "x"} |
| 346 |
|
| 347 |
|
| 348 |
@pytest.mark.parametrize( |
| 349 |
"value", |
| 350 |
["line\nbreak", "carriage\rreturn", "null\x00byte", "bell\x07"], |
| 351 |
) |
| 352 |
def test_template_rejects_control_character(value): |
| 353 |
"""These could break out of a log line or a header.""" |
| 354 |
with pytest.raises(AppriseTemplateError): |
| 355 |
validate_value("target", value) |
| 356 |
|
| 357 |
|
| 358 |
def test_template_value_length_limit(): |
| 359 |
"""Cap values so a caller cannot flood the parser.""" |
| 360 |
with pytest.raises(AppriseTemplateError): |
| 361 |
validate_value("target", "x" * (MAX_TEMPLATE_VALUE_LEN + 1)) |
| 362 |
|
| 363 |
|
| 364 |
@pytest.mark.parametrize("value", [["a"], {"a": 1}, object()]) |
| 365 |
def test_template_rejects_complex_value(value): |
| 366 |
"""Only simple values may be supplied.""" |
| 367 |
with pytest.raises(AppriseTemplateError): |
| 368 |
validate_value("target", value) |
| 369 |
|
| 370 |
|
| 371 |
@pytest.mark.parametrize( |
| 372 |
("value", "expected"), |
| 373 |
[(42, "42"), (1.5, "1.5"), (True, "yes"), (False, "no")], |
| 374 |
) |
| 375 |
def test_template_converts_scalar_value(value, expected): |
| 376 |
"""Numbers and yes/no values are converted rather than refused.""" |
| 377 |
assert validate_value("target", value) == expected |
| 378 |
|
| 379 |
|
| 380 |
@pytest.mark.parametrize( |
| 381 |
"payload", |
| 382 |
[ |
| 383 |
# Short ids keep the node name readable. Without them the payload |
| 384 |
# itself becomes the test id, and a single reported failure prints |
| 385 |
# hundreds of kilobytes, which truncates the CI log it belongs to. |
| 386 |
pytest.param("${" * 50000, id="open-markers"), |
| 387 |
pytest.param("$" * 200000, id="bare-dollars"), |
| 388 |
pytest.param("${A" * 20000, id="partial-names"), |
| 389 |
pytest.param("${" * 10000 + "}" * 10000, id="unbalanced"), |
| 390 |
pytest.param("${A}" * 100000, id="many-real-markers"), |
| 391 |
pytest.param("${" + "A" * 100000 + "}", id="over-long-name"), |
| 392 |
pytest.param("${" * 1000 + "A" + "}" * 1000, id="wrapped-braces"), |
| 393 |
pytest.param("json://h/?" + "x=${A}&" * 50000, id="long-url-tail"), |
| 394 |
pytest.param( |
| 395 |
("a" + "0" * 16 + "t" + "9" * 5000 + "z") * 20, |
| 396 |
id="placeholder-lookalikes", |
| 397 |
), |
| 398 |
], |
| 399 |
) |
| 400 |
def test_template_regex_performance(payload): |
| 401 |
"""Bound every scan so input cannot make one hang. |
| 402 |
|
| 403 |
Each pattern uses bounded quantifiers with nothing that can backtrack, |
| 404 |
so an unhelpful configuration costs time in proportion to its size and |
| 405 |
no more. |
| 406 |
""" |
| 407 |
placeholders = TemplatePlaceholderMap(schema_of("a"), "") |
| 408 |
for scan in ( |
| 409 |
placeholders.encode, |
| 410 |
placeholders.encode_url, |
| 411 |
placeholders.pattern.findall, |
| 412 |
): |
| 413 |
start = time.monotonic() |
| 414 |
scan(payload) |
| 415 |
assert time.monotonic() - start < 2 |
| 416 |
|
| 417 |
|
| 418 |
def test_template_rejects_invalid_declaration(): |
| 419 |
"""A list entry has to be a name or a name with a default.""" |
| 420 |
with pytest.raises(AppriseTemplateError): |
| 421 |
TemplateSchema.parse([["not", "valid"]]) |
| 422 |
|
| 423 |
|
| 424 |
def test_template_variable_repr(): |
| 425 |
"""Useful when looking at one in a debugger.""" |
| 426 |
variable = schema_of("target").variables["target"] |
| 427 |
assert "target" in repr(variable) |
| 428 |
assert variable.required is True |
| 429 |
|
| 430 |
|
| 431 |
def test_template_placeholder_collision_retry(): |
| 432 |
"""A prefix that clashes with the configuration is re-rolled.""" |
| 433 |
taken = "0" * 16 |
| 434 |
free = "1" * 16 |
| 435 |
with mock.patch( |
| 436 |
"apprise.utils.template.secrets.token_hex", |
| 437 |
side_effect=[taken, free], |
| 438 |
): |
| 439 |
placeholders = TemplatePlaceholderMap( |
| 440 |
schema_of("a"), f"a{taken} appears here" |
| 441 |
) |
| 442 |
|
| 443 |
assert placeholders.nonce == free |
| 444 |
|
| 445 |
|
| 446 |
def test_template_placeholder_retry_limit(): |
| 447 |
"""We never fall back to a prefix we know is unsafe.""" |
| 448 |
taken = "0" * 16 |
| 449 |
with ( |
| 450 |
mock.patch( |
| 451 |
"apprise.utils.template.secrets.token_hex", return_value=taken |
| 452 |
), |
| 453 |
pytest.raises(AppriseTemplateError), |
| 454 |
): |
| 455 |
TemplatePlaceholderMap(schema_of("a"), f"a{taken}") |
| 456 |
|
| 457 |
|
| 458 |
def test_template_shared_branch(): |
| 459 |
"""A YAML anchor used twice gives the same result both times.""" |
| 460 |
placeholders = TemplatePlaceholderMap(schema_of("a"), "") |
| 461 |
shared = {"to": "${A}"} |
| 462 |
encoded = placeholders.encode_obj({"first": shared, "second": shared}) |
| 463 |
assert encoded["first"] == encoded["second"] |
| 464 |
assert encoded["first"] is encoded["second"] |
| 465 |
|
| 466 |
|
| 467 |
def test_template_nested_setting_name(): |
| 468 |
"""A placeholder in a name is found however deeply it sits.""" |
| 469 |
placeholders = TemplatePlaceholderMap(schema_of("a"), "") |
| 470 |
nested = [{placeholders.encode("${A}"): 1}] |
| 471 |
assert placeholders.used(nested) == {"a"} |
| 472 |
assert placeholders.used([{"fine": 1}]) == set() |
| 473 |
|
| 474 |
|
| 475 |
@pytest.mark.parametrize("value", [42, None, True]) |
| 476 |
def test_template_preserves_non_text_config(value): |
| 477 |
"""Numbers and flags are left exactly as they are.""" |
| 478 |
placeholders = TemplatePlaceholderMap(schema_of("a"), "") |
| 479 |
assert placeholders.encode(value) == value |
| 480 |
assert placeholders.display(value) == value |
| 481 |
assert placeholders.substitute(value, {}) == value |
| 482 |
|
| 483 |
|
| 484 |
def test_template_rejects_non_text_name(): |
| 485 |
"""Names have to be text before they can be looked up.""" |
| 486 |
with pytest.raises(AppriseTemplateError): |
| 487 |
resolve_values(schema_of("a"), {42: "value"}, {}) |
| 488 |
|
| 489 |
|
| 490 |
def test_template_shared_setting_branch(): |
| 491 |
"""The same mapping seen twice is not walked twice.""" |
| 492 |
placeholders = TemplatePlaceholderMap(schema_of("a"), "") |
| 493 |
shared = {"fine": 1} |
| 494 |
assert placeholders.used([shared, shared]) == set() |
| 495 |
|
| 496 |
|
| 497 |
def test_template_setting_loop(): |
| 498 |
"""A loop is refused rather than followed forever.""" |
| 499 |
placeholders = TemplatePlaceholderMap(schema_of("a"), "") |
| 500 |
loop = {"fine": 1} |
| 501 |
loop["self"] = [loop] |
| 502 |
with pytest.raises(AppriseTemplateError): |
| 503 |
placeholders.used(loop) |
| 504 |
|
| 505 |
|
| 506 |
def test_template_missing_host(): |
| 507 |
"""Not every URL has a host to check.""" |
| 508 |
placeholders = TemplatePlaceholderMap(schema_of("a"), "") |
| 509 |
parsed = {"host": None, "password": placeholders.encode("${A}")} |
| 510 |
result = placeholders.substitute(parsed, {"a": "value"}) |
| 511 |
assert result["password"] == "value" |
| 512 |
|
| 513 |
|
| 514 |
def test_template_preserves_address_separators(): |
| 515 |
"""URL fields keep the punctuation deliberately supplied to them.""" |
| 516 |
placeholders = TemplatePlaceholderMap(schema_of("a"), "") |
| 517 |
parsed = {"fullpath": placeholders.encode("/${A}/x")} |
| 518 |
result = placeholders.substitute(parsed, {"a": "seg/ment?x=1&y=2#z"}) |
| 519 |
assert result["fullpath"] == "/seg/ment?x=1&y=2#z/x" |
| 520 |
|
| 521 |
|
| 522 |
def test_template_defers_service_validation(): |
| 523 |
"""Whatever else a value holds is passed straight through.""" |
| 524 |
placeholders = TemplatePlaceholderMap(schema_of("a"), "") |
| 525 |
parsed = {"host": placeholders.encode("${A}")} |
| 526 |
for value in ("evil.com", "not a host at all", "??", "a@b"): |
| 527 |
# None of these raise; the service is left to make sense of it |
| 528 |
assert placeholders.substitute(parsed, {"a": value})["host"] |
| 529 |
|
| 530 |
|
| 531 |
def test_template_keeps_credentials_unchanged(): |
| 532 |
"""Parsed credential fields safely accept ordinary delimiters.""" |
| 533 |
placeholders = TemplatePlaceholderMap(schema_of("a"), "") |
| 534 |
parsed = {"password": placeholders.encode("${A}")} |
| 535 |
result = placeholders.substitute(parsed, {"a": "user:pass@host/a&b"}) |
| 536 |
assert result["password"] == "user:pass@host/a&b" |
| 537 |
|
| 538 |
|
| 539 |
def test_template_preserves_an_embedded_host_value(): |
| 540 |
"""A partial hostname keeps all author-supplied punctuation.""" |
| 541 |
placeholders = TemplatePlaceholderMap(schema_of("a"), "") |
| 542 |
parsed = {"host": placeholders.encode("trusted-${A}")} |
| 543 |
result = placeholders.substitute( |
| 544 |
parsed, {"a": "[email protected]:80/path?x=1#part"} |
| 545 |
) |
| 546 |
assert result["host"] == "[email protected]:80/path?x=1#part" |
| 547 |
|
| 548 |
|
| 549 |
def test_template_keeps_host_beside_fixed_credentials(): |
| 550 |
"""A host value does not replace separately parsed credentials.""" |
| 551 |
placeholders = TemplatePlaceholderMap(schema_of("a"), "") |
| 552 |
parsed = { |
| 553 |
"user": "fixed", |
| 554 |
"password": None, |
| 555 |
"host": placeholders.encode("${A}"), |
| 556 |
} |
| 557 |
result = placeholders.substitute(parsed, {"a": "[email protected]:80"}) |
| 558 |
assert result["user"] == "fixed" |
| 559 |
assert result["host"] == "[email protected]:80" |
| 560 |
|
| 561 |
|
| 562 |
def test_template_allows_a_complete_email_host(): |
| 563 |
"""A whole authority field may intentionally carry an email value.""" |
| 564 |
placeholders = TemplatePlaceholderMap(schema_of("a"), "") |
| 565 |
parsed = { |
| 566 |
"user": None, |
| 567 |
"password": None, |
| 568 |
"host": placeholders.encode("${A}"), |
| 569 |
} |
| 570 |
result = placeholders.substitute(parsed, {"a": "[email protected]"}) |
| 571 |
assert result["user"] == "user" |
| 572 |
assert result["host"] == "example.com" |
| 573 |
|
| 574 |
|
| 575 |
def test_template_allows_full_authority_credentials(): |
| 576 |
"""A whole authority may carry user:pass@host.""" |
| 577 |
placeholders = TemplatePlaceholderMap(schema_of("a"), "") |
| 578 |
parsed = { |
| 579 |
"user": None, |
| 580 |
"password": None, |
| 581 |
"host": placeholders.encode("${A}"), |
| 582 |
} |
| 583 |
result = placeholders.substitute(parsed, {"a": "user:[email protected]"}) |
| 584 |
assert result["user"] == "user" |
| 585 |
assert result["password"] == "pass" |
| 586 |
assert result["host"] == "example.com" |
| 587 |
|
| 588 |
|
| 589 |
@pytest.mark.parametrize("authority", ("@example.com", "user@")) |
| 590 |
def test_template_contains_a_malformed_authority(authority): |
| 591 |
"""An incomplete authority stays in the field as supplied.""" |
| 592 |
placeholders = TemplatePlaceholderMap(schema_of("a"), "") |
| 593 |
parsed = { |
| 594 |
"user": None, |
| 595 |
"password": None, |
| 596 |
"host": placeholders.encode("${A}"), |
| 597 |
} |
| 598 |
result = placeholders.substitute(parsed, {"a": authority}) |
| 599 |
assert result["user"] is None |
| 600 |
assert result["host"] == authority |
| 601 |
|
| 602 |
|
| 603 |
def test_template_allows_combined_credentials(): |
| 604 |
"""A whole user field may carry user:pass credentials.""" |
| 605 |
placeholders = TemplatePlaceholderMap(schema_of("a"), "") |
| 606 |
parsed = { |
| 607 |
"user": placeholders.encode("${A}"), |
| 608 |
"password": None, |
| 609 |
"host": "example.com", |
| 610 |
} |
| 611 |
result = placeholders.substitute(parsed, {"a": "user:pass"}) |
| 612 |
assert result["user"] == "user" |
| 613 |
assert result["password"] == "pass" |
| 614 |
|
| 615 |
|
| 616 |
def test_template_leaves_a_setting_value_alone(): |
| 617 |
"""A setting written under the URL already says what it is for.""" |
| 618 |
placeholders = TemplatePlaceholderMap(schema_of("a"), "") |
| 619 |
parsed = {"bcc": placeholders.encode("${A}")} |
| 620 |
result = placeholders.substitute(parsed, {"a": "b64/secret@host&x"}) |
| 621 |
assert result["bcc"] == "b64/secret@host&x" |
| 622 |
|
| 623 |
|
| 624 |
def test_template_ignores_non_text_setting_keys(): |
| 625 |
"""YAML allows a number as a key; there is nothing to look at.""" |
| 626 |
placeholders = TemplatePlaceholderMap(schema_of("a"), "") |
| 627 |
entry = {1: "x", 2.5: "y"} |
| 628 |
assert placeholders.used(entry) == set() |
| 629 |
assert placeholders.substitute(entry, {}) == {1: "x", 2.5: "y"} |
| 630 |
|
| 631 |
|
| 632 |
def test_template_fills_name_beside_text(): |
| 633 |
"""A name mixing a marker with fixed text keeps the fixed part.""" |
| 634 |
placeholders = TemplatePlaceholderMap(schema_of("a"), "") |
| 635 |
entry = {"qsd": {"x-" + placeholders.encode("${A}"): 1}} |
| 636 |
assert placeholders.substitute(entry, {"a": "real"}) == { |
| 637 |
"qsd": {"x-real": 1} |
| 638 |
} |
| 639 |
|
| 640 |
|
| 641 |
def test_template_preserves_yaml_names(): |
| 642 |
"""A marker written as a YAML setting name stays plain text.""" |
| 643 |
placeholders = TemplatePlaceholderMap(schema_of("a"), "") |
| 644 |
encoded = placeholders.encode_obj({"${A}": "${A}"}) |
| 645 |
|
| 646 |
# The name is untouched while the value became a placeholder |
| 647 |
assert list(encoded) == ["${A}"] |
| 648 |
assert placeholders.used(encoded) == {"a"} |
| 649 |
|
| 650 |
|
| 651 |
@pytest.mark.parametrize( |
| 652 |
("url", "expected_names"), |
| 653 |
[ |
| 654 |
# Everything after :// is fair game |
| 655 |
("json://${A}/path?x=${A}", {"a"}), |
| 656 |
# ...and nothing before it is |
| 657 |
("${A}://host/", set()), |
| 658 |
# A URL with no separator at all has nothing to read |
| 659 |
("${A}user:pass@host/", set()), |
| 660 |
], |
| 661 |
) |
| 662 |
def test_template_encode_url_preserves_schema(url, expected_names): |
| 663 |
"""Only the text past :// is ever replaced.""" |
| 664 |
placeholders = TemplatePlaceholderMap(schema_of("a"), "") |
| 665 |
assert placeholders.used(placeholders.encode_url(url)) == expected_names |
| 666 |
|
| 667 |
|
| 668 |
def test_template_encode_url_passes_non_text_through(): |
| 669 |
"""There is no URL to read inside a number.""" |
| 670 |
placeholders = TemplatePlaceholderMap(schema_of("a"), "") |
| 671 |
assert placeholders.encode_url(42) == 42 |