Merge: Nitunit: mass compile non-simple docunits
[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 import realtime
23
24 # Extractor, Executor and Reporter for the tests in a module
25 class NitUnitExecutor
26 super HTMLDecorator
27
28 # Toolcontext used to parse Nit code blocks.
29 var toolcontext: ToolContext
30
31 # The prefix of the generated Nit source-file
32 var prefix: String
33
34 # The module to import, if any
35 var mmodule: nullable MModule
36
37 # The XML node associated to the module
38 var testsuite: HTMLTag
39
40 # The name of the suite
41 var name: String
42
43 # Markdown processor used to parse markdown comments and extract code.
44 var mdproc = new MarkdownProcessor
45
46 init do
47 mdproc.decorator = new NitunitDecorator(self)
48 end
49
50 # The associated documentation object
51 var mdoc: nullable MDoc = null
52
53 # used to generate distinct names
54 var cpt = 0
55
56 # The last docunit extracted from a mdoc.
57 #
58 # Is used because a new code-block might just be added to it.
59 var last_docunit: nullable DocUnit = null
60
61 var xml_classname: String is noautoinit
62
63 var xml_name: String is noautoinit
64
65 # The entry point for a new `ndoc` node
66 # Fill `docunits` with new discovered unit of tests.
67 fun extract(mdoc: MDoc, xml_classname, xml_name: String)
68 do
69 last_docunit = null
70 self.xml_classname = xml_classname
71 self.xml_name = xml_name
72
73 self.mdoc = mdoc
74
75 # Populate `blocks` from the markdown decorator
76 mdproc.process(mdoc.content.join("\n"))
77 end
78
79 # All extracted docunits
80 var docunits = new Array[DocUnit]
81
82 fun show_status
83 do
84 toolcontext.show_unit_status(name, docunits)
85 end
86
87 fun mark_done(du: DocUnit)
88 do
89 du.is_done = true
90 toolcontext.clear_progress_bar
91 toolcontext.show_unit(du)
92 show_status
93 end
94
95 # Execute all the docunits
96 fun run_tests
97 do
98 if docunits.is_empty then
99 return
100 end
101
102 # Try to group each nitunit into a single source file to fasten the compilation
103 var simple_du = new Array[DocUnit] # du that are simple statements
104 var single_du = new Array[DocUnit] # du that are modules or include classes
105 show_status
106 for du in docunits do
107 # Skip existing errors
108 if du.error != null then
109 continue
110 end
111
112 var ast = toolcontext.parse_something(du.block)
113 if ast isa AExpr then
114 simple_du.add du
115 else
116 single_du.add du
117 end
118 end
119
120 # Try to mass compile all the simple du as a single nit module
121 compile_simple_docunits(simple_du)
122 # Try to mass compile all the single du in a single nitc invocation with many modules
123 compile_single_docunits(single_du)
124 # If the mass compilation fail, then each one will be compiled individually
125
126 # Now test them in order
127 for du in docunits do
128 if du.error != null then
129 # Nothing to execute. Conclude
130 else if du.is_compiled then
131 # Already compiled. Execute it.
132 execute_simple_docunit(du)
133 else
134 # A mass compilation failed
135 # Need to try to recompile it, then execute it
136 test_single_docunit(du)
137 end
138 mark_done(du)
139 end
140
141 # Final status
142 show_status
143 print ""
144
145 for du in docunits do
146 testsuite.add du.to_xml
147 end
148 end
149
150 # Compiles multiples doc-units in a shared program.
151 # Used for docunits simple block of code (without modules, classes, functions etc.)
152 #
153 # In case of success, the docunits are compiled and the caller can call `execute_simple_docunit`.
154 #
155 # In case of compilation error, the docunits are let uncompiled.
156 # The caller should fallbacks to `test_single_docunit` to
157 # * locate exactly the compilation problem in the problematic docunit.
158 # * permit the execution of the other docunits that may be correct.
159 fun compile_simple_docunits(dus: Array[DocUnit])
160 do
161 if dus.is_empty then return
162
163 var file = "{prefix}-0.nit"
164
165 toolcontext.info("Compile {dus.length} simple(s) doc-unit(s) in {file}", 1)
166
167 var dir = file.dirname
168 if dir != "" then dir.mkdir
169 var f
170 f = create_unitfile(file)
171 var i = 0
172 for du in dus do
173 i += 1
174 f.write("fun run_{i} do\n")
175 f.write("# {du.full_name}\n")
176 f.write(du.block)
177 f.write("end\n")
178 end
179 f.write("var a = args.first.to_i\n")
180 for j in [1..i] do
181 f.write("if a == {j} then run_{j}\n")
182 end
183 f.close
184
185 if toolcontext.opt_noact.value then return
186
187 var res = compile_unitfile(file)
188
189 if res != 0 then
190 # Compilation error.
191 # They should be generated and compiled independently
192 return
193 end
194
195 # Compilation was a success.
196 # Store what need to be executed for each one.
197 i = 0
198 for du in dus do
199 i += 1
200 du.test_file = file
201 du.test_arg = i
202 du.is_compiled = true
203 end
204 end
205
206 # Execute a docunit compiled by `test_single_docunit`
207 fun execute_simple_docunit(du: DocUnit)
208 do
209 var file = du.test_file.as(not null)
210 var i = du.test_arg or else 0
211 toolcontext.info("Execute doc-unit {du.full_name} in {file} {i}", 1)
212 var clock = new Clock
213 var res2 = toolcontext.safe_exec("{file.to_program_name}.bin {i} >'{file}.out1' 2>&1 </dev/null")
214 if not toolcontext.opt_no_time.value then du.real_time = clock.total
215 du.was_exec = true
216
217 var content = "{file}.out1".to_path.read_all
218 du.raw_output = content
219
220 if res2 != 0 then
221 du.error = "Runtime error in {file} with argument {i}"
222 toolcontext.modelbuilder.failed_entities += 1
223 end
224 end
225
226 # Produce a single unit file for the docunit `du`.
227 fun generate_single_docunit(du: DocUnit): String
228 do
229 cpt += 1
230 var file = "{prefix}-{cpt}.nit"
231
232 var f
233 f = create_unitfile(file)
234 f.write(du.block)
235 f.close
236
237 du.test_file = file
238 return file
239 end
240
241 # Executes a single doc-unit in its own program.
242 # Used for docunits larger than a single block of code (with modules, classes, functions etc.)
243 fun test_single_docunit(du: DocUnit)
244 do
245 var file = generate_single_docunit(du)
246
247 toolcontext.info("Compile doc-unit {du.full_name} in {file}", 1)
248
249 if toolcontext.opt_noact.value then return
250
251 var res = compile_unitfile(file)
252 var content = "{file}.out1".to_path.read_all
253 du.raw_output = content
254
255 du.test_file = file
256
257 if res != 0 then
258 du.error = "Compilation error in {file}"
259 toolcontext.modelbuilder.failed_entities += 1
260 return
261 end
262
263 du.is_compiled = true
264 execute_simple_docunit(du)
265 end
266
267 # Create and fill the header of a unit file `file`.
268 #
269 # A unit file is a Nit source file generated from one
270 # or more docunits that will be compiled and executed.
271 #
272 # The handled on the file is returned and must be completed and closed.
273 #
274 # `file` should be a valid filepath for a Nit source file.
275 private fun create_unitfile(file: String): Writer
276 do
277 var dir = file.dirname
278 if dir != "" then dir.mkdir
279 var f
280 f = new FileWriter.open(file)
281 f.write("# GENERATED FILE\n")
282 f.write("# Docunits extracted from comments\n")
283 if mmodule != null then
284 f.write("intrude import {mmodule.name}\n")
285 end
286 f.write("\n")
287 return f
288 end
289
290 # Compile a unit file and return the compiler return code
291 #
292 # Can terminate the program if the compiler is not found
293 private fun compile_unitfile(file: String): Int
294 do
295 var nitc = toolcontext.find_nitc
296 var opts = new Array[String]
297 if mmodule != null then
298 # FIXME playing this way with the include dir is not safe nor robust
299 opts.add "-I {mmodule.filepath.dirname}"
300 end
301 var cmd = "{nitc} --ignore-visibility --no-color -q '{file}' {opts.join(" ")} >'{file}.out1' 2>&1 </dev/null -o '{file}.bin'"
302 var res = toolcontext.safe_exec(cmd)
303 return res
304 end
305
306 # Compile a unit file and return the compiler return code
307 #
308 # Can terminate the program if the compiler is not found
309 private fun compile_single_docunits(dus: Array[DocUnit]): Int
310 do
311 # Generate all unitfiles
312 var files = new Array[String]
313 for du in dus do
314 files.add generate_single_docunit(du)
315 end
316
317 if files.is_empty then return 0
318
319 toolcontext.info("Compile {dus.length} single(s) doc-unit(s) at once", 1)
320
321 # Mass compile them
322 var nitc = toolcontext.find_nitc
323 var opts = new Array[String]
324 if mmodule != null then
325 # FIXME playing this way with the include dir is not safe nor robust
326 opts.add "-I {mmodule.filepath.dirname}"
327 end
328 var cmd = "{nitc} --ignore-visibility --no-color -q '{files.join("' '")}' {opts.join(" ")} > '{prefix}.out1' 2>&1 </dev/null --dir {prefix.dirname}"
329 var res = toolcontext.safe_exec(cmd)
330 if res != 0 then
331 # Mass compilation failure
332 return res
333 end
334
335 # Rename each file into it expected binary name
336 for du in dus do
337 var f = du.test_file.as(not null)
338 toolcontext.safe_exec("mv '{f.strip_extension(".nit")}' '{f}.bin'")
339 du.is_compiled = true
340 end
341
342 return res
343 end
344 end
345
346 private class NitunitDecorator
347 super HTMLDecorator
348
349 var executor: NitUnitExecutor
350
351 redef fun add_code(v, block) do
352 var code = block.raw_content
353 var meta = block.meta or else "nit"
354 # Do not try to test non-nit code.
355 if meta != "nit" then return
356 # Try to parse code blocks
357 var ast = executor.toolcontext.parse_something(code)
358
359 var mdoc = executor.mdoc
360 assert mdoc != null
361
362 # Skip pure comments
363 if ast isa TComment then return
364
365 # The location is computed according to the starts of the mdoc and the block
366 # Note, the following assumes that all the comments of the mdoc are correctly aligned.
367 var loc = block.block.location
368 var line_offset = loc.line_start + mdoc.location.line_start - 2
369 var column_offset = loc.column_start + mdoc.location.column_start
370 # Hack to handle precise location in blocks
371 # TODO remove when markdown is more reliable
372 if block isa BlockFence then
373 # Skip the starting fence
374 line_offset += 1
375 else
376 # Account a standard 4 space indentation
377 column_offset += 4
378 end
379
380 # We want executable code
381 if not (ast isa AModule or ast isa ABlockExpr or ast isa AExpr) then
382 var message
383 var l = ast.location
384 # Get real location of the node (or error)
385 var location = new Location(mdoc.location.file,
386 l.line_start + line_offset,
387 l.line_end + line_offset,
388 l.column_start + column_offset,
389 l.column_end + column_offset)
390 if ast isa AError then
391 message = ast.message
392 else
393 message = "Error: Invalid Nit code."
394 end
395
396 var du = new_docunit
397 du.block += code
398 du.error_location = location
399 du.error = message
400 executor.toolcontext.modelbuilder.failed_entities += 1
401 return
402 end
403
404 # Create a first block
405 # Or create a new block for modules that are more than a main part
406 var last_docunit = executor.last_docunit
407 if last_docunit == null or ast isa AModule then
408 last_docunit = new_docunit
409 executor.last_docunit = last_docunit
410 end
411
412 # Add it to the file
413 last_docunit.block += code
414
415 # In order to retrieve precise positions,
416 # the real position of each line of the raw_content is stored.
417 # See `DocUnit::real_location`
418 line_offset -= loc.line_start - 1
419 for i in [loc.line_start..loc.line_end] do
420 last_docunit.lines.add i + line_offset
421 last_docunit.columns.add column_offset
422 end
423 end
424
425 # Return and register a new empty docunit
426 fun new_docunit: DocUnit
427 do
428 var mdoc = executor.mdoc
429 assert mdoc != null
430
431 var next_number = 1
432 var name = executor.xml_name
433 if executor.docunits.not_empty and executor.docunits.last.mdoc == mdoc then
434 next_number = executor.docunits.last.number + 1
435 name += "#" + next_number.to_s
436 end
437
438 var res = new DocUnit(mdoc, next_number, "", executor.xml_classname, name)
439 executor.docunits.add res
440 executor.toolcontext.modelbuilder.unit_entities += 1
441 return res
442 end
443 end
444
445 # A unit-test extracted from some documentation.
446 #
447 # A docunit is extracted from the code-blocks of mdocs.
448 # Each mdoc can contains more than one docunit, and a single docunit can be made of more that a single code-block.
449 class DocUnit
450 super UnitTest
451
452 # The doc that contains self
453 var mdoc: MDoc
454
455 # The numbering of self in mdoc (starting with 0)
456 var number: Int
457
458 # The generated Nit source file that contains the unit-test
459 #
460 # Note that a same generated file can be used for multiple tests.
461 # See `test_arg` that is used to distinguish them
462 var test_file: nullable String = null
463
464 # Was `test_file` successfully compiled?
465 var is_compiled = false
466
467 # The command-line argument to use when executing the test, if any.
468 var test_arg: nullable Int = null
469
470 redef fun full_name do
471 var mentity = mdoc.original_mentity
472 if mentity != null then
473 var res = mentity.full_name
474 if number > 1 then
475 res += "#{number}"
476 end
477 return res
478 else
479 return xml_classname + "." + xml_name
480 end
481 end
482
483 # The text of the code to execute.
484 #
485 # This is the verbatim content on one, or more, code-blocks from `mdoc`
486 var block: String
487
488 # For each line in `block`, the associated line in the mdoc
489 #
490 # Is used to give precise locations
491 var lines = new Array[Int]
492
493 # For each line in `block`, the associated column in the mdoc
494 #
495 # Is used to give precise locations
496 var columns = new Array[Int]
497
498 # The location of the whole docunit.
499 #
500 # If `self` is made of multiple code-blocks, then the location
501 # starts at the first code-books and finish at the last one, thus includes anything between.
502 redef var location is lazy do
503 return new Location(mdoc.location.file, lines.first, lines.last+1, columns.first+1, 0)
504 end
505
506 # Compute the real location of a node on the `ast` based on `mdoc.location`
507 #
508 # The result is basically: ast_location + markdown location of the piece + mdoc.location
509 #
510 # The fun is that a single docunit can be made of various pieces of code blocks.
511 fun real_location(ast_location: Location): Location
512 do
513 var mdoc = self.mdoc
514 var res = new Location(mdoc.location.file, lines[ast_location.line_start-1],
515 lines[ast_location.line_end-1],
516 columns[ast_location.line_start-1] + ast_location.column_start,
517 columns[ast_location.line_end-1] + ast_location.column_end)
518 return res
519 end
520
521 redef fun to_xml
522 do
523 var res = super
524 res.open("system-out").append(block)
525 return res
526 end
527
528 redef var xml_classname
529 redef var xml_name
530 end
531
532 redef class ModelBuilder
533 # Total number analyzed `MEntity`
534 var total_entities = 0
535
536 # The number of `MEntity` that have some documentation
537 var doc_entities = 0
538
539 # The total number of executed docunits
540 var unit_entities = 0
541
542 # The number failed docunits
543 var failed_entities = 0
544
545 # Extracts and executes all the docunits in the `mmodule`
546 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
547 fun test_markdown(mmodule: MModule): HTMLTag
548 do
549 var ts = new HTMLTag("testsuite")
550 toolcontext.info("nitunit: doc-unit {mmodule}", 2)
551
552 var nmodule = mmodule2node(mmodule)
553 if nmodule == null then return ts
554
555 # usualy, only the original module must be imported in the unit test.
556 var o = mmodule
557 var g = o.mgroup
558 if g != null and g.mpackage.name == "core" then
559 # except for a unit test in a module of `core`
560 # in this case, the whole `core` must be imported
561 o = get_mmodule_by_name(nmodule, g, g.mpackage.name).as(not null)
562 end
563
564 ts.attr("package", mmodule.full_name)
565
566 var prefix = toolcontext.test_dir
567 prefix = prefix.join_path(mmodule.to_s)
568 var d2m = new NitUnitExecutor(toolcontext, prefix, o, ts, "Docunits of module {mmodule.full_name}")
569
570 do
571 total_entities += 1
572 var nmoduledecl = nmodule.n_moduledecl
573 if nmoduledecl == null then break label x
574 var ndoc = nmoduledecl.n_doc
575 if ndoc == null then break label x
576 doc_entities += 1
577 # NOTE: jenkins expects a '.' in the classname attr
578 d2m.extract(ndoc.to_mdoc, "nitunit." + mmodule.full_name + ".<module>", "<module>")
579 end label x
580 for nclassdef in nmodule.n_classdefs do
581 var mclassdef = nclassdef.mclassdef
582 if mclassdef == null then continue
583 if nclassdef isa AStdClassdef then
584 total_entities += 1
585 var ndoc = nclassdef.n_doc
586 if ndoc != null then
587 doc_entities += 1
588 d2m.extract(ndoc.to_mdoc, "nitunit." + mclassdef.full_name.replace("$", "."), "<class>")
589 end
590 end
591 for npropdef in nclassdef.n_propdefs do
592 var mpropdef = npropdef.mpropdef
593 if mpropdef == null then continue
594 total_entities += 1
595 var ndoc = npropdef.n_doc
596 if ndoc != null then
597 doc_entities += 1
598 var a = mpropdef.full_name.split("$")
599 d2m.extract(ndoc.to_mdoc, "nitunit." + a[0] + "." + a[1], a[2])
600 end
601 end
602 end
603
604 d2m.run_tests
605
606 return ts
607 end
608
609 # Extracts and executes all the docunits in the readme of the `mgroup`
610 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
611 fun test_group(mgroup: MGroup): HTMLTag
612 do
613 var ts = new HTMLTag("testsuite")
614 toolcontext.info("nitunit: doc-unit group {mgroup}", 2)
615
616 # usually, only the default module must be imported in the unit test.
617 var o = mgroup.default_mmodule
618
619 ts.attr("package", mgroup.full_name)
620
621 var prefix = toolcontext.test_dir
622 prefix = prefix.join_path(mgroup.to_s)
623 var d2m = new NitUnitExecutor(toolcontext, prefix, o, ts, "Docunits of group {mgroup.full_name}")
624
625 total_entities += 1
626 var mdoc = mgroup.mdoc
627 if mdoc == null then return ts
628
629 doc_entities += 1
630 # NOTE: jenkins expects a '.' in the classname attr
631 d2m.extract(mdoc, "nitunit." + mgroup.mpackage.name + "." + mgroup.name + ".<group>", "<group>")
632
633 d2m.run_tests
634
635 return ts
636 end
637
638 # Test a document object unrelated to a Nit entity
639 fun test_mdoc(mdoc: MDoc): HTMLTag
640 do
641 var ts = new HTMLTag("testsuite")
642 var file = mdoc.location.file.filename
643
644 toolcontext.info("nitunit: doc-unit file {file}", 2)
645
646 ts.attr("package", file)
647
648 var prefix = toolcontext.test_dir / "file"
649 var d2m = new NitUnitExecutor(toolcontext, prefix, null, ts, "Docunits of file {file}")
650
651 total_entities += 1
652 doc_entities += 1
653
654 # NOTE: jenkins expects a '.' in the classname attr
655 d2m.extract(mdoc, "nitunit.<file>", file)
656 d2m.run_tests
657
658 return ts
659 end
660 end