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 # All blocks of code from a same `ADoc`
40 var blocks
= new Array[Buffer]
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 entry point for a new `ndoc` node
59 # Fill `docunits` with new discovered unit of tests.
61 # `tc` (testcase) is the pre-filled XML node
62 fun extract
(mdoc
: MDoc, tc
: HTMLTag)
69 # Populate `blocks` from the markdown decorator
70 mdproc
.process
(mdoc
.content
.join
("\n"))
71 if blocks
.is_empty
then return
73 toolcontext
.check_errors
75 if not failures
.is_empty
then
76 for msg
in failures
do
77 var ne
= new HTMLTag("failure")
78 ne
.attr
("message", msg
)
80 toolcontext
.modelbuilder
.failed_entities
+= 1
82 if blocks
.is_empty
then testsuite
.add
(tc
)
85 for block
in blocks
do
86 docunits
.add
new DocUnit(mdoc
, tc
, block
.write_to_string
)
90 # All extracted docunits
91 var docunits
= new Array[DocUnit]
93 # Execute all the docunits
96 var simple_du
= new Array[DocUnit]
98 var ast
= toolcontext
.parse_something
(du
.block
)
102 test_single_docunit
(du
)
106 test_simple_docunits
(simple_du
)
109 # Executes multiples doc-units in a shared program.
110 # Used for docunits simple block of code (without modules, classes, functions etc.)
112 # In case of compilation error, the method fallbacks to `test_single_docunit` to
113 # * locate exactly the compilation problem in the problematic docunit.
114 # * permit the execution of the other docunits that may be correct.
115 fun test_simple_docunits
(dus
: Array[DocUnit])
117 if dus
.is_empty
then return
119 var file
= "{prefix}-0.nit"
121 var dir
= file
.dirname
122 if dir
!= "" then dir
.mkdir
124 f
= create_unitfile
(file
)
129 f
.write
("fun run_{i} do\n")
130 f
.write
("# {du.testcase.attrs["name"]}\n")
134 f
.write
("var a = args.first.to_i\n")
136 f
.write
("if a == {j} then run_{j}\n")
140 if toolcontext
.opt_noact
.value
then return
142 var res
= compile_unitfile
(file
)
146 # Fall-back to individual modes:
148 test_single_docunit
(du
)
156 toolcontext
.modelbuilder
.unit_entities
+= 1
158 toolcontext
.info
("Execute doc-unit {du.testcase.attrs["name"]} in {file} {i}", 1)
159 var res2
= sys
.system
("{file.to_program_name}.bin {i} >>'{file}.out1' 2>&1 </dev/null")
162 f
= new FileReader.open
("{file}.out1")
164 n2
= new HTMLTag("system-err")
169 n2
= new HTMLTag("system-out")
174 var ne
= new HTMLTag("error")
175 ne
.attr
("message", msg
)
177 toolcontext
.warning
(du
.mdoc
.location
, "error", "ERROR: {tc.attrs["classname"]}.{tc.attrs["name"]} (in {file}): {msg}")
178 toolcontext
.modelbuilder
.failed_entities
+= 1
180 toolcontext
.check_errors
186 # Executes a single doc-unit in its own program.
187 # Used for docunits larger than a single block of code (with modules, classes, functions etc.)
188 fun test_single_docunit
(du
: DocUnit)
191 toolcontext
.modelbuilder
.unit_entities
+= 1
194 var file
= "{prefix}-{cpt}.nit"
196 toolcontext
.info
("Execute doc-unit {tc.attrs["name"]} in {file}", 1)
199 f
= create_unitfile
(file
)
203 if toolcontext
.opt_noact
.value
then return
205 var res
= compile_unitfile
(file
)
208 res2
= sys
.system
("{file.to_program_name}.bin >>'{file}.out1' 2>&1 </dev/null")
212 f
= new FileReader.open
("{file}.out1")
214 n2
= new HTMLTag("system-err")
219 n2
= new HTMLTag("system-out")
225 var ne
= new HTMLTag("failure")
226 ne
.attr
("message", msg
)
228 toolcontext
.warning
(du
.mdoc
.location
, "failure", "FAILURE: {tc.attrs["classname"]}.{tc.attrs["name"]} (in {file}): {msg}")
229 toolcontext
.modelbuilder
.failed_entities
+= 1
230 else if res2
!= 0 then
231 var ne
= new HTMLTag("error")
232 ne
.attr
("message", msg
)
234 toolcontext
.warning
(du
.mdoc
.location
, "error", "ERROR: {tc.attrs["classname"]}.{tc.attrs["name"]} (in {file}): {msg}")
235 toolcontext
.modelbuilder
.failed_entities
+= 1
237 toolcontext
.check_errors
242 # Create and fill the header of a unit file `file`.
244 # A unit file is a Nit source file generated from one
245 # or more docunits that will be compiled and executed.
247 # The handled on the file is returned and must be completed and closed.
249 # `file` should be a valid filepath for a Nit source file.
250 private fun create_unitfile
(file
: String): Writer
252 var dir
= file
.dirname
253 if dir
!= "" then dir
.mkdir
255 f
= new FileWriter.open
(file
)
256 f
.write
("# GENERATED FILE\n")
257 f
.write
("# Docunits extracted from comments\n")
258 if mmodule
!= null then
259 f
.write
("import {mmodule.name}\n")
265 # Compile an unit file and return the compiler return code
267 # Can terminate the program if the compiler is not found
268 private fun compile_unitfile
(file
: String): Int
270 var nit_dir
= toolcontext
.nit_dir
271 var nitc
= nit_dir
/"bin/nitc"
272 if not nitc
.file_exists
then
273 toolcontext
.error
(null, "Error: cannot find nitc. Set envvar NIT_DIR.")
274 toolcontext
.check_errors
276 var opts
= new Array[String]
277 if mmodule
!= null then
278 opts
.add
"-I {mmodule.location.file.filename.dirname}"
280 var cmd
= "{nitc} --ignore-visibility --no-color '{file}' {opts.join(" ")} >'{file}.out1' 2>&1 </dev/null -o '{file}.bin'"
281 var res
= sys
.system
(cmd
)
286 private class NitunitDecorator
289 var executor
: NitUnitExecutor
291 redef fun add_code
(v
, block
) do
292 var code
= code_from_block
(block
)
294 if block
isa BlockFence and block
.meta
!= null then
295 meta
= block
.meta
.to_s
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
)
303 if ast
isa TComment then return
305 # We want executable code
306 if not (ast
isa AModule or ast
isa ABlockExpr or ast
isa AExpr) then
308 if ast
isa AError then message
= " At {ast.location}: {ast.message}."
309 executor
.toolcontext
.warning
(executor
.mdoc
.location
, "invalid-block", "Error: there is a block of invalid Nit code, thus not considered a nitunit. To suppress this warning, enclose the block with a fence tagged `nitish` or `raw` (see `man nitdoc`).{message}")
310 executor
.failures
.add
("{executor.mdoc.location}: Invalid block of code.{message}")
314 # Create a first block
315 # Or create a new block for modules that are more than a main part
316 if executor
.blocks
.is_empty
or ast
isa AModule then
317 executor
.blocks
.add
(new Buffer)
321 executor
.blocks
.last
.append code
324 # Extracts code as String from a `BlockCode`.
325 fun code_from_block
(block
: BlockCode): String do
326 var infence
= block
isa BlockFence
327 var text
= new FlatBuffer
328 var line
= block
.block
.first_line
329 while line
!= null do
330 if not line
.is_empty
then
332 if not infence
and str
.has_prefix
(" ") then
333 text
.append str
.substring
(4, str
.length
- line
.trailing
)
341 return text
.write_to_string
347 # The doc that contains self
350 # The XML node that contains the information about the execution
351 var testcase
: HTMLTag
353 # The text of the code to execute
357 redef class ModelBuilder
358 # Total number analyzed `MEntity`
359 var total_entities
= 0
361 # The number of `MEntity` that have some documentation
364 # The total number of executed docunits
365 var unit_entities
= 0
367 # The number failed docunits
368 var failed_entities
= 0
370 # Extracts and executes all the docunits in the `mmodule`
371 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
372 fun test_markdown
(mmodule
: MModule): HTMLTag
374 var ts
= new HTMLTag("testsuite")
375 toolcontext
.info
("nitunit: doc-unit {mmodule}", 2)
377 var nmodule
= mmodule2node
(mmodule
)
378 if nmodule
== null then return ts
380 # usualy, only the original module must be imported in the unit test.
383 if g
!= null and g
.mproject
.name
== "standard" then
384 # except for a unit test in a module of standard
385 # in this case, the whole standard must be imported
386 o
= get_mmodule_by_name
(nmodule
, g
, g
.mproject
.name
).as(not null)
389 ts
.attr
("package", mmodule
.full_name
)
391 var prefix
= toolcontext
.test_dir
392 prefix
= prefix
.join_path
(mmodule
.to_s
)
393 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, o
, ts
)
399 var nmoduledecl
= nmodule
.n_moduledecl
400 if nmoduledecl
== null then break label x
401 var ndoc
= nmoduledecl
.n_doc
402 if ndoc
== null then break label x
404 tc
= new HTMLTag("testcase")
405 # NOTE: jenkins expects a '.' in the classname attr
406 tc
.attr
("classname", "nitunit." + mmodule
.full_name
+ ".<module>")
407 tc
.attr
("name", "<module>")
408 d2m
.extract
(ndoc
.to_mdoc
, tc
)
410 for nclassdef
in nmodule
.n_classdefs
do
411 var mclassdef
= nclassdef
.mclassdef
412 if mclassdef
== null then continue
413 if nclassdef
isa AStdClassdef then
415 var ndoc
= nclassdef
.n_doc
418 tc
= new HTMLTag("testcase")
419 tc
.attr
("classname", "nitunit." + mmodule
.full_name
+ "." + mclassdef
.mclass
.full_name
)
420 tc
.attr
("name", "<class>")
421 d2m
.extract
(ndoc
.to_mdoc
, tc
)
424 for npropdef
in nclassdef
.n_propdefs
do
425 var mpropdef
= npropdef
.mpropdef
426 if mpropdef
== null then continue
428 var ndoc
= npropdef
.n_doc
431 tc
= new HTMLTag("testcase")
432 tc
.attr
("classname", "nitunit." + mmodule
.full_name
+ "." + mclassdef
.mclass
.full_name
)
433 tc
.attr
("name", mpropdef
.mproperty
.full_name
)
434 d2m
.extract
(ndoc
.to_mdoc
, tc
)
444 # Extracts and executes all the docunits in the readme of the `mgroup`
445 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
446 fun test_group
(mgroup
: MGroup): HTMLTag
448 var ts
= new HTMLTag("testsuite")
449 toolcontext
.info
("nitunit: doc-unit group {mgroup}", 2)
451 # usually, only the default module must be imported in the unit test.
452 var o
= mgroup
.default_mmodule
454 ts
.attr
("package", mgroup
.full_name
)
456 var prefix
= toolcontext
.test_dir
457 prefix
= prefix
.join_path
(mgroup
.to_s
)
458 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, o
, ts
)
463 var mdoc
= mgroup
.mdoc
464 if mdoc
== null then return ts
467 tc
= new HTMLTag("testcase")
468 # NOTE: jenkins expects a '.' in the classname attr
469 tc
.attr
("classname", "nitunit." + mgroup
.full_name
)
470 tc
.attr
("name", "<group>")
471 d2m
.extract
(mdoc
, tc
)
478 # Test a document object unrelated to a Nit entity
479 fun test_mdoc
(mdoc
: MDoc): HTMLTag
481 var ts
= new HTMLTag("testsuite")
482 var file
= mdoc
.location
.to_s
484 toolcontext
.info
("nitunit: doc-unit file {file}", 2)
486 ts
.attr
("package", file
)
488 var prefix
= toolcontext
.test_dir
/ "file"
489 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, null, ts
)
496 tc
= new HTMLTag("testcase")
497 # NOTE: jenkins expects a '.' in the classname attr
498 tc
.attr
("classname", "nitunit.<file>")
499 tc
.attr
("name", file
)
501 d2m
.extract
(mdoc
, tc
)