30a0eb4549fee05a3b4c64a8291cb7d568974a47
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
117 # Try to mass compile all the simple du as a single nit module
118 compile_simple_docunits
(simple_du
)
119 # Now test them in order
120 for du
in docunits
do
121 if du
.error
!= null then
122 # Nothing to execute. Conclude
123 else if du
.is_compiled
then
124 # Already compiled. Execute it.
125 execute_simple_docunit
(du
)
127 # Need to try to compile it, then execute it
128 test_single_docunit
(du
)
137 for du
in docunits
do
138 testsuite
.add du
.to_xml
142 # Compiles multiples doc-units in a shared program.
143 # Used for docunits simple block of code (without modules, classes, functions etc.)
145 # In case of success, the docunits are compiled and the caller can call `execute_simple_docunit`.
147 # In case of compilation error, the docunits are let uncompiled.
148 # The caller should fallbacks to `test_single_docunit` to
149 # * locate exactly the compilation problem in the problematic docunit.
150 # * permit the execution of the other docunits that may be correct.
151 fun compile_simple_docunits
(dus
: Array[DocUnit])
153 if dus
.is_empty
then return
155 var file
= "{prefix}-0.nit"
157 toolcontext
.info
("Compile {dus.length} simple(s) doc-unit(s) in {file}", 1)
159 var dir
= file
.dirname
160 if dir
!= "" then dir
.mkdir
162 f
= create_unitfile
(file
)
166 f
.write
("fun run_{i} do\n")
167 f
.write
("# {du.full_name}\n")
171 f
.write
("var a = args.first.to_i\n")
173 f
.write
("if a == {j} then run_{j}\n")
177 if toolcontext
.opt_noact
.value
then return
179 var res
= compile_unitfile
(file
)
183 # They should be generated and compiled independently
187 # Compilation was a success.
188 # Store what need to be executed for each one.
194 du
.is_compiled
= true
198 # Execute a docunit compiled by `test_single_docunit`
199 fun execute_simple_docunit
(du
: DocUnit)
201 var file
= du
.test_file
.as(not null)
202 var i
= du
.test_arg
.as(not null)
203 toolcontext
.info
("Execute doc-unit {du.full_name} in {file} {i}", 1)
204 var clock
= new Clock
205 var res2
= toolcontext
.safe_exec
("{file.to_program_name}.bin {i} >'{file}.out1' 2>&1 </dev/null")
206 if not toolcontext
.opt_no_time
.value
then du
.real_time
= clock
.total
209 var content
= "{file}.out1".to_path
.read_all
210 du
.raw_output
= content
213 du
.error
= "Runtime error in {file} with argument {i}"
214 toolcontext
.modelbuilder
.failed_entities
+= 1
218 # Produce a single unit file for the docunit `du`.
219 fun generate_single_docunit
(du
: DocUnit): String
222 var file
= "{prefix}-{cpt}.nit"
225 f
= create_unitfile
(file
)
233 # Executes a single doc-unit in its own program.
234 # Used for docunits larger than a single block of code (with modules, classes, functions etc.)
235 fun test_single_docunit
(du
: DocUnit)
237 var file
= generate_single_docunit
(du
)
239 toolcontext
.info
("Compile doc-unit {du.full_name} in {file}", 1)
241 if toolcontext
.opt_noact
.value
then return
243 var res
= compile_unitfile
(file
)
246 var clock
= new Clock
247 res2
= toolcontext
.safe_exec
("{file.to_program_name}.bin >'{file}.out1' 2>&1 </dev/null")
248 if not toolcontext
.opt_no_time
.value
then du
.real_time
= clock
.total
252 var content
= "{file}.out1".to_path
.read_all
253 du
.raw_output
= content
256 du
.error
= "Compilation error in {file}"
257 toolcontext
.modelbuilder
.failed_entities
+= 1
258 else if res2
!= 0 then
259 du
.error
= "Runtime error in {file}"
260 toolcontext
.modelbuilder
.failed_entities
+= 1
264 # Create and fill the header of a unit file `file`.
266 # A unit file is a Nit source file generated from one
267 # or more docunits that will be compiled and executed.
269 # The handled on the file is returned and must be completed and closed.
271 # `file` should be a valid filepath for a Nit source file.
272 private fun create_unitfile
(file
: String): Writer
274 var dir
= file
.dirname
275 if dir
!= "" then dir
.mkdir
277 f
= new FileWriter.open
(file
)
278 f
.write
("# GENERATED FILE\n")
279 f
.write
("# Docunits extracted from comments\n")
280 if mmodule
!= null then
281 f
.write
("intrude import {mmodule.name}\n")
287 # Compile an unit file and return the compiler return code
289 # Can terminate the program if the compiler is not found
290 private fun compile_unitfile
(file
: String): Int
292 var nitc
= toolcontext
.find_nitc
293 var opts
= new Array[String]
294 if mmodule
!= null then
295 opts
.add
"-I {mmodule.filepath.dirname}"
297 var cmd
= "{nitc} --ignore-visibility --no-color -q '{file}' {opts.join(" ")} >'{file}.out1' 2>&1 </dev/null -o '{file}.bin'"
298 var res
= toolcontext
.safe_exec
(cmd
)
303 private class NitunitDecorator
306 var executor
: NitUnitExecutor
308 redef fun add_code
(v
, block
) do
309 var code
= block
.raw_content
310 var meta
= block
.meta
or else "nit"
311 # Do not try to test non-nit code.
312 if meta
!= "nit" then return
313 # Try to parse code blocks
314 var ast
= executor
.toolcontext
.parse_something
(code
)
316 var mdoc
= executor
.mdoc
320 if ast
isa TComment then return
322 # The location is computed according to the starts of the mdoc and the block
323 # Note, the following assumes that all the comments of the mdoc are correctly aligned.
324 var loc
= block
.block
.location
325 var line_offset
= loc
.line_start
+ mdoc
.location
.line_start
- 2
326 var column_offset
= loc
.column_start
+ mdoc
.location
.column_start
327 # Hack to handle precise location in blocks
328 # TODO remove when markdown is more reliable
329 if block
isa BlockFence then
330 # Skip the starting fence
333 # Account a standard 4 space indentation
337 # We want executable code
338 if not (ast
isa AModule or ast
isa ABlockExpr or ast
isa AExpr) then
341 # Get real location of the node (or error)
342 var location
= new Location(mdoc
.location
.file
,
343 l
.line_start
+ line_offset
,
344 l
.line_end
+ line_offset
,
345 l
.column_start
+ column_offset
,
346 l
.column_end
+ column_offset
)
347 if ast
isa AError then
348 message
= ast
.message
350 message
= "Error: Invalid Nit code."
355 du
.error_location
= location
357 executor
.toolcontext
.modelbuilder
.failed_entities
+= 1
361 # Create a first block
362 # Or create a new block for modules that are more than a main part
363 var last_docunit
= executor
.last_docunit
364 if last_docunit
== null or ast
isa AModule then
365 last_docunit
= new_docunit
366 executor
.last_docunit
= last_docunit
370 last_docunit
.block
+= code
372 # In order to retrieve precise positions,
373 # the real position of each line of the raw_content is stored.
374 # See `DocUnit::real_location`
375 line_offset
-= loc
.line_start
- 1
376 for i
in [loc
.line_start
..loc
.line_end
] do
377 last_docunit
.lines
.add i
+ line_offset
378 last_docunit
.columns
.add column_offset
382 # Return and register a new empty docunit
383 fun new_docunit
: DocUnit
385 var mdoc
= executor
.mdoc
389 var name
= executor
.xml_name
390 if executor
.docunits
.not_empty
and executor
.docunits
.last
.mdoc
== mdoc
then
391 next_number
= executor
.docunits
.last
.number
+ 1
392 name
+= "#" + next_number
.to_s
395 var res
= new DocUnit(mdoc
, next_number
, "", executor
.xml_classname
, name
)
396 executor
.docunits
.add res
397 executor
.toolcontext
.modelbuilder
.unit_entities
+= 1
402 # A unit-test extracted from some documentation.
404 # A docunit is extracted from the code-blocks of mdocs.
405 # Each mdoc can contains more than one docunit, and a single docunit can be made of more that a single code-block.
409 # The doc that contains self
412 # The numbering of self in mdoc (starting with 0)
415 # The generated Nit source file that contains the unit-test
417 # Note that a same generated file can be used for multiple tests.
418 # See `test_arg` that is used to distinguish them
419 var test_file
: nullable String = null
421 # Was `test_file` successfully compiled?
422 var is_compiled
= false
424 # The command-line argument to use when executing the test, if any.
425 var test_arg
: nullable Int = null
427 redef fun full_name
do
428 var mentity
= mdoc
.original_mentity
429 if mentity
!= null then
430 var res
= mentity
.full_name
436 return xml_classname
+ "." + xml_name
440 # The text of the code to execute.
442 # This is the verbatim content on one, or more, code-blocks from `mdoc`
445 # For each line in `block`, the associated line in the mdoc
447 # Is used to give precise locations
448 var lines
= new Array[Int]
450 # For each line in `block`, the associated column in the mdoc
452 # Is used to give precise locations
453 var columns
= new Array[Int]
455 # The location of the whole docunit.
457 # If `self` is made of multiple code-blocks, then the location
458 # starts at the first code-books and finish at the last one, thus includes anything between.
459 redef var location
is lazy
do
460 return new Location(mdoc
.location
.file
, lines
.first
, lines
.last
+1, columns
.first
+1, 0)
463 # Compute the real location of a node on the `ast` based on `mdoc.location`
465 # The result is basically: ast_location + markdown location of the piece + mdoc.location
467 # The fun is that a single docunit can be made of various pieces of code blocks.
468 fun real_location
(ast_location
: Location): Location
471 var res
= new Location(mdoc
.location
.file
, lines
[ast_location
.line_start-1
],
472 lines
[ast_location
.line_end-1
],
473 columns
[ast_location
.line_start-1
] + ast_location
.column_start
,
474 columns
[ast_location
.line_end-1
] + ast_location
.column_end
)
481 res
.open
("system-out").append
(block
)
485 redef var xml_classname
489 redef class ModelBuilder
490 # Total number analyzed `MEntity`
491 var total_entities
= 0
493 # The number of `MEntity` that have some documentation
496 # The total number of executed docunits
497 var unit_entities
= 0
499 # The number failed docunits
500 var failed_entities
= 0
502 # Extracts and executes all the docunits in the `mmodule`
503 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
504 fun test_markdown
(mmodule
: MModule): HTMLTag
506 var ts
= new HTMLTag("testsuite")
507 toolcontext
.info
("nitunit: doc-unit {mmodule}", 2)
509 var nmodule
= mmodule2node
(mmodule
)
510 if nmodule
== null then return ts
512 # usualy, only the original module must be imported in the unit test.
515 if g
!= null and g
.mpackage
.name
== "core" then
516 # except for a unit test in a module of `core`
517 # in this case, the whole `core` must be imported
518 o
= get_mmodule_by_name
(nmodule
, g
, g
.mpackage
.name
).as(not null)
521 ts
.attr
("package", mmodule
.full_name
)
523 var prefix
= toolcontext
.test_dir
524 prefix
= prefix
.join_path
(mmodule
.to_s
)
525 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, o
, ts
, "Docunits of module {mmodule.full_name}")
529 var nmoduledecl
= nmodule
.n_moduledecl
530 if nmoduledecl
== null then break label x
531 var ndoc
= nmoduledecl
.n_doc
532 if ndoc
== null then break label x
534 # NOTE: jenkins expects a '.' in the classname attr
535 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + mmodule
.full_name
+ ".<module>", "<module>")
537 for nclassdef
in nmodule
.n_classdefs
do
538 var mclassdef
= nclassdef
.mclassdef
539 if mclassdef
== null then continue
540 if nclassdef
isa AStdClassdef then
542 var ndoc
= nclassdef
.n_doc
545 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + mclassdef
.full_name
.replace
("$", "."), "<class>")
548 for npropdef
in nclassdef
.n_propdefs
do
549 var mpropdef
= npropdef
.mpropdef
550 if mpropdef
== null then continue
552 var ndoc
= npropdef
.n_doc
555 var a
= mpropdef
.full_name
.split
("$")
556 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + a
[0] + "." + a
[1], a
[2])
566 # Extracts and executes all the docunits in the readme of the `mgroup`
567 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
568 fun test_group
(mgroup
: MGroup): HTMLTag
570 var ts
= new HTMLTag("testsuite")
571 toolcontext
.info
("nitunit: doc-unit group {mgroup}", 2)
573 # usually, only the default module must be imported in the unit test.
574 var o
= mgroup
.default_mmodule
576 ts
.attr
("package", mgroup
.full_name
)
578 var prefix
= toolcontext
.test_dir
579 prefix
= prefix
.join_path
(mgroup
.to_s
)
580 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, o
, ts
, "Docunits of group {mgroup.full_name}")
583 var mdoc
= mgroup
.mdoc
584 if mdoc
== null then return ts
587 # NOTE: jenkins expects a '.' in the classname attr
588 d2m
.extract
(mdoc
, "nitunit." + mgroup
.mpackage
.name
+ "." + mgroup
.name
+ ".<group>", "<group>")
595 # Test a document object unrelated to a Nit entity
596 fun test_mdoc
(mdoc
: MDoc): HTMLTag
598 var ts
= new HTMLTag("testsuite")
599 var file
= mdoc
.location
.file
.filename
601 toolcontext
.info
("nitunit: doc-unit file {file}", 2)
603 ts
.attr
("package", file
)
605 var prefix
= toolcontext
.test_dir
/ "file"
606 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, null, ts
, "Docunits of file {file}")
611 # NOTE: jenkins expects a '.' in the classname attr
612 d2m
.extract
(mdoc
, "nitunit.<file>", file
)