nitunit/docunit: consider invalid-block as prefailed nitunits
[nit.git] / src / testing / testing_doc.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Testing from code comments.
16 module testing_doc
17
18 private import parser_util
19 import testing_base
20 import markdown
21 import html
22
23 # Extractor, Executor and Reporter for the tests in a module
24 class NitUnitExecutor
25 super HTMLDecorator
26
27 # Toolcontext used to parse Nit code blocks.
28 var toolcontext: ToolContext
29
30 # The prefix of the generated Nit source-file
31 var prefix: String
32
33 # The module to import, if any
34 var mmodule: nullable MModule
35
36 # The XML node associated to the module
37 var testsuite: HTMLTag
38
39 # Markdown processor used to parse markdown comments and extract code.
40 var mdproc = new MarkdownProcessor
41
42 init do
43 mdproc.emitter.decorator = new NitunitDecorator(self)
44 end
45
46 # The associated documentation object
47 var mdoc: nullable MDoc = null
48
49 # used to generate distinct names
50 var cpt = 0
51
52 # The last docunit extracted from a mdoc.
53 #
54 # Is used because a new code-block might just be added to it.
55 var last_docunit: nullable DocUnit = null
56
57 var xml_classname: String is noautoinit
58
59 var xml_name: String is noautoinit
60
61 # The entry point for a new `ndoc` node
62 # Fill `docunits` with new discovered unit of tests.
63 fun extract(mdoc: MDoc, xml_classname, xml_name: String)
64 do
65 last_docunit = null
66 self.xml_classname = xml_classname
67 self.xml_name = xml_name
68
69 self.mdoc = mdoc
70
71 # Populate `blocks` from the markdown decorator
72 mdproc.process(mdoc.content.join("\n"))
73
74 toolcontext.check_errors
75 end
76
77 # All extracted docunits
78 var docunits = new Array[DocUnit]
79
80 # Execute all the docunits
81 fun run_tests
82 do
83 var simple_du = new Array[DocUnit]
84 for du in docunits do
85 # Skip existing errors
86 if du.error != null then continue
87
88 var ast = toolcontext.parse_something(du.block)
89 if ast isa AExpr then
90 simple_du.add du
91 else
92 test_single_docunit(du)
93 end
94 end
95
96 test_simple_docunits(simple_du)
97
98 for du in docunits do
99 testsuite.add du.to_xml
100 end
101 end
102
103 # Executes multiples doc-units in a shared program.
104 # Used for docunits simple block of code (without modules, classes, functions etc.)
105 #
106 # In case of compilation error, the method fallbacks to `test_single_docunit` to
107 # * locate exactly the compilation problem in the problematic docunit.
108 # * permit the execution of the other docunits that may be correct.
109 fun test_simple_docunits(dus: Array[DocUnit])
110 do
111 if dus.is_empty then return
112
113 var file = "{prefix}-0.nit"
114
115 var dir = file.dirname
116 if dir != "" then dir.mkdir
117 var f
118 f = create_unitfile(file)
119 var i = 0
120 for du in dus do
121
122 i += 1
123 f.write("fun run_{i} do\n")
124 f.write("# {du.full_name}\n")
125 f.write(du.block)
126 f.write("end\n")
127 end
128 f.write("var a = args.first.to_i\n")
129 for j in [1..i] do
130 f.write("if a == {j} then run_{j}\n")
131 end
132 f.close
133
134 if toolcontext.opt_noact.value then return
135
136 var res = compile_unitfile(file)
137
138 if res != 0 then
139 # Compilation error.
140 # Fall-back to individual modes:
141 for du in dus do
142 test_single_docunit(du)
143 end
144 return
145 end
146
147 i = 0
148 for du in dus do
149 i += 1
150 toolcontext.info("Execute doc-unit {du.full_name} in {file} {i}", 1)
151 var res2 = toolcontext.safe_exec("{file.to_program_name}.bin {i} >'{file}.out1' 2>&1 </dev/null")
152
153 var content = "{file}.out1".to_path.read_all
154 var msg = content.trunc(8192).filter_nonprintable
155
156 if res2 != 0 then
157 du.error = content
158 toolcontext.warning(du.location, "error", "ERROR: {du.full_name} (in {file}): Runtime error\n{msg}")
159 toolcontext.modelbuilder.failed_entities += 1
160 end
161 toolcontext.check_errors
162 end
163 end
164
165 # Executes a single doc-unit in its own program.
166 # Used for docunits larger than a single block of code (with modules, classes, functions etc.)
167 fun test_single_docunit(du: DocUnit)
168 do
169 cpt += 1
170 var file = "{prefix}-{cpt}.nit"
171
172 toolcontext.info("Execute doc-unit {du.full_name} in {file}", 1)
173
174 var f
175 f = create_unitfile(file)
176 f.write(du.block)
177 f.close
178
179 if toolcontext.opt_noact.value then return
180
181 var res = compile_unitfile(file)
182 var res2 = 0
183 if res == 0 then
184 res2 = toolcontext.safe_exec("{file.to_program_name}.bin >'{file}.out1' 2>&1 </dev/null")
185 end
186
187 var content = "{file}.out1".to_path.read_all
188 var msg = content.trunc(8192).filter_nonprintable
189
190 if res != 0 then
191 du.error = content
192 toolcontext.warning(du.location, "failure", "FAILURE: {du.full_name} (in {file}):\n{msg}")
193 toolcontext.modelbuilder.failed_entities += 1
194 else if res2 != 0 then
195 toolcontext.warning(du.location, "error", "ERROR: {du.full_name} (in {file}):\n{msg}")
196 toolcontext.modelbuilder.failed_entities += 1
197 end
198 toolcontext.check_errors
199 end
200
201 # Create and fill the header of a unit file `file`.
202 #
203 # A unit file is a Nit source file generated from one
204 # or more docunits that will be compiled and executed.
205 #
206 # The handled on the file is returned and must be completed and closed.
207 #
208 # `file` should be a valid filepath for a Nit source file.
209 private fun create_unitfile(file: String): Writer
210 do
211 var dir = file.dirname
212 if dir != "" then dir.mkdir
213 var f
214 f = new FileWriter.open(file)
215 f.write("# GENERATED FILE\n")
216 f.write("# Docunits extracted from comments\n")
217 if mmodule != null then
218 f.write("import {mmodule.name}\n")
219 end
220 f.write("\n")
221 return f
222 end
223
224 # Compile an unit file and return the compiler return code
225 #
226 # Can terminate the program if the compiler is not found
227 private fun compile_unitfile(file: String): Int
228 do
229 var nitc = toolcontext.find_nitc
230 var opts = new Array[String]
231 if mmodule != null then
232 opts.add "-I {mmodule.filepath.dirname}"
233 end
234 var cmd = "{nitc} --ignore-visibility --no-color '{file}' {opts.join(" ")} >'{file}.out1' 2>&1 </dev/null -o '{file}.bin'"
235 var res = toolcontext.safe_exec(cmd)
236 return res
237 end
238 end
239
240 private class NitunitDecorator
241 super HTMLDecorator
242
243 var executor: NitUnitExecutor
244
245 redef fun add_code(v, block) do
246 var code = block.raw_content
247 var meta = block.meta or else "nit"
248 # Do not try to test non-nit code.
249 if meta != "nit" then return
250 # Try to parse code blocks
251 var ast = executor.toolcontext.parse_something(code)
252
253 var mdoc = executor.mdoc
254 assert mdoc != null
255
256 # Skip pure comments
257 if ast isa TComment then return
258
259 # The location is computed according to the starts of the mdoc and the block
260 # Note, the following assumes that all the comments of the mdoc are correctly aligned.
261 var loc = block.block.location
262 var line_offset = loc.line_start + mdoc.location.line_start - 2
263 var column_offset = loc.column_start + mdoc.location.column_start
264 # Hack to handle precise location in blocks
265 # TODO remove when markdown is more reliable
266 if block isa BlockFence then
267 # Skip the starting fence
268 line_offset += 1
269 else
270 # Account a standard 4 space indentation
271 column_offset += 4
272 end
273
274 # We want executable code
275 if not (ast isa AModule or ast isa ABlockExpr or ast isa AExpr) then
276 var message
277 var l = ast.location
278 # Get real location of the node (or error)
279 var location = new Location(mdoc.location.file,
280 l.line_start + line_offset,
281 l.line_end + line_offset,
282 l.column_start + column_offset,
283 l.column_end + column_offset)
284 if ast isa AError then
285 message = ast.message
286 else
287 message = "Error: Invalid Nit code."
288 end
289
290 executor.toolcontext.warning(location, "invalid-block", "{message} To suppress this message, enclose the block with a fence tagged `nitish` or `raw` (see `man nitdoc`).")
291 executor.toolcontext.modelbuilder.failed_entities += 1
292
293 var du = new_docunit
294 du.block += code
295 du.error = "{location}: {message}"
296 return
297 end
298
299 # Create a first block
300 # Or create a new block for modules that are more than a main part
301 var last_docunit = executor.last_docunit
302 if last_docunit == null or ast isa AModule then
303 last_docunit = new_docunit
304 executor.last_docunit = last_docunit
305 end
306
307 # Add it to the file
308 last_docunit.block += code
309
310 # In order to retrieve precise positions,
311 # the real position of each line of the raw_content is stored.
312 # See `DocUnit::real_location`
313 line_offset -= loc.line_start - 1
314 for i in [loc.line_start..loc.line_end] do
315 last_docunit.lines.add i + line_offset
316 last_docunit.columns.add column_offset
317 end
318 end
319
320 # Return and register a new empty docunit
321 fun new_docunit: DocUnit
322 do
323 var mdoc = executor.mdoc
324 assert mdoc != null
325
326 var next_number = 0
327 var name = executor.xml_name
328 if executor.docunits.not_empty and executor.docunits.last.mdoc == mdoc then
329 next_number = executor.docunits.last.number + 1
330 name += "+" + next_number.to_s
331 end
332
333 var res = new DocUnit(mdoc, next_number, "", executor.xml_classname, name)
334 executor.docunits.add res
335 executor.toolcontext.modelbuilder.unit_entities += 1
336 return res
337 end
338 end
339
340 # A unit-test extracted from some documentation.
341 #
342 # A docunit is extracted from the code-blocks of mdocs.
343 # Each mdoc can contains more than one docunit, and a single docunit can be made of more that a single code-block.
344 class DocUnit
345 super UnitTest
346
347 # The doc that contains self
348 var mdoc: MDoc
349
350 # The numbering of self in mdoc (starting with 0)
351 var number: Int
352
353 # The name of the unit to show in messages
354 fun full_name: String do
355 var mentity = mdoc.original_mentity
356 if mentity != null then return mentity.full_name
357 return xml_classname + "." + xml_name
358 end
359
360 # The text of the code to execute.
361 #
362 # This is the verbatim content on one, or more, code-blocks from `mdoc`
363 var block: String
364
365 # For each line in `block`, the associated line in the mdoc
366 #
367 # Is used to give precise locations
368 var lines = new Array[Int]
369
370 # For each line in `block`, the associated column in the mdoc
371 #
372 # Is used to give precise locations
373 var columns = new Array[Int]
374
375 # The location of the whole docunit.
376 #
377 # If `self` is made of multiple code-blocks, then the location
378 # starts at the first code-books and finish at the last one, thus includes anything between.
379 var location: Location is lazy do
380 return new Location(mdoc.location.file, lines.first, lines.last+1, columns.first+1, 0)
381 end
382
383 # Compute the real location of a node on the `ast` based on `mdoc.location`
384 #
385 # The result is basically: ast_location + markdown location of the piece + mdoc.location
386 #
387 # The fun is that a single docunit can be made of various pieces of code blocks.
388 fun real_location(ast_location: Location): Location
389 do
390 var mdoc = self.mdoc
391 var res = new Location(mdoc.location.file, lines[ast_location.line_start-1],
392 lines[ast_location.line_end-1],
393 columns[ast_location.line_start-1] + ast_location.column_start,
394 columns[ast_location.line_end-1] + ast_location.column_end)
395 return res
396 end
397
398 redef fun to_xml
399 do
400 var res = super
401 res.open("system-out").append(block)
402 return res
403 end
404
405 redef var xml_classname
406 redef var xml_name
407 end
408
409 redef class ModelBuilder
410 # Total number analyzed `MEntity`
411 var total_entities = 0
412
413 # The number of `MEntity` that have some documentation
414 var doc_entities = 0
415
416 # The total number of executed docunits
417 var unit_entities = 0
418
419 # The number failed docunits
420 var failed_entities = 0
421
422 # Extracts and executes all the docunits in the `mmodule`
423 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
424 fun test_markdown(mmodule: MModule): HTMLTag
425 do
426 var ts = new HTMLTag("testsuite")
427 toolcontext.info("nitunit: doc-unit {mmodule}", 2)
428
429 var nmodule = mmodule2node(mmodule)
430 if nmodule == null then return ts
431
432 # usualy, only the original module must be imported in the unit test.
433 var o = mmodule
434 var g = o.mgroup
435 if g != null and g.mpackage.name == "core" then
436 # except for a unit test in a module of `core`
437 # in this case, the whole `core` must be imported
438 o = get_mmodule_by_name(nmodule, g, g.mpackage.name).as(not null)
439 end
440
441 ts.attr("package", mmodule.full_name)
442
443 var prefix = toolcontext.test_dir
444 prefix = prefix.join_path(mmodule.to_s)
445 var d2m = new NitUnitExecutor(toolcontext, prefix, o, ts)
446
447 do
448 total_entities += 1
449 var nmoduledecl = nmodule.n_moduledecl
450 if nmoduledecl == null then break label x
451 var ndoc = nmoduledecl.n_doc
452 if ndoc == null then break label x
453 doc_entities += 1
454 # NOTE: jenkins expects a '.' in the classname attr
455 d2m.extract(ndoc.to_mdoc, "nitunit." + mmodule.full_name + ".<module>", "<module>")
456 end label x
457 for nclassdef in nmodule.n_classdefs do
458 var mclassdef = nclassdef.mclassdef
459 if mclassdef == null then continue
460 if nclassdef isa AStdClassdef then
461 total_entities += 1
462 var ndoc = nclassdef.n_doc
463 if ndoc != null then
464 doc_entities += 1
465 d2m.extract(ndoc.to_mdoc, "nitunit." + mmodule.full_name + "." + mclassdef.mclass.full_name, "<class>")
466 end
467 end
468 for npropdef in nclassdef.n_propdefs do
469 var mpropdef = npropdef.mpropdef
470 if mpropdef == null then continue
471 total_entities += 1
472 var ndoc = npropdef.n_doc
473 if ndoc != null then
474 doc_entities += 1
475 d2m.extract(ndoc.to_mdoc, "nitunit." + mmodule.full_name + "." + mclassdef.mclass.full_name, mpropdef.mproperty.full_name)
476 end
477 end
478 end
479
480 d2m.run_tests
481
482 return ts
483 end
484
485 # Extracts and executes all the docunits in the readme of the `mgroup`
486 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
487 fun test_group(mgroup: MGroup): HTMLTag
488 do
489 var ts = new HTMLTag("testsuite")
490 toolcontext.info("nitunit: doc-unit group {mgroup}", 2)
491
492 # usually, only the default module must be imported in the unit test.
493 var o = mgroup.default_mmodule
494
495 ts.attr("package", mgroup.full_name)
496
497 var prefix = toolcontext.test_dir
498 prefix = prefix.join_path(mgroup.to_s)
499 var d2m = new NitUnitExecutor(toolcontext, prefix, o, ts)
500
501 total_entities += 1
502 var mdoc = mgroup.mdoc
503 if mdoc == null then return ts
504
505 doc_entities += 1
506 # NOTE: jenkins expects a '.' in the classname attr
507 d2m.extract(mdoc, "nitunit." + mgroup.full_name, "<group>")
508
509 d2m.run_tests
510
511 return ts
512 end
513
514 # Test a document object unrelated to a Nit entity
515 fun test_mdoc(mdoc: MDoc): HTMLTag
516 do
517 var ts = new HTMLTag("testsuite")
518 var file = mdoc.location.to_s
519
520 toolcontext.info("nitunit: doc-unit file {file}", 2)
521
522 ts.attr("package", file)
523
524 var prefix = toolcontext.test_dir / "file"
525 var d2m = new NitUnitExecutor(toolcontext, prefix, null, ts)
526
527 total_entities += 1
528 doc_entities += 1
529
530 # NOTE: jenkins expects a '.' in the classname attr
531 d2m.extract(mdoc, "nitunit.<file>", file)
532 d2m.run_tests
533
534 return ts
535 end
536 end