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 # All failures from a same `ADoc`
40 var failures
= new Array[String]
42 # Markdown processor used to parse markdown comments and extract code.
43 var mdproc
= new MarkdownProcessor
46 mdproc
.emitter
.decorator
= new NitunitDecorator(self)
49 # The associated documentation object
50 var mdoc
: nullable MDoc = null
52 # used to generate distinct names
55 # The last docunit extracted from a mdoc.
57 # Is used because a new code-block might just be added to it.
58 var last_docunit
: nullable DocUnit = null
60 var xml_classname
: String is noautoinit
62 var xml_name
: String is noautoinit
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)
70 self.xml_classname
= xml_classname
71 self.xml_name
= xml_name
75 # Populate `blocks` from the markdown decorator
76 mdproc
.process
(mdoc
.content
.join
("\n"))
78 toolcontext
.check_errors
80 if not failures
.is_empty
then
81 for msg
in failures
do
82 var ne
= new HTMLTag("failure")
83 ne
.attr
("message", msg
)
85 toolcontext
.modelbuilder
.unit_entities
+= 1
86 toolcontext
.modelbuilder
.failed_entities
+= 1
88 if last_docunit
== null then testsuite
.add
(tc
)
92 # All extracted docunits
93 var docunits
= new Array[DocUnit]
95 # Execute all the docunits
98 var simple_du
= new Array[DocUnit]
100 var ast
= toolcontext
.parse_something
(du
.block
)
101 if ast
isa AExpr then
104 test_single_docunit
(du
)
108 test_simple_docunits
(simple_du
)
110 for du
in docunits
do
111 testsuite
.add du
.to_xml
115 # Executes multiples doc-units in a shared program.
116 # Used for docunits simple block of code (without modules, classes, functions etc.)
118 # In case of compilation error, the method fallbacks to `test_single_docunit` to
119 # * locate exactly the compilation problem in the problematic docunit.
120 # * permit the execution of the other docunits that may be correct.
121 fun test_simple_docunits
(dus
: Array[DocUnit])
123 if dus
.is_empty
then return
125 var file
= "{prefix}-0.nit"
127 var dir
= file
.dirname
128 if dir
!= "" then dir
.mkdir
130 f
= create_unitfile
(file
)
135 f
.write
("fun run_{i} do\n")
136 f
.write
("# {du.full_name}\n")
140 f
.write
("var a = args.first.to_i\n")
142 f
.write
("if a == {j} then run_{j}\n")
146 if toolcontext
.opt_noact
.value
then return
148 var res
= compile_unitfile
(file
)
152 # Fall-back to individual modes:
154 test_single_docunit
(du
)
162 toolcontext
.info
("Execute doc-unit {du.full_name} in {file} {i}", 1)
163 var res2
= toolcontext
.safe_exec
("{file.to_program_name}.bin {i} >'{file}.out1' 2>&1 </dev/null")
165 var content
= "{file}.out1".to_path
.read_all
166 var msg
= content
.trunc
(8192).filter_nonprintable
170 toolcontext
.warning
(du
.location
, "error", "ERROR: {du.full_name} (in {file}): Runtime error\n{msg}")
171 toolcontext
.modelbuilder
.failed_entities
+= 1
173 toolcontext
.check_errors
177 # Executes a single doc-unit in its own program.
178 # Used for docunits larger than a single block of code (with modules, classes, functions etc.)
179 fun test_single_docunit
(du
: DocUnit)
182 var file
= "{prefix}-{cpt}.nit"
184 toolcontext
.info
("Execute doc-unit {du.full_name} in {file}", 1)
187 f
= create_unitfile
(file
)
191 if toolcontext
.opt_noact
.value
then return
193 var res
= compile_unitfile
(file
)
196 res2
= toolcontext
.safe_exec
("{file.to_program_name}.bin >'{file}.out1' 2>&1 </dev/null")
199 var content
= "{file}.out1".to_path
.read_all
200 var msg
= content
.trunc
(8192).filter_nonprintable
204 toolcontext
.warning
(du
.location
, "failure", "FAILURE: {du.full_name} (in {file}):\n{msg}")
205 toolcontext
.modelbuilder
.failed_entities
+= 1
206 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
210 toolcontext
.check_errors
213 # Create and fill the header of a unit file `file`.
215 # A unit file is a Nit source file generated from one
216 # or more docunits that will be compiled and executed.
218 # The handled on the file is returned and must be completed and closed.
220 # `file` should be a valid filepath for a Nit source file.
221 private fun create_unitfile
(file
: String): Writer
223 var dir
= file
.dirname
224 if dir
!= "" then dir
.mkdir
226 f
= new FileWriter.open
(file
)
227 f
.write
("# GENERATED FILE\n")
228 f
.write
("# Docunits extracted from comments\n")
229 if mmodule
!= null then
230 f
.write
("import {mmodule.name}\n")
236 # Compile an unit file and return the compiler return code
238 # Can terminate the program if the compiler is not found
239 private fun compile_unitfile
(file
: String): Int
241 var nitc
= toolcontext
.find_nitc
242 var opts
= new Array[String]
243 if mmodule
!= null then
244 opts
.add
"-I {mmodule.filepath.dirname}"
246 var cmd
= "{nitc} --ignore-visibility --no-color '{file}' {opts.join(" ")} >'{file}.out1' 2>&1 </dev/null -o '{file}.bin'"
247 var res
= toolcontext
.safe_exec
(cmd
)
252 private class NitunitDecorator
255 var executor
: NitUnitExecutor
257 redef fun add_code
(v
, block
) do
258 var code
= block
.raw_content
259 var meta
= block
.meta
or else "nit"
260 # Do not try to test non-nit code.
261 if meta
!= "nit" then return
262 # Try to parse code blocks
263 var ast
= executor
.toolcontext
.parse_something
(code
)
265 var mdoc
= executor
.mdoc
269 if ast
isa TComment then return
271 # The location is computed according to the starts of the mdoc and the block
272 # Note, the following assumes that all the comments of the mdoc are correctly aligned.
273 var loc
= block
.block
.location
274 var line_offset
= loc
.line_start
+ mdoc
.location
.line_start
- 2
275 var column_offset
= loc
.column_start
+ mdoc
.location
.column_start
276 # Hack to handle precise location in blocks
277 # TODO remove when markdown is more reliable
278 if block
isa BlockFence then
279 # Skip the starting fence
282 # Account a standard 4 space indentation
286 # We want executable code
287 if not (ast
isa AModule or ast
isa ABlockExpr or ast
isa AExpr) then
290 # Get real location of the node (or error)
291 var location
= new Location(mdoc
.location
.file
,
292 l
.line_start
+ line_offset
,
293 l
.line_end
+ line_offset
,
294 l
.column_start
+ column_offset
,
295 l
.column_end
+ column_offset
)
296 if ast
isa AError then
297 message
= ast
.message
299 message
= "Error: Invalid Nit code."
302 executor
.toolcontext
.warning
(location
, "invalid-block", "{message} To suppress this message, enclose the block with a fence tagged `nitish` or `raw` (see `man nitdoc`).")
303 executor
.failures
.add
("{location}: {message}")
307 # Create a first block
308 # Or create a new block for modules that are more than a main part
309 var last_docunit
= executor
.last_docunit
310 if last_docunit
== null or ast
isa AModule then
311 last_docunit
= new_docunit
312 executor
.last_docunit
= last_docunit
316 last_docunit
.block
+= code
318 # In order to retrieve precise positions,
319 # the real position of each line of the raw_content is stored.
320 # See `DocUnit::real_location`
321 line_offset
-= loc
.line_start
- 1
322 for i
in [loc
.line_start
..loc
.line_end
] do
323 last_docunit
.lines
.add i
+ line_offset
324 last_docunit
.columns
.add column_offset
328 # Return and register a new empty docunit
329 fun new_docunit
: DocUnit
331 var mdoc
= executor
.mdoc
335 var name
= executor
.xml_name
336 if executor
.docunits
.not_empty
and executor
.docunits
.last
.mdoc
== mdoc
then
337 next_number
= executor
.docunits
.last
.number
+ 1
338 name
+= "+" + next_number
.to_s
341 var res
= new DocUnit(mdoc
, next_number
, "", executor
.xml_classname
, name
)
342 executor
.docunits
.add res
343 executor
.toolcontext
.modelbuilder
.unit_entities
+= 1
348 # A unit-test extracted from some documentation.
350 # A docunit is extracted from the code-blocks of mdocs.
351 # Each mdoc can contains more than one docunit, and a single docunit can be made of more that a single code-block.
355 # The doc that contains self
358 # The numbering of self in mdoc (starting with 0)
361 # The name of the unit to show in messages
362 fun full_name
: String do
363 var mentity
= mdoc
.original_mentity
364 if mentity
!= null then return mentity
.full_name
365 return xml_classname
+ "." + xml_name
368 # The text of the code to execute.
370 # This is the verbatim content on one, or more, code-blocks from `mdoc`
373 # For each line in `block`, the associated line in the mdoc
375 # Is used to give precise locations
376 var lines
= new Array[Int]
378 # For each line in `block`, the associated column in the mdoc
380 # Is used to give precise locations
381 var columns
= new Array[Int]
383 # The location of the whole docunit.
385 # If `self` is made of multiple code-blocks, then the location
386 # starts at the first code-books and finish at the last one, thus includes anything between.
387 var location
: Location is lazy
do
388 return new Location(mdoc
.location
.file
, lines
.first
, lines
.last
+1, columns
.first
+1, 0)
391 # Compute the real location of a node on the `ast` based on `mdoc.location`
393 # The result is basically: ast_location + markdown location of the piece + mdoc.location
395 # The fun is that a single docunit can be made of various pieces of code blocks.
396 fun real_location
(ast_location
: Location): Location
399 var res
= new Location(mdoc
.location
.file
, lines
[ast_location
.line_start-1
],
400 lines
[ast_location
.line_end-1
],
401 columns
[ast_location
.line_start-1
] + ast_location
.column_start
,
402 columns
[ast_location
.line_end-1
] + ast_location
.column_end
)
409 res
.open
("system-out").append
(block
)
413 redef var xml_classname
417 redef class ModelBuilder
418 # Total number analyzed `MEntity`
419 var total_entities
= 0
421 # The number of `MEntity` that have some documentation
424 # The total number of executed docunits
425 var unit_entities
= 0
427 # The number failed docunits
428 var failed_entities
= 0
430 # Extracts and executes all the docunits in the `mmodule`
431 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
432 fun test_markdown
(mmodule
: MModule): HTMLTag
434 var ts
= new HTMLTag("testsuite")
435 toolcontext
.info
("nitunit: doc-unit {mmodule}", 2)
437 var nmodule
= mmodule2node
(mmodule
)
438 if nmodule
== null then return ts
440 # usualy, only the original module must be imported in the unit test.
443 if g
!= null and g
.mpackage
.name
== "core" then
444 # except for a unit test in a module of `core`
445 # in this case, the whole `core` must be imported
446 o
= get_mmodule_by_name
(nmodule
, g
, g
.mpackage
.name
).as(not null)
449 ts
.attr
("package", mmodule
.full_name
)
451 var prefix
= toolcontext
.test_dir
452 prefix
= prefix
.join_path
(mmodule
.to_s
)
453 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, o
, ts
)
457 var nmoduledecl
= nmodule
.n_moduledecl
458 if nmoduledecl
== null then break label x
459 var ndoc
= nmoduledecl
.n_doc
460 if ndoc
== null then break label x
462 # NOTE: jenkins expects a '.' in the classname attr
463 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + mmodule
.full_name
+ ".<module>", "<module>")
465 for nclassdef
in nmodule
.n_classdefs
do
466 var mclassdef
= nclassdef
.mclassdef
467 if mclassdef
== null then continue
468 if nclassdef
isa AStdClassdef then
470 var ndoc
= nclassdef
.n_doc
473 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + mmodule
.full_name
+ "." + mclassdef
.mclass
.full_name
, "<class>")
476 for npropdef
in nclassdef
.n_propdefs
do
477 var mpropdef
= npropdef
.mpropdef
478 if mpropdef
== null then continue
480 var ndoc
= npropdef
.n_doc
483 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + mmodule
.full_name
+ "." + mclassdef
.mclass
.full_name
, mpropdef
.mproperty
.full_name
)
493 # Extracts and executes all the docunits in the readme of the `mgroup`
494 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
495 fun test_group
(mgroup
: MGroup): HTMLTag
497 var ts
= new HTMLTag("testsuite")
498 toolcontext
.info
("nitunit: doc-unit group {mgroup}", 2)
500 # usually, only the default module must be imported in the unit test.
501 var o
= mgroup
.default_mmodule
503 ts
.attr
("package", mgroup
.full_name
)
505 var prefix
= toolcontext
.test_dir
506 prefix
= prefix
.join_path
(mgroup
.to_s
)
507 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, o
, ts
)
510 var mdoc
= mgroup
.mdoc
511 if mdoc
== null then return ts
514 # NOTE: jenkins expects a '.' in the classname attr
515 d2m
.extract
(mdoc
, "nitunit." + mgroup
.full_name
, "<group>")
522 # Test a document object unrelated to a Nit entity
523 fun test_mdoc
(mdoc
: MDoc): HTMLTag
525 var ts
= new HTMLTag("testsuite")
526 var file
= mdoc
.location
.to_s
528 toolcontext
.info
("nitunit: doc-unit file {file}", 2)
530 ts
.attr
("package", file
)
532 var prefix
= toolcontext
.test_dir
/ "file"
533 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, null, ts
)
538 # NOTE: jenkins expects a '.' in the classname attr
539 d2m
.extract
(mdoc
, "nitunit.<file>", file
)