62bf57e5a37c539ff6a66d1cb82b0aea78155ed0
[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"
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 end
98
99 # A unit test is an elementary test discovered, run and reported by nitunit.
100 #
101 # This class factorizes `DocUnit` and `TestCase`.
102 abstract class UnitTest
103 # The name of the unit to show in messages
104 fun full_name: String is abstract
105
106 # The location of the unit test to show in messages.
107 fun location: Location is abstract
108
109 # Flag that indicates if the unit test was compiled/run.
110 var is_done: Bool = false is writable
111
112 # Error message occurred during test-case execution (or compilation).
113 #
114 # e.g.: `Runtime Error`
115 var error: nullable String = null is writable
116
117 # Was the test case executed at least once?
118 #
119 # This will indicate the status of the test (failture or error)
120 var was_exec = false is writable
121
122 # The raw output of the execution (or compilation)
123 #
124 # It merges the standard output and error output
125 var raw_output: nullable String = null is writable
126
127 # The location where the error occurred, if it makes sense.
128 var error_location: nullable Location = null is writable
129
130 # A colorful `[OK]` or `[KO]`.
131 fun status_tag: String do
132 if not is_done then
133 return "[ ]"
134 else if error != null then
135 return "[KO]".red.bold
136 else
137 return "[OK]".green.bold
138 end
139 end
140
141 # The full (color) description of the test-case.
142 #
143 # `more message`, if any, is added after the error message.
144 fun to_screen(more_message: nullable String): String do
145 var res
146 var error = self.error
147 if error != null then
148 if more_message != null then error += " " + more_message
149 var loc = error_location or else location
150 res = "{status_tag} {full_name}\n {loc.to_s.yellow}: {error}\n{loc.colored_line("1;31")}"
151 var output = self.raw_output
152 if output != null then
153 res += "\n Output\n\t{output.chomp.replace("\n", "\n\t")}\n"
154 end
155 else
156 res = "{status_tag} {full_name}"
157 if more_message != null then res += more_message
158 end
159 return res
160 end
161
162 # Return a `<testcase>` XML node in format compatible with Jenkins unit tests.
163 fun to_xml: HTMLTag do
164 var tc = new HTMLTag("testcase")
165 tc.attr("classname", xml_classname)
166 tc.attr("name", xml_name)
167 var error = self.error
168 if error != null then
169 if was_exec then
170 tc.open("error").append(error)
171 else
172 tc.open("failure").append(error)
173 end
174 end
175 var output = self.raw_output
176 if output != null then
177 tc.open("system-err").append(output.trunc(8192).filter_nonprintable)
178 end
179 return tc
180 end
181
182 # The `classname` attribute of the XML format.
183 #
184 # NOTE: jenkins expects a '.' in the classname attr
185 #
186 # See to_xml
187 fun xml_classname: String is abstract
188
189 # The `name` attribute of the XML format.
190 #
191 # See to_xml
192 fun xml_name: String is abstract
193 end
194
195 redef class String
196 # If needed, truncate `self` at `max_length` characters and append an informative `message`.
197 #
198 # ~~~
199 # assert "hello".trunc(10) == "hello"
200 # assert "hello".trunc(2) == "he[truncated. Full size is 5]"
201 # assert "hello".trunc(2, "...") == "he..."
202 # ~~~
203 fun trunc(max_length: Int, message: nullable String): String
204 do
205 if length <= max_length then return self
206 if message == null then message = "[truncated. Full size is {length}]"
207 return substring(0, max_length) + message
208 end
209
210 # Use a special notation for whitespace characters that are not `'\n'` (LFD) or `' '` (space).
211 #
212 # ~~~
213 # assert "hello".filter_nonprintable == "hello"
214 # assert "\r\n\t".filter_nonprintable == "^13\n^9"
215 # ~~~
216 fun filter_nonprintable: String
217 do
218 var buf = new Buffer
219 for c in self do
220 var cp = c.code_point
221 if cp < 32 and c != '\n' then
222 buf.append "^{cp}"
223 else
224 buf.add c
225 end
226 end
227 return buf.to_s
228 end
229 end