Coverage for gpkit\tests\from_paths.py: 0%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

39 statements  

1"Runs each file listed in pwd/TESTS as a test" 

2import unittest 

3import os 

4import re 

5from gpkit import settings 

6from gpkit.tests.helpers import generate_example_tests, new_test 

7 

8 

9class TestFiles(unittest.TestCase): 

10 "Stub to be filled with files in $pwd/TESTS" 

11 

12 

13def clean(string): 

14 """Parses string into valid python variable name 

15 

16 https://stackoverflow.com/questions/3303312/ 

17 how-do-i-convert-a-string-to-a-valid-variable-name-in-python 

18 """ 

19 string = re.sub('[^0-9a-zA-Z_]', '_', string) # Replace invalid with _ 

20 return re.sub('^[^a-zA-Z_]+', '', string) # Remove leading until valid 

21 

22 

23def add_filetest(testclass, path): 

24 "Add test that imports the given path and runs its test() function" 

25 path = path.strip() 

26 print("adding test for", repr(path)) 

27 

28 def test_fn(self): 

29 top_level = os.getcwd() 

30 try: 

31 dirname = os.path.dirname(path) 

32 if dirname: 

33 os.chdir(os.path.dirname(path)) 

34 mod = __import__(os.path.basename(path)[:-3]) 

35 if not hasattr(mod, "test"): 

36 self.fail("file '%s' had no `test` function." % path) 

37 mod.test() 

38 finally: 

39 os.chdir(top_level) 

40 

41 setattr(testclass, "test_"+clean(path), test_fn) 

42 

43 

44def newtest_fn(name, solver, import_dict, path): 

45 "Doubly nested callbacks to run the test with `getattr(self, name)()`" 

46 return new_test(name, solver, import_dict, path, 

47 testfn=(lambda name, import_dict, path: 

48 lambda self: getattr(self, name)())) # pylint:disable=undefined-variable 

49 

50 

51def run(filename="TESTS", xmloutput=False, skipsolvers="look around"): 

52 "Parse and run paths from a given file for each solver" 

53 with open(filename, "r") as f: 

54 for path in f: 

55 add_filetest(TestFiles, path) 

56 if skipsolvers == "look around": 

57 from .test_repo import get_settings 

58 skipsolvers = get_settings()["skipsolvers"] 

59 solvers = [s for s in settings["installed_solvers"] 

60 if not skipsolvers or s not in skipsolvers] 

61 tests = generate_example_tests("", [TestFiles], solvers, 

62 newtest_fn=newtest_fn) 

63 if not solvers: 

64 # Dummy test in case all installed solvers are skipped. 

65 tests[0].test_dummy = lambda self: None 

66 from gpkit.tests.run_tests import run as run_ 

67 run_(tests=tests, xmloutput=xmloutput)