forked from csci-e-29/0000aa-pset-0-starter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_pset.py
109 lines (84 loc) · 2.62 KB
/
test_pset.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
import signal
import sys
from contextlib import contextmanager
from io import StringIO
from time import sleep, time
from unittest import TestCase, main
from fibonacci import SummableSequence, last_8, optimized_fibonacci
from pyramid import print_pyramid
try:
# Absent on Windows, trigger AttributeError
signal.alarm
def _timeout(signum, frame):
raise TimeoutError()
signal.signal(signal.SIGALRM, _timeout)
@contextmanager
def timeout(seconds=1, message="Timeout!"):
# NB: doesn't work on windows
signal.alarm(seconds)
try:
yield
except TimeoutError:
raise TimeoutError(message)
finally:
signal.alarm(0)
except AttributeError:
@contextmanager
def timeout(seconds=1, message="Timeout!"):
t0 = time()
yield
if time() - t0 > seconds:
raise TimeoutError(message)
@contextmanager
def capture_print():
_stdout = sys.stdout
sys.stdout = StringIO()
try:
yield sys.stdout
finally:
sys.stdout = _stdout
class FibTests(TestCase):
def test_fibonnacci(self):
for n, expected in [
# Check progressively more complex values, see if time out
(0, 0),
(1, 1),
(6, 8),
(10, 55),
(15, 610),
(20, 6765),
(30, 832040),
(40, 102334155),
(100, 354224848179261915075),
]:
with timeout(message="Timeout running f({})".format(n)):
self.assertEqual(expected, optimized_fibonacci(n))
def test_summable(self):
ss = SummableSequence(0, 1)
for n in range(0, 50, 5):
with timeout(message="Timeout running f({})".format(n)):
raise NotImplementedError(
"You should implement this and other SummableSequence tests!"
)
class TestTimeout(TestCase):
def test_timeout(self):
with self.assertRaises(TimeoutError):
with timeout():
sleep(2)
class MiscTests(TestCase):
def test_8(self):
self.assertEqual(123, last_8(123))
self.assertEqual(23456789, last_8(123456789))
class PyramidTests(TestCase):
def _assert_expected(self, rows, expected):
with capture_print() as std:
print_pyramid(rows)
std.seek(0)
captured = std.read()
self.assertEqual(expected, captured)
def test_pyramid_one(self):
self._assert_expected(1, "=\n")
def test_pyramid_two(self):
self._assert_expected(2, "-=-\n" + "===\n")
if __name__ == "__main__":
main()