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.
19 intrude import docdown
21 # Extractor, Executor and Reporter for the tests in a module
25 # The prefix of the generated Nit source-file
28 # The module to import
31 # The XML node associated to the module
32 var testsuite
: HTMLTag
34 # All blocks of code from a same `ADoc`
35 var blocks
= new Array[Array[String]]
37 # All failures from a same `ADoc`
38 var failures
= new Array[String]
40 redef fun process_code
(n
: HTMLTag, text
: String, tag
: nullable String)
43 if n
.tag
!= "pre" then return
46 if tag
!= null and tag
!= "nit" and tag
!= "" then
51 var ast
= toolcontext
.parse_something
(text
)
54 if ast
isa TComment then return
56 # We want executable code
57 if not (ast
isa AModule or ast
isa ABlockExpr or ast
isa AExpr) then
59 if ast
isa AError then message
= " At {ast.location}: {ast.message}."
60 toolcontext
.warning
(ndoc
.location
, "invalid-block", "Error: There is a block of code that is not valid Nit, thus not considered a nitunit. To suppress this warning, enclose the block with a fence tagged `nitish` or `raw` (see `man nitdoc`).{message}")
61 failures
.add
("{ndoc.location}: Invalid block of code.{message}")
65 # Create a first block
66 # Or create a new block for modules that are more than a main part
67 if blocks
.is_empty
or ast
isa AModule then
68 blocks
.add
(new Array[String])
75 # The associated node to localize warnings
76 var ndoc
: nullable ADoc = null
78 # used to generate distinct names
81 # The entry point for a new `ndoc` node
82 # Fill `docunits` with new discovered unit of tests.
84 # `tc` (testcase) is the pre-filled XML node
85 fun extract
(ndoc
: ADoc, tc
: HTMLTag)
94 toolcontext
.check_errors
96 if not failures
.is_empty
then
97 for msg
in failures
do
98 var ne
= new HTMLTag("failure")
99 ne
.attr
("message", msg
)
101 toolcontext
.modelbuilder
.failed_entities
+= 1
103 if blocks
.is_empty
then testsuite
.add
(tc
)
106 if blocks
.is_empty
then return
108 for block
in blocks
do
109 docunits
.add
new DocUnit(ndoc
, tc
, block
.join
(""))
113 # All extracted docunits
114 var docunits
= new Array[DocUnit]
116 # Execute all the docunits
119 var simple_du
= new Array[DocUnit]
120 for du
in docunits
do
121 var ast
= toolcontext
.parse_something
(du
.block
)
122 if ast
isa AExpr then
125 test_single_docunit
(du
)
129 test_simple_docunits
(simple_du
)
132 # Executes multiples doc-units in a shared program.
133 # Used for docunits simple block of code (without modules, classes, functions etc.)
135 # In case of compilation error, the method fallbacks to `test_single_docunit` to
136 # * locate exactly the compilation problem in the problematic docunit.
137 # * permit the execution of the other docunits that may be correct.
138 fun test_simple_docunits
(dus
: Array[DocUnit])
140 if dus
.is_empty
then return
142 var file
= "{prefix}-0.nit"
144 var dir
= file
.dirname
145 if dir
!= "" then dir
.mkdir
147 f
= new OFStream.open
(file
)
148 f
.write
("# GENERATED FILE\n")
149 f
.write
("# Docunits extracted from comments\n")
150 f
.write
("import {mmodule.name}\n")
156 f
.write
("fun run_{i} do\n")
157 f
.write
("# {du.testcase.attrs["name"]}\n")
161 f
.write
("var a = args.first.to_i\n")
163 f
.write
("if a == {j} then run_{j}\n")
167 if toolcontext
.opt_noact
.value
then return
169 var nit_dir
= toolcontext
.nit_dir
170 var nitg
= nit_dir
/"bin/nitg"
171 if not nitg
.file_exists
then
172 toolcontext
.error
(null, "Cannot find nitg. Set envvar NIT_DIR.")
173 toolcontext
.check_errors
175 var cmd
= "{nitg} --ignore-visibility --no-color '{file}' -I {mmodule.location.file.filename.dirname} >'{file}.out1' 2>&1 </dev/null -o '{file}.bin'"
176 var res
= sys
.system
(cmd
)
180 # Fall-back to individual modes:
182 test_single_docunit
(du
)
190 toolcontext
.modelbuilder
.unit_entities
+= 1
192 toolcontext
.info
("Execute doc-unit {du.testcase.attrs["name"]} in {file} {i}", 1)
193 var res2
= sys
.system
("{file.to_program_name}.bin {i} >>'{file}.out1' 2>&1 </dev/null")
196 f
= new IFStream.open
("{file}.out1")
198 n2
= new HTMLTag("system-err")
203 n2
= new HTMLTag("system-out")
208 var ne
= new HTMLTag("error")
209 ne
.attr
("message", msg
)
211 toolcontext
.warning
(du
.ndoc
.location
, "error", "ERROR: {tc.attrs["classname"]}.{tc.attrs["name"]} (in {file}): {msg}")
212 toolcontext
.modelbuilder
.failed_entities
+= 1
214 toolcontext
.check_errors
220 # Executes a single doc-unit in its own program.
221 # Used for docunits larger than a single block of code (with modules, classes, functions etc.)
222 fun test_single_docunit
(du
: DocUnit)
225 toolcontext
.modelbuilder
.unit_entities
+= 1
228 var file
= "{prefix}-{cpt}.nit"
230 toolcontext
.info
("Execute doc-unit {tc.attrs["name"]} in {file}", 1)
232 var dir
= file
.dirname
233 if dir
!= "" then dir
.mkdir
235 f
= new OFStream.open
(file
)
236 f
.write
("# GENERATED FILE\n")
237 f
.write
("# Example extracted from a documentation\n")
238 f
.write
("import {mmodule.name}\n")
243 if toolcontext
.opt_noact
.value
then return
245 var nit_dir
= toolcontext
.nit_dir
246 var nitg
= nit_dir
/"bin/nitg"
247 if not nitg
.file_exists
then
248 toolcontext
.error
(null, "Cannot find nitg. Set envvar NIT_DIR.")
249 toolcontext
.check_errors
251 var cmd
= "{nitg} --ignore-visibility --no-color '{file}' -I {mmodule.location.file.filename.dirname} >'{file}.out1' 2>&1 </dev/null -o '{file}.bin'"
252 var res
= sys
.system
(cmd
)
255 res2
= sys
.system
("{file.to_program_name}.bin >>'{file}.out1' 2>&1 </dev/null")
259 f
= new IFStream.open
("{file}.out1")
261 n2
= new HTMLTag("system-err")
266 n2
= new HTMLTag("system-out")
272 var ne
= new HTMLTag("failure")
273 ne
.attr
("message", msg
)
275 toolcontext
.warning
(du
.ndoc
.location
, "failure", "FAILURE: {tc.attrs["classname"]}.{tc.attrs["name"]} (in {file}): {msg}")
276 toolcontext
.modelbuilder
.failed_entities
+= 1
277 else if res2
!= 0 then
278 var ne
= new HTMLTag("error")
279 ne
.attr
("message", msg
)
281 toolcontext
.warning
(du
.ndoc
.location
, "error", "ERROR: {tc.attrs["classname"]}.{tc.attrs["name"]} (in {file}): {msg}")
282 toolcontext
.modelbuilder
.failed_entities
+= 1
284 toolcontext
.check_errors
292 # The original comment node
295 # The XML node that contains the information about the execution
296 var testcase
: HTMLTag
298 # The text of the code to execute
302 redef class ModelBuilder
303 # Total number analyzed `MEntity`
304 var total_entities
= 0
306 # The number of `MEntity` that have some documentation
309 # The total number of executed docunits
310 var unit_entities
= 0
312 # The number failed docunits
313 var failed_entities
= 0
315 # Extracts and executes all the docunits in the `mmodule`
316 # Returns a JUnit-compatible `<testsuite>` XML element that contains the results of the executions.
317 fun test_markdown
(mmodule
: MModule): HTMLTag
319 var ts
= new HTMLTag("testsuite")
320 toolcontext
.info
("nitunit: doc-unit {mmodule}", 2)
322 var nmodule
= mmodule2node
(mmodule
)
323 if nmodule
== null then return ts
325 # usualy, only the original module must be imported in the unit test.
328 if g
!= null and g
.mproject
.name
== "standard" then
329 # except for a unit test in a module of standard
330 # in this case, the whole standard must be imported
331 o
= get_mmodule_by_name
(nmodule
, g
, g
.mproject
.name
).as(not null)
334 ts
.attr
("package", mmodule
.full_name
)
336 var prefix
= toolcontext
.test_dir
337 prefix
= prefix
.join_path
(mmodule
.to_s
)
338 var d2m
= new NitUnitExecutor(toolcontext
, prefix
, o
, ts
)
344 var nmoduledecl
= nmodule
.n_moduledecl
345 if nmoduledecl
== null then break label x
346 var ndoc
= nmoduledecl
.n_doc
347 if ndoc
== null then break label x
349 tc
= new HTMLTag("testcase")
350 # NOTE: jenkins expects a '.' in the classname attr
351 tc
.attr
("classname", "nitunit." + mmodule
.full_name
+ ".<module>")
352 tc
.attr
("name", "<module>")
353 d2m
.extract
(ndoc
, tc
)
355 for nclassdef
in nmodule
.n_classdefs
do
356 var mclassdef
= nclassdef
.mclassdef
357 if mclassdef
== null then continue
358 if nclassdef
isa AStdClassdef then
360 var ndoc
= nclassdef
.n_doc
363 tc
= new HTMLTag("testcase")
364 tc
.attr
("classname", "nitunit." + mmodule
.full_name
+ "." + mclassdef
.mclass
.full_name
)
365 tc
.attr
("name", "<class>")
366 d2m
.extract
(ndoc
, tc
)
369 for npropdef
in nclassdef
.n_propdefs
do
370 var mpropdef
= npropdef
.mpropdef
371 if mpropdef
== null then continue
373 var ndoc
= npropdef
.n_doc
376 tc
= new HTMLTag("testcase")
377 tc
.attr
("classname", "nitunit." + mmodule
.full_name
+ "." + mclassdef
.mclass
.full_name
)
378 tc
.attr
("name", mpropdef
.mproperty
.full_name
)
379 d2m
.extract
(ndoc
, tc
)