nitunit: remove warnings from testing_base
[nit.git] / src / testing / testing_suite.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 # Testing from external files.
16 module testing_suite
17
18 import testing_base
19 import html
20 private import annotation
21 private import realtime
22
23 redef class ToolContext
24 # --pattern
25 var opt_pattern = new OptionString("Only run test case with name that match pattern", "-p", "--pattern")
26 # --autosav
27 var opt_autosav = new OptionBool("Automatically create/update .res files for black box testing", "--autosav")
28 end
29
30 # Used to test nitunit test files.
31 class NitUnitTester
32
33 # `ModelBuilder` used to parse test files.
34 var mbuilder: ModelBuilder
35
36 # Compile and execute `mmodule` as a test suite.
37 fun test_module_unit(mmodule: MModule): TestSuite do
38 var toolcontext = mbuilder.toolcontext
39 var suite = new TestSuite(mmodule, toolcontext)
40 # method to execute before all tests in the module
41 var before_module = mmodule.before_test
42 if before_module != null then
43 toolcontext.modelbuilder.total_tests += 1
44 suite.before_module = new TestCase(suite, before_module, toolcontext)
45 end
46 # generate all test cases
47 for mclassdef in mmodule.mclassdefs do
48 if not mclassdef.is_test then continue
49 if not suite_match_pattern(mclassdef) then continue
50 toolcontext.modelbuilder.total_classes += 1
51 for mpropdef in mclassdef.mpropdefs do
52 if not mpropdef isa MMethodDef or not mpropdef.is_test then continue
53 if not case_match_pattern(mpropdef) then continue
54 toolcontext.modelbuilder.total_tests += 1
55 var test = new TestCase(suite, mpropdef, toolcontext)
56 suite.add_test test
57 end
58 end
59 # method to execute after all tests in the module
60 var after_module = mmodule.after_test
61 if after_module != null then
62 toolcontext.modelbuilder.total_tests += 1
63 suite.after_module = new TestCase(suite, after_module, toolcontext)
64 end
65 suite.run
66 return suite
67 end
68
69 # Is the test suite name match the pattern option?
70 private fun suite_match_pattern(suite: MClassDef): Bool do
71 var pattern = mbuilder.toolcontext.opt_pattern.value
72 if pattern == null then return true
73 var ps = pattern.split_with("::")
74 var p = ps.first
75 if ps.length == 1 and p.first.is_lower then return true
76 if ps.length == 2 and p.first.is_lower then return false
77 if p.has_suffix("*") then
78 p = p.substring(0, p.length - 1)
79 if suite.name.has_prefix(p) then return true
80 else
81 if suite.name == p then return true
82 end
83 return false
84 end
85
86 # Is the test case name match the pattern option?
87 private fun case_match_pattern(case: MPropDef): Bool do
88 var pattern = mbuilder.toolcontext.opt_pattern.value
89 if pattern == null then return true
90 var ps = pattern.split_with("::")
91 var p = ps.last
92 if ps.length == 1 and p.first.is_upper then return true
93 if ps.length == 2 and p.first.is_upper then return false
94 if p.has_suffix("*") then
95 p = p.substring(0, p.length - 1)
96 if case.name.has_prefix(p) then return true
97 else
98 if case.name == p then return true
99 end
100 return false
101 end
102 end
103
104 # A test suite contains all the test cases for a `MModule`.
105 class TestSuite
106
107 # `MModule` under test
108 var mmodule: MModule
109
110 # `ToolContext` to use to display messages.
111 var toolcontext: ToolContext
112
113 # List of `TestCase` to be executed in this suite.
114 var test_cases = new Array[TestCase]
115
116 # Add a `TestCase` to the suite.
117 fun add_test(case: TestCase) do test_cases.add case
118
119 # Test to be executed before the whole test suite.
120 var before_module: nullable TestCase = null
121
122 # Test to be executed after the whole test suite.
123 var after_module: nullable TestCase = null
124
125 fun show_status
126 do
127 toolcontext.show_unit_status("Test-suite of module " + mmodule.full_name, test_cases)
128 end
129
130 # Execute the test suite
131 fun run do
132 show_status
133 if not toolcontext.test_dir.file_exists then
134 toolcontext.test_dir.mkdir
135 end
136 write_to_nit
137 compile
138 if failure != null then
139 for case in test_cases do
140 case.is_done = true
141 case.error = "Compilation Error"
142 case.raw_output = failure
143 toolcontext.modelbuilder.failed_tests += 1
144 toolcontext.clear_progress_bar
145 toolcontext.show_unit(case)
146 end
147 show_status
148 print ""
149 return
150 end
151 toolcontext.info("Execute test-suite {mmodule.name}", 1)
152 var before_module = self.before_module
153 if not before_module == null then before_module.run
154 for case in test_cases do
155 case.run
156 toolcontext.clear_progress_bar
157 toolcontext.show_unit(case)
158 show_status
159 end
160
161 var after_module = self.after_module
162 if not after_module == null then after_module.run
163
164 show_status
165 print ""
166 end
167
168 # Write the test unit for `self` in a nit compilable file.
169 fun write_to_nit do
170 var file = new Template
171 file.addn "intrude import test_suite"
172 file.addn "import {mmodule.name}\n"
173 file.addn "var name = args.first"
174 for case in test_cases do
175 case.write_to_nit(file)
176 end
177 file.write_to_file("{test_file}.nit")
178 end
179
180 # Return the test suite in XML format compatible with Jenkins.
181 # Contents depends on the `run` execution.
182 fun to_xml: HTMLTag do
183 var n = new HTMLTag("testsuite")
184 n.attr("package", mmodule.name)
185 for test in test_cases do n.add test.to_xml
186 return n
187 end
188
189 # Generated test file name.
190 fun test_file: String do
191 return toolcontext.test_dir / "gen_{mmodule.name.escape_to_c}"
192 end
193
194 # Compile all `test_cases` cases in one file.
195 fun compile do
196 # find nitc
197 var nitc = toolcontext.find_nitc
198 # compile test suite
199 var file = test_file
200 var module_file = mmodule.location.file
201 if module_file == null then
202 toolcontext.error(null, "Error: cannot find module file for {mmodule.name}.")
203 toolcontext.check_errors
204 return
205 end
206 var include_dir = module_file.filename.dirname
207 var cmd = "{nitc} --no-color -q '{file}.nit' -I {include_dir} -o '{file}.bin' > '{file}.out' 2>&1 </dev/null"
208 var res = toolcontext.safe_exec(cmd)
209 var f = new FileReader.open("{file}.out")
210 var msg = f.read_all
211 f.close
212 if res != 0 then
213 failure = msg
214 end
215 end
216
217 # Error occured during test-suite compilation.
218 var failure: nullable String = null
219 end
220
221 # A test case is a unit test considering only a `MMethodDef`.
222 class TestCase
223 super UnitTest
224
225 # Test suite wich `self` belongs to.
226 var test_suite: TestSuite
227
228 # Test method to be compiled and tested.
229 var test_method: MMethodDef
230
231 redef fun full_name do return test_method.full_name
232
233 redef fun location do return test_method.location
234
235 # `ToolContext` to use to display messages and find `nitc` bin.
236 var toolcontext: ToolContext
237
238 # Generate the test unit for `self` in `file`.
239 fun write_to_nit(file: Template) do
240 var name = test_method.name
241 file.addn "if name == \"{name}\" then"
242 if test_method.mproperty.is_toplevel then
243 file.addn "\t{name}"
244 else
245 file.addn "\tvar subject = new {test_method.mclassdef.name}.nitunit"
246 file.addn "\tsubject.before_test"
247 file.addn "\tsubject.{name}"
248 file.addn "\tsubject.after_test"
249 end
250 file.addn "end"
251 end
252
253 # Execute the test case.
254 fun run do
255 toolcontext.info("Execute test-case {test_method.name}", 1)
256 was_exec = true
257 if toolcontext.opt_noact.value then return
258 # execute
259 var method_name = test_method.name
260 var test_file = test_suite.test_file
261 var res_name = "{test_file}_{method_name.escape_to_c}"
262 var clock = new Clock
263 var res = toolcontext.safe_exec("{test_file}.bin {method_name} > '{res_name}.out1' 2>&1 </dev/null")
264 if not toolcontext.opt_no_time.value then real_time = clock.total
265
266 var raw_output = "{res_name}.out1".to_path.read_all
267 self.raw_output = raw_output
268 # set test case result
269 if res != 0 then
270 error = "Runtime Error in file {test_file}.nit"
271 toolcontext.modelbuilder.failed_tests += 1
272 else
273 # no error, check with res file, if any.
274 var mmodule = test_method.mclassdef.mmodule
275 var file = mmodule.filepath
276 if file != null then
277 var tries = [ file.dirname / mmodule.name + ".sav" / test_method.name + ".res",
278 file.dirname / "sav" / test_method.name + ".res" ,
279 file.dirname / test_method.name + ".res" ]
280 var savs = [ for t in tries do if t.file_exists then t ]
281 if savs.length == 1 then
282 var sav = savs.first
283 toolcontext.info("Diff output with {sav}", 1)
284 res = toolcontext.safe_exec("diff -u --label 'expected:{sav}' --label 'got:{res_name}.out1' '{sav}' '{res_name}.out1' > '{res_name}.diff' 2>&1 </dev/null")
285 if res == 0 then
286 # OK
287 else if toolcontext.opt_autosav.value then
288 raw_output.write_to_file(sav)
289 info = "Expected output updated: {sav} (--autoupdate)"
290 else
291 self.raw_output = "Diff\n" + "{res_name}.diff".to_path.read_all
292 error = "Difference with expected output: diff -u {sav} {res_name}.out1"
293 toolcontext.modelbuilder.failed_tests += 1
294 end
295 else if savs.length > 1 then
296 toolcontext.info("Conflicting diffs: {savs.join(", ")}", 1)
297 error = "Conflicting expected output: {savs.join(", ", " and ")} all exist"
298 toolcontext.modelbuilder.failed_tests += 1
299 else if not raw_output.is_empty then
300 toolcontext.info("No diff: {tries.join(", ", " or ")} not found", 1)
301 if toolcontext.opt_autosav.value then
302 var sav = tries.first
303 sav.dirname.mkdir
304 raw_output.write_to_file(sav)
305 info = "Expected output saved: {sav} (--autoupdate)"
306 end
307 end
308 end
309 end
310 is_done = true
311 end
312
313 redef fun xml_classname do
314 var a = test_method.full_name.split("$")
315 return "nitunit.{a[0]}.{a[1]}"
316 end
317
318 redef fun xml_name do
319 var a = test_method.full_name.split("$")
320 return a[2]
321 end
322 end
323
324 redef class MMethodDef
325 # TODO use annotations?
326
327 # Is the method a test_method?
328 # i.e. begins with "test_"
329 private fun is_test: Bool do return name.has_prefix("test_")
330
331 # Is the method a "before_module"?
332 private fun is_before_module: Bool do return mproperty.is_toplevel and name == "before_module"
333
334 # Is the method a "after_module"?
335 private fun is_after_module: Bool do return mproperty.is_toplevel and name == "after_module"
336 end
337
338 redef class MClassDef
339 # Is the class a TestClass?
340 # i.e. is a subclass of `TestSuite`
341 private fun is_test: Bool do
342 var in_hierarchy = self.in_hierarchy
343 if in_hierarchy == null then return false
344 for sup in in_hierarchy.greaters do
345 if sup.name == "TestSuite" then return true
346 end
347 return false
348 end
349 end
350
351 redef class MModule
352 # "before_module" method for this module.
353 private fun before_test: nullable MMethodDef do
354 for mclassdef in mclassdefs do
355 if not mclassdef.name == "Object" then continue
356 for mpropdef in mclassdef.mpropdefs do
357 if mpropdef isa MMethodDef and mpropdef.is_before_module then return mpropdef
358 end
359 end
360 return null
361 end
362
363 # "after_module" method for this module.
364 private fun after_test: nullable MMethodDef do
365 for mclassdef in mclassdefs do
366 if not mclassdef.name == "Object" then continue
367 for mpropdef in mclassdef.mpropdefs do
368 if mpropdef isa MMethodDef and mpropdef.is_after_module then return mpropdef
369 end
370 end
371 return null
372 end
373 end
374
375 redef class ModelBuilder
376 # Number of test classes generated.
377 var total_classes = 0
378
379 # Number of tests generated.
380 var total_tests = 0
381
382 # Number of failed tests.
383 var failed_tests = 0
384
385 # Run NitUnit test suite for `mmodule` (if it is one).
386 fun test_unit(mmodule: MModule): nullable HTMLTag do
387 # is the module a test_suite?
388 if get_mmodule_annotation("test_suite", mmodule) == null then return null
389 toolcontext.info("nitunit: test-suite {mmodule}", 2)
390
391 var tester = new NitUnitTester(self)
392 var res = tester.test_module_unit(mmodule)
393 return res.to_xml
394 end
395 end