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"))
75 # All extracted docunits
76 var docunits
= new Array[DocUnit]
78 fun mark_done
(du
: DocUnit)
83 # Execute all the docunits
86 var simple_du
= new Array[DocUnit]
88 # Skip existing errors
89 if du
.error
!= null then
94 var ast
= toolcontext
.parse_something
(du
.block
)
98 test_single_docunit
(du
)
102 test_simple_docunits
(simple_du
)
104 for du
in docunits
do
108 for du
in docunits
do
109 testsuite
.add du
.to_xml
113 # Executes multiples doc-units in a shared program.
114 # Used for docunits simple block of code (without modules, classes, functions etc.)
116 # In case of compilation error, the method fallbacks to `test_single_docunit` to
117 # * locate exactly the compilation problem in the problematic docunit.
118 # * permit the execution of the other docunits that may be correct.
119 fun test_simple_docunits
(dus
: Array[DocUnit])
121 if dus
.is_empty
then return
123 var file
= "{prefix}-0.nit"
125 var dir
= file
.dirname
126 if dir
!= "" then dir
.mkdir
128 f
= create_unitfile
(file
)
133 f
.write
("fun run_{i} do\n")
134 f
.write
("# {du.full_name}\n")
138 f
.write
("var a = args.first.to_i\n")
140 f
.write
("if a == {j} then run_{j}\n")
144 if toolcontext
.opt_noact
.value
then return
146 var res
= compile_unitfile
(file
)
150 # Fall-back to individual modes:
152 test_single_docunit
(du
)
160 toolcontext
.info
("Execute doc-unit {du.full_name} in {file} {i}", 1)
161 var res2
= toolcontext
.safe_exec
("{file.to_program_name}.bin {i} >'{file}.out1' 2>&1 </dev/null")
164 var content
= "{file}.out1".to_path
.read_all
165 du
.raw_output
= content
168 du
.error
= "Runtime error in {file} with argument {i}"
169 toolcontext
.modelbuilder
.failed_entities
+= 1
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 du
.raw_output
= content
202 du
.error
= "Compilation error in {file}"
203 toolcontext
.modelbuilder
.failed_entities
+= 1
204 else if res2
!= 0 then
205 du
.error
= "Runtime error in {file}"
206 toolcontext
.modelbuilder
.failed_entities
+= 1
211 # Create and fill the header of a unit file `file`.
213 # A unit file is a Nit source file generated from one
214 # or more docunits that will be compiled and executed.
216 # The handled on the file is returned and must be completed and closed.
218 # `file` should be a valid filepath for a Nit source file.
219 private fun create_unitfile
(file
: String): Writer
221 var dir
= file
.dirname
222 if dir
!= "" then dir
.mkdir
224 f
= new FileWriter.open
(file
)
225 f
.write
("# GENERATED FILE\n")
226 f
.write
("# Docunits extracted from comments\n")
227 if mmodule
!= null then
228 f
.write
("import {mmodule.name}\n")
234 # Compile an unit file and return the compiler return code
236 # Can terminate the program if the compiler is not found
237 private fun compile_unitfile
(file
: String): Int
239 var nitc
= toolcontext
.find_nitc
240 var opts
= new Array[String]
241 if mmodule
!= null then
242 opts
.add
"-I {mmodule.filepath.dirname}"
244 var cmd
= "{nitc} --ignore-visibility --no-color '{file}' {opts.join(" ")} >'{file}.out1' 2>&1 </dev/null -o '{file}.bin'"
245 var res
= toolcontext
.safe_exec
(cmd
)
250 private class NitunitDecorator
253 var executor
: NitUnitExecutor
255 redef fun add_code
(v
, block
) do
256 var code
= block
.raw_content
257 var meta
= block
.meta
or else "nit"
258 # Do not try to test non-nit code.
259 if meta
!= "nit" then return
260 # Try to parse code blocks
261 var ast
= executor
.toolcontext
.parse_something
(code
)
263 var mdoc
= executor
.mdoc
267 if ast
isa TComment then return
269 # The location is computed according to the starts of the mdoc and the block
270 # Note, the following assumes that all the comments of the mdoc are correctly aligned.
271 var loc
= block
.block
.location
272 var line_offset
= loc
.line_start
+ mdoc
.location
.line_start
- 2
273 var column_offset
= loc
.column_start
+ mdoc
.location
.column_start
274 # Hack to handle precise location in blocks
275 # TODO remove when markdown is more reliable
276 if block
isa BlockFence then
277 # Skip the starting fence
280 # Account a standard 4 space indentation
284 # We want executable code
285 if not (ast
isa AModule or ast
isa ABlockExpr or ast
isa AExpr) then
288 # Get real location of the node (or error)
289 var location
= new Location(mdoc
.location
.file
,
290 l
.line_start
+ line_offset
,
291 l
.line_end
+ line_offset
,
292 l
.column_start
+ column_offset
,
293 l
.column_end
+ column_offset
)
294 if ast
isa AError then
295 message
= ast
.message
297 message
= "Error: Invalid Nit code."
302 du
.error_location
= location
304 executor
.toolcontext
.modelbuilder
.failed_entities
+= 1
308 # Create a first block
309 # Or create a new block for modules that are more than a main part
310 var last_docunit
= executor
.last_docunit
311 if last_docunit
== null or ast
isa AModule then
312 last_docunit
= new_docunit
313 executor
.last_docunit
= last_docunit
317 last_docunit
.block
+= code
319 # In order to retrieve precise positions,
320 # the real position of each line of the raw_content is stored.
321 # See `DocUnit::real_location`
322 line_offset
-= loc
.line_start
- 1
323 for i
in [loc
.line_start
..loc
.line_end
] do
324 last_docunit
.lines
.add i
+ line_offset
325 last_docunit
.columns
.add column_offset
329 # Return and register a new empty docunit
330 fun new_docunit
: DocUnit
332 var mdoc
= executor
.mdoc
336 var name
= executor
.xml_name
337 if executor
.docunits
.not_empty
and executor
.docunits
.last
.mdoc
== mdoc
then
338 next_number
= executor
.docunits
.last
.number
+ 1
339 name
+= "+" + next_number
.to_s
342 var res
= new DocUnit(mdoc
, next_number
, "", executor
.xml_classname
, name
)
343 executor
.docunits
.add res
344 executor
.toolcontext
.modelbuilder
.unit_entities
+= 1
349 # A unit-test extracted from some documentation.
351 # A docunit is extracted from the code-blocks of mdocs.
352 # Each mdoc can contains more than one docunit, and a single docunit can be made of more that a single code-block.
356 # The doc that contains self
359 # The numbering of self in mdoc (starting with 0)
362 redef fun full_name
do
363 var mentity
= mdoc
.original_mentity
364 if mentity
!= null then
365 return mentity
.full_name
367 return xml_classname
+ "." + xml_name
371 # The text of the code to execute.
373 # This is the verbatim content on one, or more, code-blocks from `mdoc`
376 # For each line in `block`, the associated line in the mdoc
378 # Is used to give precise locations
379 var lines
= new Array[Int]
381 # For each line in `block`, the associated column in the mdoc
383 # Is used to give precise locations
384 var columns
= new Array[Int]
386 # The location of the whole docunit.
388 # If `self` is made of multiple code-blocks, then the location
389 # starts at the first code-books and finish at the last one, thus includes anything between.
390 redef var location
is lazy
do
391 return new Location(mdoc
.location
.file
, lines
.first
, lines
.last
+1, columns
.first
+1, 0)
394 # Compute the real location of a node on the `ast` based on `mdoc.location`
396 # The result is basically: ast_location + markdown location of the piece + mdoc.location
398 # The fun is that a single docunit can be made of various pieces of code blocks.
399 fun real_location
(ast_location
: Location): Location
402 var res
= new Location(mdoc
.location
.file
, lines
[ast_location
.line_start-1
],
403 lines
[ast_location
.line_end-1
],
404 columns
[ast_location
.line_start-1
] + ast_location
.column_start
,
405 columns
[ast_location
.line_end-1
] + ast_location
.column_end
)
412 res
.open
("system-out").append
(block
)
416 redef var xml_classname
420 redef class ModelBuilder
421 # Total number analyzed `MEntity`
422 var total_entities
= 0
424 # The number of `MEntity` that have some documentation
427 # The total number of executed docunits
428 var unit_entities
= 0
430 # The number failed docunits
431 var failed_entities
= 0
433 # Extracts and executes all the docunits in the `mmodule`
434 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
435 fun test_markdown
(mmodule
: MModule): HTMLTag
437 var ts
= new HTMLTag("testsuite")
438 toolcontext
.info
("nitunit: doc-unit {mmodule}", 2)
440 var nmodule
= mmodule2node
(mmodule
)
441 if nmodule
== null then return ts
443 # usualy, only the original module must be imported in the unit test.
446 if g
!= null and g
.mpackage
.name
== "core" then
447 # except for a unit test in a module of `core`
448 # in this case, the whole `core` must be imported
449 o
= get_mmodule_by_name
(nmodule
, g
, g
.mpackage
.name
).as(not null)
452 ts
.attr
("package", mmodule
.full_name
)
454 var prefix
= toolcontext
.test_dir
455 prefix
= prefix
.join_path
(mmodule
.to_s
)
456 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, o
, ts
)
460 var nmoduledecl
= nmodule
.n_moduledecl
461 if nmoduledecl
== null then break label x
462 var ndoc
= nmoduledecl
.n_doc
463 if ndoc
== null then break label x
465 # NOTE: jenkins expects a '.' in the classname attr
466 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + mmodule
.full_name
+ ".<module>", "<module>")
468 for nclassdef
in nmodule
.n_classdefs
do
469 var mclassdef
= nclassdef
.mclassdef
470 if mclassdef
== null then continue
471 if nclassdef
isa AStdClassdef then
473 var ndoc
= nclassdef
.n_doc
476 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + mmodule
.full_name
+ "." + mclassdef
.mclass
.full_name
, "<class>")
479 for npropdef
in nclassdef
.n_propdefs
do
480 var mpropdef
= npropdef
.mpropdef
481 if mpropdef
== null then continue
483 var ndoc
= npropdef
.n_doc
486 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + mmodule
.full_name
+ "." + mclassdef
.mclass
.full_name
, mpropdef
.mproperty
.full_name
)
496 # Extracts and executes all the docunits in the readme of the `mgroup`
497 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
498 fun test_group
(mgroup
: MGroup): HTMLTag
500 var ts
= new HTMLTag("testsuite")
501 toolcontext
.info
("nitunit: doc-unit group {mgroup}", 2)
503 # usually, only the default module must be imported in the unit test.
504 var o
= mgroup
.default_mmodule
506 ts
.attr
("package", mgroup
.full_name
)
508 var prefix
= toolcontext
.test_dir
509 prefix
= prefix
.join_path
(mgroup
.to_s
)
510 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, o
, ts
)
513 var mdoc
= mgroup
.mdoc
514 if mdoc
== null then return ts
517 # NOTE: jenkins expects a '.' in the classname attr
518 d2m
.extract
(mdoc
, "nitunit." + mgroup
.full_name
, "<group>")
525 # Test a document object unrelated to a Nit entity
526 fun test_mdoc
(mdoc
: MDoc): HTMLTag
528 var ts
= new HTMLTag("testsuite")
529 var file
= mdoc
.location
.to_s
531 toolcontext
.info
("nitunit: doc-unit file {file}", 2)
533 ts
.attr
("package", file
)
535 var prefix
= toolcontext
.test_dir
/ "file"
536 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, null, ts
)
541 # NOTE: jenkins expects a '.' in the classname attr
542 d2m
.extract
(mdoc
, "nitunit.<file>", file
)