1 """ 2 Use this module to get and run all tk tests. 3 4 Tkinter tests should live in a package inside the directory where this file 5 lives, like test_tkinter. 6 Extensions also should live in packages following the same rule as above. 7 """ 8 9 import os 10 import sys 11 import unittest 12 import importlib 13 import test.test_support 14 15 this_dir_path = os.path.abspath(os.path.dirname(__file__)) 16 17 def is_package(path): 18 for name in os.listdir(path): 19 if name in ('__init__.py', '__init__.pyc', '__init.pyo'): 20 return True 21 return False 22 23 def get_tests_modules(basepath=this_dir_path, gui=True, packages=None): 24 """This will import and yield modules whose names start with test_ 25 and are inside packages found in the path starting at basepath. 26 27 If packages is specified it should contain package names that want 28 their tests collected. 29 """ 30 py_ext = '.py' 31 32 for dirpath, dirnames, filenames in os.walk(basepath): 33 for dirname in list(dirnames): 34 if dirname[0] == '.': 35 dirnames.remove(dirname) 36 37 if is_package(dirpath) and filenames: 38 pkg_name = dirpath[len(basepath) + len(os.sep):].replace('/', '.') 39 if packages and pkg_name not in packages: 40 continue 41 42 filenames = filter( 43 lambda x: x.startswith('test_') and x.endswith(py_ext), 44 filenames) 45 46 for name in filenames: 47 try: 48 yield importlib.import_module( 49 ".%s" % name[:-len(py_ext)], pkg_name) 50 except test.test_support.ResourceDenied: 51 if gui: 52 raise 53 54 def get_tests(text=True, gui=True, packages=None): 55 """Yield all the tests in the modules found by get_tests_modules. 56 57 If nogui is True, only tests that do not require a GUI will be 58 returned.""" 59 attrs = [] 60 if text: 61 attrs.append('tests_nogui') 62 if gui: 63 attrs.append('tests_gui') 64 for module in get_tests_modules(gui=gui, packages=packages): 65 for attr in attrs: 66 for test in getattr(module, attr, ()): 67 yield test 68 69 if __name__ == "__main__": 70 test.test_support.run_unittest(*get_tests()) 71