7419c9f1402cadcb9a424713d9af9886705d2d56
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]
81 fun mark_done
(du
: DocUnit)
86 # Execute all the docunits
89 var simple_du
= new Array[DocUnit]
91 # Skip existing errors
92 if du
.error
!= null then
97 var ast
= toolcontext
.parse_something
(du
.block
)
101 test_single_docunit
(du
)
105 test_simple_docunits
(simple_du
)
107 for du
in docunits
do
111 for du
in docunits
do
112 testsuite
.add du
.to_xml
116 # Executes multiples doc-units in a shared program.
117 # Used for docunits simple block of code (without modules, classes, functions etc.)
119 # In case of compilation error, the method fallbacks to `test_single_docunit` to
120 # * locate exactly the compilation problem in the problematic docunit.
121 # * permit the execution of the other docunits that may be correct.
122 fun test_simple_docunits
(dus
: Array[DocUnit])
124 if dus
.is_empty
then return
126 var file
= "{prefix}-0.nit"
128 var dir
= file
.dirname
129 if dir
!= "" then dir
.mkdir
131 f
= create_unitfile
(file
)
136 f
.write
("fun run_{i} do\n")
137 f
.write
("# {du.full_name}\n")
141 f
.write
("var a = args.first.to_i\n")
143 f
.write
("if a == {j} then run_{j}\n")
147 if toolcontext
.opt_noact
.value
then return
149 var res
= compile_unitfile
(file
)
153 # Fall-back to individual modes:
155 test_single_docunit
(du
)
163 toolcontext
.info
("Execute doc-unit {du.full_name} in {file} {i}", 1)
164 var res2
= toolcontext
.safe_exec
("{file.to_program_name}.bin {i} >'{file}.out1' 2>&1 </dev/null")
167 var content
= "{file}.out1".to_path
.read_all
168 du
.raw_output
= content
171 du
.error
= "Runtime error in {file} with argument {i}"
172 toolcontext
.modelbuilder
.failed_entities
+= 1
178 # Executes a single doc-unit in its own program.
179 # Used for docunits larger than a single block of code (with modules, classes, functions etc.)
180 fun test_single_docunit
(du
: DocUnit)
183 var file
= "{prefix}-{cpt}.nit"
185 toolcontext
.info
("Execute doc-unit {du.full_name} in {file}", 1)
188 f
= create_unitfile
(file
)
192 if toolcontext
.opt_noact
.value
then return
194 var res
= compile_unitfile
(file
)
197 res2
= toolcontext
.safe_exec
("{file.to_program_name}.bin >'{file}.out1' 2>&1 </dev/null")
201 var content
= "{file}.out1".to_path
.read_all
202 du
.raw_output
= content
205 du
.error
= "Compilation error in {file}"
206 toolcontext
.modelbuilder
.failed_entities
+= 1
207 else if res2
!= 0 then
208 du
.error
= "Runtime error in {file}"
209 toolcontext
.modelbuilder
.failed_entities
+= 1
214 # Create and fill the header of a unit file `file`.
216 # A unit file is a Nit source file generated from one
217 # or more docunits that will be compiled and executed.
219 # The handled on the file is returned and must be completed and closed.
221 # `file` should be a valid filepath for a Nit source file.
222 private fun create_unitfile
(file
: String): Writer
224 var dir
= file
.dirname
225 if dir
!= "" then dir
.mkdir
227 f
= new FileWriter.open
(file
)
228 f
.write
("# GENERATED FILE\n")
229 f
.write
("# Docunits extracted from comments\n")
230 if mmodule
!= null then
231 f
.write
("import {mmodule.name}\n")
237 # Compile an unit file and return the compiler return code
239 # Can terminate the program if the compiler is not found
240 private fun compile_unitfile
(file
: String): Int
242 var nitc
= toolcontext
.find_nitc
243 var opts
= new Array[String]
244 if mmodule
!= null then
245 opts
.add
"-I {mmodule.filepath.dirname}"
247 var cmd
= "{nitc} --ignore-visibility --no-color '{file}' {opts.join(" ")} >'{file}.out1' 2>&1 </dev/null -o '{file}.bin'"
248 var res
= toolcontext
.safe_exec
(cmd
)
253 private class NitunitDecorator
256 var executor
: NitUnitExecutor
258 redef fun add_code
(v
, block
) do
259 var code
= block
.raw_content
260 var meta
= block
.meta
or else "nit"
261 # Do not try to test non-nit code.
262 if meta
!= "nit" then return
263 # Try to parse code blocks
264 var ast
= executor
.toolcontext
.parse_something
(code
)
266 var mdoc
= executor
.mdoc
270 if ast
isa TComment then return
272 # The location is computed according to the starts of the mdoc and the block
273 # Note, the following assumes that all the comments of the mdoc are correctly aligned.
274 var loc
= block
.block
.location
275 var line_offset
= loc
.line_start
+ mdoc
.location
.line_start
- 2
276 var column_offset
= loc
.column_start
+ mdoc
.location
.column_start
277 # Hack to handle precise location in blocks
278 # TODO remove when markdown is more reliable
279 if block
isa BlockFence then
280 # Skip the starting fence
283 # Account a standard 4 space indentation
287 # We want executable code
288 if not (ast
isa AModule or ast
isa ABlockExpr or ast
isa AExpr) then
291 # Get real location of the node (or error)
292 var location
= new Location(mdoc
.location
.file
,
293 l
.line_start
+ line_offset
,
294 l
.line_end
+ line_offset
,
295 l
.column_start
+ column_offset
,
296 l
.column_end
+ column_offset
)
297 if ast
isa AError then
298 message
= ast
.message
300 message
= "Error: Invalid Nit code."
305 du
.error_location
= location
307 executor
.toolcontext
.modelbuilder
.failed_entities
+= 1
311 # Create a first block
312 # Or create a new block for modules that are more than a main part
313 var last_docunit
= executor
.last_docunit
314 if last_docunit
== null or ast
isa AModule then
315 last_docunit
= new_docunit
316 executor
.last_docunit
= last_docunit
320 last_docunit
.block
+= code
322 # In order to retrieve precise positions,
323 # the real position of each line of the raw_content is stored.
324 # See `DocUnit::real_location`
325 line_offset
-= loc
.line_start
- 1
326 for i
in [loc
.line_start
..loc
.line_end
] do
327 last_docunit
.lines
.add i
+ line_offset
328 last_docunit
.columns
.add column_offset
332 # Return and register a new empty docunit
333 fun new_docunit
: DocUnit
335 var mdoc
= executor
.mdoc
339 var name
= executor
.xml_name
340 if executor
.docunits
.not_empty
and executor
.docunits
.last
.mdoc
== mdoc
then
341 next_number
= executor
.docunits
.last
.number
+ 1
342 name
+= "+" + next_number
.to_s
345 var res
= new DocUnit(mdoc
, next_number
, "", executor
.xml_classname
, name
)
346 executor
.docunits
.add res
347 executor
.toolcontext
.modelbuilder
.unit_entities
+= 1
352 # A unit-test extracted from some documentation.
354 # A docunit is extracted from the code-blocks of mdocs.
355 # Each mdoc can contains more than one docunit, and a single docunit can be made of more that a single code-block.
359 # The doc that contains self
362 # The numbering of self in mdoc (starting with 0)
365 redef fun full_name
do
366 var mentity
= mdoc
.original_mentity
367 if mentity
!= null then
368 return mentity
.full_name
370 return xml_classname
+ "." + xml_name
374 # The text of the code to execute.
376 # This is the verbatim content on one, or more, code-blocks from `mdoc`
379 # For each line in `block`, the associated line in the mdoc
381 # Is used to give precise locations
382 var lines
= new Array[Int]
384 # For each line in `block`, the associated column in the mdoc
386 # Is used to give precise locations
387 var columns
= new Array[Int]
389 # The location of the whole docunit.
391 # If `self` is made of multiple code-blocks, then the location
392 # starts at the first code-books and finish at the last one, thus includes anything between.
393 redef var location
is lazy
do
394 return new Location(mdoc
.location
.file
, lines
.first
, lines
.last
+1, columns
.first
+1, 0)
397 # Compute the real location of a node on the `ast` based on `mdoc.location`
399 # The result is basically: ast_location + markdown location of the piece + mdoc.location
401 # The fun is that a single docunit can be made of various pieces of code blocks.
402 fun real_location
(ast_location
: Location): Location
405 var res
= new Location(mdoc
.location
.file
, lines
[ast_location
.line_start-1
],
406 lines
[ast_location
.line_end-1
],
407 columns
[ast_location
.line_start-1
] + ast_location
.column_start
,
408 columns
[ast_location
.line_end-1
] + ast_location
.column_end
)
415 res
.open
("system-out").append
(block
)
419 redef var xml_classname
423 redef class ModelBuilder
424 # Total number analyzed `MEntity`
425 var total_entities
= 0
427 # The number of `MEntity` that have some documentation
430 # The total number of executed docunits
431 var unit_entities
= 0
433 # The number failed docunits
434 var failed_entities
= 0
436 # Extracts and executes all the docunits in the `mmodule`
437 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
438 fun test_markdown
(mmodule
: MModule): HTMLTag
440 var ts
= new HTMLTag("testsuite")
441 toolcontext
.info
("nitunit: doc-unit {mmodule}", 2)
443 var nmodule
= mmodule2node
(mmodule
)
444 if nmodule
== null then return ts
446 # usualy, only the original module must be imported in the unit test.
449 if g
!= null and g
.mpackage
.name
== "core" then
450 # except for a unit test in a module of `core`
451 # in this case, the whole `core` must be imported
452 o
= get_mmodule_by_name
(nmodule
, g
, g
.mpackage
.name
).as(not null)
455 ts
.attr
("package", mmodule
.full_name
)
457 var prefix
= toolcontext
.test_dir
458 prefix
= prefix
.join_path
(mmodule
.to_s
)
459 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, o
, ts
, "Docunits of module {mmodule.full_name}")
463 var nmoduledecl
= nmodule
.n_moduledecl
464 if nmoduledecl
== null then break label x
465 var ndoc
= nmoduledecl
.n_doc
466 if ndoc
== null then break label x
468 # NOTE: jenkins expects a '.' in the classname attr
469 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + mmodule
.full_name
+ ".<module>", "<module>")
471 for nclassdef
in nmodule
.n_classdefs
do
472 var mclassdef
= nclassdef
.mclassdef
473 if mclassdef
== null then continue
474 if nclassdef
isa AStdClassdef then
476 var ndoc
= nclassdef
.n_doc
479 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + mmodule
.full_name
+ "." + mclassdef
.mclass
.full_name
, "<class>")
482 for npropdef
in nclassdef
.n_propdefs
do
483 var mpropdef
= npropdef
.mpropdef
484 if mpropdef
== null then continue
486 var ndoc
= npropdef
.n_doc
489 d2m
.extract
(ndoc
.to_mdoc
, "nitunit." + mmodule
.full_name
+ "." + mclassdef
.mclass
.full_name
, mpropdef
.mproperty
.full_name
)
499 # Extracts and executes all the docunits in the readme of the `mgroup`
500 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
501 fun test_group
(mgroup
: MGroup): HTMLTag
503 var ts
= new HTMLTag("testsuite")
504 toolcontext
.info
("nitunit: doc-unit group {mgroup}", 2)
506 # usually, only the default module must be imported in the unit test.
507 var o
= mgroup
.default_mmodule
509 ts
.attr
("package", mgroup
.full_name
)
511 var prefix
= toolcontext
.test_dir
512 prefix
= prefix
.join_path
(mgroup
.to_s
)
513 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, o
, ts
, "Docunits of group {mgroup.full_name}")
516 var mdoc
= mgroup
.mdoc
517 if mdoc
== null then return ts
520 # NOTE: jenkins expects a '.' in the classname attr
521 d2m
.extract
(mdoc
, "nitunit." + mgroup
.full_name
, "<group>")
528 # Test a document object unrelated to a Nit entity
529 fun test_mdoc
(mdoc
: MDoc): HTMLTag
531 var ts
= new HTMLTag("testsuite")
532 var file
= mdoc
.location
.to_s
534 toolcontext
.info
("nitunit: doc-unit file {file}", 2)
536 ts
.attr
("package", file
)
538 var prefix
= toolcontext
.test_dir
/ "file"
539 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, null, ts
, "Docunits of file {file}")
544 # NOTE: jenkins expects a '.' in the classname attr
545 d2m
.extract
(mdoc
, "nitunit.<file>", file
)