-
Notifications
You must be signed in to change notification settings - Fork 315
/
validator.py
275 lines (225 loc) · 8.61 KB
/
validator.py
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
import sys
import os
from traitlets.config import LoggingConfigurable
from traitlets import List, Unicode, Integer, Bool
from nbformat import current_nbformat
from textwrap import fill, dedent
from nbconvert.filters import ansi2html, strip_ansi
from .preprocessors import Execute, ClearOutput, CheckCellMetadata
from .nbgraderformat import read as read_nb
from . import utils
class Validator(LoggingConfigurable):
preprocessors = List([
CheckCellMetadata,
ClearOutput,
Execute
])
indent = Unicode(
" ",
help="A string containing whitespace that will be used to indent code and errors"
).tag(config=True)
width = Integer(
90,
help="Maximum line width for displaying code/errors"
).tag(config=True)
invert = Bool(
False,
help="Complain when cells pass, rather than fail."
).tag(config=True)
ignore_checksums = Bool(
False,
help=dedent(
"""
Don't complain if cell checksums have changed (if they are locked
cells) or haven't changed (if they are solution cells)
"""
)
).tag(config=True)
changed_warning = Unicode(
dedent(
"""
THE CONTENTS OF {num_changed} TEST CELL(S) HAVE CHANGED!
This might mean that even though the tests are passing
now, they won't pass when your assignment is graded.
"""
).strip() + "\n",
help="Warning to display when a cell has changed."
).tag(config=True)
failed_warning = Unicode(
dedent(
"""
VALIDATION FAILED ON {num_failed} CELL(S)! If you submit
your assignment as it is, you WILL NOT receive full
credit.
"""
).strip() + "\n",
help="Warning to display when a cell fails."
).tag(config=True)
passed_warning = Unicode(
dedent(
"""
NOTEBOOK PASSED ON {num_passed} CELL(S)!
"""
).strip() + "\n",
help="Warning to display when a cell passes (when invert=True)"
).tag(config=True)
stream = sys.stdout
def _indent(self, val):
lines = val.split("\n")
new_lines = []
for line in lines:
new_line = self.indent + strip_ansi(line)
if len(new_line) > (self.width - 3):
new_line = new_line[:(self.width - 3)] + "..."
new_lines.append(new_line)
return "\n".join(new_lines)
def _extract_error(self, cell):
errors = []
if cell.cell_type == "code":
for output in cell.outputs:
if output.output_type == "error":
errors.append("\n".join(output.traceback))
if len(errors) == 0:
errors.append("You did not provide a response.")
else:
errors.append("You did not provide a response.")
return "\n".join(errors)
def _print_changed(self, source):
self.stream.write("\n" + "=" * self.width + "\n")
self.stream.write("The following cell has changed:\n\n")
self.stream.write(self._indent(source) + "\n\n")
def _print_error(self, source, error):
self.stream.write("\n" + "=" * self.width + "\n")
self.stream.write("The following cell failed:\n\n")
self.stream.write(self._indent(source) + "\n\n")
self.stream.write("The error was:\n\n")
self.stream.write(self._indent(error) + "\n\n")
def _print_pass(self, source):
self.stream.write("\n" + "=" * self.width + "\n")
self.stream.write("The following cell passed:\n\n")
self.stream.write(self._indent(source) + "\n\n")
def _print_num_changed(self, num_changed):
if num_changed == 0:
return
else:
self.stream.write(
fill(
self.changed_warning.format(num_changed=num_changed),
width=self.width
)
)
def _print_num_failed(self, num_failed):
if num_failed == 0:
self.stream.write("Success! Your notebook passes all the tests.\n")
else:
self.stream.write(
fill(
self.failed_warning.format(num_failed=num_failed),
width=self.width
)
)
def _print_num_passed(self, num_passed):
if num_passed == 0:
self.stream.write("Success! The notebook does not pass any tests.\n")
else:
self.stream.write(
fill(
self.passed_warning.format(num_passed=num_passed),
width=self.width
)
)
def _get_changed_cells(self, nb):
changed = []
for cell in nb.cells:
if not (utils.is_grade(cell) or utils.is_locked(cell)):
continue
# if we're ignoring checksums, then remove the checksum from the
# cell metadata
if self.ignore_checksums and 'checksum' in cell.metadata.nbgrader:
del cell.metadata.nbgrader['checksum']
# verify checksums of cells
if utils.is_locked(cell) and 'checksum' in cell.metadata.nbgrader:
old_checksum = cell.metadata.nbgrader['checksum']
new_checksum = utils.compute_checksum(cell)
if old_checksum != new_checksum:
changed.append(cell)
return changed
def _get_failed_cells(self, nb):
failed = []
for cell in nb.cells:
if not (utils.is_grade(cell) or utils.is_locked(cell)):
continue
# if it's a grade cell, the check the grade
if utils.is_grade(cell):
score, max_score = utils.determine_grade(cell)
# it's a markdown cell, so we can't do anything
if score is None:
pass
elif score < max_score:
failed.append(cell)
return failed
def _get_passed_cells(self, nb):
passed = []
for cell in nb.cells:
if not (utils.is_grade(cell) or utils.is_locked(cell)):
continue
# if it's a grade cell, the check the grade
if utils.is_grade(cell):
score, max_score = utils.determine_grade(cell)
# it's a markdown cell, so we can't do anything
if score is None:
pass
elif score >= max_score:
passed.append(cell)
return passed
def _preprocess(self, filename):
nb = read_nb(filename, as_version=current_nbformat)
resources = {}
for preprocessor in self.preprocessors:
pp = preprocessor()
nb, resources = pp.preprocess(nb, resources)
return nb
def validate(self, filename):
self.log.info("Validating '{}'".format(os.path.abspath(filename)))
basename = os.path.basename(filename)
dirname = os.path.dirname(filename)
with utils.chdir(dirname):
nb = self._preprocess(basename)
changed = self._get_changed_cells(nb)
passed = self._get_passed_cells(nb)
failed = self._get_failed_cells(nb)
results = {}
if not self.ignore_checksums and len(changed) > 0:
results['changed'] = [{
"source": cell.source.strip()
} for cell in changed]
elif self.invert:
if len(passed) > 0:
results['passed'] = [{
"source": cell.source.strip()
} for cell in passed]
else:
if len(failed) > 0:
results['failed'] = [{
"source": cell.source.strip(),
"error": ansi2html(self._extract_error(cell)),
"raw_error": self._extract_error(cell)
} for cell in failed]
return results
def validate_and_print(self, filename):
results = self.validate(filename)
changed = results.get('changed', [])
passed = results.get('passed', [])
failed = results.get('failed', [])
if not self.ignore_checksums and len(changed) > 0:
self._print_num_changed(len(changed))
for cell in changed:
self._print_changed(cell['source'])
elif self.invert:
self._print_num_passed(len(passed))
for cell in passed:
self._print_pass(cell['source'])
else:
self._print_num_failed(len(failed))
for cell in failed:
self._print_error(cell['source'], cell['raw_error'])