21
|
1 #! /usr/bin/env python
|
16
|
2 # Copyright (c) 2010 Chortos-2 <chortos@inbox.lv>
|
|
3
|
21
|
4 from __future__ import division, with_statement
|
|
5
|
|
6 try:
|
|
7 from compat import *
|
|
8 import files, problem, config
|
|
9 except ImportError:
|
|
10 import __main__
|
|
11 __main__.import_error(sys.exc_info()[1])
|
|
12 else:
|
|
13 from __main__ import clock, options
|
|
14
|
|
15 import glob, re, sys, tempfile, time
|
|
16 from subprocess import Popen, PIPE, STDOUT
|
|
17
|
|
18 import os
|
|
19 devnull = open(os.path.devnull, 'w+')
|
|
20
|
|
21 try:
|
|
22 from signal import SIGTERM, SIGKILL
|
|
23 except ImportError:
|
|
24 SIGTERM = 15
|
|
25 SIGKILL = 9
|
|
26
|
16
|
27 try:
|
21
|
28 from _subprocess import TerminateProcess
|
|
29 except ImportError:
|
|
30 # CPython 2.5 does define _subprocess.TerminateProcess even though it is
|
|
31 # not used in the subprocess module, but maybe something else does not
|
|
32 try:
|
|
33 import ctypes
|
|
34 TerminateProcess = ctypes.windll.kernel32.TerminateProcess
|
|
35 except (ImportError, AttributeError):
|
|
36 TerminateProcess = None
|
|
37
|
|
38 __all__ = ('TestCase', 'load_problem', 'TestCaseNotPassed',
|
|
39 'TimeLimitExceeded', 'WrongAnswer', 'NonZeroExitCode',
|
|
40 'CannotStartTestee', 'CannotStartValidator',
|
|
41 'CannotReadOutputFile')
|
|
42
|
|
43
|
|
44
|
|
45 # Exceptions
|
|
46
|
|
47 class TestCaseNotPassed(Exception): __slots__ = ()
|
|
48 class TimeLimitExceeded(TestCaseNotPassed): __slots__ = ()
|
|
49
|
|
50 class WrongAnswer(TestCaseNotPassed):
|
|
51 __slots__ = 'comment'
|
|
52 def __init__(self, comment=''):
|
|
53 self.comment = comment
|
|
54
|
|
55 class NonZeroExitCode(TestCaseNotPassed):
|
|
56 __slots__ = 'exitcode'
|
|
57 def __init__(self, exitcode):
|
|
58 self.exitcode = exitcode
|
|
59
|
|
60 class ExceptionWrapper(TestCaseNotPassed):
|
|
61 __slots__ = 'upstream'
|
|
62 def __init__(self, upstream):
|
|
63 self.upstream = upstream
|
|
64
|
|
65 class CannotStartTestee(ExceptionWrapper): __slots__ = ()
|
|
66 class CannotStartValidator(ExceptionWrapper): __slots__ = ()
|
|
67 class CannotReadOutputFile(ExceptionWrapper): __slots__ = ()
|
|
68 class CannotReadInputFile(ExceptionWrapper): __slots__ = ()
|
|
69 class CannotReadAnswerFile(ExceptionWrapper): __slots__ = ()
|
|
70
|
|
71
|
|
72
|
|
73 # Test case types
|
16
|
74
|
|
75 class TestCase(object):
|
21
|
76 __slots__ = ('problem', 'id', 'isdummy', 'infile', 'outfile', 'points',
|
|
77 'process', 'time_started', 'time_stopped', 'time_limit_string',
|
|
78 'realinname', 'realoutname', 'maxtime', 'maxmemory')
|
|
79
|
|
80 if ABCMeta:
|
|
81 __metaclass__ = ABCMeta
|
16
|
82
|
21
|
83 def __init__(case, prob, id, isdummy, points):
|
16
|
84 case.problem = prob
|
21
|
85 case.id = id
|
|
86 case.isdummy = isdummy
|
|
87 case.points = points
|
|
88 case.maxtime = case.problem.config.maxtime
|
|
89 case.maxmemory = case.problem.config.maxmemory
|
|
90 if case.maxtime:
|
|
91 case.time_limit_string = '/%.3f' % case.maxtime
|
|
92 else:
|
|
93 case.time_limit_string = ''
|
|
94 if not isdummy:
|
|
95 case.realinname = case.problem.config.testcaseinname
|
|
96 case.realoutname = case.problem.config.testcaseoutname
|
|
97 else:
|
|
98 case.realinname = case.problem.config.dummyinname
|
|
99 case.realoutname = case.problem.config.dummyoutname
|
|
100
|
|
101 @abstractmethod
|
|
102 def test(case): raise NotImplementedError
|
16
|
103
|
|
104 def __call__(case):
|
21
|
105 try:
|
|
106 return case.test()
|
|
107 finally:
|
|
108 case.cleanup()
|
|
109
|
|
110 def cleanup(case):
|
|
111 if not getattr(case, 'time_started', None):
|
|
112 case.time_started = case.time_stopped = clock()
|
|
113 elif not getattr(case, 'time_stopped', None):
|
|
114 case.time_stopped = clock()
|
|
115 #if getattr(case, 'infile', None):
|
|
116 # case.infile.close()
|
|
117 #if getattr(case, 'outfile', None):
|
|
118 # case.outfile.close()
|
|
119 if getattr(case, 'process', None):
|
|
120 # Try killing after three unsuccessful TERM attempts in a row
|
|
121 # (except on Windows, where TERMing is killing)
|
|
122 for i in range(3):
|
|
123 try:
|
|
124 try:
|
|
125 case.process.terminate()
|
|
126 except AttributeError:
|
|
127 # Python 2.5
|
|
128 if TerminateProcess and hasattr(proc, '_handle'):
|
|
129 # Windows API
|
|
130 TerminateProcess(proc._handle, 1)
|
|
131 else:
|
|
132 # POSIX
|
|
133 os.kill(proc.pid, SIGTERM)
|
|
134 except Exception:
|
|
135 time.sleep(0)
|
|
136 case.process.poll()
|
|
137 else:
|
|
138 break
|
|
139 else:
|
|
140 # If killing the process is unsuccessful three times in a row,
|
|
141 # just silently stop trying
|
|
142 for i in range(3):
|
|
143 try:
|
|
144 try:
|
|
145 case.process.kill()
|
|
146 except AttributeError:
|
|
147 # Python 2.5
|
|
148 if TerminateProcess and hasattr(proc, '_handle'):
|
|
149 # Windows API
|
|
150 TerminateProcess(proc._handle, 1)
|
|
151 else:
|
|
152 # POSIX
|
|
153 os.kill(proc.pid, SIGKILL)
|
|
154 except Exception:
|
|
155 time.sleep(0)
|
|
156 case.process.poll()
|
|
157 else:
|
|
158 break
|
|
159
|
|
160 def open_infile(case):
|
|
161 try:
|
|
162 case.infile = files.File('/'.join((case.problem.name, case.realinname.replace('$', case.id))))
|
|
163 except IOError:
|
|
164 e = sys.exc_info()[1]
|
|
165 raise CannotReadInputFile(e)
|
|
166
|
|
167 def open_outfile(case):
|
|
168 try:
|
|
169 case.outfile = files.File('/'.join((case.problem.name, case.realoutname.replace('$', case.id))))
|
|
170 except IOError:
|
|
171 e = sys.exc_info()[1]
|
|
172 raise CannotReadAnswerFile(e)
|
|
173
|
16
|
174
|
21
|
175 class ValidatedTestCase(TestCase):
|
|
176 __slots__ = 'validator'
|
|
177
|
|
178 def __init__(case, *args):
|
|
179 TestCase.__init__(case, *args)
|
|
180 if not case.problem.config.tester:
|
|
181 case.validator = None
|
|
182 else:
|
|
183 case.validator = case.problem.config.tester
|
|
184
|
|
185 # TODO
|
|
186 def validate(case, output):
|
|
187 if not case.validator:
|
|
188 # Compare the output with the reference output
|
|
189 case.open_outfile()
|
|
190 with case.outfile.open() as refoutput:
|
|
191 for line, refline in zip(output, refoutput):
|
|
192 if not isinstance(refline, basestring):
|
|
193 line = bytes(line, sys.getdefaultencoding())
|
|
194 if line != refline:
|
|
195 raise WrongAnswer()
|
|
196 try:
|
|
197 try:
|
|
198 next(output)
|
|
199 except NameError:
|
|
200 output.next()
|
|
201 except StopIteration:
|
|
202 pass
|
|
203 else:
|
|
204 raise WrongAnswer()
|
|
205 try:
|
|
206 try:
|
|
207 next(refoutput)
|
|
208 except NameError:
|
|
209 refoutput.next()
|
|
210 except StopIteration:
|
|
211 pass
|
|
212 else:
|
|
213 raise WrongAnswer()
|
|
214 return case.points
|
|
215 elif callable(case.validator):
|
|
216 return case.validator(output)
|
|
217 else:
|
|
218 # Call the validator program
|
|
219 output.close()
|
|
220 case.open_outfile()
|
|
221 if case.problem.config.ansname:
|
|
222 case.outfile.copy(case.problem.config.ansname)
|
|
223 case.process = Popen(case.validator, stdin=devnull, stdout=PIPE, stderr=STDOUT, universal_newlines=True, bufsize=-1)
|
|
224 comment = case.process.communicate()[0].strip()
|
|
225 lower = comment.lower()
|
|
226 match = re.match(r'(ok|correct|wrong(?:(?:\s|_)*answer)?)(?:$|\s+|[.,!:]+\s*)', lower)
|
|
227 if match:
|
|
228 comment = comment[match.end():]
|
|
229 if not case.problem.config.maxexitcode:
|
|
230 if case.process.returncode:
|
|
231 raise WrongAnswer(comment)
|
|
232 else:
|
|
233 return case.points, comment
|
|
234 else:
|
|
235 return case.points * case.process.returncode / case.problem.config.maxexitcode, comment
|
|
236
|
|
237
|
|
238 class BatchTestCase(ValidatedTestCase):
|
|
239 __slots__ = ()
|
|
240
|
|
241 def test(case):
|
|
242 if sys.platform == 'win32' or not case.maxmemory:
|
|
243 preexec_fn = None
|
|
244 else:
|
|
245 def preexec_fn():
|
|
246 try:
|
|
247 import resource
|
|
248 maxmemory = int(case.maxmemory * 1048576)
|
|
249 resource.setrlimit(resource.RLIMIT_AS, (maxmemory, maxmemory))
|
|
250 # I would also set a CPU time limit but I do not want the time
|
|
251 # that passes between the calls to fork and exec to be counted in
|
|
252 except MemoryError:
|
|
253 # We do not have enough memory for ourselves;
|
|
254 # let the parent know about this
|
|
255 raise
|
|
256 except Exception:
|
|
257 # Well, at least we tried
|
|
258 pass
|
|
259 case.open_infile()
|
|
260 case.time_started = None
|
|
261 if case.problem.config.stdio:
|
|
262 if options.erase and not case.validator:
|
|
263 # FIXME: 2.5 lacks the delete parameter
|
|
264 with tempfile.NamedTemporaryFile(delete=False) as f:
|
|
265 inputdatafname = f.name
|
|
266 else:
|
|
267 inputdatafname = case.problem.config.inname
|
|
268 case.infile.copy(inputdatafname)
|
|
269 # FIXME: inputdatafname should be deleted on __exit__
|
|
270 with open(inputdatafname, 'rU') as infile:
|
|
271 with tempfile.TemporaryFile('w+') if options.erase and not case.validator else open(case.problem.config.outname, 'w+') as outfile:
|
|
272 try:
|
|
273 try:
|
|
274 case.process = Popen(case.problem.config.path, stdin=infile, stdout=outfile, stderr=devnull, universal_newlines=True, bufsize=-1, preexec_fn=preexec_fn)
|
|
275 except MemoryError:
|
|
276 # If there is not enough memory for the forked test.py,
|
|
277 # opt for silent dropping of the limit
|
|
278 case.process = Popen(case.problem.config.path, stdin=infile, stdout=outfile, stderr=devnull, universal_newlines=True, bufsize=-1)
|
|
279 except OSError:
|
|
280 raise CannotStartTestee(sys.exc_info()[1])
|
|
281 case.time_started = clock()
|
|
282 # If we use a temporary file, it may not be a true file object,
|
|
283 # and if so, Popen will relay the standard output through pipes
|
|
284 if not case.maxtime:
|
|
285 case.process.communicate()
|
|
286 case.time_stopped = clock()
|
|
287 else:
|
|
288 time_end = case.time_started + case.maxtime
|
|
289 # FIXME: emulate communicate()
|
|
290 while True:
|
|
291 exitcode = case.process.poll()
|
|
292 now = clock()
|
|
293 if exitcode is not None:
|
|
294 case.time_stopped = now
|
|
295 break
|
|
296 elif now >= time_end:
|
|
297 raise TimeLimitExceeded()
|
|
298 if config.globalconf.force_zero_exitcode and case.process.returncode:
|
|
299 raise NonZeroExitCode(case.process.returncode)
|
|
300 outfile.seek(0)
|
|
301 return case.validate(outfile)
|
|
302 else:
|
|
303 if case.problem.config.inname:
|
|
304 case.infile.copy(case.problem.config.inname)
|
|
305 try:
|
|
306 try:
|
|
307 case.process = Popen(case.problem.config.path, stdin=devnull, stdout=devnull, stderr=STDOUT, preexec_fn=preexec_fn)
|
|
308 except MemoryError:
|
|
309 # If there is not enough memory for the forked test.py,
|
|
310 # opt for silent dropping of the limit
|
|
311 case.process = Popen(case.problem.config.path, stdin=devnull, stdout=devnull, stderr=STDOUT)
|
|
312 except OSError:
|
|
313 raise CannotStartTestee(sys.exc_info()[1])
|
|
314 case.time_started = clock()
|
|
315 if not case.maxtime:
|
|
316 case.process.wait()
|
|
317 case.time_stopped = clock()
|
|
318 else:
|
|
319 time_end = case.time_started + case.maxtime
|
|
320 while True:
|
|
321 exitcode = case.process.poll()
|
|
322 now = clock()
|
|
323 if exitcode is not None:
|
|
324 case.time_stopped = now
|
|
325 break
|
|
326 elif now >= time_end:
|
|
327 raise TimeLimitExceeded()
|
|
328 if config.globalconf.force_zero_exitcode and case.process.returncode:
|
|
329 raise NonZeroExitCode(case.process.returncode)
|
|
330 with open(case.problem.config.outname, 'rU') as output:
|
|
331 return case.validate(output)
|
|
332
|
|
333
|
|
334 # This is the only test case type not executing any programs to be tested
|
|
335 class OutputOnlyTestCase(ValidatedTestCase):
|
|
336 __slots__ = ()
|
|
337 def cleanup(case): pass
|
|
338
|
|
339 class BestOutputTestCase(ValidatedTestCase):
|
|
340 __slots__ = ()
|
|
341
|
|
342 # This is the only test case type executing two programs simultaneously
|
|
343 class ReactiveTestCase(TestCase):
|
|
344 __slots__ = ()
|
|
345 # The basic idea is to launch the program to be tested and the grader
|
|
346 # and to pipe their standard I/O from and to each other,
|
|
347 # and then to capture the grader's exit code and use it
|
|
348 # like the exit code of a test validator is used.
|
|
349
|
|
350
|
|
351 def load_problem(prob, _types={'batch' : BatchTestCase,
|
|
352 'outonly' : OutputOnlyTestCase,
|
|
353 'bestout' : BestOutputTestCase,
|
|
354 'reactive': ReactiveTestCase}):
|
16
|
355 if prob.config.usegroups:
|
|
356 pass
|
|
357 else:
|
21
|
358 # We will need to iterate over these configuration variables twice
|
|
359 try:
|
|
360 len(prob.config.dummies)
|
|
361 except Exception:
|
|
362 prob.config.dummies = tuple(prob.config.dummies)
|
|
363 try:
|
|
364 len(prob.config.tests)
|
|
365 except Exception:
|
|
366 prob.config.dummies = tuple(prob.config.tests)
|
|
367 # First get prob.cache.padoutput right
|
|
368 for i in prob.config.dummies:
|
|
369 s = 'sample ' + str(i).zfill(prob.config.paddummies)
|
|
370 prob.cache.padoutput = max(prob.cache.padoutput, len(s))
|
16
|
371 for i in prob.config.tests:
|
21
|
372 s = str(i).zfill(prob.config.padtests)
|
|
373 prob.cache.padoutput = max(prob.cache.padoutput, len(s))
|
|
374 # Now yield the actual test cases
|
|
375 for i in prob.config.dummies:
|
|
376 s = str(i).zfill(prob.config.paddummies)
|
|
377 yield _types[prob.config.kind](prob, s, True, 0)
|
|
378 for i in prob.config.tests:
|
|
379 s = str(i).zfill(prob.config.padtests)
|
|
380 yield _types[prob.config.kind](prob, s, False, prob.config.pointmap.get(i, prob.config.pointmap.get(None, prob.config.maxexitcode if prob.config.maxexitcode else 1))) |