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