-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathcode_helpers.py
More file actions
273 lines (222 loc) Β· 8.39 KB
/
code_helpers.py
File metadata and controls
273 lines (222 loc) Β· 8.39 KB
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
# -*- coding: UTF-8 -*-
"""Collect up the functions used in all the sets."""
import getpass
import importlib.util as importUtils
import inspect
import json
import os
import re
import subprocess
import threading
import traceback
from pathlib import Path
from typing import Optional, Union
import colorama
import pandas as pd
from colorama import Fore, Style
from treats import deadpool, grumpy, nyan_cat
colorama.init()
class RunCmd(threading.Thread):
"""Run a subprocess command, if it exceeds the timeout kill it.
(without mercy)
"""
def __init__(self, cmd, timeout):
threading.Thread.__init__(self)
self.cmd = cmd
self.timeout = timeout
def run(self):
self.p = subprocess.Popen(self.cmd)
self.p.wait()
def Run(self):
self.start()
self.join(self.timeout)
if self.is_alive():
self.p.terminate() # use self.p.kill() if process needs a kill -9
self.join()
def terse_results(results):
s = ""
for result in results:
mark = "π" if result.get("value") == 1 else "π©"
s += f"{mark} {result.get('name','')}\n"
return s
def finish_up(
testResults: list[dict],
message: str,
the_treat: str,
week_number: int = 0,
path_to_save_trace_to: str = "../me",
print_results_summary=True,
) -> dict[str, Union[int, str, list[dict]]]:
if print_results_summary:
print(
"\n\nResult summary: (π scroll up for more details β)\n"
+ terse_results(testResults),
)
total = sum([r["value"] for r in testResults])
out_of = len(testResults)
package = {
"of_total": out_of,
"mark": total,
"results": testResults,
"week_number": week_number,
}
if total == out_of and total > 0:
print(the_treat)
completion_message(message, len(message) + 2)
else:
print("\nKeep going champ! πβ¨πβ¨ I believe in you! πβ¨πβ¨\n")
print(f"{total}/{out_of} (passed/attempted)")
if getpass.getuser() != "bdoherty":
# This stops it writing the results if it's running on Ben's computer. It's a fancier version of:
# os.getlogin() != "bdoherty":
write_results(package, week_number, path_to_save_trace_to)
return package
def write_results(
package: dict[str, Union[int, str, list[dict]]],
week_number: int = 0,
path_to_save_trace_to: str = "../me",
) -> None:
trace: str = ""
tracefile = os.path.join(path_to_save_trace_to, "trace.json")
if os.path.isfile(tracefile):
with open(tracefile, "r", encoding="utf-8") as f:
trace = json.load(f)
trace[week_number - 1] = package
with open(tracefile, "w", encoding="utf-8") as f:
json.dump(trace, f, indent=2)
else:
with open(tracefile, "w", encoding="utf-8") as f:
trace = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
trace[week_number] = package
json.dump(trace, f, indent=2)
def test(testResult: bool, name: str) -> dict:
"""Report on the test.
Returns 1 and 0 so that the 1s can be summed to give a mark.
"""
value = 0
try:
if testResult:
print((f"{Fore.GREEN}β {name}{Style.RESET_ALL}"))
value = 1
else:
print((f"{Fore.MAGENTA}β {name}{Style.RESET_ALL}"))
except Exception as e:
print(e)
print((f"{Fore.MAGENTA}β {name}{Style.RESET_ALL}"))
return {"value": value, "name": name}
def test_pydocstyle(fileName, flags="-e") -> bool:
"""Check to see if the file at file_path is pydocstyle compliant."""
getFrame = inspect.getfile(inspect.currentframe())
absPath = os.path.abspath(getFrame)
test_dir = os.path.dirname(absPath)
file_path = os.path.join(test_dir, fileName)
print(file_path)
try:
child = subprocess.Popen(
["pydocstyle", file_path, flags], stdout=subprocess.PIPE
)
streamdata = child.communicate()[0]
print(f"streamdata: {streamdata}") # I don't know what streamdata is for
rc = child.returncode
print(f"returncode: {rc}")
if rc == 0:
print("all good")
return True
elif rc is None:
print("all good, I think")
return True
else:
print(f"U haz docstring errorz {grumpy()}")
return False
except Exception as e:
print(f"failed to doc check: {e}")
return False
def lab_book_entry_completed(setNumber: int, repo_path: str) -> bool:
"""Check if a lab book has been completed with student content.
Ignores content between <!-- PROMPT START --> and <!-- PROMPT END --> markers,
allowing instructors to add helpful prompts without affecting the test.
"""
lab_book = Path(os.path.join(repo_path, f"set{setNumber}/readme.md"))
if lab_book.is_file():
with open(lab_book, "r", encoding="utf-8", errors="ignore") as f:
content = f.read()
# Strip out prompt sections (content between HTML comment markers)
content = re.sub(
r"<!-- PROMPT START -->.*?<!-- PROMPT END -->",
"",
content,
flags=re.DOTALL | re.IGNORECASE,
)
lines_stripped = [
line.strip() for line in content.splitlines() if line.strip() != ""
]
basic_lab_book_content = [
"TODO: Reflect on what you learned this week and what is still unclear."
]
if lines_stripped == basic_lab_book_content:
return False
elif lines_stripped:
return True
return False
def load_exercise_file(repo_path: str, setNumber: int = 2, exerciseNumber: int = 0):
path = os.path.join(repo_path, f"set{setNumber}", f"exercise{exerciseNumber}.py")
spec = importUtils.spec_from_file_location("exercise0", path)
ex = importUtils.module_from_spec(spec)
spec.loader.exec_module(ex)
return ex
def ex_runs(repo_path: str, setNumber: int = 2, exerciseNumber: int = 1) -> bool:
"""Check that this exercise runs at all."""
try:
p = os.path.normpath(
os.path.join(repo_path, f"set{setNumber}/exercise{exerciseNumber}.py")
)
spec = importUtils.spec_from_file_location("exercise", os.path.abspath(p))
ex = importUtils.module_from_spec(spec)
spec.loader.exec_module(ex)
return True
except Exception as e:
syntax_error_message(exerciseNumber, e)
return False
def syntax_error_message(exerciseNumber: int, e) -> None:
"""Give a readable error message."""
print("\n{s:{c}^{n}}\n{s:{c}^{n}}".format(n=50, c="*", s=""))
print(f"There is a syntax error in exercise{exerciseNumber}\n{e}")
print(traceback.print_exc())
print("\nWARNING: there might be more tests, but they won't run")
print(f"until you fix the syntax errors in exercise{exerciseNumber}.py")
print("{s:{c}^{n}}\n{s:{c}^{n}}\n".format(n=50, c="*", s=""))
def completion_message(message, width) -> None:
"""Print an obvious message.
Example:
In [5]: completion_message("this is the message", 30)
******************************
β this is the message
******************************
"""
cap = "{start}{s:{c}^{n}}{end}".format(
n=width, c="*", s="", start=Fore.GREEN, end=Style.RESET_ALL
)
print(f"{cap}\n")
print((f"{Fore.GREEN}β {message}{Style.RESET_ALL}"))
print(f"\n{cap}")
def print_timeout_message(
function_name: str = "unknown function name",
args=(1, 2, 3),
timeout_in_seconds: int = 5,
) -> None:
"""Print a message to explain to the user that their function didn't complete in the available time.
The message looks like:
do_stuff ([2, "tree", {"k", "v"}]) could not complete within 5 seconds and was killed.
Args:
function_name (str, optional): the name of the function. Defaults to "unknown function name".
args (tuple, optional): the args passed to the function. Defaults to (1, 2, 3).
timeout_in_seconds (int, optional): Time in seconds available to complete. Defaults to 5.
"""
print(
f"{function_name}({args}) could not complete "
f"within {timeout_in_seconds} seconds and was killed."
)
if __name__ == "__main__":
print(
"you probably meant to run something else, not this collection of helper files"
)