Skip to content

Commit a34f7f1

Browse files
committed
Add script to test algorithms
A quick and dirty script to more quickly test implementations. Runs all algorithms or optionally accepts an argument to run just one.
1 parent b259603 commit a34f7f1

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

test.py

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#!/usr/bin/env python3
2+
3+
import random
4+
import sorting_algorithms
5+
import sys
6+
7+
from typing import Callable, List
8+
9+
GREEN = '\033[32m'
10+
RED = '\033[31m'
11+
ENDC = '\033[m'
12+
13+
14+
def _print_test_run_output(name: str, is_sorted: bool, result: List[float]) -> None:
15+
if is_sorted:
16+
print(f"{name}{GREEN} PASS {ENDC}")
17+
else:
18+
print(f"{name}{RED} FAIL {ENDC}")
19+
print(f"The array was not sorted:\n{result}\n")
20+
21+
22+
def _print_test_exception_output(name: str, error_message: str) -> None:
23+
print(f"{name}{RED} FAIL {ENDC}")
24+
print(f"{error_message}\n")
25+
26+
27+
def _is_algorithm(key: str, value: str) -> bool:
28+
# Ignore imported typings and helper functions.
29+
return not value.startswith("typing") and not key.startswith("_")
30+
31+
32+
def _generate_test_input() -> List[float]:
33+
return [random.random() for _ in range(10)]
34+
35+
36+
def _is_sorted(arr: List[float]) -> bool:
37+
return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))
38+
39+
40+
def _execute_test(algorithm: Callable[[List[float]], List[float]], algorithm_name: str) -> None:
41+
try:
42+
result = algorithm(_generate_test_input())
43+
_print_test_run_output(algorithm_name, _is_sorted(result), result)
44+
45+
except:
46+
_print_test_exception_output(algorithm_name, str(sys.exc_info()[1]))
47+
48+
49+
def test_one() -> None:
50+
algorithm = getattr(sorting_algorithms, sys.argv[1])
51+
_execute_test(algorithm, algorithm.__name__)
52+
53+
54+
def test_all() -> None:
55+
for key, value in sorting_algorithms.__dict__.items():
56+
if callable(value) and _is_algorithm(str(key), str(value)):
57+
_execute_test(value, key)
58+
59+
60+
if len(sys.argv) == 1:
61+
test_all()
62+
else:
63+
test_one()

0 commit comments

Comments
 (0)