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