nitunit: lower verbosity level to track each execution of test
[nit.git] / src / nitunit.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
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
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
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.
14
15 # Program to extract and execute unit tests from nit source files
16 module nitunit
17
18 import modelize_property
19 intrude import markdown
20 import parser_util
21
22 # Extractor, Executor an Reporter for the tests in a module
23 class NitUnitExecutor
24 super Doc2Mdwn
25
26 # The name of the module to import
27 var modname: String
28
29 # The prefix of the generated Nit source-file
30 var prefix: String
31
32 # The XML node associated to the module
33 var testsuite: HTMLTag
34
35 # Initialize a new e
36 init(toolcontext: ToolContext, prefix: String, modname: String, testsuite: HTMLTag)
37 do
38 super(toolcontext)
39 self.prefix = prefix
40 self.modname = modname
41 self.testsuite = testsuite
42 end
43
44 # All blocks of code from a same `ADoc`
45 var block = new Array[String]
46
47 redef fun process_code(n: HTMLTag, text: String)
48 do
49 # Try to parse it
50 var ast = toolcontext.parse_something(text)
51
52 # We want executable code
53 if not (ast isa AModule or ast isa ABlockExpr or ast isa AExpr) then return
54
55 # Search `assert` in the AST
56 var v = new SearchAssertVisitor
57 v.enter_visit(ast)
58 if not v.foundit then return
59
60 # Add it to the file
61 block.add(text)
62 end
63
64 # used to generate distinct names
65 var cpt = 0
66
67 # The entry point for a new `ndoc` node
68 # Fill the prepated `tc` (testcase) XTM node
69 fun extract(ndoc: ADoc, tc: HTMLTag)
70 do
71 block.clear
72
73 work(ndoc.to_mdoc)
74
75 if block.is_empty then return
76
77 toolcontext.modelbuilder.unit_entities += 1
78
79 cpt += 1
80 var file = "{prefix}{cpt}.nit"
81
82 toolcontext.info("Execute {tc.attrs["classname"]}.{tc.attrs["name"]} in {file}", 1)
83
84 var dir = file.dirname
85 if dir != "" then dir.mkdir
86 var f
87 f = new OFStream.open(file)
88 f.write("# GENERATED FILE\n")
89 f.write("# Example extracted from a documentation\n")
90 var modname = self.modname
91 f.write("import {modname}\n")
92 f.write("\n")
93 for text in block do
94 f.write(text)
95 end
96 f.close
97
98 if toolcontext.opt_noact.value then return
99
100 var nit_dir = toolcontext.nit_dir
101 var nitg = "{nit_dir}/bin/nitg"
102 if nit_dir == null or not nitg.file_exists then
103 toolcontext.error(null, "Cannot find nitg. Set envvar NIT_DIR.")
104 toolcontext.check_errors
105 end
106 var cmd = "{nitg} --ignore-visibility --no-color '{file}' -I . >'{file}.out1' 2>&1 </dev/null -o '{file}.bin'"
107 var res = sys.system(cmd)
108 var res2 = 0
109 if res == 0 then
110 res2 = sys.system("./{file}.bin >>'{file}.out1' 2>&1 </dev/null")
111 end
112
113 var msg
114 f = new IFStream.open("{file}.out1")
115 var n2
116 n2 = new HTMLTag("system-err")
117 tc.add n2
118 msg = f.read_all
119 f.close
120
121 n2 = new HTMLTag("system-out")
122 tc.add n2
123 for text in block do n2.append(text)
124
125
126 if res != 0 then
127 var ne = new HTMLTag("failure")
128 ne.attr("message", msg)
129 tc.add ne
130 toolcontext.warning(ndoc.location, "FAILURE: {tc.attrs["classname"]}.{tc.attrs["name"]} (in {file}): {msg}")
131 toolcontext.modelbuilder.failed_entities += 1
132 else if res2 != 0 then
133 var ne = new HTMLTag("error")
134 ne.attr("message", msg)
135 tc.add ne
136 toolcontext.warning(ndoc.location, "ERROR: {tc.attrs["classname"]}.{tc.attrs["name"]} (in {file}): {msg}")
137 toolcontext.modelbuilder.failed_entities += 1
138 end
139 toolcontext.check_errors
140
141 testsuite.add(tc)
142 end
143 end
144
145 class SearchAssertVisitor
146 super Visitor
147 var foundit = false
148 redef fun visit(node)
149 do
150 if foundit then
151 return
152 else if node isa AAssertExpr then
153 foundit = true
154 return
155 else
156 node.visit_all(self)
157 end
158 end
159 end
160
161 redef class ModelBuilder
162 var total_entities = 0
163 var doc_entities = 0
164 var unit_entities = 0
165 var failed_entities = 0
166
167 fun test_markdown(mmodule: MModule): HTMLTag
168 do
169 var ts = new HTMLTag("testsuite")
170 toolcontext.info("nitunit: {mmodule}", 2)
171 if not mmodule2nmodule.has_key(mmodule) then return ts
172
173 var nmodule = mmodule2nmodule[mmodule]
174 assert nmodule != null
175
176 # what module to import in the unit test.
177 # try to detect the main module of the project
178 # TODO do things correctly once the importation of arbitraty nested module is legal
179 var o = mmodule
180 var g = o.mgroup
181 if g != null then
182 o = get_mmodule_by_name(nmodule, g, g.mproject.name).as(not null)
183 end
184
185 ts.attr("package", mmodule.full_name)
186
187 var prefix = toolcontext.opt_dir.value
188 if prefix == null then prefix = ".nitunit"
189 prefix = prefix.join_path(mmodule.to_s)
190 var d2m = new NitUnitExecutor(toolcontext, prefix, o.name, ts)
191
192 var tc
193
194 do
195 total_entities += 1
196 var nmoduledecl = nmodule.n_moduledecl
197 if nmoduledecl == null then break label x
198 var ndoc = nmoduledecl.n_doc
199 if ndoc == null then break label x
200 doc_entities += 1
201 tc = new HTMLTag("testcase")
202 # NOTE: jenkins expects a '.' in the classname attr
203 tc.attr("classname", mmodule.full_name + ".<module>")
204 tc.attr("name", "<module>")
205 d2m.extract(ndoc, tc)
206 end label x
207 for nclassdef in nmodule.n_classdefs do
208 var mclassdef = nclassdef.mclassdef.as(not null)
209 if nclassdef isa AStdClassdef then
210 total_entities += 1
211 var ndoc = nclassdef.n_doc
212 if ndoc != null then
213 doc_entities += 1
214 tc = new HTMLTag("testcase")
215 tc.attr("classname", mmodule.full_name + "." + mclassdef.mclass.full_name)
216 tc.attr("name", "<class>")
217 d2m.extract(ndoc, tc)
218 end
219 end
220 for npropdef in nclassdef.n_propdefs do
221 var mpropdef = npropdef.mpropdef.as(not null)
222 total_entities += 1
223 var ndoc = npropdef.n_doc
224 if ndoc != null then
225 doc_entities += 1
226 tc = new HTMLTag("testcase")
227 tc.attr("classname", mmodule.full_name + "." + mclassdef.mclass.full_name)
228 tc.attr("name", mpropdef.mproperty.full_name)
229 d2m.extract(ndoc, tc)
230 end
231 end
232 end
233
234 return ts
235 end
236 end
237
238 redef class ToolContext
239 var opt_full = new OptionBool("Process also imported modules", "--full")
240 var opt_output = new OptionString("Output name (default is 'nitunit.xml')", "-o", "--output")
241 var opt_dir = new OptionString("Working directory (default is '.nitunit')", "--dir")
242 var opt_noact = new OptionBool("Does not compile and run tests", "--no-act")
243 end
244
245 var toolcontext = new ToolContext
246
247 toolcontext.option_context.add_option(toolcontext.opt_full, toolcontext.opt_output, toolcontext.opt_dir, toolcontext.opt_noact)
248 toolcontext.tooldescription = "Usage: nitunit [OPTION]... <file.nit>...\nExecutes the unit tests from Nit source files."
249
250 toolcontext.process_options(args)
251 var args = toolcontext.option_context.rest
252
253 var model = new Model
254 var modelbuilder = new ModelBuilder(model, toolcontext)
255
256 var mmodules = modelbuilder.parse(args)
257 modelbuilder.run_phases
258
259 var page = new HTMLTag("testsuites")
260
261 if toolcontext.opt_full.value then mmodules = model.mmodules
262
263 for m in mmodules do
264 page.add modelbuilder.test_markdown(m)
265 end
266
267 var file = toolcontext.opt_output.value
268 if file == null then file = "nitunit.xml"
269 page.write_to_file(file)
270 print "Results saved in {file}"
271
272 if modelbuilder.unit_entities == 0 then
273 print "No nitunits found"
274 else if modelbuilder.failed_entities == 0 and not toolcontext.opt_noact.value then
275 print "Success"
276 end
277 print "Entities: {modelbuilder.total_entities}; Documented ones: {modelbuilder.doc_entities}; With nitunits: {modelbuilder.unit_entities}; Failures: {modelbuilder.failed_entities}"