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