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
.is_compiled
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.
189 du
.is_compiled
= true
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 clock
= new Clock
200 var res2
= toolcontext
.safe_exec
("{file.to_program_name}.bin {i} >'{file}.out1' 2>&1 </dev/null")
201 if not toolcontext
.opt_no_time
.value
then du
.real_time
= clock
.total
204 var content
= "{file}.out1".to_path
.read_all
205 du
.raw_output
= content
208 du
.error
= "Runtime error in {file} with argument {i}"
209 toolcontext
.modelbuilder
.failed_entities
+= 1
213 # Executes a single doc-unit in its own program.
214 # Used for docunits larger than a single block of code (with modules, classes, functions etc.)
215 fun test_single_docunit
(du
: DocUnit)
218 var file
= "{prefix}-{cpt}.nit"
220 toolcontext
.info
("Execute doc-unit {du.full_name} in {file}", 1)
223 f
= create_unitfile
(file
)
227 if toolcontext
.opt_noact
.value
then return
229 var res
= compile_unitfile
(file
)
232 var clock
= new Clock
233 res2
= toolcontext
.safe_exec
("{file.to_program_name}.bin >'{file}.out1' 2>&1 </dev/null")
234 if not toolcontext
.opt_no_time
.value
then du
.real_time
= clock
.total
238 var content
= "{file}.out1".to_path
.read_all
239 du
.raw_output
= content
242 du
.error
= "Compilation error in {file}"
243 toolcontext
.modelbuilder
.failed_entities
+= 1
244 else if res2
!= 0 then
245 du
.error
= "Runtime error in {file}"
246 toolcontext
.modelbuilder
.failed_entities
+= 1
250 # Create and fill the header of a unit file `file`.
252 # A unit file is a Nit source file generated from one
253 # or more docunits that will be compiled and executed.
255 # The handled on the file is returned and must be completed and closed.
257 # `file` should be a valid filepath for a Nit source file.
258 private fun create_unitfile
(file
: String): Writer
260 var dir
= file
.dirname
261 if dir
!= "" then dir
.mkdir
263 f
= new FileWriter.open
(file
)
264 f
.write
("# GENERATED FILE\n")
265 f
.write
("# Docunits extracted from comments\n")
266 if mmodule
!= null then
267 f
.write
("intrude import {mmodule.name}\n")
273 # Compile an unit file and return the compiler return code
275 # Can terminate the program if the compiler is not found
276 private fun compile_unitfile
(file
: String): Int
278 var nitc
= toolcontext
.find_nitc
279 var opts
= new Array[String]
280 if mmodule
!= null then
281 opts
.add
"-I {mmodule.filepath.dirname}"
283 var cmd
= "{nitc} --ignore-visibility --no-color -q '{file}' {opts.join(" ")} >'{file}.out1' 2>&1 </dev/null -o '{file}.bin'"
284 var res
= toolcontext
.safe_exec
(cmd
)
289 private class NitunitDecorator
292 var executor
: NitUnitExecutor
294 redef fun add_code
(v
, block
) do
295 var code
= block
.raw_content
296 var meta
= block
.meta
or else "nit"
297 # Do not try to test non-nit code.
298 if meta
!= "nit" then return
299 # Try to parse code blocks
300 var ast
= executor
.toolcontext
.parse_something
(code
)
302 var mdoc
= executor
.mdoc
306 if ast
isa TComment then return
308 # The location is computed according to the starts of the mdoc and the block
309 # Note, the following assumes that all the comments of the mdoc are correctly aligned.
310 var loc
= block
.block
.location
311 var line_offset
= loc
.line_start
+ mdoc
.location
.line_start
- 2
312 var column_offset
= loc
.column_start
+ mdoc
.location
.column_start
313 # Hack to handle precise location in blocks
314 # TODO remove when markdown is more reliable
315 if block
isa BlockFence then
316 # Skip the starting fence
319 # Account a standard 4 space indentation
323 # We want executable code
324 if not (ast
isa AModule or ast
isa ABlockExpr or ast
isa AExpr) then
327 # Get real location of the node (or error)
328 var location
= new Location(mdoc
.location
.file
,
329 l
.line_start
+ line_offset
,
330 l
.line_end
+ line_offset
,
331 l
.column_start
+ column_offset
,
332 l
.column_end
+ column_offset
)
333 if ast
isa AError then
334 message
= ast
.message
336 message
= "Error: Invalid Nit code."
341 du
.error_location
= location
343 executor
.toolcontext
.modelbuilder
.failed_entities
+= 1
347 # Create a first block
348 # Or create a new block for modules that are more than a main part
349 var last_docunit
= executor
.last_docunit
350 if last_docunit
== null or ast
isa AModule then
351 last_docunit
= new_docunit
352 executor
.last_docunit
= last_docunit
356 last_docunit
.block
+= code
358 # In order to retrieve precise positions,
359 # the real position of each line of the raw_content is stored.
360 # See `DocUnit::real_location`
361 line_offset
-= loc
.line_start
- 1
362 for i
in [loc
.line_start
..loc
.line_end
] do
363 last_docunit
.lines
.add i
+ line_offset
364 last_docunit
.columns
.add column_offset
368 # Return and register a new empty docunit
369 fun new_docunit
: DocUnit
371 var mdoc
= executor
.mdoc
375 var name
= executor
.xml_name
376 if executor
.docunits
.not_empty
and executor
.docunits
.last
.mdoc
== mdoc
then
377 next_number
= executor
.docunits
.last
.number
+ 1
378 name
+= "#" + next_number
.to_s
381 var res
= new DocUnit(mdoc
, next_number
, "", executor
.xml_classname
, name
)
382 executor
.docunits
.add res
383 executor
.toolcontext
.modelbuilder
.unit_entities
+= 1
388 # A unit-test extracted from some documentation.
390 # A docunit is extracted from the code-blocks of mdocs.
391 # Each mdoc can contains more than one docunit, and a single docunit can be made of more that a single code-block.
395 # The doc that contains self
398 # The numbering of self in mdoc (starting with 0)
401 # The generated Nit source file that contains the unit-test
403 # Note that a same generated file can be used for multiple tests.
404 # See `test_arg` that is used to distinguish them
405 var test_file
: nullable String = null
407 # Was `test_file` successfully compiled?
408 var is_compiled
= false
410 # The command-line argument to use when executing the test, if any.
411 var test_arg
: nullable Int = null
413 redef fun full_name
do
414 var mentity
= mdoc
.original_mentity
415 if mentity
!= null then
416 var res
= mentity
.full_name
422 return xml_classname
+ "." + xml_name
426 # The text of the code to execute.
428 # This is the verbatim content on one, or more, code-blocks from `mdoc`
431 # For each line in `block`, the associated line in the mdoc
433 # Is used to give precise locations
434 var lines
= new Array[Int]
436 # For each line in `block`, the associated column in the mdoc
438 # Is used to give precise locations
439 var columns
= new Array[Int]
441 # The location of the whole docunit.
443 # If `self` is made of multiple code-blocks, then the location
444 # starts at the first code-books and finish at the last one, thus includes anything between.
445 redef var location
is lazy
do
446 return new Location(mdoc
.location
.file
, lines
.first
, lines
.last
+1, columns
.first
+1, 0)
449 # Compute the real location of a node on the `ast` based on `mdoc.location`
451 # The result is basically: ast_location + markdown location of the piece + mdoc.location
453 # The fun is that a single docunit can be made of various pieces of code blocks.
454 fun real_location
(ast_location
: Location): Location
457 var res
= new Location(mdoc
.location
.file
, lines
[ast_location
.line_start-1
],
458 lines
[ast_location
.line_end-1
],
459 columns
[ast_location
.line_start-1
] + ast_location
.column_start
,
460 columns
[ast_location
.line_end-1
] + ast_location
.column_end
)
467 res
.open
("system-out").append
(block
)
471 redef var xml_classname
475 redef class ModelBuilder
476 # Total number analyzed `MEntity`
477 var total_entities
= 0
479 # The number of `MEntity` that have some documentation
482 # The total number of executed docunits
483 var unit_entities
= 0
485 # The number failed docunits
486 var failed_entities
= 0
488 # Extracts and executes all the docunits in the `mmodule`
489 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
490 fun test_markdown
(mmodule
: MModule): HTMLTag
492 var ts
= new HTMLTag("testsuite")
493 toolcontext
.info
("nitunit: doc-unit {mmodule}", 2)
495 var nmodule
= mmodule2node
(mmodule
)
496 if nmodule
== null then return ts
498 # usualy, only the original module must be imported in the unit test.
501 if g
!= null and g
.mpackage
.name
== "core" then
502 # except for a unit test in a module of `core`
503 # in this case, the whole `core` must be imported
504 o
= get_mmodule_by_name
(nmodule
, g
, g
.mpackage
.name
).as(not null)
507 ts
.attr
("package", mmodule
.full_name
)
509 var prefix
= toolcontext
.test_dir
510 prefix
= prefix
.join_path
(mmodule
.to_s
)
511 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, o
, ts
, "Docunits of module {mmodule.full_name}")
515 var nmoduledecl
= nmodule
.n_moduledecl
516 if nmoduledecl
== null then break label x
517 var ndoc
= nmoduledecl
.n_doc
518 if ndoc
== null then break label x
520 # NOTE: jenkins expects a '.' in the classname attr
521 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + mmodule
.full_name
+ ".<module>", "<module>")
523 for nclassdef
in nmodule
.n_classdefs
do
524 var mclassdef
= nclassdef
.mclassdef
525 if mclassdef
== null then continue
526 if nclassdef
isa AStdClassdef then
528 var ndoc
= nclassdef
.n_doc
531 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + mclassdef
.full_name
.replace
("$", "."), "<class>")
534 for npropdef
in nclassdef
.n_propdefs
do
535 var mpropdef
= npropdef
.mpropdef
536 if mpropdef
== null then continue
538 var ndoc
= npropdef
.n_doc
541 var a
= mpropdef
.full_name
.split
("$")
542 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + a
[0] + "." + a
[1], a
[2])
552 # Extracts and executes all the docunits in the readme of the `mgroup`
553 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
554 fun test_group
(mgroup
: MGroup): HTMLTag
556 var ts
= new HTMLTag("testsuite")
557 toolcontext
.info
("nitunit: doc-unit group {mgroup}", 2)
559 # usually, only the default module must be imported in the unit test.
560 var o
= mgroup
.default_mmodule
562 ts
.attr
("package", mgroup
.full_name
)
564 var prefix
= toolcontext
.test_dir
565 prefix
= prefix
.join_path
(mgroup
.to_s
)
566 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, o
, ts
, "Docunits of group {mgroup.full_name}")
569 var mdoc
= mgroup
.mdoc
570 if mdoc
== null then return ts
573 # NOTE: jenkins expects a '.' in the classname attr
574 d2m
.extract
(mdoc
, "nitunit." + mgroup
.mpackage
.name
+ "." + mgroup
.name
+ ".<group>", "<group>")
581 # Test a document object unrelated to a Nit entity
582 fun test_mdoc
(mdoc
: MDoc): HTMLTag
584 var ts
= new HTMLTag("testsuite")
585 var file
= mdoc
.location
.file
.filename
587 toolcontext
.info
("nitunit: doc-unit file {file}", 2)
589 ts
.attr
("package", file
)
591 var prefix
= toolcontext
.test_dir
/ "file"
592 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, null, ts
, "Docunits of file {file}")
597 # NOTE: jenkins expects a '.' in the classname attr
598 d2m
.extract
(mdoc
, "nitunit.<file>", file
)