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