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