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
.emitter
.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]
105 for du
in docunits
do
106 # Skip existing errors
107 if du
.error
!= null then
111 var ast
= toolcontext
.parse_something
(du
.block
)
112 if ast
isa AExpr then
116 test_simple_docunits
(simple_du
)
118 # Now test them in order
119 for du
in docunits
do
120 if du
.error
!= null then
121 # Nothing to execute. Conclude
122 else if du
.test_file
!= null then
123 # Already compiled. Execute it.
124 execute_simple_docunit
(du
)
126 # Need to try to compile it, then execute it
127 test_single_docunit
(du
)
136 for du
in docunits
do
137 testsuite
.add du
.to_xml
141 # Executes multiples doc-units in a shared program.
142 # Used for docunits simple block of code (without modules, classes, functions etc.)
144 # In case of compilation error, the method fallbacks to `test_single_docunit` to
145 # * locate exactly the compilation problem in the problematic docunit.
146 # * permit the execution of the other docunits that may be correct.
147 fun test_simple_docunits
(dus
: Array[DocUnit])
149 if dus
.is_empty
then return
151 var file
= "{prefix}-0.nit"
153 var dir
= file
.dirname
154 if dir
!= "" then dir
.mkdir
156 f
= create_unitfile
(file
)
161 f
.write
("fun run_{i} do\n")
162 f
.write
("# {du.full_name}\n")
166 f
.write
("var a = args.first.to_i\n")
168 f
.write
("if a == {j} then run_{j}\n")
172 if toolcontext
.opt_noact
.value
then return
174 var res
= compile_unitfile
(file
)
178 # They will be executed independently
182 # Compilation was a success.
183 # Store what need to be executed for each one.
192 # Execute a docunit compiled by `test_single_docunit`
193 fun execute_simple_docunit
(du
: DocUnit)
195 var file
= du
.test_file
.as(not null)
196 var i
= du
.test_arg
.as(not null)
197 toolcontext
.info
("Execute doc-unit {du.full_name} in {file} {i}", 1)
198 var clock
= new Clock
199 var res2
= toolcontext
.safe_exec
("{file.to_program_name}.bin {i} >'{file}.out1' 2>&1 </dev/null")
200 if not toolcontext
.opt_no_time
.value
then du
.real_time
= clock
.total
203 var content
= "{file}.out1".to_path
.read_all
204 du
.raw_output
= content
207 du
.error
= "Runtime error in {file} with argument {i}"
208 toolcontext
.modelbuilder
.failed_entities
+= 1
212 # Executes a single doc-unit in its own program.
213 # Used for docunits larger than a single block of code (with modules, classes, functions etc.)
214 fun test_single_docunit
(du
: DocUnit)
217 var file
= "{prefix}-{cpt}.nit"
219 toolcontext
.info
("Execute doc-unit {du.full_name} in {file}", 1)
222 f
= create_unitfile
(file
)
226 if toolcontext
.opt_noact
.value
then return
228 var res
= compile_unitfile
(file
)
231 var clock
= new Clock
232 res2
= toolcontext
.safe_exec
("{file.to_program_name}.bin >'{file}.out1' 2>&1 </dev/null")
233 if not toolcontext
.opt_no_time
.value
then du
.real_time
= clock
.total
237 var content
= "{file}.out1".to_path
.read_all
238 du
.raw_output
= content
241 du
.error
= "Compilation error in {file}"
242 toolcontext
.modelbuilder
.failed_entities
+= 1
243 else if res2
!= 0 then
244 du
.error
= "Runtime error in {file}"
245 toolcontext
.modelbuilder
.failed_entities
+= 1
249 # Create and fill the header of a unit file `file`.
251 # A unit file is a Nit source file generated from one
252 # or more docunits that will be compiled and executed.
254 # The handled on the file is returned and must be completed and closed.
256 # `file` should be a valid filepath for a Nit source file.
257 private fun create_unitfile
(file
: String): Writer
259 var dir
= file
.dirname
260 if dir
!= "" then dir
.mkdir
262 f
= new FileWriter.open
(file
)
263 f
.write
("# GENERATED FILE\n")
264 f
.write
("# Docunits extracted from comments\n")
265 if mmodule
!= null then
266 f
.write
("intrude import {mmodule.name}\n")
272 # Compile an unit file and return the compiler return code
274 # Can terminate the program if the compiler is not found
275 private fun compile_unitfile
(file
: String): Int
277 var nitc
= toolcontext
.find_nitc
278 var opts
= new Array[String]
279 if mmodule
!= null then
280 opts
.add
"-I {mmodule.filepath.dirname}"
282 var cmd
= "{nitc} --ignore-visibility --no-color -q '{file}' {opts.join(" ")} >'{file}.out1' 2>&1 </dev/null -o '{file}.bin'"
283 var res
= toolcontext
.safe_exec
(cmd
)
288 private class NitunitDecorator
291 var executor
: NitUnitExecutor
293 redef fun add_code
(v
, block
) do
294 var code
= block
.raw_content
295 var meta
= block
.meta
or else "nit"
296 # Do not try to test non-nit code.
297 if meta
!= "nit" then return
298 # Try to parse code blocks
299 var ast
= executor
.toolcontext
.parse_something
(code
)
301 var mdoc
= executor
.mdoc
305 if ast
isa TComment then return
307 # The location is computed according to the starts of the mdoc and the block
308 # Note, the following assumes that all the comments of the mdoc are correctly aligned.
309 var loc
= block
.block
.location
310 var line_offset
= loc
.line_start
+ mdoc
.location
.line_start
- 2
311 var column_offset
= loc
.column_start
+ mdoc
.location
.column_start
312 # Hack to handle precise location in blocks
313 # TODO remove when markdown is more reliable
314 if block
isa BlockFence then
315 # Skip the starting fence
318 # Account a standard 4 space indentation
322 # We want executable code
323 if not (ast
isa AModule or ast
isa ABlockExpr or ast
isa AExpr) then
326 # Get real location of the node (or error)
327 var location
= new Location(mdoc
.location
.file
,
328 l
.line_start
+ line_offset
,
329 l
.line_end
+ line_offset
,
330 l
.column_start
+ column_offset
,
331 l
.column_end
+ column_offset
)
332 if ast
isa AError then
333 message
= ast
.message
335 message
= "Error: Invalid Nit code."
340 du
.error_location
= location
342 executor
.toolcontext
.modelbuilder
.failed_entities
+= 1
346 # Create a first block
347 # Or create a new block for modules that are more than a main part
348 var last_docunit
= executor
.last_docunit
349 if last_docunit
== null or ast
isa AModule then
350 last_docunit
= new_docunit
351 executor
.last_docunit
= last_docunit
355 last_docunit
.block
+= code
357 # In order to retrieve precise positions,
358 # the real position of each line of the raw_content is stored.
359 # See `DocUnit::real_location`
360 line_offset
-= loc
.line_start
- 1
361 for i
in [loc
.line_start
..loc
.line_end
] do
362 last_docunit
.lines
.add i
+ line_offset
363 last_docunit
.columns
.add column_offset
367 # Return and register a new empty docunit
368 fun new_docunit
: DocUnit
370 var mdoc
= executor
.mdoc
374 var name
= executor
.xml_name
375 if executor
.docunits
.not_empty
and executor
.docunits
.last
.mdoc
== mdoc
then
376 next_number
= executor
.docunits
.last
.number
+ 1
377 name
+= "#" + next_number
.to_s
380 var res
= new DocUnit(mdoc
, next_number
, "", executor
.xml_classname
, name
)
381 executor
.docunits
.add res
382 executor
.toolcontext
.modelbuilder
.unit_entities
+= 1
387 # A unit-test extracted from some documentation.
389 # A docunit is extracted from the code-blocks of mdocs.
390 # Each mdoc can contains more than one docunit, and a single docunit can be made of more that a single code-block.
394 # The doc that contains self
397 # The numbering of self in mdoc (starting with 0)
400 # The generated Nit source file that contains the unit-test
402 # Note that a same generated file can be used for multiple tests.
403 # See `test_arg` that is used to distinguish them
404 var test_file
: nullable String = null
406 # The command-line argument to use when executing the test, if any.
407 var test_arg
: nullable Int = null
409 redef fun full_name
do
410 var mentity
= mdoc
.original_mentity
411 if mentity
!= null then
412 var res
= mentity
.full_name
418 return xml_classname
+ "." + xml_name
422 # The text of the code to execute.
424 # This is the verbatim content on one, or more, code-blocks from `mdoc`
427 # For each line in `block`, the associated line in the mdoc
429 # Is used to give precise locations
430 var lines
= new Array[Int]
432 # For each line in `block`, the associated column in the mdoc
434 # Is used to give precise locations
435 var columns
= new Array[Int]
437 # The location of the whole docunit.
439 # If `self` is made of multiple code-blocks, then the location
440 # starts at the first code-books and finish at the last one, thus includes anything between.
441 redef var location
is lazy
do
442 return new Location(mdoc
.location
.file
, lines
.first
, lines
.last
+1, columns
.first
+1, 0)
445 # Compute the real location of a node on the `ast` based on `mdoc.location`
447 # The result is basically: ast_location + markdown location of the piece + mdoc.location
449 # The fun is that a single docunit can be made of various pieces of code blocks.
450 fun real_location
(ast_location
: Location): Location
453 var res
= new Location(mdoc
.location
.file
, lines
[ast_location
.line_start-1
],
454 lines
[ast_location
.line_end-1
],
455 columns
[ast_location
.line_start-1
] + ast_location
.column_start
,
456 columns
[ast_location
.line_end-1
] + ast_location
.column_end
)
463 res
.open
("system-out").append
(block
)
467 redef var xml_classname
471 redef class ModelBuilder
472 # Total number analyzed `MEntity`
473 var total_entities
= 0
475 # The number of `MEntity` that have some documentation
478 # The total number of executed docunits
479 var unit_entities
= 0
481 # The number failed docunits
482 var failed_entities
= 0
484 # Extracts and executes all the docunits in the `mmodule`
485 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
486 fun test_markdown
(mmodule
: MModule): HTMLTag
488 var ts
= new HTMLTag("testsuite")
489 toolcontext
.info
("nitunit: doc-unit {mmodule}", 2)
491 var nmodule
= mmodule2node
(mmodule
)
492 if nmodule
== null then return ts
494 # usualy, only the original module must be imported in the unit test.
497 if g
!= null and g
.mpackage
.name
== "core" then
498 # except for a unit test in a module of `core`
499 # in this case, the whole `core` must be imported
500 o
= get_mmodule_by_name
(nmodule
, g
, g
.mpackage
.name
).as(not null)
503 ts
.attr
("package", mmodule
.full_name
)
505 var prefix
= toolcontext
.test_dir
506 prefix
= prefix
.join_path
(mmodule
.to_s
)
507 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, o
, ts
, "Docunits of module {mmodule.full_name}")
511 var nmoduledecl
= nmodule
.n_moduledecl
512 if nmoduledecl
== null then break label x
513 var ndoc
= nmoduledecl
.n_doc
514 if ndoc
== null then break label x
516 # NOTE: jenkins expects a '.' in the classname attr
517 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + mmodule
.full_name
+ ".<module>", "<module>")
519 for nclassdef
in nmodule
.n_classdefs
do
520 var mclassdef
= nclassdef
.mclassdef
521 if mclassdef
== null then continue
522 if nclassdef
isa AStdClassdef then
524 var ndoc
= nclassdef
.n_doc
527 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + mclassdef
.full_name
.replace
("$", "."), "<class>")
530 for npropdef
in nclassdef
.n_propdefs
do
531 var mpropdef
= npropdef
.mpropdef
532 if mpropdef
== null then continue
534 var ndoc
= npropdef
.n_doc
537 var a
= mpropdef
.full_name
.split
("$")
538 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + a
[0] + "." + a
[1], a
[2])
548 # Extracts and executes all the docunits in the readme of the `mgroup`
549 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
550 fun test_group
(mgroup
: MGroup): HTMLTag
552 var ts
= new HTMLTag("testsuite")
553 toolcontext
.info
("nitunit: doc-unit group {mgroup}", 2)
555 # usually, only the default module must be imported in the unit test.
556 var o
= mgroup
.default_mmodule
558 ts
.attr
("package", mgroup
.full_name
)
560 var prefix
= toolcontext
.test_dir
561 prefix
= prefix
.join_path
(mgroup
.to_s
)
562 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, o
, ts
, "Docunits of group {mgroup.full_name}")
565 var mdoc
= mgroup
.mdoc
566 if mdoc
== null then return ts
569 # NOTE: jenkins expects a '.' in the classname attr
570 d2m
.extract
(mdoc
, "nitunit." + mgroup
.mpackage
.name
+ "." + mgroup
.name
+ ".<group>", "<group>")
577 # Test a document object unrelated to a Nit entity
578 fun test_mdoc
(mdoc
: MDoc): HTMLTag
580 var ts
= new HTMLTag("testsuite")
581 var file
= mdoc
.location
.file
.filename
583 toolcontext
.info
("nitunit: doc-unit file {file}", 2)
585 ts
.attr
("package", file
)
587 var prefix
= toolcontext
.test_dir
/ "file"
588 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, null, ts
, "Docunits of file {file}")
593 # NOTE: jenkins expects a '.' in the classname attr
594 d2m
.extract
(mdoc
, "nitunit.<file>", file
)