nitunit: the working dir is now `nitunit.out`
[nit.git] / src / testing / testing_base.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 # Base options for testing tools.
16 module testing_base
17
18 import modelize
19 private import parser_util
20 import html
21 import console
22
23 redef class ToolContext
24 # opt --full
25 var opt_full = new OptionBool("Process also imported modules", "--full")
26 # opt --output
27 var opt_output = new OptionString("Output name (default is 'nitunit.xml')", "-o", "--output")
28 # opt --dirr
29 var opt_dir = new OptionString("Working directory (default is '.nitunit')", "--dir")
30 # opt --no-act
31 var opt_noact = new OptionBool("Does not compile and run tests", "--no-act")
32 # opt --nitc
33 var opt_nitc = new OptionString("nitc compiler to use", "--nitc")
34
35 # Working directory for testing.
36 fun test_dir: String do
37 var dir = opt_dir.value
38 if dir == null then return "nitunit.out"
39 return dir
40 end
41
42 # Search the `nitc` compiler to use
43 #
44 # If not `nitc` is suitable, then prints an error and quit.
45 fun find_nitc: String
46 do
47 var nitc = opt_nitc.value
48 if nitc != null then
49 if not nitc.file_exists then
50 fatal_error(null, "error: cannot find `{nitc}` given by --nitc.")
51 abort
52 end
53 return nitc
54 end
55
56 nitc = "NITC".environ
57 if nitc != "" then
58 if not nitc.file_exists then
59 fatal_error(null, "error: cannot find `{nitc}` given by NITC.")
60 abort
61 end
62 return nitc
63 end
64
65 var nit_dir = nit_dir
66 nitc = nit_dir/"bin/nitc"
67 if not nitc.file_exists then
68 fatal_error(null, "Error: cannot find nitc. Set envvar NIT_DIR or NITC or use the --nitc option.")
69 abort
70 end
71 return nitc
72 end
73
74 # Execute a system command in a more safe context than `Sys::system`.
75 fun safe_exec(command: String): Int
76 do
77 info(command, 2)
78 var real_command = """
79 bash -c "
80 ulimit -f {{{ulimit_file}}} 2> /dev/null
81 ulimit -t {{{ulimit_usertime}}} 2> /dev/null
82 {{{command}}}
83 "
84 """
85 return system(real_command)
86 end
87
88 # The maximum size (in KB) of files written by a command executed trough `safe_exec`
89 #
90 # Default: 64MB
91 var ulimit_file = 65536 is writable
92
93 # The maximum amount of cpu time (in seconds) for a command executed trough `safe_exec`
94 #
95 # Default: 10 CPU minute
96 var ulimit_usertime = 600 is writable
97
98 # Show a single-line status to use as a progression.
99 #
100 # Note that the line starts with `'\r'` and is not ended by a `'\n'`.
101 # So it is expected that:
102 # * no other output is printed between two calls
103 # * the last `show_unit_status` is followed by a new-line
104 fun show_unit_status(name: String, tests: SequenceRead[UnitTest], more_message: nullable String)
105 do
106 var esc = 27.code_point.to_s
107 var line = "\r{esc}[K* {name} ["
108 var done = tests.length
109 for t in tests do
110 if not t.is_done then
111 line += " "
112 done -= 1
113 else if t.error == null then
114 line += ".".green.bold
115 else
116 line += "X".red.bold
117 end
118 end
119
120 if opt_no_color.value then
121 if done == 0 then
122 print "* {name} ({tests.length} tests)"
123 end
124 return
125 end
126
127 line += "] {done}/{tests.length}"
128 if more_message != null then
129 line += " " + more_message
130 end
131 printn "{line}"
132 end
133
134 # Shoe the full description of the test-case.
135 #
136 # The output honors `--no-color`.
137 #
138 # `more message`, if any, is added after the error message.
139 fun show_unit(test: UnitTest, more_message: nullable String) do
140 print test.to_screen(more_message, not opt_no_color.value)
141 end
142 end
143
144 # A unit test is an elementary test discovered, run and reported by nitunit.
145 #
146 # This class factorizes `DocUnit` and `TestCase`.
147 abstract class UnitTest
148 # The name of the unit to show in messages
149 fun full_name: String is abstract
150
151 # The location of the unit test to show in messages.
152 fun location: Location is abstract
153
154 # Flag that indicates if the unit test was compiled/run.
155 var is_done: Bool = false is writable
156
157 # Error message occurred during test-case execution (or compilation).
158 #
159 # e.g.: `Runtime Error`
160 var error: nullable String = null is writable
161
162 # Was the test case executed at least once?
163 #
164 # This will indicate the status of the test (failture or error)
165 var was_exec = false is writable
166
167 # The raw output of the execution (or compilation)
168 #
169 # It merges the standard output and error output
170 var raw_output: nullable String = null is writable
171
172 # The location where the error occurred, if it makes sense.
173 var error_location: nullable Location = null is writable
174
175 # A colorful `[OK]` or `[KO]`.
176 fun status_tag(color: nullable Bool): String do
177 color = color or else true
178 if not is_done then
179 return "[ ]"
180 else if error != null then
181 var res = "[KO]"
182 if color then res = res.red.bold
183 return res
184 else
185 var res = "[OK]"
186 if color then res = res.green.bold
187 return res
188 end
189 end
190
191 # The full (color) description of the test-case.
192 #
193 # `more message`, if any, is added after the error message.
194 fun to_screen(more_message: nullable String, color: nullable Bool): String do
195 color = color or else true
196 var res
197 var error = self.error
198 if error != null then
199 if more_message != null then error += " " + more_message
200 var loc = error_location or else location
201 if color then
202 res = "{status_tag(color)} {full_name}\n {loc.to_s.yellow}: {error}\n{loc.colored_line("1;31")}"
203 else
204 res = "{status_tag(color)} {full_name}\n {loc}: {error}"
205 end
206 var output = self.raw_output
207 if output != null then
208 res += "\n Output\n\t{output.chomp.replace("\n", "\n\t")}\n"
209 end
210 else
211 res = "{status_tag(color)} {full_name}"
212 if more_message != null then res += more_message
213 end
214 return res
215 end
216
217 # Return a `<testcase>` XML node in format compatible with Jenkins unit tests.
218 fun to_xml: HTMLTag do
219 var tc = new HTMLTag("testcase")
220 tc.attr("classname", xml_classname)
221 tc.attr("name", xml_name)
222 var error = self.error
223 if error != null then
224 if was_exec then
225 tc.open("error").append(error)
226 else
227 tc.open("failure").append(error)
228 end
229 end
230 var output = self.raw_output
231 if output != null then
232 tc.open("system-err").append(output.trunc(8192).filter_nonprintable)
233 end
234 return tc
235 end
236
237 # The `classname` attribute of the XML format.
238 #
239 # NOTE: jenkins expects a '.' in the classname attr
240 #
241 # See to_xml
242 fun xml_classname: String is abstract
243
244 # The `name` attribute of the XML format.
245 #
246 # See to_xml
247 fun xml_name: String is abstract
248 end
249
250 redef class String
251 # If needed, truncate `self` at `max_length` characters and append an informative `message`.
252 #
253 # ~~~
254 # assert "hello".trunc(10) == "hello"
255 # assert "hello".trunc(2) == "he[truncated. Full size is 5]"
256 # assert "hello".trunc(2, "...") == "he..."
257 # ~~~
258 fun trunc(max_length: Int, message: nullable String): String
259 do
260 if length <= max_length then return self
261 if message == null then message = "[truncated. Full size is {length}]"
262 return substring(0, max_length) + message
263 end
264
265 # Use a special notation for whitespace characters that are not `'\n'` (LFD) or `' '` (space).
266 #
267 # ~~~
268 # assert "hello".filter_nonprintable == "hello"
269 # assert "\r\n\t".filter_nonprintable == "^13\n^9"
270 # ~~~
271 fun filter_nonprintable: String
272 do
273 var buf = new Buffer
274 for c in self do
275 var cp = c.code_point
276 if cp < 32 and c != '\n' then
277 buf.append "^{cp}"
278 else
279 buf.add c
280 end
281 end
282 return buf.to_s
283 end
284 end