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 # Unit class name in XML output
62 var xml_classname
: String is noautoinit
64 # Unit name in xml output
65 var xml_name
: String is noautoinit
67 # The entry point for a new `ndoc` node
68 # Fill `docunits` with new discovered unit of tests.
69 fun extract
(mdoc
: MDoc, xml_classname
, xml_name
: String)
72 self.xml_classname
= xml_classname
73 self.xml_name
= xml_name
77 # Populate `blocks` from the markdown decorator
78 mdproc
.process
(mdoc
.content
.join
("\n"))
81 # All extracted docunits
82 var docunits
= new Array[DocUnit]
84 # Display current testing status
85 fun show_status
do toolcontext
.show_unit_status
(name
, docunits
)
87 # Update display when a test case is done
88 fun mark_done
(du
: DocUnit)
91 toolcontext
.clear_progress_bar
92 toolcontext
.show_unit
(du
)
96 # Execute all the docunits
99 if docunits
.is_empty
then
103 # Try to group each nitunit into a single source file to fasten the compilation
104 var simple_du
= new Array[DocUnit] # du that are simple statements
105 var single_du
= new Array[DocUnit] # du that are modules or include classes
107 for du
in docunits
do
108 # Skip existing errors
109 if du
.error
!= null then
113 var ast
= toolcontext
.parse_something
(du
.block
)
114 if ast
isa AExpr then
121 # Try to mass compile all the simple du as a single nit module
122 compile_simple_docunits
(simple_du
)
123 # Try to mass compile all the single du in a single nitc invocation with many modules
124 compile_single_docunits
(single_du
)
125 # If the mass compilation fail, then each one will be compiled individually
127 # Now test them in order
128 for du
in docunits
do
129 if du
.error
!= null then
130 # Nothing to execute. Conclude
131 else if du
.is_compiled
then
132 # Already compiled. Execute it.
133 execute_simple_docunit
(du
)
135 # A mass compilation failed
136 # Need to try to recompile it, then execute it
137 test_single_docunit
(du
)
146 for du
in docunits
do
147 testsuite
.add du
.to_xml
151 # Compiles multiples doc-units in a shared program.
152 # Used for docunits simple block of code (without modules, classes, functions etc.)
154 # In case of success, the docunits are compiled and the caller can call `execute_simple_docunit`.
156 # In case of compilation error, the docunits are let uncompiled.
157 # The caller should fallbacks to `test_single_docunit` to
158 # * locate exactly the compilation problem in the problematic docunit.
159 # * permit the execution of the other docunits that may be correct.
160 fun compile_simple_docunits
(dus
: Array[DocUnit])
162 if dus
.is_empty
then return
164 var file
= "{prefix}-0.nit"
166 toolcontext
.info
("Compile {dus.length} simple(s) doc-unit(s) in {file}", 1)
168 var dir
= file
.dirname
169 if dir
!= "" then dir
.mkdir
171 f
= create_unitfile
(file
)
175 f
.write
("fun run_{i} do\n")
176 f
.write
("# {du.full_name}\n")
180 f
.write
("var a = args.first.to_i\n")
182 f
.write
("if a == {j} then run_{j}\n")
186 if toolcontext
.opt_noact
.value
then return
188 var res
= compile_unitfile
(file
)
192 # They should be generated and compiled independently
196 # Compilation was a success.
197 # Store what need to be executed for each one.
203 du
.is_compiled
= true
207 # Execute a docunit compiled by `test_single_docunit`
208 fun execute_simple_docunit
(du
: DocUnit)
210 var file
= du
.test_file
.as(not null)
211 var i
= du
.test_arg
or else 0
212 toolcontext
.info
("Execute doc-unit {du.full_name} in {file} {i}", 1)
213 var clock
= new Clock
214 var res2
= toolcontext
.safe_exec
("{file.to_program_name}.bin {i} >'{file}.out1' 2>&1 </dev/null")
215 if not toolcontext
.opt_no_time
.value
then du
.real_time
= clock
.total
218 var content
= "{file}.out1".to_path
.read_all
219 du
.raw_output
= content
222 du
.error
= "Runtime error in {file} with argument {i}"
223 toolcontext
.modelbuilder
.failed_entities
+= 1
227 # Produce a single unit file for the docunit `du`.
228 fun generate_single_docunit
(du
: DocUnit): String
231 var file
= "{prefix}-{cpt}.nit"
234 f
= create_unitfile
(file
)
242 # Executes a single doc-unit in its own program.
243 # Used for docunits larger than a single block of code (with modules, classes, functions etc.)
244 fun test_single_docunit
(du
: DocUnit)
246 var file
= generate_single_docunit
(du
)
248 toolcontext
.info
("Compile doc-unit {du.full_name} in {file}", 1)
250 if toolcontext
.opt_noact
.value
then return
252 var res
= compile_unitfile
(file
)
253 var content
= "{file}.out1".to_path
.read_all
254 du
.raw_output
= content
259 du
.error
= "Compilation error in {file}"
260 toolcontext
.modelbuilder
.failed_entities
+= 1
264 du
.is_compiled
= true
265 execute_simple_docunit
(du
)
268 # Create and fill the header of a unit file `file`.
270 # A unit file is a Nit source file generated from one
271 # or more docunits that will be compiled and executed.
273 # The handled on the file is returned and must be completed and closed.
275 # `file` should be a valid filepath for a Nit source file.
276 private fun create_unitfile
(file
: String): Writer
278 var mmodule
= self.mmodule
279 var dir
= file
.dirname
280 if dir
!= "" then dir
.mkdir
282 f
= new FileWriter.open
(file
)
283 f
.write
("# GENERATED FILE\n")
284 f
.write
("# Docunits extracted from comments\n")
285 if mmodule
!= null then
286 f
.write
("intrude import {mmodule.name}\n")
292 # Compile a unit file and return the compiler return code
294 # Can terminate the program if the compiler is not found
295 private fun compile_unitfile
(file
: String): Int
297 var mmodule
= self.mmodule
298 var nitc
= toolcontext
.find_nitc
299 var opts
= new Array[String]
300 if mmodule
!= null then
301 # FIXME playing this way with the include dir is not safe nor robust
302 opts
.add
"-I {mmodule.filepath.as(not null).dirname}"
304 var cmd
= "{nitc} --ignore-visibility --no-color -q '{file}' {opts.join(" ")} >'{file}.out1' 2>&1 </dev/null -o '{file}.bin'"
305 var res
= toolcontext
.safe_exec
(cmd
)
309 # Compile a unit file and return the compiler return code
311 # Can terminate the program if the compiler is not found
312 private fun compile_single_docunits
(dus
: Array[DocUnit]): Int
314 # Generate all unitfiles
315 var files
= new Array[String]
317 files
.add generate_single_docunit
(du
)
320 if files
.is_empty
then return 0
322 toolcontext
.info
("Compile {dus.length} single(s) doc-unit(s) at once", 1)
325 var nitc
= toolcontext
.find_nitc
326 var opts
= new Array[String]
327 if mmodule
!= null then
328 # FIXME playing this way with the include dir is not safe nor robust
329 opts
.add
"-I {mmodule.filepath.dirname}"
331 var cmd
= "{nitc} --ignore-visibility --no-color -q '{files.join("' '")}' {opts.join(" ")} > '{prefix}.out1' 2>&1 </dev/null --dir {prefix.dirname}"
332 var res
= toolcontext
.safe_exec
(cmd
)
334 # Mass compilation failure
338 # Rename each file into it expected binary name
340 var f
= du
.test_file
.as(not null)
341 toolcontext
.safe_exec
("mv '{f.strip_extension(".nit")}' '{f}.bin'")
342 du
.is_compiled
= true
349 private class NitunitDecorator
352 var executor
: NitUnitExecutor
354 redef fun add_code
(v
, block
) do
355 var code
= block
.raw_content
356 var meta
= block
.meta
or else "nit"
357 # Do not try to test non-nit code.
358 if meta
!= "nit" then return
359 # Try to parse code blocks
360 var ast
= executor
.toolcontext
.parse_something
(code
)
362 var mdoc
= executor
.mdoc
366 if ast
isa TComment then return
368 # The location is computed according to the starts of the mdoc and the block
369 # Note, the following assumes that all the comments of the mdoc are correctly aligned.
370 var loc
= block
.block
.location
371 var line_offset
= loc
.line_start
+ mdoc
.location
.line_start
- 2
372 var column_offset
= loc
.column_start
+ mdoc
.location
.column_start
373 # Hack to handle precise location in blocks
374 # TODO remove when markdown is more reliable
375 if block
isa BlockFence then
376 # Skip the starting fence
379 # Account a standard 4 space indentation
383 # We want executable code
384 if not (ast
isa AModule or ast
isa ABlockExpr or ast
isa AExpr) then
387 # Get real location of the node (or error)
388 var location
= new Location(mdoc
.location
.file
,
389 l
.line_start
+ line_offset
,
390 l
.line_end
+ line_offset
,
391 l
.column_start
+ column_offset
,
392 l
.column_end
+ column_offset
)
393 if ast
isa AError then
394 message
= ast
.message
396 message
= "Error: Invalid Nit code."
401 du
.error_location
= location
403 executor
.toolcontext
.modelbuilder
.failed_entities
+= 1
407 # Create a first block
408 # Or create a new block for modules that are more than a main part
409 var last_docunit
= executor
.last_docunit
410 if last_docunit
== null or ast
isa AModule then
411 last_docunit
= new_docunit
412 executor
.last_docunit
= last_docunit
416 last_docunit
.block
+= code
418 # In order to retrieve precise positions,
419 # the real position of each line of the raw_content is stored.
420 # See `DocUnit::real_location`
421 line_offset
-= loc
.line_start
- 1
422 for i
in [loc
.line_start
..loc
.line_end
] do
423 last_docunit
.lines
.add i
+ line_offset
424 last_docunit
.columns
.add column_offset
428 # Return and register a new empty docunit
429 fun new_docunit
: DocUnit
431 var mdoc
= executor
.mdoc
435 var name
= executor
.xml_name
436 if executor
.docunits
.not_empty
and executor
.docunits
.last
.mdoc
== mdoc
then
437 next_number
= executor
.docunits
.last
.number
+ 1
438 name
+= "#" + next_number
.to_s
441 var res
= new DocUnit(mdoc
, next_number
, "", executor
.xml_classname
, name
)
442 executor
.docunits
.add res
443 executor
.toolcontext
.modelbuilder
.unit_entities
+= 1
448 # A unit-test extracted from some documentation.
450 # A docunit is extracted from the code-blocks of mdocs.
451 # Each mdoc can contains more than one docunit, and a single docunit can be made of more that a single code-block.
455 # The doc that contains self
458 # The numbering of self in mdoc (starting with 0)
461 # The generated Nit source file that contains the unit-test
463 # Note that a same generated file can be used for multiple tests.
464 # See `test_arg` that is used to distinguish them
465 var test_file
: nullable String = null
467 # Was `test_file` successfully compiled?
468 var is_compiled
= false
470 # The command-line argument to use when executing the test, if any.
471 var test_arg
: nullable Int = null
473 redef fun full_name
do
474 var mentity
= mdoc
.original_mentity
475 if mentity
!= null then
476 var res
= mentity
.full_name
482 return xml_classname
+ "." + xml_name
486 # The text of the code to execute.
488 # This is the verbatim content on one, or more, code-blocks from `mdoc`
491 # For each line in `block`, the associated line in the mdoc
493 # Is used to give precise locations
494 var lines
= new Array[Int]
496 # For each line in `block`, the associated column in the mdoc
498 # Is used to give precise locations
499 var columns
= new Array[Int]
501 # The location of the whole docunit.
503 # If `self` is made of multiple code-blocks, then the location
504 # starts at the first code-books and finish at the last one, thus includes anything between.
505 redef var location
is lazy
do
506 return new Location(mdoc
.location
.file
, lines
.first
, lines
.last
+1, columns
.first
+1, 0)
509 # Compute the real location of a node on the `ast` based on `mdoc.location`
511 # The result is basically: ast_location + markdown location of the piece + mdoc.location
513 # The fun is that a single docunit can be made of various pieces of code blocks.
514 fun real_location
(ast_location
: Location): Location
517 var res
= new Location(mdoc
.location
.file
, lines
[ast_location
.line_start-1
],
518 lines
[ast_location
.line_end-1
],
519 columns
[ast_location
.line_start-1
] + ast_location
.column_start
,
520 columns
[ast_location
.line_end-1
] + ast_location
.column_end
)
527 res
.open
("system-out").append
(block
)
531 redef var xml_classname
535 redef class ModelBuilder
536 # Total number analyzed `MEntity`
537 var total_entities
= 0
539 # The number of `MEntity` that have some documentation
542 # The total number of executed docunits
543 var unit_entities
= 0
545 # The number failed docunits
546 var failed_entities
= 0
548 # Extracts and executes all the docunits in the `mmodule`
549 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
550 fun test_markdown
(mmodule
: MModule): HTMLTag
552 var ts
= new HTMLTag("testsuite")
553 toolcontext
.info
("nitunit: doc-unit {mmodule}", 2)
555 var nmodule
= mmodule2node
(mmodule
)
556 if nmodule
== null then return ts
558 # usualy, only the original module must be imported in the unit test.
561 if g
!= null and g
.mpackage
.name
== "core" then
562 # except for a unit test in a module of `core`
563 # in this case, the whole `core` must be imported
564 o
= get_mmodule_by_name
(nmodule
, g
, g
.mpackage
.name
).as(not null)
567 ts
.attr
("package", mmodule
.full_name
)
569 var prefix
= toolcontext
.test_dir
570 prefix
= prefix
.join_path
(mmodule
.to_s
)
571 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, o
, ts
, "Docunits of module {mmodule.full_name}")
575 var nmoduledecl
= nmodule
.n_moduledecl
576 if nmoduledecl
== null then break label x
577 var ndoc
= nmoduledecl
.n_doc
578 if ndoc
== null then break label x
580 # NOTE: jenkins expects a '.' in the classname attr
581 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + mmodule
.full_name
+ ".<module>", "<module>")
583 for nclassdef
in nmodule
.n_classdefs
do
584 var mclassdef
= nclassdef
.mclassdef
585 if mclassdef
== null then continue
586 if nclassdef
isa AStdClassdef then
588 var ndoc
= nclassdef
.n_doc
591 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + mclassdef
.full_name
.replace
("$", "."), "<class>")
594 for npropdef
in nclassdef
.n_propdefs
do
595 var mpropdef
= npropdef
.mpropdef
596 if mpropdef
== null then continue
598 var ndoc
= npropdef
.n_doc
601 var a
= mpropdef
.full_name
.split
("$")
602 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + a
[0] + "." + a
[1], a
[2])
612 # Extracts and executes all the docunits in the readme of the `mgroup`
613 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
614 fun test_group
(mgroup
: MGroup): HTMLTag
616 var ts
= new HTMLTag("testsuite")
617 toolcontext
.info
("nitunit: doc-unit group {mgroup}", 2)
619 # usually, only the default module must be imported in the unit test.
620 var o
= mgroup
.default_mmodule
622 ts
.attr
("package", mgroup
.full_name
)
624 var prefix
= toolcontext
.test_dir
625 prefix
= prefix
.join_path
(mgroup
.to_s
)
626 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, o
, ts
, "Docunits of group {mgroup.full_name}")
629 var mdoc
= mgroup
.mdoc
630 if mdoc
== null then return ts
633 # NOTE: jenkins expects a '.' in the classname attr
634 d2m
.extract
(mdoc
, "nitunit." + mgroup
.mpackage
.name
+ "." + mgroup
.name
+ ".<group>", "<group>")
641 # Test a document object unrelated to a Nit entity
642 fun test_mdoc
(mdoc
: MDoc): HTMLTag
644 var ts
= new HTMLTag("testsuite")
645 var file
= mdoc
.location
.file
.as(not null).filename
647 toolcontext
.info
("nitunit: doc-unit file {file}", 2)
649 ts
.attr
("package", file
)
651 var prefix
= toolcontext
.test_dir
/ "file"
652 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, null, ts
, "Docunits of file {file}")
657 # NOTE: jenkins expects a '.' in the classname attr
658 d2m
.extract
(mdoc
, "nitunit.<file>", file
)