-
Notifications
You must be signed in to change notification settings - Fork 0
/
test
executable file
·318 lines (253 loc) · 7.66 KB
/
test
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
#!/usr/bin/env python3
import os
from threading import Thread
from subprocess import run, PIPE, Popen
from pathlib import Path, PurePath
from distutils.spawn import find_executable
from optparse import OptionParser
from time import time, sleep
from itertools import cycle
class Checker(object):
"""Checker class for solution"""
checked = []
def __init__(self, compiler, file):
self.compiler = compiler.split()
self.file = file
self.check()
def check(self):
binary = self.compiler[0]
if binary not in self.checked and not find_executable(binary):
raise EnvironmentError("{!r} not found. Do you have the compilers?".format(binary)) # noqa
elif binary not in self.checked:
self.checked += binary
class Execute(Checker):
"""Checker class that simply runs a command and inject an input to stdin"""
def run(self, input):
"""Given an input, run a command and insert the input into the stdin"""
command = ' '.join(self.compiler + [self.file])
program = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
return program.communicate(input=input.encode())
class Build(Execute):
"""Build is a checker that compiles it's file then change it's
file and compiler command to simply run the new generated ./compiled.out"""
fout = "compiled.out"
def compile(self):
"""Compile the file before running"""
output = os.path.join(os.path.dirname(self.file), self.fout)
args = self.compiler + [self.file, "-o", output]
program = Popen(args, stdout=PIPE)
if program.wait() != 0:
raise EnvironmentError("Compile fails")
# Once compiled, change it's compiler command and file
# so that it's super class Execute may run the newly compiled
# compiled.out
self.compiler = 'bash -c'.split()
self.file = os.path.abspath(output)
def cleanup(self):
"""Delete the compiled file after runs"""
os.remove(self.file)
CHECKERS = {
"Python": {
"cmdline": "python3",
"ext": "py",
"checker": Execute
},
"Go": {
"cmdline": "go run",
"ext": "go",
"checker": Execute
},
"Clojure": {
"cmdline": "clojure",
"ext": "clj",
"checker": Execute
},
"CommonLisp": {
"cmdline": "clisp",
"ext": "lisp",
"checker": Execute
},
"Haskell": {
"cmdline": "runhaskell",
"ext": "hs",
"checker": Execute
},
"C": {
"cmdline": "gcc -std=c99 -lm",
"ext": "c",
"checker": Build
},
"C++": {
"cmdline": "g++ -std=c++0x",
"ext": "cpp",
"checker": Build
},
"Lua": {
"cmdline": "lua",
"ext": "lua",
"checker": Execute
},
"Ruby": {
"cmdline": "ruby",
"ext": "rb",
"checker": Execute
},
"Bash": {
"cmdline": "bash",
"ext": "sh",
"checker": Execute
},
"Elixir": {
"cmdline": "elixir",
"ext": "exs",
"checker": Execute
},
"Objective-C": {
"cmdline": "gcc -Wall -lm -lobjc",
"ext": "m",
"checker": Build
},
"PHP": {
"cmdline": "php",
"ext": "php",
"checker": Execute
},
"Swift": {
"cmdline": "swift",
"ext": "swift",
"checker": Execute
}
}
def chunks(l, n):
"""Yield successive n-sized chunks from a list."""
return [l[i:i + n] for i in range(0, len(l), n)]
def cases(year, event, problem):
"""Prepare a test case
=> Find the test case folder
=> Load files
=> Sort by name
=> Read file contents
=> Chunk together .in (inputs) and .sol (solution) files
returns: [["input text", "expected solution"], ...]
"""
dir = '{}/{}/{}/__TESTS__'.format(year, event, problem)
files = sorted(os.listdir(dir))
return list(chunks([
Path('{}/{}'.format(dir, file)).read_text()
for file in files
], 2))
def solution_path(year, event, problem, language, id):
return './{}/{}/{}/{}/solution_{}.{}'.format(
year, event, problem, language, id, CHECKERS[language]['ext']
)
def test(checker, input, expected):
"""Given a checker, a input and a expected output,
return a 2-uple with a boolean representing if the test passed
and the value returned by stderr or stdout"""
out, err = checker.run(input)
solution = bytes.decode(out)
error = bytes.decode(err)
if error:
return (False, error)
if solution == expected:
return (True, solution)
else:
return (False, solution)
def test_all(year, event, problem, language, id):
"""Test all cases from the given problem"""
test_case = cases(year, event, problem)
file = solution_path(year, event, problem, language, id)
checker = prepare_checker(language, file)
for input, expected in test_case:
yield test(checker, input, expected)
if isinstance(checker, Build):
checker.cleanup()
def prepare_checker(language, file):
"""Given a language and a file, instance a builder object"""
cmdline = CHECKERS[language]['cmdline']
checker_type = CHECKERS[language]['checker']
checker = checker_type(cmdline, file)
if isinstance(checker, Build):
checker.compile()
return checker
def print_tests(results):
"""Tell our solver if everything went right"""
control = SpinnerController()
spin_thread = Thread(target=spinner, args=(control,))
spin_thread.start()
fails = []
for i, (passed, output) in enumerate(results):
control.current += 1
control.current_started = time()
id = i + 1
if not passed:
control.failed += 1
fails.append((id, output))
else:
control.passed += 1
control.done = True
spin_thread.join()
if not fails:
print("Perfect solution!")
else:
for (i, output) in fails:
print(
'Wrong response for case {}. Output was {}'
.format(i, output[:-1])
)
class SpinnerController:
done = False
current = 1
passed = 0
failed = 0
current_started = 0
def __init__(self):
self.current_started = time()
def progress_text(self):
return '{:02d} Passed. {:02d} Failed. Current: {:02d}. Time: {:.2f}s'.format(self.passed, self.failed, self.current, time() - self.current_started)
def last_text(self):
return '{:02d} Passed. {:02d} Failed.'.format(self.passed, self.failed)
def spinner(control):
animation = r"⣾⣽⣻⢿⡿⣟⣯"
for c in cycle(animation):
done = control.done
if not done:
message = ' ({}) {}'.format(c, control.progress_text())
else:
message = '{}'.format(control.last_text())
print(message, end='\r')
sleep(0.1)
if not done:
print(len(message) * " ", end='\r')
else:
print('')
break
# CLI
if __name__ == '__main__':
parser = OptionParser(
usage = 'Usage: ./%prog year problem lang solution_number [--event Main]',
version = '1.0'
)
parser.add_option('-e', '--event',
default="Main")
(options, args) = parser.parse_args()
if len(args) < 4:
parser.error('Wrong number of arguments')
if options.event not in ['Main', 'Warming']:
parser.error('Wrong kind of event. Must be "Main" or "Warming"')
event = options.event
year, problem, lang, id = args
if not year.isdigit():
parser.error('Year is not a number')
if not id.isdigit():
parser.error('Solution id is not a number')
if lang not in CHECKERS:
parser.error(
'Language not found.\nAvailable: {}'
.format(", ".join(CHECKERS.keys()))
)
file = solution_path(year, event, problem, lang, id)
if not os.path.isfile(os.path.abspath(file)):
parser.error('Solution file not found.\nDid you make the file ./{}?'
.format(file))
print_tests(test_all(int(year), event, problem, lang, int(id)))