cadf871c30da2f02d402072795e00c1fc47ba961
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 current test-case xml element
40 var tc
: HTMLTag is noautoinit
42 # All failures from a same `ADoc`
43 var failures
= new Array[String]
45 # Markdown processor used to parse markdown comments and extract code.
46 var mdproc
= new MarkdownProcessor
49 mdproc
.emitter
.decorator
= new NitunitDecorator(self)
52 # The associated documentation object
53 var mdoc
: nullable MDoc = null
55 # used to generate distinct names
58 # The last docunit extracted from a mdoc.
60 # Is used because a new code-block might just be added to it.
61 var last_docunit
: nullable DocUnit = null
63 # The entry point for a new `ndoc` node
64 # Fill `docunits` with new discovered unit of tests.
66 # `tc` (testcase) is the pre-filled XML node
67 fun extract
(mdoc
: MDoc, tc
: HTMLTag)
75 # Populate `blocks` from the markdown decorator
76 mdproc
.process
(mdoc
.content
.join
("\n"))
78 toolcontext
.check_errors
80 if not failures
.is_empty
then
81 for msg
in failures
do
82 var ne
= new HTMLTag("failure")
83 ne
.attr
("message", msg
)
85 toolcontext
.modelbuilder
.unit_entities
+= 1
86 toolcontext
.modelbuilder
.failed_entities
+= 1
88 if last_docunit
== null then testsuite
.add
(tc
)
92 # All extracted docunits
93 var docunits
= new Array[DocUnit]
95 # Execute all the docunits
98 var simple_du
= new Array[DocUnit]
100 var ast
= toolcontext
.parse_something
(du
.block
)
101 if ast
isa AExpr then
104 test_single_docunit
(du
)
108 test_simple_docunits
(simple_du
)
110 for du
in docunits
do
111 testsuite
.add du
.to_xml
115 # Executes multiples doc-units in a shared program.
116 # Used for docunits simple block of code (without modules, classes, functions etc.)
118 # In case of compilation error, the method fallbacks to `test_single_docunit` to
119 # * locate exactly the compilation problem in the problematic docunit.
120 # * permit the execution of the other docunits that may be correct.
121 fun test_simple_docunits
(dus
: Array[DocUnit])
123 if dus
.is_empty
then return
125 var file
= "{prefix}-0.nit"
127 var dir
= file
.dirname
128 if dir
!= "" then dir
.mkdir
130 f
= create_unitfile
(file
)
135 f
.write
("fun run_{i} do\n")
136 f
.write
("# {du.testcase.attrs["name"]}\n")
140 f
.write
("var a = args.first.to_i\n")
142 f
.write
("if a == {j} then run_{j}\n")
146 if toolcontext
.opt_noact
.value
then return
148 var res
= compile_unitfile
(file
)
152 # Fall-back to individual modes:
154 test_single_docunit
(du
)
162 toolcontext
.modelbuilder
.unit_entities
+= 1
164 toolcontext
.info
("Execute doc-unit {du.testcase.attrs["name"]} in {file} {i}", 1)
165 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 var msg
= content
.trunc
(8192).filter_nonprintable
172 toolcontext
.warning
(du
.location
, "error", "ERROR: {tc.attrs["classname"]}.{tc.attrs["name"]} (in {file}): Runtime error\n{msg}")
173 toolcontext
.modelbuilder
.failed_entities
+= 1
175 toolcontext
.check_errors
179 # Executes a single doc-unit in its own program.
180 # Used for docunits larger than a single block of code (with modules, classes, functions etc.)
181 fun test_single_docunit
(du
: DocUnit)
184 toolcontext
.modelbuilder
.unit_entities
+= 1
187 var file
= "{prefix}-{cpt}.nit"
189 toolcontext
.info
("Execute doc-unit {tc.attrs["name"]} in {file}", 1)
192 f
= create_unitfile
(file
)
196 if toolcontext
.opt_noact
.value
then return
198 var res
= compile_unitfile
(file
)
201 res2
= toolcontext
.safe_exec
("{file.to_program_name}.bin >'{file}.out1' 2>&1 </dev/null")
204 var content
= "{file}.out1".to_path
.read_all
205 var msg
= content
.trunc
(8192).filter_nonprintable
210 toolcontext
.warning
(du
.location
, "failure", "FAILURE: {tc.attrs["classname"]}.{tc.attrs["name"]} (in {file}):\n{msg}")
211 toolcontext
.modelbuilder
.failed_entities
+= 1
212 else if res2
!= 0 then
213 toolcontext
.warning
(du
.location
, "error", "ERROR: {tc.attrs["classname"]}.{tc.attrs["name"]} (in {file}):\n{msg}")
214 toolcontext
.modelbuilder
.failed_entities
+= 1
216 toolcontext
.check_errors
219 # Create and fill the header of a unit file `file`.
221 # A unit file is a Nit source file generated from one
222 # or more docunits that will be compiled and executed.
224 # The handled on the file is returned and must be completed and closed.
226 # `file` should be a valid filepath for a Nit source file.
227 private fun create_unitfile
(file
: String): Writer
229 var dir
= file
.dirname
230 if dir
!= "" then dir
.mkdir
232 f
= new FileWriter.open
(file
)
233 f
.write
("# GENERATED FILE\n")
234 f
.write
("# Docunits extracted from comments\n")
235 if mmodule
!= null then
236 f
.write
("import {mmodule.name}\n")
242 # Compile an unit file and return the compiler return code
244 # Can terminate the program if the compiler is not found
245 private fun compile_unitfile
(file
: String): Int
247 var nitc
= toolcontext
.find_nitc
248 var opts
= new Array[String]
249 if mmodule
!= null then
250 opts
.add
"-I {mmodule.filepath.dirname}"
252 var cmd
= "{nitc} --ignore-visibility --no-color '{file}' {opts.join(" ")} >'{file}.out1' 2>&1 </dev/null -o '{file}.bin'"
253 var res
= toolcontext
.safe_exec
(cmd
)
258 private class NitunitDecorator
261 var executor
: NitUnitExecutor
263 redef fun add_code
(v
, block
) do
264 var code
= block
.raw_content
265 var meta
= block
.meta
or else "nit"
266 # Do not try to test non-nit code.
267 if meta
!= "nit" then return
268 # Try to parse code blocks
269 var ast
= executor
.toolcontext
.parse_something
(code
)
271 var mdoc
= executor
.mdoc
275 if ast
isa TComment then return
277 # The location is computed according to the starts of the mdoc and the block
278 # Note, the following assumes that all the comments of the mdoc are correctly aligned.
279 var loc
= block
.block
.location
280 var line_offset
= loc
.line_start
+ mdoc
.location
.line_start
- 2
281 var column_offset
= loc
.column_start
+ mdoc
.location
.column_start
282 # Hack to handle precise location in blocks
283 # TODO remove when markdown is more reliable
284 if block
isa BlockFence then
285 # Skip the starting fence
288 # Account a standard 4 space indentation
292 # We want executable code
293 if not (ast
isa AModule or ast
isa ABlockExpr or ast
isa AExpr) then
296 # Get real location of the node (or error)
297 var location
= new Location(mdoc
.location
.file
,
298 l
.line_start
+ line_offset
,
299 l
.line_end
+ line_offset
,
300 l
.column_start
+ column_offset
,
301 l
.column_end
+ column_offset
)
302 if ast
isa AError then
303 message
= ast
.message
305 message
= "Error: Invalid Nit code."
308 executor
.toolcontext
.warning
(location
, "invalid-block", "{message} To suppress this message, enclose the block with a fence tagged `nitish` or `raw` (see `man nitdoc`).")
309 executor
.failures
.add
("{location}: {message}")
313 # Create a first block
314 # Or create a new block for modules that are more than a main part
315 var last_docunit
= executor
.last_docunit
316 if last_docunit
== null or ast
isa AModule then
317 last_docunit
= new DocUnit(executor
.mdoc
.as(not null), executor
.tc
, "")
318 executor
.docunits
.add last_docunit
322 last_docunit
.block
+= code
324 # In order to retrieve precise positions,
325 # the real position of each line of the raw_content is stored.
326 # See `DocUnit::real_location`
327 line_offset
-= loc
.line_start
- 1
328 for i
in [loc
.line_start
..loc
.line_end
] do
329 last_docunit
.lines
.add i
+ line_offset
330 last_docunit
.columns
.add column_offset
335 # A unit-test extracted from some documentation.
337 # A docunit is extracted from the code-blocks of mdocs.
338 # Each mdoc can contains more than one docunit, and a single docunit can be made of more that a single code-block.
342 # The doc that contains self
345 # The XML node that contains the information about the execution
346 var testcase
: HTMLTag
348 # The text of the code to execute.
350 # This is the verbatim content on one, or more, code-blocks from `mdoc`
353 # For each line in `block`, the associated line in the mdoc
355 # Is used to give precise locations
356 var lines
= new Array[Int]
358 # For each line in `block`, the associated column in the mdoc
360 # Is used to give precise locations
361 var columns
= new Array[Int]
363 # The location of the whole docunit.
365 # If `self` is made of multiple code-blocks, then the location
366 # starts at the first code-books and finish at the last one, thus includes anything between.
367 var location
: Location is lazy
do
368 return new Location(mdoc
.location
.file
, lines
.first
, lines
.last
+1, columns
.first
+1, 0)
371 # Compute the real location of a node on the `ast` based on `mdoc.location`
373 # The result is basically: ast_location + markdown location of the piece + mdoc.location
375 # The fun is that a single docunit can be made of various pieces of code blocks.
376 fun real_location
(ast_location
: Location): Location
379 var res
= new Location(mdoc
.location
.file
, lines
[ast_location
.line_start-1
],
380 lines
[ast_location
.line_end-1
],
381 columns
[ast_location
.line_start-1
] + ast_location
.column_start
,
382 columns
[ast_location
.line_end-1
] + ast_location
.column_end
)
389 res
.open
("system-out").append
(block
)
395 redef class ModelBuilder
396 # Total number analyzed `MEntity`
397 var total_entities
= 0
399 # The number of `MEntity` that have some documentation
402 # The total number of executed docunits
403 var unit_entities
= 0
405 # The number failed docunits
406 var failed_entities
= 0
408 # Extracts and executes all the docunits in the `mmodule`
409 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
410 fun test_markdown
(mmodule
: MModule): HTMLTag
412 var ts
= new HTMLTag("testsuite")
413 toolcontext
.info
("nitunit: doc-unit {mmodule}", 2)
415 var nmodule
= mmodule2node
(mmodule
)
416 if nmodule
== null then return ts
418 # usualy, only the original module must be imported in the unit test.
421 if g
!= null and g
.mpackage
.name
== "core" then
422 # except for a unit test in a module of `core`
423 # in this case, the whole `core` must be imported
424 o
= get_mmodule_by_name
(nmodule
, g
, g
.mpackage
.name
).as(not null)
427 ts
.attr
("package", mmodule
.full_name
)
429 var prefix
= toolcontext
.test_dir
430 prefix
= prefix
.join_path
(mmodule
.to_s
)
431 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, o
, ts
)
437 var nmoduledecl
= nmodule
.n_moduledecl
438 if nmoduledecl
== null then break label x
439 var ndoc
= nmoduledecl
.n_doc
440 if ndoc
== null then break label x
442 tc
= new HTMLTag("testcase")
443 # NOTE: jenkins expects a '.' in the classname attr
444 tc
.attr
("classname", "nitunit." + mmodule
.full_name
+ ".<module>")
445 tc
.attr
("name", "<module>")
446 d2m
.extract
(ndoc
.to_mdoc
, tc
)
448 for nclassdef
in nmodule
.n_classdefs
do
449 var mclassdef
= nclassdef
.mclassdef
450 if mclassdef
== null then continue
451 if nclassdef
isa AStdClassdef then
453 var ndoc
= nclassdef
.n_doc
456 tc
= new HTMLTag("testcase")
457 tc
.attr
("classname", "nitunit." + mmodule
.full_name
+ "." + mclassdef
.mclass
.full_name
)
458 tc
.attr
("name", "<class>")
459 d2m
.extract
(ndoc
.to_mdoc
, tc
)
462 for npropdef
in nclassdef
.n_propdefs
do
463 var mpropdef
= npropdef
.mpropdef
464 if mpropdef
== null then continue
466 var ndoc
= npropdef
.n_doc
469 tc
= new HTMLTag("testcase")
470 tc
.attr
("classname", "nitunit." + mmodule
.full_name
+ "." + mclassdef
.mclass
.full_name
)
471 tc
.attr
("name", mpropdef
.mproperty
.full_name
)
472 d2m
.extract
(ndoc
.to_mdoc
, tc
)
482 # Extracts and executes all the docunits in the readme of the `mgroup`
483 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
484 fun test_group
(mgroup
: MGroup): HTMLTag
486 var ts
= new HTMLTag("testsuite")
487 toolcontext
.info
("nitunit: doc-unit group {mgroup}", 2)
489 # usually, only the default module must be imported in the unit test.
490 var o
= mgroup
.default_mmodule
492 ts
.attr
("package", mgroup
.full_name
)
494 var prefix
= toolcontext
.test_dir
495 prefix
= prefix
.join_path
(mgroup
.to_s
)
496 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, o
, ts
)
501 var mdoc
= mgroup
.mdoc
502 if mdoc
== null then return ts
505 tc
= new HTMLTag("testcase")
506 # NOTE: jenkins expects a '.' in the classname attr
507 tc
.attr
("classname", "nitunit." + mgroup
.full_name
)
508 tc
.attr
("name", "<group>")
509 d2m
.extract
(mdoc
, tc
)
516 # Test a document object unrelated to a Nit entity
517 fun test_mdoc
(mdoc
: MDoc): HTMLTag
519 var ts
= new HTMLTag("testsuite")
520 var file
= mdoc
.location
.to_s
522 toolcontext
.info
("nitunit: doc-unit file {file}", 2)
524 ts
.attr
("package", file
)
526 var prefix
= toolcontext
.test_dir
/ "file"
527 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, null, ts
)
534 tc
= new HTMLTag("testcase")
535 # NOTE: jenkins expects a '.' in the classname attr
536 tc
.attr
("classname", "nitunit.<file>")
537 tc
.attr
("name", file
)
539 d2m
.extract
(mdoc
, tc
)