Coverage for tdom/processor_error_notes_test.py: 97%

175 statements  

« prev     ^ index     » next       coverage.py v7.16.0, created at 2026-10-31 18:53 +0000

1""" 

2Tests for error notes generated during template processing exceptions. 

3 

4@NOTE: These tests are meant to only check the strings in `e.__notes__` are correct. 

5 

6The primary tests for the processor are meant to check that all error conditions are "handled". 

7""" 

8 

9from dataclasses import dataclass 

10from string.templatelib import Template 

11 

12import pytest 

13from markupsafe import Markup 

14 

15from .processor import ( 

16 AttributeProcessingError, 

17 ComponentProcessingError, 

18 ProcessContext, 

19 TemplateParserProxy, 

20 TextProcessingError, 

21 _make_default_template_processor, 

22) 

23 

24processor_api = _make_default_template_processor( 

25 parser_api=TemplateParserProxy(), # do not use cache 

26) 

27 

28 

29def make_ctx(**kwargs): 

30 return ProcessContext(**kwargs) 

31 

32 

33def html(template: Template, assume_ctx: ProcessContext | None = None): 

34 if assume_ctx is None: 

35 assume_ctx = ProcessContext() 

36 return processor_api.process(template, assume_ctx=assume_ctx) 

37 

38 

39def assert_notes(actual: list[str], expected: list[str]) -> None: 

40 """ 

41 Check note by note so the diff isn't exploded when one note is off but fallback to full comparison. 

42 """ 

43 expected_count = len(expected) 

44 actual_count = len(actual) 

45 for index in range(actual_count): 

46 if index < expected_count: 

47 # Compare line by line to catch formatting differences 

48 assert actual[index] == expected[index], ( 

49 f"actual[{index}] != expected[{index}]" 

50 ) 

51 else: 

52 break 

53 # Catch parity differences and anything else but with special pytest handling. 

54 if expected_count != actual_count: 

55 assert actual == expected 

56 

57 

58@pytest.fixture 

59def cb_value_error(): 

60 """Callback that just raises value error.""" 

61 

62 def _cb_value_error(): 

63 raise ValueError("Callback failed.") 

64 

65 return _cb_value_error 

66 

67 

68@pytest.fixture 

69def markup_maker(): 

70 return MarkupMaker 

71 

72 

73@dataclass 

74class MarkupMaker: 

75 """ 

76 Returns supposedly sanitized HTML via __html__(). 

77 

78 Use the fixture `markup_maker` instead of using this directly. 

79 """ 

80 

81 payload: str = "" 

82 

83 throw: bool = False 

84 

85 def __html__(self) -> str: 

86 if self.throw: 

87 raise ValueError("Failed to make markup.") 

88 return self.payload 

89 

90 

91@pytest.fixture 

92def wrapper_maker(): 

93 return WrapperMaker 

94 

95 

96@dataclass 

97class WrapperMaker: 

98 """ 

99 Configure a component that wraps all children in the specified tag. 

100 

101 Use fixture `wrapper_maker` instead of using this directly. 

102 

103 @NOTE: This component only supports the "1st call" usage because it is preconfigured. 

104 """ 

105 

106 tag: str = "div" 

107 

108 def __call__(self, children: Template) -> Template: 

109 return Template(f"<{self.tag}>") + t"{children}" + Template(f"</{self.tag}>") 

110 

111 

112class TestAttributes: 

113 """ 

114 Test error notes from attributes. 

115 """ 

116 

117 def test_interpolated_attribute(self): 

118 with pytest.raises( 

119 AttributeProcessingError, match="Cannot use int as value" 

120 ) as exc_info: 

121 _ = html(t"<div aria={0}></div>") 

122 assert_notes( 

123 exc_info.value.__notes__, 

124 [ 

125 "... in interpolated attribute aria={0} for <div aria={0}> at line 1 offset 0" 

126 ], 

127 ) 

128 

129 def test_templated_attribute(self): 

130 with pytest.raises( 

131 AttributeProcessingError, match="data attributes cannot be templated" 

132 ) as exc_info: 

133 _ = html(t'<div data="label_{0}"></div>') 

134 assert_notes( 

135 exc_info.value.__notes__, 

136 [ 

137 '... in templated attribute data=label_{0} for <div data="label_{0}"> at line 1 offset 0' 

138 ], 

139 ) 

140 

141 def test_spread_attribute(self): 

142 with pytest.raises(AttributeProcessingError, match="no") as exc_info: 

143 _ = html(t"<div {0}></div>") 

144 assert_notes( 

145 exc_info.value.__notes__, 

146 ["... in spread attribute {0} for <div {0}> at line 1 offset 0"], 

147 ) 

148 

149 def test_literal_attribute(self): 

150 with pytest.raises( 

151 AttributeProcessingError, match="Invalid number of parts" 

152 ) as exc_info: 

153 _ = html(t'<div style="status:great" style="status:"></div>') 

154 assert_notes( 

155 exc_info.value.__notes__, 

156 [ 

157 '... in literal attribute style=status: for <div style="status:great" style="status:"> at line 1 offset 0' 

158 ], 

159 ) 

160 

161 

162class TestTextInterpolations: 

163 """ 

164 Test error notes from text node interpolations. 

165 

166 A singleton TemplateRef is exactly 1 interpolation without any leading or trailing text. 

167 - <div>{singleton}</div> 

168 - <script>{singleton}</script> 

169 - <!--{singleton}--> 

170 - {singleton} 

171 

172 A "mixed" TemplateRef is either 1 interpolation with non-empty leading and/or trailing text or 2 or more interpolations. 

173 """ 

174 

175 def test_ambiguous_singleton(self, cb_value_error): 

176 with pytest.raises(Exception) as exc_info: 

177 # This text is not in any element at all. 

178 _ = html(t"{cb_value_error:callback}") 

179 assert_notes( 

180 exc_info.value.__notes__, 

181 [ 

182 "... in {cb_value_error:callback} at line 1 offset 0", 

183 ], 

184 ) 

185 

186 def test_singleton(self, cb_value_error): 

187 with pytest.raises(Exception) as exc_info: 

188 _ = html(t"<div>{cb_value_error:callback}</div>") 

189 assert_notes( 

190 exc_info.value.__notes__, 

191 [ 

192 "... in {cb_value_error:callback} at line 1 offset 5", 

193 "... in <div> at line 1 offset 0", 

194 ], 

195 ) 

196 

197 def test_ambiguous_mixed(self, cb_value_error): 

198 with pytest.raises(Exception) as exc_info: 

199 # This text is not in any element at all. 

200 _ = html(t"ok {cb_value_error:callback}") 

201 assert_notes( 

202 exc_info.value.__notes__, 

203 [ 

204 "... in {cb_value_error:callback} within ok {cb_value_error:callback} at line 1 offset 0", 

205 ], 

206 ) 

207 

208 def test_mixed_multiline(self, cb_value_error): 

209 def setup_template(): 

210 return t"""<b>\nabc {cb_value_error:callback}\n</b>""" 

211 

212 with pytest.raises(Exception) as exc_info: 

213 _ = html(setup_template()) 

214 assert_notes( 

215 exc_info.value.__notes__, 

216 [ 

217 # @NOTE: This offset is to the TText position in the Template 

218 # and not the interpolation's location WITHIN the TText. 

219 "... in {cb_value_error:callback} within \nabc {cb_value_error:callback}\n at line 1 offset 3", 

220 "... in <b> at line 1 offset 0", 

221 ], 

222 ) 

223 

224 def test_singleton_with_ambiguous_singleton_template(self, cb_value_error): 

225 def setup_template(): # avoidqa: RUF027 

226 inner_t = t"{cb_value_error:callback}" 

227 return t"<div>{inner_t}</div>" 

228 

229 with pytest.raises(ValueError, match="Callback failed") as exc_info: 

230 _ = html(setup_template()) 

231 assert_notes( 

232 exc_info.value.__notes__, 

233 [ 

234 "... in {cb_value_error:callback} at line 1 offset 0", 

235 "... in {inner_t} at line 1 offset 5", 

236 "... in <div> at line 1 offset 0", 

237 ], 

238 ) 

239 

240 def test_mixed_with_ambiguous_singleton_template(self, cb_value_error): 

241 def setup_template(): # avoidqa: RUF027 

242 inner_t = t"{cb_value_error:callback}" 

243 return t"<div>ok {inner_t}</div>" 

244 

245 with pytest.raises(ValueError, match="Callback failed") as exc_info: 

246 _ = html(setup_template()) 

247 assert_notes( 

248 exc_info.value.__notes__, 

249 [ 

250 "... in {cb_value_error:callback} at line 1 offset 0", 

251 "... in {inner_t} within ok {inner_t} at line 1 offset 5", 

252 "... in <div> at line 1 offset 0", 

253 ], 

254 ) 

255 

256 def test_singleton_with_mixed_template(self, cb_value_error): 

257 def setup_template(): # avoidqa: RUF027 

258 inner_t = t"ok {cb_value_error:callback}" 

259 return t"<div>{inner_t}</div>" 

260 

261 with pytest.raises(ValueError, match="Callback failed") as exc_info: 

262 _ = html(setup_template()) 

263 assert_notes( 

264 exc_info.value.__notes__, 

265 [ 

266 "... in {cb_value_error:callback} within ok {cb_value_error:callback} at line 1 offset 0", 

267 "... in {inner_t} at line 1 offset 5", 

268 "... in <div> at line 1 offset 0", 

269 ], 

270 ) 

271 

272 

273class TestCommentInterpolations: 

274 """ 

275 Test error notes from comment node interpolations. 

276 """ 

277 

278 def test_singleton(self, cb_value_error): 

279 with pytest.raises(ValueError, match="Callback failed") as exc_info: 

280 _ = html(t"<!--{cb_value_error:callback}-->") 

281 assert_notes( 

282 exc_info.value.__notes__, 

283 [ 

284 "... in <!--{cb_value_error:callback}--> at line 1 offset 0", 

285 ], 

286 ) 

287 

288 def test_mixed(self, cb_value_error): 

289 with pytest.raises(ValueError, match="Callback failed") as exc_info: 

290 _ = html(t"<!--ok {cb_value_error:callback}-->") 

291 assert_notes( 

292 exc_info.value.__notes__, 

293 [ 

294 "... in {cb_value_error:callback} within <!--ok {cb_value_error:callback}--> at line 1 offset 0", 

295 ], 

296 ) 

297 

298 

299class TestComponentInterpolations: 

300 """ 

301 Test error notes from component node interpolations. 

302 """ 

303 

304 def test_children_mixed_interpolation(self, cb_value_error, wrapper_maker): 

305 def setup_template() -> Template: 

306 DivWrapper = wrapper_maker("div") # avoidqa: RUF027 

307 return t"""<{DivWrapper}>ok? {cb_value_error:callback}</{DivWrapper}>""" 

308 

309 with pytest.raises(ValueError) as exc_info: 

310 _ = html(setup_template()) 

311 assert_notes( 

312 exc_info.value.__notes__, 

313 [ 

314 "... in {cb_value_error:callback} within ok? {cb_value_error:callback} at line 1 offset 0", 

315 "... in {children} at line 1 offset 5", # @TODO: Should this be inlined into the parent tag? 

316 "... in <div> at line 1 offset 0", 

317 "... in <{DivWrapper}> at line 1 offset 0", 

318 ], 

319 ) 

320 

321 def test_children_singleton_interpolation(self, cb_value_error, wrapper_maker): 

322 def setup_template() -> Template: 

323 DivWrapper = wrapper_maker("div") # avoidqa: RUF027 

324 return t"""<{DivWrapper}>{cb_value_error:callback}</{DivWrapper}>""" 

325 

326 with pytest.raises(ValueError) as exc_info: 

327 _ = html(setup_template()) 

328 assert_notes( 

329 exc_info.value.__notes__, 

330 [ 

331 "... in {cb_value_error:callback} at line 1 offset 0", 

332 "... in {children} at line 1 offset 5", 

333 "... in <div> at line 1 offset 0", 

334 "... in <{DivWrapper}> at line 1 offset 0", 

335 ], 

336 ) 

337 

338 

339class TestComponentAttributes: 

340 """ 

341 Test error notes from component node attributes. 

342 """ 

343 

344 def test_missing(self): 

345 def setup_template() -> Template: 

346 def Badge(label: str) -> Template: 

347 return t"<b>{label}</b>" 

348 

349 return t"<div><{Badge}/></div>" 

350 

351 with pytest.raises( 

352 ComponentProcessingError, 

353 match="Missing required parameters for component: label", 

354 ) as exc_info: 

355 _ = html(setup_template()) 

356 assert_notes( 

357 exc_info.value.__notes__, 

358 [ 

359 "... in <{Badge}/> at line 1 offset 5", 

360 ], 

361 ) 

362 

363 

364class TestNestedProcessorCallout: 

365 """ 

366 Test error notes involving nested calls to html() while already actively processing a template with html(). 

367 

368 @NOTE: This isn't recommended usage but it should still work and 

369 is helpful as a sanity check if we are cleaning up properly. 

370 """ 

371 

372 def test_another_html_via_callback(self, cb_value_error): 

373 """Make a 2nd call to html() from a callback during processing the 1st html() call.""" 

374 

375 def setup_template() -> Template: 

376 def get_content() -> str: 

377 return Markup(html(t"<span>{cb_value_error:callback}</span>")) 

378 

379 return t"<div>{get_content:callback}</div>" 

380 

381 with pytest.raises(ValueError, match="Callback failed") as exc_info: 

382 _ = html(setup_template()) 

383 assert_notes( 

384 exc_info.value.__notes__, 

385 [ 

386 "... in {cb_value_error:callback} at line 1 offset 6", 

387 "... in <span> at line 1 offset 0", 

388 "... in {get_content:callback} at line 1 offset 5", 

389 "... in <div> at line 1 offset 0", 

390 ], 

391 ) 

392 

393 def test_another_html_via_component(self, cb_value_error): 

394 """Make a 2nd call to html() from a component during processing the 1st html() call.""" 

395 

396 def setup_template() -> Template: 

397 def Content(children: Template) -> Template: 

398 content = Markup(html(children)) 

399 return t"<span>{content}</span>" 

400 

401 return t"<div><{Content}><b>{cb_value_error:callback}</b></{Content}></div>" 

402 

403 with pytest.raises(ValueError, match="Callback failed") as exc_info: 

404 _ = html(setup_template()) 

405 assert_notes( 

406 exc_info.value.__notes__, 

407 [ 

408 "... in {cb_value_error:callback} at line 1 offset 3", 

409 "... in <b> at line 1 offset 0", 

410 "... in <{Content}> at line 1 offset 5", 

411 ], 

412 ) 

413 

414 

415class TestHTMLDunder: 

416 """ 

417 Test error notes involving objects with __html__ methods. 

418 """ 

419 

420 def test_via_normal_interpolation(self, markup_maker): 

421 def setup_template(): 

422 content = markup_maker(throw=True) 

423 return t"<div>{content}</div>" 

424 

425 with pytest.raises(ValueError, match="Failed to make markup") as exc_info: 

426 _ = html(setup_template()) 

427 assert_notes( 

428 exc_info.value.__notes__, 

429 [ 

430 "... in {content} at line 1 offset 5", 

431 "... in <div> at line 1 offset 0", 

432 ], 

433 ) 

434 

435 def test_via_script_interpolation(self, markup_maker): 

436 def setup_template(): 

437 content = markup_maker(throw=True) 

438 return t"<div><script>{content}</script></div>" 

439 

440 with pytest.raises(ValueError, match="Failed to make markup") as exc_info: 

441 _ = html(setup_template()) 

442 assert_notes( 

443 exc_info.value.__notes__, 

444 [ 

445 "... in {content} at line 1 offset 13", 

446 "... in <script> at line 1 offset 5", 

447 ], 

448 ) 

449 

450 def test_via_script_mixed_not_allowed(self, markup_maker): 

451 """ 

452 Markup objects are not allowed inside scripts unless the content is a single interpolation. 

453 """ 

454 

455 def setup_template() -> Template: 

456 content = markup_maker(payload="<span></span>", throw=False) 

457 return t"<div><script>Ok? {content}</script></div>" 

458 

459 with pytest.raises( 

460 TextProcessingError, match="are not supported within script" 

461 ) as exc_info: 

462 _ = html(setup_template()) 

463 assert_notes( 

464 exc_info.value.__notes__, 

465 [ 

466 "... in {content} within Ok? {content} at line 1 offset 13", 

467 "... in <script> at line 1 offset 5", 

468 ], 

469 )