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