/
from_paths.py
67 lines (54 loc) · 2.37 KB
/
from_paths.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
"Runs each file listed in pwd/TESTS as a test"
import unittest
import os
import re
from gpkit import settings
from gpkit.tests.helpers import generate_example_tests, new_test
class TestFiles(unittest.TestCase):
"Stub to be filled with files in $pwd/TESTS"
def clean(string):
"""Parses string into valid python variable name
https://stackoverflow.com/questions/3303312/
how-do-i-convert-a-string-to-a-valid-variable-name-in-python
"""
string = re.sub('[^0-9a-zA-Z_]', '_', string) # Replace invalid with _
return re.sub('^[^a-zA-Z_]+', '', string) # Remove leading until valid
def add_filetest(testclass, path):
"Add test that imports the given path and runs its test() function"
path = path.strip()
print("adding test for", repr(path))
def test_fn(self):
top_level = os.getcwd()
try:
dirname = os.path.dirname(path)
if dirname:
os.chdir(os.path.dirname(path))
mod = __import__(os.path.basename(path)[:-3])
if not hasattr(mod, "test"):
self.fail("file '%s' had no `test` function." % path)
mod.test()
finally:
os.chdir(top_level)
setattr(testclass, "test_"+clean(path), test_fn)
def newtest_fn(name, solver, import_dict, path):
"Doubly nested callbacks to run the test with `getattr(self, name)()`"
return new_test(name, solver, import_dict, path,
testfn=(lambda name, import_dict, path:
lambda self: getattr(self, name)())) # pylint:disable=undefined-variable
def run(filename="TESTS", xmloutput=False, skipsolvers="look around"):
"Parse and run paths from a given file for each solver"
with open(filename, "r") as f:
for path in f:
add_filetest(TestFiles, path)
if skipsolvers == "look around":
from .test_repo import get_settings
skipsolvers = get_settings()["skipsolvers"]
solvers = [s for s in settings["installed_solvers"]
if not skipsolvers or s not in skipsolvers]
tests = generate_example_tests("", [TestFiles], solvers,
newtest_fn=newtest_fn)
if not solvers:
# Dummy test in case all installed solvers are skipped.
tests[0].test_dummy = lambda self: None
from gpkit.tests.run_tests import run as run_
run_(tests=tests, xmloutput=xmloutput)