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 # The name of the suite
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)
69 self.xml_classname
= xml_classname
70 self.xml_name
= xml_name
74 # Populate `blocks` from the markdown decorator
75 mdproc
.process
(mdoc
.content
.join
("\n"))
78 # All extracted docunits
79 var docunits
= new Array[DocUnit]
83 toolcontext
.show_unit_status
(name
, docunits
)
86 fun mark_done
(du
: DocUnit)
92 # Execute all the docunits
95 if docunits
.is_empty
then
99 # Try to group each nitunit into a single source file to fasten the compilation
100 var simple_du
= new Array[DocUnit]
102 for du
in docunits
do
103 # Skip existing errors
104 if du
.error
!= null then
108 var ast
= toolcontext
.parse_something
(du
.block
)
109 if ast
isa AExpr then
113 test_simple_docunits
(simple_du
)
115 # Now test them in order
116 for du
in docunits
do
117 if du
.error
!= null then
118 # Nothing to execute. Conclude
119 else if du
.test_file
!= null then
120 # Already compiled. Execute it.
121 execute_simple_docunit
(du
)
123 # Need to try to compile it, then execute it
124 test_single_docunit
(du
)
133 for du
in docunits
do
134 toolcontext
.show_unit
(du
)
137 for du
in docunits
do
138 testsuite
.add du
.to_xml
142 # Executes multiples doc-units in a shared program.
143 # Used for docunits simple block of code (without modules, classes, functions etc.)
145 # In case of compilation error, the method fallbacks to `test_single_docunit` to
146 # * locate exactly the compilation problem in the problematic docunit.
147 # * permit the execution of the other docunits that may be correct.
148 fun test_simple_docunits
(dus
: Array[DocUnit])
150 if dus
.is_empty
then return
152 var file
= "{prefix}-0.nit"
154 var dir
= file
.dirname
155 if dir
!= "" then dir
.mkdir
157 f
= create_unitfile
(file
)
162 f
.write
("fun run_{i} do\n")
163 f
.write
("# {du.full_name}\n")
167 f
.write
("var a = args.first.to_i\n")
169 f
.write
("if a == {j} then run_{j}\n")
173 if toolcontext
.opt_noact
.value
then return
175 var res
= compile_unitfile
(file
)
179 # They will be executed independently
183 # Compilation was a success.
184 # Store what need to be executed for each one.
193 # Execute a docunit compiled by `test_single_docunit`
194 fun execute_simple_docunit
(du
: DocUnit)
196 var file
= du
.test_file
.as(not null)
197 var i
= du
.test_arg
.as(not null)
198 toolcontext
.info
("Execute doc-unit {du.full_name} in {file} {i}", 1)
199 var res2
= toolcontext
.safe_exec
("{file.to_program_name}.bin {i} >'{file}.out1' 2>&1 </dev/null")
202 var content
= "{file}.out1".to_path
.read_all
203 du
.raw_output
= content
206 du
.error
= "Runtime error in {file} with argument {i}"
207 toolcontext
.modelbuilder
.failed_entities
+= 1
211 # Executes a single doc-unit in its own program.
212 # Used for docunits larger than a single block of code (with modules, classes, functions etc.)
213 fun test_single_docunit
(du
: DocUnit)
216 var file
= "{prefix}-{cpt}.nit"
218 toolcontext
.info
("Execute doc-unit {du.full_name} in {file}", 1)
221 f
= create_unitfile
(file
)
225 if toolcontext
.opt_noact
.value
then return
227 var res
= compile_unitfile
(file
)
230 res2
= toolcontext
.safe_exec
("{file.to_program_name}.bin >'{file}.out1' 2>&1 </dev/null")
234 var content
= "{file}.out1".to_path
.read_all
235 du
.raw_output
= content
238 du
.error
= "Compilation error in {file}"
239 toolcontext
.modelbuilder
.failed_entities
+= 1
240 else if res2
!= 0 then
241 du
.error
= "Runtime error in {file}"
242 toolcontext
.modelbuilder
.failed_entities
+= 1
246 # Create and fill the header of a unit file `file`.
248 # A unit file is a Nit source file generated from one
249 # or more docunits that will be compiled and executed.
251 # The handled on the file is returned and must be completed and closed.
253 # `file` should be a valid filepath for a Nit source file.
254 private fun create_unitfile
(file
: String): Writer
256 var dir
= file
.dirname
257 if dir
!= "" then dir
.mkdir
259 f
= new FileWriter.open
(file
)
260 f
.write
("# GENERATED FILE\n")
261 f
.write
("# Docunits extracted from comments\n")
262 if mmodule
!= null then
263 f
.write
("import {mmodule.name}\n")
269 # Compile an unit file and return the compiler return code
271 # Can terminate the program if the compiler is not found
272 private fun compile_unitfile
(file
: String): Int
274 var nitc
= toolcontext
.find_nitc
275 var opts
= new Array[String]
276 if mmodule
!= null then
277 opts
.add
"-I {mmodule.filepath.dirname}"
279 var cmd
= "{nitc} --ignore-visibility --no-color '{file}' {opts.join(" ")} >'{file}.out1' 2>&1 </dev/null -o '{file}.bin'"
280 var res
= toolcontext
.safe_exec
(cmd
)
285 private class NitunitDecorator
288 var executor
: NitUnitExecutor
290 redef fun add_code
(v
, block
) do
291 var code
= block
.raw_content
292 var meta
= block
.meta
or else "nit"
293 # Do not try to test non-nit code.
294 if meta
!= "nit" then return
295 # Try to parse code blocks
296 var ast
= executor
.toolcontext
.parse_something
(code
)
298 var mdoc
= executor
.mdoc
302 if ast
isa TComment then return
304 # The location is computed according to the starts of the mdoc and the block
305 # Note, the following assumes that all the comments of the mdoc are correctly aligned.
306 var loc
= block
.block
.location
307 var line_offset
= loc
.line_start
+ mdoc
.location
.line_start
- 2
308 var column_offset
= loc
.column_start
+ mdoc
.location
.column_start
309 # Hack to handle precise location in blocks
310 # TODO remove when markdown is more reliable
311 if block
isa BlockFence then
312 # Skip the starting fence
315 # Account a standard 4 space indentation
319 # We want executable code
320 if not (ast
isa AModule or ast
isa ABlockExpr or ast
isa AExpr) then
323 # Get real location of the node (or error)
324 var location
= new Location(mdoc
.location
.file
,
325 l
.line_start
+ line_offset
,
326 l
.line_end
+ line_offset
,
327 l
.column_start
+ column_offset
,
328 l
.column_end
+ column_offset
)
329 if ast
isa AError then
330 message
= ast
.message
332 message
= "Error: Invalid Nit code."
337 du
.error_location
= location
339 executor
.toolcontext
.modelbuilder
.failed_entities
+= 1
343 # Create a first block
344 # Or create a new block for modules that are more than a main part
345 var last_docunit
= executor
.last_docunit
346 if last_docunit
== null or ast
isa AModule then
347 last_docunit
= new_docunit
348 executor
.last_docunit
= last_docunit
352 last_docunit
.block
+= code
354 # In order to retrieve precise positions,
355 # the real position of each line of the raw_content is stored.
356 # See `DocUnit::real_location`
357 line_offset
-= loc
.line_start
- 1
358 for i
in [loc
.line_start
..loc
.line_end
] do
359 last_docunit
.lines
.add i
+ line_offset
360 last_docunit
.columns
.add column_offset
364 # Return and register a new empty docunit
365 fun new_docunit
: DocUnit
367 var mdoc
= executor
.mdoc
371 var name
= executor
.xml_name
372 if executor
.docunits
.not_empty
and executor
.docunits
.last
.mdoc
== mdoc
then
373 next_number
= executor
.docunits
.last
.number
+ 1
374 name
+= "#" + next_number
.to_s
377 var res
= new DocUnit(mdoc
, next_number
, "", executor
.xml_classname
, name
)
378 executor
.docunits
.add res
379 executor
.toolcontext
.modelbuilder
.unit_entities
+= 1
384 # A unit-test extracted from some documentation.
386 # A docunit is extracted from the code-blocks of mdocs.
387 # Each mdoc can contains more than one docunit, and a single docunit can be made of more that a single code-block.
391 # The doc that contains self
394 # The numbering of self in mdoc (starting with 0)
397 # The generated Nit source file that contains the unit-test
399 # Note that a same generated file can be used for multiple tests.
400 # See `test_arg` that is used to distinguish them
401 var test_file
: nullable String = null
403 # The command-line argument to use when executing the test, if any.
404 var test_arg
: nullable Int = null
406 redef fun full_name
do
407 var mentity
= mdoc
.original_mentity
408 if mentity
!= null then
409 var res
= mentity
.full_name
415 return xml_classname
+ "." + xml_name
419 # The text of the code to execute.
421 # This is the verbatim content on one, or more, code-blocks from `mdoc`
424 # For each line in `block`, the associated line in the mdoc
426 # Is used to give precise locations
427 var lines
= new Array[Int]
429 # For each line in `block`, the associated column in the mdoc
431 # Is used to give precise locations
432 var columns
= new Array[Int]
434 # The location of the whole docunit.
436 # If `self` is made of multiple code-blocks, then the location
437 # starts at the first code-books and finish at the last one, thus includes anything between.
438 redef var location
is lazy
do
439 return new Location(mdoc
.location
.file
, lines
.first
, lines
.last
+1, columns
.first
+1, 0)
442 # Compute the real location of a node on the `ast` based on `mdoc.location`
444 # The result is basically: ast_location + markdown location of the piece + mdoc.location
446 # The fun is that a single docunit can be made of various pieces of code blocks.
447 fun real_location
(ast_location
: Location): Location
450 var res
= new Location(mdoc
.location
.file
, lines
[ast_location
.line_start-1
],
451 lines
[ast_location
.line_end-1
],
452 columns
[ast_location
.line_start-1
] + ast_location
.column_start
,
453 columns
[ast_location
.line_end-1
] + ast_location
.column_end
)
460 res
.open
("system-out").append
(block
)
464 redef var xml_classname
468 redef class ModelBuilder
469 # Total number analyzed `MEntity`
470 var total_entities
= 0
472 # The number of `MEntity` that have some documentation
475 # The total number of executed docunits
476 var unit_entities
= 0
478 # The number failed docunits
479 var failed_entities
= 0
481 # Extracts and executes all the docunits in the `mmodule`
482 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
483 fun test_markdown
(mmodule
: MModule): HTMLTag
485 var ts
= new HTMLTag("testsuite")
486 toolcontext
.info
("nitunit: doc-unit {mmodule}", 2)
488 var nmodule
= mmodule2node
(mmodule
)
489 if nmodule
== null then return ts
491 # usualy, only the original module must be imported in the unit test.
494 if g
!= null and g
.mpackage
.name
== "core" then
495 # except for a unit test in a module of `core`
496 # in this case, the whole `core` must be imported
497 o
= get_mmodule_by_name
(nmodule
, g
, g
.mpackage
.name
).as(not null)
500 ts
.attr
("package", mmodule
.full_name
)
502 var prefix
= toolcontext
.test_dir
503 prefix
= prefix
.join_path
(mmodule
.to_s
)
504 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, o
, ts
, "Docunits of module {mmodule.full_name}")
508 var nmoduledecl
= nmodule
.n_moduledecl
509 if nmoduledecl
== null then break label x
510 var ndoc
= nmoduledecl
.n_doc
511 if ndoc
== null then break label x
513 # NOTE: jenkins expects a '.' in the classname attr
514 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + mmodule
.full_name
+ ".<module>", "<module>")
516 for nclassdef
in nmodule
.n_classdefs
do
517 var mclassdef
= nclassdef
.mclassdef
518 if mclassdef
== null then continue
519 if nclassdef
isa AStdClassdef then
521 var ndoc
= nclassdef
.n_doc
524 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + mmodule
.full_name
+ "." + mclassdef
.mclass
.full_name
, "<class>")
527 for npropdef
in nclassdef
.n_propdefs
do
528 var mpropdef
= npropdef
.mpropdef
529 if mpropdef
== null then continue
531 var ndoc
= npropdef
.n_doc
534 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + mmodule
.full_name
+ "." + mclassdef
.mclass
.full_name
, mpropdef
.mproperty
.full_name
)
544 # Extracts and executes all the docunits in the readme of the `mgroup`
545 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
546 fun test_group
(mgroup
: MGroup): HTMLTag
548 var ts
= new HTMLTag("testsuite")
549 toolcontext
.info
("nitunit: doc-unit group {mgroup}", 2)
551 # usually, only the default module must be imported in the unit test.
552 var o
= mgroup
.default_mmodule
554 ts
.attr
("package", mgroup
.full_name
)
556 var prefix
= toolcontext
.test_dir
557 prefix
= prefix
.join_path
(mgroup
.to_s
)
558 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, o
, ts
, "Docunits of group {mgroup.full_name}")
561 var mdoc
= mgroup
.mdoc
562 if mdoc
== null then return ts
565 # NOTE: jenkins expects a '.' in the classname attr
566 d2m
.extract
(mdoc
, "nitunit." + mgroup
.full_name
, "<group>")
573 # Test a document object unrelated to a Nit entity
574 fun test_mdoc
(mdoc
: MDoc): HTMLTag
576 var ts
= new HTMLTag("testsuite")
577 var file
= mdoc
.location
.file
.filename
579 toolcontext
.info
("nitunit: doc-unit file {file}", 2)
581 ts
.attr
("package", file
)
583 var prefix
= toolcontext
.test_dir
/ "file"
584 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, null, ts
, "Docunits of file {file}")
589 # NOTE: jenkins expects a '.' in the classname attr
590 d2m
.extract
(mdoc
, "nitunit.<file>", file
)