1 # This file is part of NIT ( http://www.nitlanguage.org ).
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
15 # Testing from code comments.
18 private import parser_util
23 # Extractor, Executor and Reporter for the tests in a module
27 # Toolcontext used to parse Nit code blocks.
28 var toolcontext
: ToolContext
30 # The prefix of the generated Nit source-file
33 # The module to import, if any
34 var mmodule
: nullable MModule
36 # The XML node associated to the module
37 var testsuite
: HTMLTag
39 # Markdown processor used to parse markdown comments and extract code.
40 var mdproc
= new MarkdownProcessor
43 mdproc
.emitter
.decorator
= new NitunitDecorator(self)
46 # The associated documentation object
47 var mdoc
: nullable MDoc = null
49 # used to generate distinct names
52 # The last docunit extracted from a mdoc.
54 # Is used because a new code-block might just be added to it.
55 var last_docunit
: nullable DocUnit = null
57 var xml_classname
: String is noautoinit
59 var xml_name
: String is noautoinit
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)
66 self.xml_classname
= xml_classname
67 self.xml_name
= xml_name
71 # Populate `blocks` from the markdown decorator
72 mdproc
.process
(mdoc
.content
.join
("\n"))
74 toolcontext
.check_errors
77 # All extracted docunits
78 var docunits
= new Array[DocUnit]
80 fun mark_done
(du
: DocUnit)
85 # Execute all the docunits
88 var simple_du
= new Array[DocUnit]
90 # Skip existing errors
91 if du
.error
!= null then
96 var ast
= toolcontext
.parse_something
(du
.block
)
100 test_single_docunit
(du
)
104 test_simple_docunits
(simple_du
)
106 for du
in docunits
do
107 testsuite
.add du
.to_xml
111 # Executes multiples doc-units in a shared program.
112 # Used for docunits simple block of code (without modules, classes, functions etc.)
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])
119 if dus
.is_empty
then return
121 var file
= "{prefix}-0.nit"
123 var dir
= file
.dirname
124 if dir
!= "" then dir
.mkdir
126 f
= create_unitfile
(file
)
131 f
.write
("fun run_{i} do\n")
132 f
.write
("# {du.full_name}\n")
136 f
.write
("var a = args.first.to_i\n")
138 f
.write
("if a == {j} then run_{j}\n")
142 if toolcontext
.opt_noact
.value
then return
144 var res
= compile_unitfile
(file
)
148 # Fall-back to individual modes:
150 test_single_docunit
(du
)
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")
162 var content
= "{file}.out1".to_path
.read_all
163 var msg
= content
.trunc
(8192).filter_nonprintable
167 toolcontext
.warning
(du
.location
, "error", "ERROR: {du.full_name} (in {file}): Runtime error\n{msg}")
168 toolcontext
.modelbuilder
.failed_entities
+= 1
171 toolcontext
.check_errors
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)
180 var file
= "{prefix}-{cpt}.nit"
182 toolcontext
.info
("Execute doc-unit {du.full_name} in {file}", 1)
185 f
= create_unitfile
(file
)
189 if toolcontext
.opt_noact
.value
then return
191 var res
= compile_unitfile
(file
)
194 res2
= toolcontext
.safe_exec
("{file.to_program_name}.bin >'{file}.out1' 2>&1 </dev/null")
198 var content
= "{file}.out1".to_path
.read_all
199 var msg
= content
.trunc
(8192).filter_nonprintable
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
207 toolcontext
.warning
(du
.location
, "error", "ERROR: {du.full_name} (in {file}):\n{msg}")
208 toolcontext
.modelbuilder
.failed_entities
+= 1
211 toolcontext
.check_errors
214 # Create and fill the header of a unit file `file`.
216 # A unit file is a Nit source file generated from one
217 # or more docunits that will be compiled and executed.
219 # The handled on the file is returned and must be completed and closed.
221 # `file` should be a valid filepath for a Nit source file.
222 private fun create_unitfile
(file
: String): Writer
224 var dir
= file
.dirname
225 if dir
!= "" then dir
.mkdir
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")
237 # Compile an unit file and return the compiler return code
239 # Can terminate the program if the compiler is not found
240 private fun compile_unitfile
(file
: String): Int
242 var nitc
= toolcontext
.find_nitc
243 var opts
= new Array[String]
244 if mmodule
!= null then
245 opts
.add
"-I {mmodule.filepath.dirname}"
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
)
253 private class NitunitDecorator
256 var executor
: NitUnitExecutor
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
)
266 var mdoc
= executor
.mdoc
270 if ast
isa TComment then return
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
283 # Account a standard 4 space indentation
287 # We want executable code
288 if not (ast
isa AModule or ast
isa ABlockExpr or ast
isa AExpr) then
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
300 message
= "Error: Invalid Nit code."
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
308 du
.error_location
= location
310 executor
.toolcontext
.modelbuilder
.failed_entities
+= 1
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
323 last_docunit
.block
+= code
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
335 # Return and register a new empty docunit
336 fun new_docunit
: DocUnit
338 var mdoc
= executor
.mdoc
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
348 var res
= new DocUnit(mdoc
, next_number
, "", executor
.xml_classname
, name
)
349 executor
.docunits
.add res
350 executor
.toolcontext
.modelbuilder
.unit_entities
+= 1
355 # A unit-test extracted from some documentation.
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.
362 # The doc that contains self
365 # The numbering of self in mdoc (starting with 0)
368 redef fun full_name
do
369 var mentity
= mdoc
.original_mentity
370 if mentity
!= null then
371 return mentity
.full_name
373 return xml_classname
+ "." + xml_name
377 # The text of the code to execute.
379 # This is the verbatim content on one, or more, code-blocks from `mdoc`
382 # For each line in `block`, the associated line in the mdoc
384 # Is used to give precise locations
385 var lines
= new Array[Int]
387 # For each line in `block`, the associated column in the mdoc
389 # Is used to give precise locations
390 var columns
= new Array[Int]
392 # The location of the whole docunit.
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)
400 # Compute the real location of a node on the `ast` based on `mdoc.location`
402 # The result is basically: ast_location + markdown location of the piece + mdoc.location
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
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
)
418 res
.open
("system-out").append
(block
)
422 redef var xml_classname
426 redef class ModelBuilder
427 # Total number analyzed `MEntity`
428 var total_entities
= 0
430 # The number of `MEntity` that have some documentation
433 # The total number of executed docunits
434 var unit_entities
= 0
436 # The number failed docunits
437 var failed_entities
= 0
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
443 var ts
= new HTMLTag("testsuite")
444 toolcontext
.info
("nitunit: doc-unit {mmodule}", 2)
446 var nmodule
= mmodule2node
(mmodule
)
447 if nmodule
== null then return ts
449 # usualy, only the original module must be imported in the unit test.
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)
458 ts
.attr
("package", mmodule
.full_name
)
460 var prefix
= toolcontext
.test_dir
461 prefix
= prefix
.join_path
(mmodule
.to_s
)
462 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, o
, ts
)
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
471 # NOTE: jenkins expects a '.' in the classname attr
472 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + mmodule
.full_name
+ ".<module>", "<module>")
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
479 var ndoc
= nclassdef
.n_doc
482 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + mmodule
.full_name
+ "." + mclassdef
.mclass
.full_name
, "<class>")
485 for npropdef
in nclassdef
.n_propdefs
do
486 var mpropdef
= npropdef
.mpropdef
487 if mpropdef
== null then continue
489 var ndoc
= npropdef
.n_doc
492 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + mmodule
.full_name
+ "." + mclassdef
.mclass
.full_name
, mpropdef
.mproperty
.full_name
)
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
506 var ts
= new HTMLTag("testsuite")
507 toolcontext
.info
("nitunit: doc-unit group {mgroup}", 2)
509 # usually, only the default module must be imported in the unit test.
510 var o
= mgroup
.default_mmodule
512 ts
.attr
("package", mgroup
.full_name
)
514 var prefix
= toolcontext
.test_dir
515 prefix
= prefix
.join_path
(mgroup
.to_s
)
516 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, o
, ts
)
519 var mdoc
= mgroup
.mdoc
520 if mdoc
== null then return ts
523 # NOTE: jenkins expects a '.' in the classname attr
524 d2m
.extract
(mdoc
, "nitunit." + mgroup
.full_name
, "<group>")
531 # Test a document object unrelated to a Nit entity
532 fun test_mdoc
(mdoc
: MDoc): HTMLTag
534 var ts
= new HTMLTag("testsuite")
535 var file
= mdoc
.location
.to_s
537 toolcontext
.info
("nitunit: doc-unit file {file}", 2)
539 ts
.attr
("package", file
)
541 var prefix
= toolcontext
.test_dir
/ "file"
542 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, null, ts
)
547 # NOTE: jenkins expects a '.' in the classname attr
548 d2m
.extract
(mdoc
, "nitunit.<file>", file
)