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
24 # Extractor, Executor and Reporter for the tests in a module
28 # Toolcontext used to parse Nit code blocks.
29 var toolcontext
: ToolContext
31 # The prefix of the generated Nit source-file
34 # The module to import, if any
35 var mmodule
: nullable MModule
37 # The XML node associated to the module
38 var testsuite
: HTMLTag
40 # The name of the suite
43 # Markdown processor used to parse markdown comments and extract code.
44 var mdproc
= new MarkdownProcessor
47 mdproc
.decorator
= new NitunitDecorator(self)
50 # The associated documentation object
51 var mdoc
: nullable MDoc = null
53 # used to generate distinct names
56 # The last docunit extracted from a mdoc.
58 # Is used because a new code-block might just be added to it.
59 var last_docunit
: nullable DocUnit = null
61 var xml_classname
: String is noautoinit
63 var xml_name
: String is noautoinit
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)
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"))
79 # All extracted docunits
80 var docunits
= new Array[DocUnit]
84 toolcontext
.show_unit_status
(name
, docunits
)
87 fun mark_done
(du
: DocUnit)
90 toolcontext
.clear_progress_bar
91 toolcontext
.show_unit
(du
)
95 # Execute all the docunits
98 if docunits
.is_empty
then
102 # Try to group each nitunit into a single source file to fasten the compilation
103 var simple_du
= new Array[DocUnit] # du that are simple statements
104 var single_du
= new Array[DocUnit] # du that are modules or include classes
106 for du
in docunits
do
107 # Skip existing errors
108 if du
.error
!= null then
112 var ast
= toolcontext
.parse_something
(du
.block
)
113 if ast
isa AExpr then
120 # Try to mass compile all the simple du as a single nit module
121 compile_simple_docunits
(simple_du
)
122 # Try to mass compile all the single du in a single nitc invocation with many modules
123 compile_single_docunits
(single_du
)
124 # If the mass compilation fail, then each one will be compiled individually
126 # Now test them in order
127 for du
in docunits
do
128 if du
.error
!= null then
129 # Nothing to execute. Conclude
130 else if du
.is_compiled
then
131 # Already compiled. Execute it.
132 execute_simple_docunit
(du
)
134 # A mass compilation failed
135 # Need to try to recompile it, then execute it
136 test_single_docunit
(du
)
145 for du
in docunits
do
146 testsuite
.add du
.to_xml
150 # Compiles multiples doc-units in a shared program.
151 # Used for docunits simple block of code (without modules, classes, functions etc.)
153 # In case of success, the docunits are compiled and the caller can call `execute_simple_docunit`.
155 # In case of compilation error, the docunits are let uncompiled.
156 # The caller should fallbacks to `test_single_docunit` to
157 # * locate exactly the compilation problem in the problematic docunit.
158 # * permit the execution of the other docunits that may be correct.
159 fun compile_simple_docunits
(dus
: Array[DocUnit])
161 if dus
.is_empty
then return
163 var file
= "{prefix}-0.nit"
165 toolcontext
.info
("Compile {dus.length} simple(s) doc-unit(s) in {file}", 1)
167 var dir
= file
.dirname
168 if dir
!= "" then dir
.mkdir
170 f
= create_unitfile
(file
)
174 f
.write
("fun run_{i} do\n")
175 f
.write
("# {du.full_name}\n")
179 f
.write
("var a = args.first.to_i\n")
181 f
.write
("if a == {j} then run_{j}\n")
185 if toolcontext
.opt_noact
.value
then return
187 var res
= compile_unitfile
(file
)
191 # They should be generated and compiled independently
195 # Compilation was a success.
196 # Store what need to be executed for each one.
202 du
.is_compiled
= true
206 # Execute a docunit compiled by `test_single_docunit`
207 fun execute_simple_docunit
(du
: DocUnit)
209 var file
= du
.test_file
.as(not null)
210 var i
= du
.test_arg
or else 0
211 toolcontext
.info
("Execute doc-unit {du.full_name} in {file} {i}", 1)
212 var clock
= new Clock
213 var res2
= toolcontext
.safe_exec
("{file.to_program_name}.bin {i} >'{file}.out1' 2>&1 </dev/null")
214 if not toolcontext
.opt_no_time
.value
then du
.real_time
= clock
.total
217 var content
= "{file}.out1".to_path
.read_all
218 du
.raw_output
= content
221 du
.error
= "Runtime error in {file} with argument {i}"
222 toolcontext
.modelbuilder
.failed_entities
+= 1
226 # Produce a single unit file for the docunit `du`.
227 fun generate_single_docunit
(du
: DocUnit): String
230 var file
= "{prefix}-{cpt}.nit"
233 f
= create_unitfile
(file
)
241 # Executes a single doc-unit in its own program.
242 # Used for docunits larger than a single block of code (with modules, classes, functions etc.)
243 fun test_single_docunit
(du
: DocUnit)
245 var file
= generate_single_docunit
(du
)
247 toolcontext
.info
("Compile doc-unit {du.full_name} in {file}", 1)
249 if toolcontext
.opt_noact
.value
then return
251 var res
= compile_unitfile
(file
)
252 var content
= "{file}.out1".to_path
.read_all
253 du
.raw_output
= content
258 du
.error
= "Compilation error in {file}"
259 toolcontext
.modelbuilder
.failed_entities
+= 1
263 du
.is_compiled
= true
264 execute_simple_docunit
(du
)
267 # Create and fill the header of a unit file `file`.
269 # A unit file is a Nit source file generated from one
270 # or more docunits that will be compiled and executed.
272 # The handled on the file is returned and must be completed and closed.
274 # `file` should be a valid filepath for a Nit source file.
275 private fun create_unitfile
(file
: String): Writer
277 var dir
= file
.dirname
278 if dir
!= "" then dir
.mkdir
280 f
= new FileWriter.open
(file
)
281 f
.write
("# GENERATED FILE\n")
282 f
.write
("# Docunits extracted from comments\n")
283 if mmodule
!= null then
284 f
.write
("intrude import {mmodule.name}\n")
290 # Compile a unit file and return the compiler return code
292 # Can terminate the program if the compiler is not found
293 private fun compile_unitfile
(file
: String): Int
295 var nitc
= toolcontext
.find_nitc
296 var opts
= new Array[String]
297 if mmodule
!= null then
298 # FIXME playing this way with the include dir is not safe nor robust
299 opts
.add
"-I {mmodule.filepath.dirname}"
301 var cmd
= "{nitc} --ignore-visibility --no-color -q '{file}' {opts.join(" ")} >'{file}.out1' 2>&1 </dev/null -o '{file}.bin'"
302 var res
= toolcontext
.safe_exec
(cmd
)
306 # Compile a unit file and return the compiler return code
308 # Can terminate the program if the compiler is not found
309 private fun compile_single_docunits
(dus
: Array[DocUnit]): Int
311 # Generate all unitfiles
312 var files
= new Array[String]
314 files
.add generate_single_docunit
(du
)
317 if files
.is_empty
then return 0
319 toolcontext
.info
("Compile {dus.length} single(s) doc-unit(s) at once", 1)
322 var nitc
= toolcontext
.find_nitc
323 var opts
= new Array[String]
324 if mmodule
!= null then
325 # FIXME playing this way with the include dir is not safe nor robust
326 opts
.add
"-I {mmodule.filepath.dirname}"
328 var cmd
= "{nitc} --ignore-visibility --no-color -q '{files.join("' '")}' {opts.join(" ")} > '{prefix}.out1' 2>&1 </dev/null --dir {prefix.dirname}"
329 var res
= toolcontext
.safe_exec
(cmd
)
331 # Mass compilation failure
335 # Rename each file into it expected binary name
337 var f
= du
.test_file
.as(not null)
338 toolcontext
.safe_exec
("mv '{f.strip_extension(".nit")}' '{f}.bin'")
339 du
.is_compiled
= true
346 private class NitunitDecorator
349 var executor
: NitUnitExecutor
351 redef fun add_code
(v
, block
) do
352 var code
= block
.raw_content
353 var meta
= block
.meta
or else "nit"
354 # Do not try to test non-nit code.
355 if meta
!= "nit" then return
356 # Try to parse code blocks
357 var ast
= executor
.toolcontext
.parse_something
(code
)
359 var mdoc
= executor
.mdoc
363 if ast
isa TComment then return
365 # The location is computed according to the starts of the mdoc and the block
366 # Note, the following assumes that all the comments of the mdoc are correctly aligned.
367 var loc
= block
.block
.location
368 var line_offset
= loc
.line_start
+ mdoc
.location
.line_start
- 2
369 var column_offset
= loc
.column_start
+ mdoc
.location
.column_start
370 # Hack to handle precise location in blocks
371 # TODO remove when markdown is more reliable
372 if block
isa BlockFence then
373 # Skip the starting fence
376 # Account a standard 4 space indentation
380 # We want executable code
381 if not (ast
isa AModule or ast
isa ABlockExpr or ast
isa AExpr) then
384 # Get real location of the node (or error)
385 var location
= new Location(mdoc
.location
.file
,
386 l
.line_start
+ line_offset
,
387 l
.line_end
+ line_offset
,
388 l
.column_start
+ column_offset
,
389 l
.column_end
+ column_offset
)
390 if ast
isa AError then
391 message
= ast
.message
393 message
= "Error: Invalid Nit code."
398 du
.error_location
= location
400 executor
.toolcontext
.modelbuilder
.failed_entities
+= 1
404 # Create a first block
405 # Or create a new block for modules that are more than a main part
406 var last_docunit
= executor
.last_docunit
407 if last_docunit
== null or ast
isa AModule then
408 last_docunit
= new_docunit
409 executor
.last_docunit
= last_docunit
413 last_docunit
.block
+= code
415 # In order to retrieve precise positions,
416 # the real position of each line of the raw_content is stored.
417 # See `DocUnit::real_location`
418 line_offset
-= loc
.line_start
- 1
419 for i
in [loc
.line_start
..loc
.line_end
] do
420 last_docunit
.lines
.add i
+ line_offset
421 last_docunit
.columns
.add column_offset
425 # Return and register a new empty docunit
426 fun new_docunit
: DocUnit
428 var mdoc
= executor
.mdoc
432 var name
= executor
.xml_name
433 if executor
.docunits
.not_empty
and executor
.docunits
.last
.mdoc
== mdoc
then
434 next_number
= executor
.docunits
.last
.number
+ 1
435 name
+= "#" + next_number
.to_s
438 var res
= new DocUnit(mdoc
, next_number
, "", executor
.xml_classname
, name
)
439 executor
.docunits
.add res
440 executor
.toolcontext
.modelbuilder
.unit_entities
+= 1
445 # A unit-test extracted from some documentation.
447 # A docunit is extracted from the code-blocks of mdocs.
448 # Each mdoc can contains more than one docunit, and a single docunit can be made of more that a single code-block.
452 # The doc that contains self
455 # The numbering of self in mdoc (starting with 0)
458 # The generated Nit source file that contains the unit-test
460 # Note that a same generated file can be used for multiple tests.
461 # See `test_arg` that is used to distinguish them
462 var test_file
: nullable String = null
464 # Was `test_file` successfully compiled?
465 var is_compiled
= false
467 # The command-line argument to use when executing the test, if any.
468 var test_arg
: nullable Int = null
470 redef fun full_name
do
471 var mentity
= mdoc
.original_mentity
472 if mentity
!= null then
473 var res
= mentity
.full_name
479 return xml_classname
+ "." + xml_name
483 # The text of the code to execute.
485 # This is the verbatim content on one, or more, code-blocks from `mdoc`
488 # For each line in `block`, the associated line in the mdoc
490 # Is used to give precise locations
491 var lines
= new Array[Int]
493 # For each line in `block`, the associated column in the mdoc
495 # Is used to give precise locations
496 var columns
= new Array[Int]
498 # The location of the whole docunit.
500 # If `self` is made of multiple code-blocks, then the location
501 # starts at the first code-books and finish at the last one, thus includes anything between.
502 redef var location
is lazy
do
503 return new Location(mdoc
.location
.file
, lines
.first
, lines
.last
+1, columns
.first
+1, 0)
506 # Compute the real location of a node on the `ast` based on `mdoc.location`
508 # The result is basically: ast_location + markdown location of the piece + mdoc.location
510 # The fun is that a single docunit can be made of various pieces of code blocks.
511 fun real_location
(ast_location
: Location): Location
514 var res
= new Location(mdoc
.location
.file
, lines
[ast_location
.line_start-1
],
515 lines
[ast_location
.line_end-1
],
516 columns
[ast_location
.line_start-1
] + ast_location
.column_start
,
517 columns
[ast_location
.line_end-1
] + ast_location
.column_end
)
524 res
.open
("system-out").append
(block
)
528 redef var xml_classname
532 redef class ModelBuilder
533 # Total number analyzed `MEntity`
534 var total_entities
= 0
536 # The number of `MEntity` that have some documentation
539 # The total number of executed docunits
540 var unit_entities
= 0
542 # The number failed docunits
543 var failed_entities
= 0
545 # Extracts and executes all the docunits in the `mmodule`
546 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
547 fun test_markdown
(mmodule
: MModule): HTMLTag
549 var ts
= new HTMLTag("testsuite")
550 toolcontext
.info
("nitunit: doc-unit {mmodule}", 2)
552 var nmodule
= mmodule2node
(mmodule
)
553 if nmodule
== null then return ts
555 # usualy, only the original module must be imported in the unit test.
558 if g
!= null and g
.mpackage
.name
== "core" then
559 # except for a unit test in a module of `core`
560 # in this case, the whole `core` must be imported
561 o
= get_mmodule_by_name
(nmodule
, g
, g
.mpackage
.name
).as(not null)
564 ts
.attr
("package", mmodule
.full_name
)
566 var prefix
= toolcontext
.test_dir
567 prefix
= prefix
.join_path
(mmodule
.to_s
)
568 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, o
, ts
, "Docunits of module {mmodule.full_name}")
572 var nmoduledecl
= nmodule
.n_moduledecl
573 if nmoduledecl
== null then break label x
574 var ndoc
= nmoduledecl
.n_doc
575 if ndoc
== null then break label x
577 # NOTE: jenkins expects a '.' in the classname attr
578 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + mmodule
.full_name
+ ".<module>", "<module>")
580 for nclassdef
in nmodule
.n_classdefs
do
581 var mclassdef
= nclassdef
.mclassdef
582 if mclassdef
== null then continue
583 if nclassdef
isa AStdClassdef then
585 var ndoc
= nclassdef
.n_doc
588 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + mclassdef
.full_name
.replace
("$", "."), "<class>")
591 for npropdef
in nclassdef
.n_propdefs
do
592 var mpropdef
= npropdef
.mpropdef
593 if mpropdef
== null then continue
595 var ndoc
= npropdef
.n_doc
598 var a
= mpropdef
.full_name
.split
("$")
599 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + a
[0] + "." + a
[1], a
[2])
609 # Extracts and executes all the docunits in the readme of the `mgroup`
610 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
611 fun test_group
(mgroup
: MGroup): HTMLTag
613 var ts
= new HTMLTag("testsuite")
614 toolcontext
.info
("nitunit: doc-unit group {mgroup}", 2)
616 # usually, only the default module must be imported in the unit test.
617 var o
= mgroup
.default_mmodule
619 ts
.attr
("package", mgroup
.full_name
)
621 var prefix
= toolcontext
.test_dir
622 prefix
= prefix
.join_path
(mgroup
.to_s
)
623 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, o
, ts
, "Docunits of group {mgroup.full_name}")
626 var mdoc
= mgroup
.mdoc
627 if mdoc
== null then return ts
630 # NOTE: jenkins expects a '.' in the classname attr
631 d2m
.extract
(mdoc
, "nitunit." + mgroup
.mpackage
.name
+ "." + mgroup
.name
+ ".<group>", "<group>")
638 # Test a document object unrelated to a Nit entity
639 fun test_mdoc
(mdoc
: MDoc): HTMLTag
641 var ts
= new HTMLTag("testsuite")
642 var file
= mdoc
.location
.file
.filename
644 toolcontext
.info
("nitunit: doc-unit file {file}", 2)
646 ts
.attr
("package", file
)
648 var prefix
= toolcontext
.test_dir
/ "file"
649 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, null, ts
, "Docunits of file {file}")
654 # NOTE: jenkins expects a '.' in the classname attr
655 d2m
.extract
(mdoc
, "nitunit.<file>", file
)